code stringlengths 4 1.01M | language stringclasses 2
values |
|---|---|
var Connection = require("./db/db-connection").Connection;
var Tables = require("./db/tables");
const R = require("ramda");
var QUERY_MATCHES = {
$or: [
{percent_name: {$gt: 0.9}},
{
distance: {$lt: 1}
},
{
percent_name: {$gt: 0.8},
distance: {$lt: 30}
},
{
percent_name: {$gt: 0.8},
percent_address_phonetic: 1,
distance: {$lt: 50}
}
]
};
var connection = new Connection();
connection.connect()
.then(connection.collection.bind(connection, Tables.FUZZY_MATCHES_FB))
.then(coll=> {
return coll.find(QUERY_MATCHES).toArray()
})
.then(matches=> {
var promises = matches.map(match=> {
return Promise.resolve(R.filter(item=>(item.id_p1 == match.id_p1 || item.id_p2 == match.id_p1), matches)).then(response=> {
return {
id: match.id_p1.toString(),
name: match.name_p1,
response: R.compose(
R.sortBy(R.identity),
R.uniq,
R.flatten,
R.map(place=> {
return [place.id_p1.toString(), place.id_p2.toString()]
})
)(response)
}
})
});
return Promise.all(promises);
})
.then(matches=> {
matches = R.groupBy(item=>item.id, matches);
matches = Object.keys(matches).map((key)=> {
var get_ids = R.compose(
R.reduce((prev, id)=> {
prev.id_facebook.push(id);
return prev;
}, {id_facebook: [], id_google: [], id_opendata: [], id_imprese: []}),
R.sortBy(R.identity),
R.uniq,
R.flatten
, R.map(R.prop("response"))
);
var ids = get_ids(matches[key]);
return Object.assign({
name: matches[key][0].name
}, ids)
});
var uniq_matches = [];
for (var i = 0; i < matches.length; i++) {
var match = matches[i];
var found = R.find(nm=> {
var has_fb = match.id_facebook.filter(id=>nm.id_facebook.includes(id)).length;
return has_fb;
})(uniq_matches);
if (!found) {
uniq_matches.push(match);
}else {
found.id_facebook=R.uniq(found.id_facebook.concat(match.id_facebook));
}
}
var fuzzyMatchColl = connection.db.collection(Tables.FUZZY_MATCHES_FB_ONE_TO_MANY);
return fuzzyMatchColl.drop().then(_=>{
return fuzzyMatchColl.insertMany(uniq_matches);
})
})
.then(_=> {
connection.db.close();
console.log("DONE");
process.exit(0);
})
.catch(_=> {
console.log(_);
connection.db.close();
process.exit(1);
}); | Java |
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - Surname - BESSEY</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li class = "CurrentSection"><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li><a href="../../../events.html" title="Events">Events</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="SurnameDetail">
<h3>BESSEY</h3>
<p id="description">
This page contains an index of all the individuals in the database with the surname of BESSEY. Selecting the person’s name will take you to that person’s individual page.
</p>
<table class="infolist primobjlist surname">
<thead>
<tr>
<th class="ColumnName">Given Name</th>
<th class="ColumnDate">Birth</th>
<th class="ColumnDate">Death</th>
<th class="ColumnPartner">Partner</th>
<th class="ColumnParents">Parents</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnName">
<a href="../../../ppl/f/0/d15f5fd139f63d85a3442c71a0f.html">June T.<span class="grampsid"> [I1845]</span></a>
</td>
<td class="ColumnBirth"> </td>
<td class="ColumnDeath"> </td>
<td class="ColumnPartner">
</td>
<td class="ColumnParents"> </td>
</tr>
</tbody>
</table>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:07<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
| Java |
///////////////////////////////////////////////////////////////////////////////
//
//
//
//
///////////////////////////////////////////////////////////////////////////////
// Includes
#include "include/mdShared.h"
#include "include/mdBreakPoint.h"
#include "include/mdSpy.h"
#include "include/mdSymbol.h"
#include "include/mdSymbolPair.h"
#include "include/mdListLine.h"
#include "include/mdSection.h"
#include "include/mdSpiesPanel.h"
#include "include/mdFrmMain.h"
#include "include/mdApp.h"
#include "include/mdEmu.h"
#include "include/mdProject.h"
///////////////////////////////////////////////////////////////////////////////
// Events
///////////////////////////////////////////////////////////////////////////////
mdProject::mdProject()
{
AddDefaultSymbols();
}
mdProject::~mdProject()
{
ClearAllSpies();
ClearAllBreakPoints();
ClearAllSymbols();
}
///////////////////////////////////////////////////////////////////////////////
// Gestion des symboles
///////////////////////////////////////////////////////////////////////////////
void mdProject::AddDefaultSymbols()
{
// Ajoute des symboles par défaut
wxString b;
b=_T("VDP_DATA");
InsertSymbol(NULL,b,0xc00000,0,false);
b=_T("VDP_DATA");
InsertSymbol(NULL,b,0xc00002,0,false);
b=_T("VDP_CTRL");
InsertSymbol(NULL,b,0xc00004,0,false);
b=_T("VDP_CTRL");
InsertSymbol(NULL,b,0xc00006,0,false);
b=_T("HV_COUNTER");
InsertSymbol(NULL,b,0xc00008,0,false);
b=_T("HV_COUNTER");
InsertSymbol(NULL,b,0xc0000a,0,false);
b=_T("HV_COUNTER");
InsertSymbol(NULL,b,0xc0000c,0,false);
b=_T("HV_COUNTER");
InsertSymbol(NULL,b,0xc0000e,0,false);
b=_T("SN76489_PSG");
InsertSymbol(NULL,b,0xc00011,0,false);
b=_T("SN76489_PSG");
InsertSymbol(NULL,b,0xc00013,0,false);
b=_T("SN76489_PSG");
InsertSymbol(NULL,b,0xc00015,0,false);
b=_T("SN76489_PSG");
InsertSymbol(NULL,b,0xc00017,0,false);
b=_T("Z80_BUSREQ");
InsertSymbol(NULL,b,0xa11100,0,false);
b=_T("Z80_RESET");
InsertSymbol(NULL,b,0xa11200,0,false);
b=_T("MD_VERSION");
InsertSymbol(NULL,b,0xa10001,0,false);
b=_T("DATA_PORT_A");
InsertSymbol(NULL,b,0xa10003,0,false);
b=_T("DATA_PORT_B");
InsertSymbol(NULL,b,0xa10005,0,false);
b=_T("DATA_PORT_C");
InsertSymbol(NULL,b,0xa10007,0,false);
b=_T("CTRL_PORT_A");
InsertSymbol(NULL,b,0xa10009,0,false);
b=_T("CTRL_PORT_B");
InsertSymbol(NULL,b,0xa1000b,0,false);
b=_T("CTRL_PORT_C");
InsertSymbol(NULL,b,0xa1000d,0,false);
b=_T("TxDATA_PORT_A");
InsertSymbol(NULL,b,0xa10000,0,false);
b=_T("RxDATA_PORT_A");
InsertSymbol(NULL,b,0xa10011,0,false);
b=_T("S_CTRL_PORT_A");
InsertSymbol(NULL,b,0xa10013,0,false);
b=_T("TxDATA_PORT_B");
InsertSymbol(NULL,b,0xa10015,0,false);
b=_T("RxDATA_PORT_B");
InsertSymbol(NULL,b,0xa10017,0,false);
b=_T("S_CTRL_PORT_B");
InsertSymbol(NULL,b,0xa10019,0,false);
b=_T("TxDATA_PORT_C");
InsertSymbol(NULL,b,0xa1001b,0,false);
b=_T("RxDATA_PORT_C");
InsertSymbol(NULL,b,0xa1001d,0,false);
b=_T("S_CTRL_PORT_C");
InsertSymbol(NULL,b,0xa1001f,0,false);
DumpFile_Rom=_T("");
DumpFile_68kRam=_T("");
DumpFile_Z80Ram=_T("");
DumpFile_CRam=_T("");
DumpFile_VRam=_T("");
DumpFile_VSRam=_T("");
}
void mdProject::ClearAllSymbols(void)
{
mdSymbolList::iterator it;
for( it = m_Symbols.begin(); it != m_Symbols.end(); ++it )
{ mdSymbolPair *s=(mdSymbolPair*) it->second;
if(s!=NULL)
{
if(s->Label!=NULL)
delete(s->Label);
if(s->Variable!=NULL)
delete(s->Variable);
delete(s);
}
}
m_Symbols.clear();
}
int mdProject::CountSymbols(void)
{
return m_Symbols.size();
}
mdSymbol* mdProject::GetSymbol(int type,int pc)
{
mdSymbolPair *sp=GetSymbolPair(pc);
if(sp!=NULL)
{ if(type==0)
return sp->Variable;
else
return sp->Label;
}
return NULL;
}
mdSymbolPair* mdProject::GetSymbolPair(int pc)
{
mdSymbolList::iterator it;
it=m_Symbols.find(pc);
if(it!=m_Symbols.end())
{ return (mdSymbolPair*) it->second;
}
return NULL;
}
mdSymbol* mdProject::InsertSymbol(mdSection *Section_ID,wxString &Name,unsigned int Address,int Type,bool UserCreated)
{
mdSymbol *s=new mdSymbol();
s->Section=Section_ID;
s->Address=Address;
s->Name=Name;
s->UserCreated=UserCreated;
// vérifie si on a un symbol racine
mdSymbolPair *sp=GetSymbolPair(Address);
if(sp==NULL)
{ sp=new mdSymbolPair();
if(Type==0)
sp->Variable=s;
else
sp->Label=s;
m_Symbols[Address]=sp;
}
else
{ if(Type==0)
{ if(sp->Variable!=NULL)
delete(sp->Variable);
sp->Variable=s;
}
else
{ if(sp->Label!=NULL)
delete(sp->Label);
sp->Label=s;
}
}
return s;
}
bool mdProject::CheckSymbolPairExist(int pc)
{
mdBreakPointList::iterator it;
it=m_BreakPoints.find(pc);
if(it!=m_BreakPoints.end())
return true;
return false;
}
char* mdProject::GetSymbolName(int pc)
{
mdSymbolPair *sp=NULL;
mdSymbolList::iterator it;
it=m_Symbols.find(pc);
if(it!=m_Symbols.end())
{ sp=(mdSymbolPair*) it->second;
if(sp->Label!=NULL)
return (char*)sp->Label->Name.c_str();
if(sp->Variable!=NULL)
return (char*)sp->Variable->Name.c_str();
}
return NULL;
}
char* mdProject::GetSymbolLabelName(int pc)
{
mdSymbolPair *sp=NULL;
mdSymbolList::iterator it;
it=m_Symbols.find(pc);
if(it!=m_Symbols.end())
{ sp=(mdSymbolPair*) it->second;
if(sp->Label!=NULL)
return (char*)sp->Label->Name.c_str();
else
{
if(sp->Variable!=NULL)
return (char*)sp->Variable->Name.c_str();
}
}
return NULL;
}
char* mdProject::GetSymbolVariableName(int pc)
{
mdSymbolPair *sp=NULL;
mdSymbolList::iterator it;
it=m_Symbols.find(pc);
if(it!=m_Symbols.end())
{ sp=(mdSymbolPair*) it->second;
if(sp->Variable!=NULL)
return (char*)sp->Variable->Name.c_str();
}
return NULL;
}
void mdProject::RemoveSymbol(int type,int pc)
{
//m_Spies.erase(IntIndex);
mdSymbolPair *sp=GetSymbolPair(pc);
if(sp!=NULL)
{
if(type==0)
{ if(sp->Variable!=NULL)
{ if(sp->Variable->UserCreated==true)
{ delete(sp->Variable);
sp->Variable=NULL;
}
}
}
if(type==1)
{ if(sp->Label!=NULL)
{ delete(sp->Label);
sp->Label=NULL;
}
}
if(sp->Label==NULL && sp->Variable==NULL)
{ m_Symbols.erase(pc);
delete(sp);
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Gestion des watchers
///////////////////////////////////////////////////////////////////////////////
mdSpy* mdProject::InsertSpy( int IntIndex,
mdSection *Section,
wxString &name,
unsigned int address,
int length,
bool isfromarray)
{
mdSpy *Spy=new mdSpy();
Spy->SetName(name);
Spy->SetAddress(address,true);
Spy->m_Symbol->Section=Section;
Spy->m_Length=length;
Spy->m_ListIndex=IntIndex;
Spy->m_IsFromArray=isfromarray;
Spy->m_Value=0;
m_Spies[IntIndex]=Spy;
return Spy;
}
mdSpy* mdProject::GetSpy(int IntIndex)
{ return (mdSpy*)m_Spies[IntIndex];
}
void mdProject::RemoveSpy(int IntIndex)
{
m_Spies.erase(IntIndex);
}
void mdProject::ClearAllSpies(void)
{
mdSpiesList::iterator it;
for( it = m_Spies.begin(); it != m_Spies.end(); ++it )
{ mdSpy *s=(mdSpy*) it->second;
if(s!=NULL)
delete(s);
}
m_Spies.clear();
}
int mdProject::CountSpies(void)
{
return m_Spies.size();
}
///////////////////////////////////////////////////////////////////////////////
// Gestion des BerakPoints
///////////////////////////////////////////////////////////////////////////////
mdBreakPoint* mdProject::InsertBreakPoint(int IntIndex)
{
mdBreakPointList::iterator it;
it=m_BreakPoints.find(IntIndex);
if(it==m_BreakPoints.end())
{ mdBreakPoint *bk=new mdBreakPoint();
bk->m_Hits=0;
bk->m_Enabled=TRUE;
m_BreakPoints[IntIndex]=bk;
return bk;
}
return NULL;
}
bool mdProject::CheckGotBreakPoint(int pc)
{
mdBreakPointList::iterator it;
it=m_BreakPoints.find(pc);
if(it!=m_BreakPoints.end())
return true;
return false;
}
void mdProject::RemoveBreakPoint(int IntIndex)
{
m_BreakPoints.erase(IntIndex);
}
int mdProject::CountBreakPoint(void)
{
return m_BreakPoints.size();
}
void mdProject::ClearAllBreakPoints(void)
{
mdBreakPointList::iterator it;
for( it = m_BreakPoints.begin(); it != m_BreakPoints.end(); ++it )
{ mdBreakPoint *s=(mdBreakPoint*) it->second;
if(s!=NULL)
delete(s);
}
m_BreakPoints.clear();
}
mdBreakPoint* mdProject::GetBreakPoint(int pc)
{
return(mdBreakPoint*) m_BreakPoints[pc];
}
int mdProject::ExecuteBreakPoint(int pc)
{
mdBreakPointList::iterator it;
it=m_BreakPoints.find(pc);
if(it!=m_BreakPoints.end())
{ // trouver breakpoint incrémente le hits
mdBreakPoint *value =(mdBreakPoint*) it->second;
if(value->m_Enabled==true)
{ value->m_Hits++;
return 1;
}
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// Load les symboles et étiquettes
///////////////////////////////////////////////////////////////////////////////
int mdProject::LoadSymbols(int type,wxString& FileName)
{
// nasm pour commencer
wxString str="";
wxTextFile file;
file.Open(FileName);
int etat=-1;
int ligne_cnt=0;
wxString Section="";
ClearAllSymbols();
AddDefaultSymbols();
for ( str = file.GetFirstLine(); !file.Eof(); str = file.GetNextLine() )
{
if(ligne_cnt==0)
{
switch(etat)
{
case -1:
{
// traite le fichier
if(str.Contains(" Section ")==true)
{ // doit virer
etat=1;
Section=str.BeforeLast('\'');
Section=Section.AfterFirst('\'');
ligne_cnt=5;
}
else
{
if(str.Contains("Value Type Class Symbol Refs Line File")==true)
{ etat=1;
Section=_T("");
ligne_cnt=2;
}
}
}break;
case 1:
{
if(str.Trim().Length()==0)
etat=-1;
else
{ wxString var_name="";
wxString taille=str.SubString(12,18);
wxString index=str.SubString(0,9);
long value=0;
int addr_index= index.ToLong(&value,16);
int addresse=value;
taille=taille.Trim();
var_name=str.SubString(25,48);
var_name=var_name.Trim(true);
if(taille.Trim().Length()>0)
{
int size=0;
if(taille.CmpNoCase("byte")==0)
{ size=1;
}
if(taille.CmpNoCase("word")==0)
{ size=2;
}
if(taille.CmpNoCase("long")==0)
{ size=4;
}
if(size>0)
{
if(Section.CmpNoCase("vars")==0)
{ addresse = 0xff0000 + value; }
// attribue une section
gFrmMain->GetSpiesPanel()->InsertSpy(NULL,var_name,addresse,size,1,false);
}
}
else
{
// étiquette
InsertSymbol(NULL,var_name,value,1,false);
}
}
}break;
}
}
else
{ ligne_cnt--; }
}
file.Close();
return 0;
}
int mdProject::LoadList(wxString& FileName)
{
//// nasm pour commencer
//wxString str="";
//wxTextFile file;
//file.Open(FileName);
//int nbligne=file.GetLineCount();
//for ( str = file.GetFirstLine(); !file.Eof(); str = file.GetNextLine() )
//{
// wxString *s=new wxString(str);
//}
//file.Close();
return 0;
}
| Java |
Bitrix 16.5 Business Demo = ea7587a817bea036305172b8333d43ef
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- 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 fr.cryptohash.CubeHashCore (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 fr.cryptohash.CubeHashCore (burstcoin 1.3.6cg API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<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="../../../fr/cryptohash/CubeHashCore.html" title="class in fr.cryptohash">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?fr/cryptohash/class-use/CubeHashCore.html" target="_top">Frames</a></li>
<li><a href="CubeHashCore.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class fr.cryptohash.CubeHashCore" class="title">Uses of Class<br>fr.cryptohash.CubeHashCore</h2>
</div>
<div class="classUseContainer">
<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="../../../fr/cryptohash/CubeHashCore.html" title="class in fr.cryptohash">CubeHashCore</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="#fr.cryptohash">fr.cryptohash</a></td>
<td class="colLast">
<div class="block">The <code>fr.cryptohash</code> package contains implementations of
various cryptographic hash functions.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="fr.cryptohash">
<!-- -->
</a>
<h3>Uses of <a href="../../../fr/cryptohash/CubeHashCore.html" title="class in fr.cryptohash">CubeHashCore</a> in <a href="../../../fr/cryptohash/package-summary.html">fr.cryptohash</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../fr/cryptohash/CubeHashCore.html" title="class in fr.cryptohash">CubeHashCore</a> in <a href="../../../fr/cryptohash/package-summary.html">fr.cryptohash</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../fr/cryptohash/CubeHash224.html" title="class in fr.cryptohash">CubeHash224</a></span></code>
<div class="block">This class implements the CubeHash-224 digest algorithm under the
<a href="../../../fr/cryptohash/Digest.html" title="interface in fr.cryptohash"><code>Digest</code></a> API.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../fr/cryptohash/CubeHash256.html" title="class in fr.cryptohash">CubeHash256</a></span></code>
<div class="block">This class implements the CubeHash-256 digest algorithm under the
<a href="../../../fr/cryptohash/Digest.html" title="interface in fr.cryptohash"><code>Digest</code></a> API.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../fr/cryptohash/CubeHash384.html" title="class in fr.cryptohash">CubeHash384</a></span></code>
<div class="block">This class implements the CubeHash-384 digest algorithm under the
<a href="../../../fr/cryptohash/Digest.html" title="interface in fr.cryptohash"><code>Digest</code></a> API.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../fr/cryptohash/CubeHash512.html" title="class in fr.cryptohash">CubeHash512</a></span></code>
<div class="block">This class implements the CubeHash-512 digest algorithm under the
<a href="../../../fr/cryptohash/Digest.html" title="interface in fr.cryptohash"><code>Digest</code></a> API.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../fr/cryptohash/package-summary.html">fr.cryptohash</a> with parameters of type <a href="../../../fr/cryptohash/CubeHashCore.html" title="class in fr.cryptohash">CubeHashCore</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../fr/cryptohash/Digest.html" title="interface in fr.cryptohash">Digest</a></code></td>
<td class="colLast"><span class="typeNameLabel">CubeHashCore.</span><code><span class="memberNameLink"><a href="../../../fr/cryptohash/CubeHashCore.html#copyState-fr.cryptohash.CubeHashCore-">copyState</a></span>(<a href="../../../fr/cryptohash/CubeHashCore.html" title="class in fr.cryptohash">CubeHashCore</a> dst)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<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="../../../fr/cryptohash/CubeHashCore.html" title="class in fr.cryptohash">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?fr/cryptohash/class-use/CubeHashCore.html" target="_top">Frames</a></li>
<li><a href="CubeHashCore.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017. All rights reserved.</small></p>
</body>
</html>
| Java |
from math import ceil
import numpy as np
from ipywidgets import widgets
from tqdm.notebook import tqdm
from matplotlib import pyplot as plt
import lib.iq_mixer_calibration
from drivers import IQAWG
from lib.data_management import load_IQMX_calibration_database, \
save_IQMX_calibration
from lib.iq_mixer_calibration import IQCalibrator
class IQVectorGenerator:
def __init__(self, name, lo, iq_awg: IQAWG, sa, calibration_db_name="IQVG",
default_calibration_power=-30, marker_period_divisor=None,
slave_iqvgs=None, calibration_step=10e6):
"""
Parameters
----------
lo
iq_awg
sa
calibration_db_name
default_calibration_power
marker_period_divisor: int, ns
by default, the marker period should be divisible by the if_period
however, in some cases other divisor may be required, i.e. when
m3202 is used with PXICLK10 trigger sync mode this divisor
should be set to 100
"""
self._name = name
self._lo = lo
self._iqawg = iq_awg
self._sa = sa
self._cal_db_name = calibration_db_name
self._default_calibration_power = default_calibration_power
self._calibration_widget = widgets.HTML()
self._recalibrate_mixer = False
self._frequency = 5e9
self.set_if_frequency(100e6)
if marker_period_divisor is not None:
self._marker_period_divisor = marker_period_divisor
else:
self._marker_period_divisor = self._if_period
# for marker period synchronization when iqvgs are on the same AWG
self._slave_iqvgs = slave_iqvgs if slave_iqvgs is not None else []
self._power = default_calibration_power
self._dac_overridden = False
self._current_cal = None
self._requested_cal: lib.iq_mixer_calibration.IQCalibrationData = None
self._cal_db = None
self._marker_period = None
self._requested_marker_period = None
self.set_marker_period(1000)
self._calibration_initial_guess = {"dc_offsets": np.random.uniform(.03, 0.1, size=2),
"if_amplitudes": (.1, .1),
"if_phase": -np.pi * 0.54}
self._calibration_step = calibration_step
self._calibration_test_data = []
self._load_cal_db()
def get_calibration_widget(self):
return self._calibration_widget
def set_parameters(self, parameters_dict):
if "power" in parameters_dict:
self.set_power(parameters_dict["power"])
if "freq" in parameters_dict:
self.set_frequency(parameters_dict["freq"])
if "dac_overridden" in parameters_dict:
self._dac_overridden = parameters_dict["dac_overridden"]
else:
self._dac_overridden = False
def get_iqawg(self):
self._iqawg.set_parameters(
{'calibration': self._current_cal}) # ensure
return self._iqawg
def set_if_frequency(self, if_frequency):
self._if_frequency = if_frequency
self._if_period = 1 / if_frequency * 1e9 # ns
def get_if_frequency(self):
return self._if_frequency
def set_output_state(self, state):
self._lo.set_output_state(state)
def set_frequency(self, freq):
self._frequency = freq
self._lo.set_frequency(self._frequency + self._if_frequency)
self._requested_cal = self.get_calibration(self._frequency,
self._power)
self._output_SSB()
def set_power(self, power):
if power > self._default_calibration_power + 10:
raise ValueError("Power can be % dBm max, requested %d dBm" % (
self._default_calibration_power + 10, power))
self._power = power
self._requested_cal = self.get_calibration(self._frequency,
self._power)
self._lo.set_power(self._requested_cal.get_lo_power())
self._output_SSB()
def get_power(self):
return self._power
def set_marker_period(self, marker_period):
'''
For some applications there is need to control the length of the interval between triggers
output by the AWG of the IQVectorGenerator.
Parameters
----------
marker_period: ns, float
real trigger period will be recalculated to be not shorter than <marker_period> ns,
but still divisible by the IF period
'''
self._requested_marker_period = marker_period
correct_marker_period = ceil(
marker_period / self._marker_period_divisor) * \
self._marker_period_divisor
if correct_marker_period != self._marker_period:
self._marker_period = correct_marker_period
if self._requested_cal is not None:
self._current_cal = None
self._output_SSB()
for slave_iqvg in self._slave_iqvgs:
slave_iqvg.set_marker_period(self._marker_period)
def _output_SSB(self):
if self._requested_cal != self._current_cal:
# print(f"IQVG {self._name}: outputting pulse sequence to update calibration for frequency: {self._frequency/1e9:.4f} GHz"
# f", power: {self._power} dBm.")
self._iqawg.set_parameters({"calibration": self._requested_cal})
pb = self._iqawg.get_pulse_builder()
if_freq = self._requested_cal.get_radiation_parameters()[
"if_frequency"]
resolution = self._requested_cal.get_radiation_parameters()[
"waveform_resolution"]
if_period = 1 / if_freq * 1e9
if (if_period * 1e9) % resolution != 0:
print(
f"IQVectorGenerator {self._name} warning: IF period is not divisible by "
"calibration waveform resolution. Phase coherence will be bad.")
seq = pb.add_sine_pulse(self._marker_period).build()
self._iqawg.output_pulse_sequence(seq)
self._current_cal = self._requested_cal
# time.sleep(1)
def _load_cal_db(self):
self._cal_db = load_IQMX_calibration_database(self._cal_db_name, 0)
def _around_frequency(self, frequency):
# return ceil(frequency/self._calibration_step)*self._calibration_step
return round(frequency / self._calibration_step) * self._calibration_step
def get_calibration(self, frequency, power):
frequency = self._around_frequency(frequency)
# frequency = round(frequency/self._calibration_step)*self._calibration_step
if self._cal_db is None:
self._load_cal_db()
cal = \
self._cal_db.get(frozenset(dict(lo_power=14,
ssb_power=self._default_calibration_power,
lo_frequency=self._if_frequency + frequency,
if_frequency=self._if_frequency,
waveform_resolution=1,
sideband_to_maintain='left').items()))
if (cal is None) or self._recalibrate_mixer:
calibrator = IQCalibrator(self._iqawg, self._sa, self._lo,
self._cal_db_name, 0,
sidebands_to_suppress=6,
output_widget=self._calibration_widget)
ig = self._calibration_initial_guess
cal = calibrator.calibrate(
lo_frequency=frequency + self._if_frequency,
if_frequency=self._if_frequency,
lo_power=14,
ssb_power=self._default_calibration_power,
waveform_resolution=1,
iterations=3,
minimize_iterlimit=100,
sa_res_bandwidth=300,
initial_guess=ig)
save_IQMX_calibration(cal)
self._load_cal_db() # make sure to include new calibration into cache
cal._ssb_power = power
cal._if_amplitudes = cal._if_amplitudes / np.sqrt(
10 ** ((self._default_calibration_power - power) / 10))
# self._calibration_initial_guess["if_amplitudes"] = cal._if_amplitudes
self._calibration_initial_guess["if_phase"] = cal._if_phase
return cal
else:
cal = cal.copy()
cal._if_amplitudes = cal._if_amplitudes / np.sqrt(
10 ** ((self._default_calibration_power - power) / 10))
return cal
def calibrate_mixer(self, fstart, fstop, recalibrate=False):
"""
Performs calibration of the mixer in a frequency range
Parameters
----------
fstart: float
start of the frequency range
fstop : float
stop of the frequency range
recalibrate : bool
Whether or not to calibrate from scratch and override previous
calibration in this interval.
"""
fstart = self._around_frequency(fstart)
fstop = self._around_frequency(fstop)
self._recalibrate_mixer = recalibrate
pb = tqdm(np.arange(fstart, fstop + self._calibration_step, self._calibration_step),
smoothing=0)
for frequency in pb:
pb.set_description("%.3f GHz" % (frequency / 1e9))
for counter in range(3):
try:
self.set_frequency(frequency)
break
except ValueError:
print("Poor calibration at %.3f GHz, retry count "
"%d" % (frequency / 1e9, counter))
self._calibration_initial_guess["dc_offest"] = \
np.random.uniform(.03, 0.1, size=2)
self._recalibrate_mixer = False
def test_calibration(self, fstart, fstop, step=1e6,
sidebands_to_plot=[-1, 0, 1],
remeasure=False):
"""
Tests the saved calibrations by monitoring all the sidebands throughout
the specified frequency range
Parameters
----------
fstart: float, Hz
start of the frequency range
fstop: float, Hz
stop of the frequency range
step: float, Hz
step of the scan
remeasure : bool
remeasure or just replot the data from the previous run
"""
sideband_shifts = np.linspace(-3, 3, 7) * self._if_frequency
freqs = np.arange(fstart, fstop + step, step)
if remeasure or len(self._calibration_test_data) == 0:
self._calibration_test_data = []
for frequency in tqdm(freqs, smoothing=0):
self.set_frequency(frequency)
sa_freqs = sideband_shifts + self._frequency
self._sa.setup_list_sweep(list(sa_freqs), [1000] * 3)
self._sa.prepare_for_stb()
self._sa.sweep_single()
self._sa.wait_for_stb()
self._calibration_test_data.append(self._sa.get_tracedata())
self._calibration_test_data = np.array(
self._calibration_test_data).T
sidebands_to_plot_idcs = np.array(sidebands_to_plot, dtype=int) + 3
sideband_shifts = sideband_shifts[sidebands_to_plot_idcs]
data = self._calibration_test_data[sidebands_to_plot_idcs]
for row, sideband_shift in zip(data, sideband_shifts):
plt.plot(freqs, row, label=f"{(sideband_shift / 1e6):.2f} MHz")
plt.legend()
self._sa.setup_swept_sa(-self._if_frequency + self._frequency,
10 * self._if_frequency,
nop=1001, rbw=1e4)
self._sa.set_continuous()
| Java |
/*
Copyright 2012-2016 Michael Pozhidaev <michael.pozhidaev@gmail.com>
This file is part of LUWRAIN.
LUWRAIN is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
LUWRAIN is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
*/
package org.luwrain.core;
import java.util.*;
class ShortcutManager
{
class Entry
{
String name = "";
Shortcut shortcut;
Entry(String name, Shortcut shortcut)
{
NullCheck.notNull(name, "name");
NullCheck.notNull(shortcut, "shortcut");
if (name.trim().isEmpty())
throw new IllegalArgumentException("name may not be empty");
this.name = name;
this.shortcut = shortcut;
}
}
private final TreeMap<String, Entry> shortcuts = new TreeMap<String, Entry>();
boolean add(Shortcut shortcut)
{
NullCheck.notNull(shortcut, "shortcut");
final String name = shortcut.getName();
if (name == null || name.trim().isEmpty())
return false;
if (shortcuts.containsKey(name))
return false;
shortcuts.put(name, new Entry(name, shortcut));
return true;
}
Application[] prepareApp(String name, String[] args)
{
NullCheck.notNull(name, "name");
NullCheck.notNullItems(args, "args");
if (name.trim().isEmpty())
throw new IllegalArgumentException("name may not be empty");
if (!shortcuts.containsKey(name))
return null;
return shortcuts.get(name).shortcut.prepareApp(args);
}
String[] getShortcutNames()
{
final Vector<String> res = new Vector<String>();
for(Map.Entry<String, Entry> e: shortcuts.entrySet())
res.add(e.getKey());
String[] str = res.toArray(new String[res.size()]);
Arrays.sort(str);
return str;
}
void addBasicShortcuts()
{
add(new Shortcut(){
@Override public String getName()
{
return "registry";
}
@Override public Application[] prepareApp(String[] args)
{
Application[] res = new Application[1];
res[0] = new org.luwrain.app.registry.RegistryApp();
return res;
}
});
}
void addOsShortcuts(Luwrain luwrain, Registry registry)
{
NullCheck.notNull(luwrain, "luwrain");
NullCheck.notNull(registry, "registry");
registry.addDirectory(Settings.OS_SHORTCUTS_PATH);
for(String s: registry.getDirectories(Settings.OS_SHORTCUTS_PATH))
{
if (s.trim().isEmpty())
continue;
final OsCommands.OsShortcut shortcut = new OsCommands.OsShortcut(luwrain);
if (shortcut.init(Settings.createOsShortcut(registry, Registry.join(Settings.OS_SHORTCUTS_PATH, s))))
add(shortcut);
}
}
}
| Java |
---
ID: 2
post_title: Sample Page
author: moises
post_date: 2016-12-14 02:19:15
post_excerpt: ""
layout: page
permalink: http://pepmeup.ie/sample-page/
published: true
---
This is an example page. It's different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say something like this:
<blockquote>Hi there! I'm a bike messenger by day, aspiring actor by night, and this is my website. I live in Los Angeles, have a great dog named Jack, and I like piña coladas. (And gettin' caught in the rain.)</blockquote>
...or something like this:
<blockquote>The XYZ Doohickey Company was founded in 1971, and has been providing quality doohickeys to the public ever since. Located in Gotham City, XYZ employs over 2,000 people and does all kinds of awesome things for the Gotham community.</blockquote>
As a new WordPress user, you should go to <a href="http:/wordpress/wp-admin/">your dashboard</a> to delete this page and create new pages for your content. Have fun! | Java |
Namespace Interpreter.Parser.Tokens
''' <summary>
''' 该表达式之中的操作符
''' </summary>
Public Class [Operator] : Inherits Token
Public Enum Operators As Integer
NULL = -1
''' <summary>
''' <- Assign value to variable;
''' </summary>
ValueAssign
''' <summary>
''' -> Extension method calling;
''' </summary>
ExtCall
''' <summary>
''' <= Collection and hash table operations;
''' </summary>
CollectionOprOrDelegate
''' <summary>
''' = Self type cast;
''' </summary>
SelfCast
''' <summary>
''' << Hybrids scripting;
''' </summary>
HybridsScript
''' <summary>
''' >> Setup variable of hybrids scripting;
''' </summary>
HybirdsScriptPush
''' <summary>
''' => 函数指针
''' </summary>
HashOprOrDelegate
''' <summary>
''' <
''' </summary>
DynamicsCast
''' <summary>
''' >
''' </summary>
IODevice
End Enum
Public ReadOnly Property Type As [Operator].Operators
Public Overrides ReadOnly Property TokenType As TokenTypes
Get
Return TokenTypes.Operator
End Get
End Property
''' <summary>
'''
''' </summary>
''' <param name="opr">
''' [<- Assign value to variable;]
'''
'''
''' [-> Extension method calling;]
'''
'''
''' [<= Collection and hash table operations;]
'''
'''
''' [= Self type cast;]
'''
'''
''' [<< Hybrids scripting;]
'''
'''
''' [>> Setup variable of hybrids scripting;]
'''
''' </param>
Sub New(opr As String)
Call MyBase.New(0, opr)
Type = GetOperator(opr)
End Sub
Public Shared Function GetOperator(opr As String) As Operators
Select Case Trim(opr)
Case "<-", "=" : Return Operators.ValueAssign
Case "->" : Return Operators.ExtCall
Case "<=" : Return Operators.CollectionOprOrDelegate
' Case "=" : Return Operators.ValueAssign
Case "<<" : Return Operators.HybridsScript
Case ">>" : Return Operators.HybirdsScriptPush
Case "=>" : Return Operators.HashOprOrDelegate
Case "<" : Return Operators.DynamicsCast
Case ">" : Return Operators.IODevice
Case Else
Return Operators.NULL
' Throw New NotImplementedException($"The operator {NameOf(opr)}:={opr} is currently not support yet!")
End Select
End Function
Public Overrides Function ToString() As String
Return $"( {_TokenValue } ) {Type.GetType.FullName}.{Type.ToString}"
End Function
End Class
End Namespace | Java |
#include "tool_move.hpp"
#include "document/idocument_board.hpp"
#include "board/board.hpp"
#include "document/idocument_package.hpp"
#include "pool/package.hpp"
#include "document/idocument_padstack.hpp"
#include "pool/padstack.hpp"
#include "document/idocument_schematic.hpp"
#include "schematic/schematic.hpp"
#include "document/idocument_symbol.hpp"
#include "pool/symbol.hpp"
#include "imp/imp_interface.hpp"
#include "util/accumulator.hpp"
#include "util/util.hpp"
#include <iostream>
#include "core/tool_id.hpp"
namespace horizon {
ToolMove::ToolMove(IDocument *c, ToolID tid) : ToolBase(c, tid), ToolHelperMove(c, tid), ToolHelperMerge(c, tid)
{
}
void ToolMove::expand_selection()
{
std::set<SelectableRef> pkgs_fixed;
std::set<SelectableRef> new_sel;
for (const auto &it : selection) {
switch (it.type) {
case ObjectType::LINE: {
Line *line = doc.r->get_line(it.uuid);
new_sel.emplace(line->from.uuid, ObjectType::JUNCTION);
new_sel.emplace(line->to.uuid, ObjectType::JUNCTION);
} break;
case ObjectType::POLYGON_EDGE: {
Polygon *poly = doc.r->get_polygon(it.uuid);
auto vs = poly->get_vertices_for_edge(it.vertex);
new_sel.emplace(poly->uuid, ObjectType::POLYGON_VERTEX, vs.first);
new_sel.emplace(poly->uuid, ObjectType::POLYGON_VERTEX, vs.second);
} break;
case ObjectType::NET_LABEL: {
auto &la = doc.c->get_sheet()->net_labels.at(it.uuid);
new_sel.emplace(la.junction->uuid, ObjectType::JUNCTION);
} break;
case ObjectType::BUS_LABEL: {
auto &la = doc.c->get_sheet()->bus_labels.at(it.uuid);
new_sel.emplace(la.junction->uuid, ObjectType::JUNCTION);
} break;
case ObjectType::POWER_SYMBOL: {
auto &ps = doc.c->get_sheet()->power_symbols.at(it.uuid);
new_sel.emplace(ps.junction->uuid, ObjectType::JUNCTION);
} break;
case ObjectType::BUS_RIPPER: {
auto &rip = doc.c->get_sheet()->bus_rippers.at(it.uuid);
new_sel.emplace(rip.junction->uuid, ObjectType::JUNCTION);
} break;
case ObjectType::LINE_NET: {
auto line = &doc.c->get_sheet()->net_lines.at(it.uuid);
for (auto &it_ft : {line->from, line->to}) {
if (it_ft.is_junc()) {
new_sel.emplace(it_ft.junc.uuid, ObjectType::JUNCTION);
}
}
} break;
case ObjectType::TRACK: {
auto track = &doc.b->get_board()->tracks.at(it.uuid);
for (auto &it_ft : {track->from, track->to}) {
if (it_ft.is_junc()) {
new_sel.emplace(it_ft.junc.uuid, ObjectType::JUNCTION);
}
}
} break;
case ObjectType::VIA: {
auto via = &doc.b->get_board()->vias.at(it.uuid);
new_sel.emplace(via->junction->uuid, ObjectType::JUNCTION);
} break;
case ObjectType::POLYGON: {
auto poly = doc.r->get_polygon(it.uuid);
int i = 0;
for (const auto &itv : poly->vertices) {
(void)sizeof itv;
new_sel.emplace(poly->uuid, ObjectType::POLYGON_VERTEX, i);
i++;
}
} break;
case ObjectType::ARC: {
Arc *arc = doc.r->get_arc(it.uuid);
new_sel.emplace(arc->from.uuid, ObjectType::JUNCTION);
new_sel.emplace(arc->to.uuid, ObjectType::JUNCTION);
new_sel.emplace(arc->center.uuid, ObjectType::JUNCTION);
} break;
case ObjectType::SCHEMATIC_SYMBOL: {
auto sym = doc.c->get_schematic_symbol(it.uuid);
for (const auto &itt : sym->texts) {
new_sel.emplace(itt->uuid, ObjectType::TEXT);
}
} break;
case ObjectType::BOARD_PACKAGE: {
BoardPackage *pkg = &doc.b->get_board()->packages.at(it.uuid);
if (pkg->fixed) {
pkgs_fixed.insert(it);
}
else {
for (const auto &itt : pkg->texts) {
new_sel.emplace(itt->uuid, ObjectType::TEXT);
}
}
} break;
default:;
}
}
selection.insert(new_sel.begin(), new_sel.end());
if (pkgs_fixed.size() && imp)
imp->tool_bar_flash("can't move fixed package");
for (auto it = selection.begin(); it != selection.end();) {
if (pkgs_fixed.count(*it))
it = selection.erase(it);
else
++it;
}
}
Coordi ToolMove::get_selection_center()
{
Accumulator<Coordi> accu;
std::set<SelectableRef> items_ignore;
for (const auto &it : selection) {
if (it.type == ObjectType::BOARD_PACKAGE) {
const auto &pkg = doc.b->get_board()->packages.at(it.uuid);
for (auto &it_txt : pkg.texts) {
items_ignore.emplace(it_txt->uuid, ObjectType::TEXT);
}
}
else if (it.type == ObjectType::SCHEMATIC_SYMBOL) {
const auto &sym = doc.c->get_sheet()->symbols.at(it.uuid);
for (auto &it_txt : sym.texts) {
items_ignore.emplace(it_txt->uuid, ObjectType::TEXT);
}
}
}
for (const auto &it : selection) {
if (items_ignore.count(it))
continue;
switch (it.type) {
case ObjectType::JUNCTION:
accu.accumulate(doc.r->get_junction(it.uuid)->position);
break;
case ObjectType::HOLE:
accu.accumulate(doc.r->get_hole(it.uuid)->placement.shift);
break;
case ObjectType::BOARD_HOLE:
accu.accumulate(doc.b->get_board()->holes.at(it.uuid).placement.shift);
break;
case ObjectType::SYMBOL_PIN:
accu.accumulate(doc.y->get_symbol_pin(it.uuid).position);
break;
case ObjectType::SCHEMATIC_SYMBOL:
accu.accumulate(doc.c->get_schematic_symbol(it.uuid)->placement.shift);
break;
case ObjectType::BOARD_PACKAGE:
accu.accumulate(doc.b->get_board()->packages.at(it.uuid).placement.shift);
break;
case ObjectType::PAD:
accu.accumulate(doc.k->get_package().pads.at(it.uuid).placement.shift);
break;
case ObjectType::TEXT:
accu.accumulate(doc.r->get_text(it.uuid)->placement.shift);
break;
case ObjectType::POLYGON_VERTEX:
accu.accumulate(doc.r->get_polygon(it.uuid)->vertices.at(it.vertex).position);
break;
case ObjectType::DIMENSION:
if (it.vertex < 2) {
auto dim = doc.r->get_dimension(it.uuid);
accu.accumulate(it.vertex == 0 ? dim->p0 : dim->p1);
}
break;
case ObjectType::POLYGON_ARC_CENTER:
accu.accumulate(doc.r->get_polygon(it.uuid)->vertices.at(it.vertex).arc_center);
break;
case ObjectType::SHAPE:
accu.accumulate(doc.a->get_padstack().shapes.at(it.uuid).placement.shift);
break;
case ObjectType::BOARD_PANEL:
accu.accumulate(doc.b->get_board()->board_panels.at(it.uuid).placement.shift);
break;
case ObjectType::PICTURE:
accu.accumulate(doc.r->get_picture(it.uuid)->placement.shift);
break;
case ObjectType::BOARD_DECAL:
accu.accumulate(doc.b->get_board()->decals.at(it.uuid).placement.shift);
break;
default:;
}
}
if (doc.c || doc.y)
return (accu.get() / 1.25_mm) * 1.25_mm;
else
return accu.get();
}
ToolResponse ToolMove::begin(const ToolArgs &args)
{
std::cout << "tool move\n";
move_init(args.coords);
Coordi selection_center;
if (tool_id == ToolID::ROTATE_CURSOR || tool_id == ToolID::MIRROR_CURSOR)
selection_center = args.coords;
else
selection_center = get_selection_center();
collect_nets();
if (tool_id == ToolID::ROTATE || tool_id == ToolID::MIRROR_X || tool_id == ToolID::MIRROR_Y
|| tool_id == ToolID::ROTATE_CURSOR || tool_id == ToolID::MIRROR_CURSOR) {
move_mirror_or_rotate(selection_center, tool_id == ToolID::ROTATE || tool_id == ToolID::ROTATE_CURSOR);
if (tool_id == ToolID::MIRROR_Y) {
move_mirror_or_rotate(selection_center, true);
move_mirror_or_rotate(selection_center, true);
}
finish();
return ToolResponse::commit();
}
if (tool_id == ToolID::MOVE_EXACTLY) {
if (auto r = imp->dialogs.ask_datum_coord("Move exactly")) {
move_do(*r);
finish();
return ToolResponse::commit();
}
else {
return ToolResponse::end();
}
}
imp->tool_bar_set_actions({
{InToolActionID::LMB},
{InToolActionID::RMB},
{InToolActionID::ROTATE, InToolActionID::MIRROR, "rotate/mirror"},
{InToolActionID::ROTATE_CURSOR, InToolActionID::MIRROR_CURSOR, "rotate/mirror around cursor"},
{InToolActionID::RESTRICT},
});
update_tip();
for (const auto &it : selection) {
if (it.type == ObjectType::POLYGON_VERTEX || it.type == ObjectType::POLYGON_EDGE) {
auto poly = doc.r->get_polygon(it.uuid);
if (auto plane = dynamic_cast<Plane *>(poly->usage.ptr)) {
planes.insert(plane);
}
}
}
for (auto plane : planes) {
plane->fragments.clear();
plane->revision++;
}
InToolActionID action = InToolActionID::NONE;
switch (tool_id) {
case ToolID::MOVE_KEY_FINE_UP:
action = InToolActionID::MOVE_UP_FINE;
break;
case ToolID::MOVE_KEY_UP:
action = InToolActionID::MOVE_UP;
break;
case ToolID::MOVE_KEY_FINE_DOWN:
action = InToolActionID::MOVE_DOWN_FINE;
break;
case ToolID::MOVE_KEY_DOWN:
action = InToolActionID::MOVE_DOWN;
break;
case ToolID::MOVE_KEY_FINE_LEFT:
action = InToolActionID::MOVE_LEFT_FINE;
break;
case ToolID::MOVE_KEY_LEFT:
action = InToolActionID::MOVE_LEFT;
break;
case ToolID::MOVE_KEY_FINE_RIGHT:
action = InToolActionID::MOVE_RIGHT_FINE;
break;
case ToolID::MOVE_KEY_RIGHT:
action = InToolActionID::MOVE_RIGHT;
break;
default:;
}
if (action != InToolActionID::NONE) {
is_key = true;
ToolArgs args2;
args2.type = ToolEventType::ACTION;
args2.action = action;
update(args2);
}
if (tool_id == ToolID::MOVE_KEY)
is_key = true;
imp->tool_bar_set_tool_name("Move");
return ToolResponse();
}
void ToolMove::collect_nets()
{
for (const auto &it : selection) {
switch (it.type) {
case ObjectType::BOARD_PACKAGE: {
BoardPackage *pkg = &doc.b->get_board()->packages.at(it.uuid);
for (const auto &itt : pkg->package.pads) {
if (itt.second.net)
nets.insert(itt.second.net->uuid);
}
} break;
case ObjectType::JUNCTION: {
auto ju = doc.r->get_junction(it.uuid);
if (ju->net)
nets.insert(ju->net->uuid);
} break;
default:;
}
}
}
bool ToolMove::can_begin()
{
expand_selection();
return selection.size() > 0;
}
void ToolMove::update_tip()
{
auto delta = get_delta();
std::string s = coord_to_string(delta + key_delta, true) + " ";
if (!is_key) {
s += restrict_mode_to_string();
}
imp->tool_bar_set_tip(s);
}
void ToolMove::do_move(const Coordi &d)
{
move_do_cursor(d);
if (doc.b && update_airwires && nets.size()) {
doc.b->get_board()->update_airwires(true, nets);
}
update_tip();
}
void ToolMove::finish()
{
for (const auto &it : selection) {
if (it.type == ObjectType::SCHEMATIC_SYMBOL) {
auto sym = doc.c->get_schematic_symbol(it.uuid);
doc.c->get_schematic()->autoconnect_symbol(doc.c->get_sheet(), sym);
if (sym->component->connections.size() == 0) {
doc.c->get_schematic()->place_bipole_on_line(doc.c->get_sheet(), sym);
}
}
}
if (doc.c) {
merge_selected_junctions();
}
if (doc.b) {
auto brd = doc.b->get_board();
brd->expand_flags = static_cast<Board::ExpandFlags>(Board::EXPAND_AIRWIRES);
brd->airwires_expand = nets;
for (auto plane : planes) {
brd->update_plane(plane);
}
}
}
ToolResponse ToolMove::update(const ToolArgs &args)
{
if (args.type == ToolEventType::MOVE) {
if (!is_key)
do_move(args.coords);
return ToolResponse();
}
else if (args.type == ToolEventType::ACTION) {
if (any_of(args.action, {InToolActionID::LMB, InToolActionID::COMMIT})
|| (is_transient && args.action == InToolActionID::LMB_RELEASE)) {
finish();
return ToolResponse::commit();
}
else if (any_of(args.action, {InToolActionID::RMB, InToolActionID::CANCEL})) {
return ToolResponse::revert();
}
else if (args.action == InToolActionID::RESTRICT) {
cycle_restrict_mode();
do_move(args.coords);
}
else if (any_of(args.action, {InToolActionID::ROTATE, InToolActionID::MIRROR})) {
bool rotate = args.action == InToolActionID::ROTATE;
const auto selection_center = get_selection_center();
move_mirror_or_rotate(selection_center, rotate);
}
else if (any_of(args.action, {InToolActionID::ROTATE_CURSOR, InToolActionID::MIRROR_CURSOR})) {
bool rotate = args.action == InToolActionID::ROTATE_CURSOR;
move_mirror_or_rotate(args.coords, rotate);
}
else {
const auto [dir, fine] = dir_from_action(args.action);
if (dir.x || dir.y) {
auto sp = imp->get_grid_spacing();
if (fine)
sp = sp / 10;
key_delta += dir * sp;
move_do(dir * sp);
update_tip();
}
}
}
return ToolResponse();
}
} // namespace horizon
| Java |
#include <cstdlib> // srand()
#include <ctime> // time()
#include "StateManager.hpp"
#include "SDL.hpp"
#include "Log.hpp"
#include "Config.hpp"
#include "GameStateMainMenu.hpp"
#include "GameStateGame.hpp"
#include "GameStateGameOver.hpp"
#include "Window.hpp"
#include "Graphics.hpp"
StateManager::StateManager(int width, int height)
{
SDL::init(30);
Window::init(width, height, "Prototype", "yes");
Graphics::init(Window::screen);
Config::load("config.ini");
if (Config::debugMode)
Log::debugMode(true);
// Here we start the game!
this->currentState = new GameStateMainMenu();
this->currentState->load();
this->sharedInfo = 0;
srand(time(NULL));
}
StateManager::~StateManager()
{
SDL::exit();
if (this->currentState)
{
this->currentState->unload();
delete this->currentState;
}
}
void StateManager::run()
{
bool letsQuit = false;
while (!letsQuit)
{
// The delta time from the last frame
uint32_t delta = SDL::getDelta();
// Normally i'd refresh input right here, but
// each state must do it individually
int whatToDoNow = this->currentState->update(delta);
switch (whatToDoNow)
{
case GameState::CONTINUE:
break;
case GameState::QUIT:
letsQuit = true;
break;
case GameState::GAME_START:
this->sharedInfo = this->currentState->unload();
delete (this->currentState);
this->currentState = new GameStateGame();
this->currentState->load(this->sharedInfo);
break;
case GameState::GAME_OVER:
this->sharedInfo = this->currentState->unload();
delete (this->currentState);
this->currentState = new GameStateGameOver();
this->currentState->load(this->sharedInfo);
break;
default:
break;
}
Window::clear();
this->currentState->render();
Window::refresh();
// Let's wait a bit if the framerate is too low.
SDL::framerateWait();
}
}
| Java |
/*
Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Free
Software Foundation, Inc.
This file is part of GNU Inetutils.
GNU Inetutils is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
GNU Inetutils is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see `http://www.gnu.org/licenses/'. */
/*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <config.h>
#if defined AUTHENTICATION || defined ENCRYPTION
# include <unistd.h>
# include <sys/types.h>
# include <arpa/telnet.h>
# include <libtelnet/encrypt.h>
# include <libtelnet/misc.h>
# include "general.h"
# include "ring.h"
# include "externs.h"
# include "defines.h"
# include "types.h"
int
net_write (unsigned char *str, int len)
{
if (NETROOM () > len)
{
ring_supply_data (&netoring, str, len);
if (str[0] == IAC && str[1] == SE)
printsub ('>', &str[2], len - 2);
return (len);
}
return (0);
}
void
net_encrypt ()
{
# ifdef ENCRYPTION
if (encrypt_output)
ring_encrypt (&netoring, encrypt_output);
else
ring_clearto (&netoring);
# endif /* ENCRYPTION */
}
int
telnet_spin ()
{
return (-1);
}
char *
telnet_getenv (char *val)
{
return ((char *) env_getvalue (val));
}
char *
telnet_gets (char *prompt, char *result, int length, int echo)
{
# if !HAVE_DECL_GETPASS
extern char *getpass ();
# endif
extern int globalmode;
int om = globalmode;
char *res;
TerminalNewMode (-1);
if (echo)
{
printf ("%s", prompt);
res = fgets (result, length, stdin);
}
else
{
res = getpass (prompt);
if (res)
{
strncpy (result, res, length);
memset (res, 0, strlen (res));
res = result;
}
}
TerminalNewMode (om);
return (res);
}
#endif /* defined(AUTHENTICATION) || defined(ENCRYPTION) */
| Java |
ace.require("ace/ext/language_tools");
var editor = ace.edit("editor");
editor.setOptions({
enableBasicAutocompletion: true
});
editor.setTheme("ace/theme/eclipse");
editor.getSession().setMode("ace/mode/java");
document.getElementById('editor').style.fontSize = '18px';
editor.setAutoScrollEditorIntoView(true);
var codeTemplates = {};
var viewConfig = {
showOutput: false,
showInput: false
};
var prevLang;
function showOutput(output) {
var stdout = '';
var stderr = '';
if (output.status === 0) {
stdout = output.output;
} else if (output.status === 1) {
stderr = '<p class="error">Compiler error !</p>';
stderr += output.error;
} else if (output.status === 2) {
stderr = '<p class="error">Runtime error !</p>';
stderr += output.error;
} else if (output.status === 3) {
stderr = '<p class="error">Timeout !</p>';
stderr += output.error;
}
var out = '';
if (stderr) {
out += '<b>Stderror</b>\n' + stderr;
}
if (stdout) {
out += stdout;
}
if (!viewConfig.showOutput) {
$('#btn-show-output').click();
}
$('#output-p').html(out);
// $('#output-data').show();
// if (!$('#bottom-pane').hasClass('opened')) {
// $('#bottom-pane').addClass('opened');
// }
windowResized();
}
function loadLangs() {
$('#btn-run').prop('disabled', true);
$.ajax({
type: "GET",
url: '/apis/langs'
}).done(function (data) {
showLangs(data);
$('#btn-run').prop('disabled', false);
}).fail(function (data) {
alert("error");
$('#btn-run').prop('disabled', false);
});
}
function showLangs(langs) {
for (var i = 0; i < langs.supportedLangs.length; i++) {
var supportedLang = langs.supportedLangs[i];
$('#lang').append($('<option>', {
value: supportedLang.id,
text: supportedLang.name
}));
codeTemplates[supportedLang.id] = supportedLang.template;
}
$('#lang').val(langs.supportedLangs[0].id);
onLangChanged();
}
$(document).ready(function () {
$('#btn-output').click(function () {
$('#output-data').toggle();
$('#bottom-pane').toggleClass('opened');
windowResized();
});
$('#btn-run').click(function () {
onRunning();
var codeRunRequest = {
lang: $('#lang').find(":selected").val(),
code: editor.getValue(),
input: $('#text-input').val()
};
runCode(codeRunRequest);
// $.ajax({
// type: "POST",
// url: '/apis/run',
// data: JSON.stringify(codeRunRequest),
// contentType: 'application/json'
// }).done(function (data) {
// showOutput(data);
// $('#btn-run').prop('disabled', false);
// }).fail(function (data) {
// alert("error");
// $('#btn-run').prop('disabled', false);
// });
});
$('#btn-hide-output').click(function () {
$('#btn-hide-output').hide();
$('#btn-show-output').show();
viewConfig.showOutput = false;
windowResized();
});
$('#btn-show-output').click(function () {
$('#btn-hide-output').show();
$('#btn-show-output').hide();
viewConfig.showOutput = true;
windowResized();
});
$('#btn-hide-input').click(function () {
$('#btn-hide-input').hide();
$('#btn-show-input').show();
viewConfig.showInput = false;
windowResized();
});
$('#btn-show-input').click(function () {
$('#btn-hide-input').show();
$('#btn-show-input').hide();
viewConfig.showInput = true;
windowResized();
});
loadLangs();
$(window).resize(function () {
windowResized();
});
windowResized();
});
$('#lang').change(function () {
onLangChanged();
});
function onLangChanged() {
var lang = $('#lang').find(":selected").val();
if (prevLang) {
codeTemplates[prevLang] = editor.getValue();
}
editor.setValue(codeTemplates[lang], -1);
prevLang = lang;
if (lang === 'java7') {
editor.getSession().setMode("ace/mode/java");
} else if (lang === 'python3') {
editor.getSession().setMode("ace/mode/python");
} else if (lang === 'c' || lang === 'c++') {
editor.getSession().setMode("ace/mode/c_cpp");
} else if (lang === 'c#') {
editor.getSession().setMode("ace/mode/csharp");
}
}
function windowResized() {
var aceWrapper = $('#ace_wrapper');
var aceEditor = $('#editor');
var outputWrapper = $('#output-wrapper');
var outputData = $('#output-data');
var inputWrapper = $('#input-wrapper');
var textInput = $('#text-input');
var rightDiff;
var inputHeight;
var outputHeight;
var textInputWidth;
var textInputHeight;
if (viewConfig.showInput || viewConfig.showOutput) {
rightDiff = outputWrapper.width() + 4;
} else {
rightDiff = 0;
}
var aceHeight = window.innerHeight - aceWrapper.position().top;// - bottomPane.height();
var aceWidth = window.innerWidth - rightDiff;
if (viewConfig.showOutput) {
outputWrapper.show();
outputHeight = aceHeight;
} else {
outputWrapper.hide();
outputHeight = 0;
}
if (viewConfig.showInput) {
inputWrapper.show();
inputHeight = 225;
if (viewConfig.showOutput) {
outputHeight -= inputHeight;
} else {
inputHeight = aceHeight;
}
textInputHeight = inputHeight - 62;
textInputWidth = rightDiff - 23;
} else {
inputWrapper.hide();
inputHeight = 0;
}
// var bottomPane = $('#bottom-pane');
// var outputWrapperHeight = aceHeight - inputWrapper.height() - 2;
var outputTextHeight = outputHeight - 52;
aceWrapper.css('height', aceHeight + 'px');
aceWrapper.css('width', aceWidth + 'px');
aceEditor.css('height', aceHeight + 'px');
aceEditor.css('width', aceWidth + 'px');
editor.resize();
if (viewConfig.showOutput) {
outputWrapper.css('height', outputHeight + 'px');
outputData.css('max-height', outputTextHeight + 'px');
}
if (viewConfig.showInput) {
inputWrapper.css('height', inputHeight + 'px');
textInput.css('width', textInputWidth + 'px');
textInput.css('height', textInputHeight + 'px');
// outputData.css('max-height', outputTextHeight + 'px');
}
}
var stompClient;
function connect() {
var socket = new SockJS('/coderun');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
// window.alert("connected !");
stompClient.subscribe('/user/queue/reply', function (reply) {
showOutput(JSON.parse(reply.body));
onFinished();
});
});
}
function runCode(codeRunRequest) {
stompClient.send('/iapis/run', {}, JSON.stringify(codeRunRequest));
}
function onRunning() {
$('#btn-run').prop('disabled', true);
$('#icon-running').show();
$('#icon-run').hide();
}
function onFinished() {
$('#btn-run').prop('disabled', false);
$('#icon-running').hide();
$('#icon-run').show();
}
connect(); | Java |
<html xmlns:wicket="http://wicket.apache.org/dtds.data/wicket-xhtml1.4-strict.dtd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://wicket.apache.org/dtds.data/wicket-xhtml1.4-strict.dtd ">
<head>
<title>Admin</title>
<link rel="stylesheet" type="text/css" href="../../base/default.css"/>
</head>
<body>
<div id="wrapper">
<div id="header" wicket:id="header">
<div id="logo">
<h1><a href="#">Marbles </a></h1>
<p> by <a href="http://my-volk.de/">Thomas Volk</a></p>
</div>
</div>
<!-- end #header -->
<div id="menu" wicket:id="menu">
<ul>
<li wicket:id="items"><a>Home</a></li>
<li wicket:id="items"><a>Test</a></li>
</ul>
</div>
<!-- end #menu -->
<div id="page">
<div id="page-bgtop">
<div id="page-bgbtm">
<div id="content">
<wicket:extend>
<div class="pageContent">
<h2>
<wicket:message key="title"/>
</h2>
<div class="messages" wicket:id="messages"></div>
<form wicket:id="updateUserForm">
<div>
<div><label for="name">
<wicket:message key="name"/>
</label></div>
<span wicket:id="name" id="name"/>
</div>
<div>
<div><label for="email">
<wicket:message key="email"/>
</label></div>
<span wicket:id="email" id="email"/>
</div>
<div wicket:id="passwordPanel"></div>
<div class="buttons">
<input type="submit" wicket:id="save"/>
</div>
</form>
</div>
</wicket:extend>
<div style="clear: both;"> </div>
</div>
<!-- end #content -->
<div id="sidebar" wicket:id="sidebar"></div>
<!-- end #sidebar -->
<div style="clear: both;"> </div>
</div>
</div>
</div>
<!-- end #page -->
</div>
<div id="footer" wicket:id="footer">
<p>Copyright (c) 2011 by <a href="http://my-volk.de/">Thomas Volk</a>.</p>
</div>
<!-- end #footer -->
</body>
</html> | Java |
import {Component, OnInit} from '@angular/core';
import {FundDataService} from '../funddata/funddata.service';
@Component({
selector: 'app-fund-table',
templateUrl: './fund-table.component.html',
styleUrls: ['./fund-table.component.css']
})
export class FundTableComponent implements OnInit {
private colShow: string[] = ['link_linkDisplay', 'fundResult_morningstarRating', 'oneQuarterAgoChange'];
private columns: string[];
private funds: Object[];
private fundsShow: Object[];
private error: any;
constructor(private fundDataService: FundDataService) {
}
ngOnInit() {
this.fundDataService.loadFunds().subscribe((datas) => {
this.funds = datas;
this.fundsShow = datas;
this.columns = Object.keys(datas[0]);
// console.log('columns: ' + this.columns);
// console.log(JSON.stringify(datas));
}, (err) => {// error
console.log(err);
this.error = err;
}, () => {// complete
});
}
toggleColumn(col: string) {
if (this.colShow.indexOf(col) === -1) {
this.colShow.push(col);
} else {
this.colShow.splice(this.colShow.indexOf(col), 1);
}
}
}
| Java |
/*
* Copyright appNativa Inc. All Rights Reserved.
*
* This file is part of the Real-time Application Rendering Engine (RARE).
*
* RARE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.appnativa.rare.platform.swing.ui.view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import com.appnativa.rare.Platform;
import com.appnativa.rare.iConstants;
import com.appnativa.rare.iPlatformAppContext;
import com.appnativa.rare.platform.swing.ui.util.SwingGraphics;
import com.appnativa.rare.ui.ColorUtils;
import com.appnativa.rare.ui.FontUtils;
import com.appnativa.rare.ui.UIColor;
import com.appnativa.rare.ui.UIDimension;
import com.appnativa.rare.ui.iPlatformIcon;
import com.appnativa.rare.ui.painter.iPainter;
import com.appnativa.rare.ui.painter.iPainterSupport;
import com.appnativa.rare.ui.painter.iPlatformComponentPainter;
import com.appnativa.util.CharArray;
import com.appnativa.util.XMLUtils;
public class RadioButtonView extends JRadioButton implements iPainterSupport, iView {
protected static iPlatformIcon deselectedIconDisabled_;
protected static iPlatformIcon deselectedIcon_;
protected static iPlatformIcon deselectedPressedIcon_;
protected static iPlatformIcon selectedIconDisabled_;
protected static iPlatformIcon selectedIcon_;
protected static iPlatformIcon selectedPressedIcon_;
private String originalText;
private boolean wordWrap;
public RadioButtonView() {
super();
initialize();
}
public RadioButtonView(Icon icon) {
super(icon);
initialize();
}
public RadioButtonView(String text) {
super(text);
initialize();
}
public RadioButtonView(String text, Icon icon) {
super(text, icon);
initialize();
}
AffineTransform transform;
protected SwingGraphics graphics;
private iPlatformComponentPainter componentPainter;
@Override
public boolean isOpaque() {
return ((componentPainter != null) && componentPainter.isBackgroundPaintEnabled())
? false
: super.isOpaque();
}
@Override
public void setTransformEx(AffineTransform tx) {
transform = tx;
}
@Override
public Color getForeground() {
Color c=super.getForeground();
if(c instanceof UIColor && !isEnabled()) {
c=((UIColor)c).getDisabledColor();
}
return c;
}
@Override
public AffineTransform getTransformEx() {
return transform;
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
AffineTransform tx = g2.getTransform();
if (transform != null) {
g2.transform(transform);
}
graphics = SwingGraphics.fromGraphics(g2, this, graphics);
super.paint(g2);
if (tx != null) {
g2.setTransform(tx);
}
graphics.clear();
}
@Override
protected void paintBorder(Graphics g) {
if (componentPainter == null) {
super.paintBorder(g);
}
}
@Override
protected void paintChildren(Graphics g) {
super.paintChildren(graphics.getGraphics());
iPlatformComponentPainter cp = getComponentPainter();
if (cp != null) {
float height = getHeight();
float width = getWidth();
cp.paint(graphics, 0, 0, width, height, iPainter.HORIZONTAL, true);
}
}
@Override
protected void paintComponent(Graphics g) {
graphics = SwingGraphics.fromGraphics(g, this, graphics);
iPlatformComponentPainter cp = getComponentPainter();
if (cp != null) {
float height = getHeight();
float width = getWidth();
cp.paint(graphics, 0, 0, width, height, iPainter.HORIZONTAL, false);
}
super.paintComponent(g);
}
@Override
public void setComponentPainter(iPlatformComponentPainter cp) {
componentPainter = cp;
}
@Override
public iPlatformComponentPainter getComponentPainter() {
return componentPainter;
}
@Override
public void getMinimumSize(UIDimension size, int maxWidth) {
Dimension d = getMinimumSize();
size.width = d.width;
size.height = d.height;
}
@Override
public void setText(String text) {
if (text == null) {
text = "";
}
originalText = text;
int len = text.length();
if (wordWrap && (len > 0) &&!text.startsWith("<html>")) {
CharArray ca = new CharArray(text.length() + 20);
ca.append("<html>");
XMLUtils.escape(text.toCharArray(), 0, len, true, ca);
ca.append("</html>");
text = ca.toString();
}
super.setText(text);
}
public void setWordWrap(boolean wordWrap) {
this.wordWrap = wordWrap;
}
@Override
public String getText() {
return originalText;
}
public boolean isWordWrap() {
return wordWrap;
}
protected void initialize() {
setOpaque(false);
setFont(FontUtils.getDefaultFont());
setForeground(ColorUtils.getForeground());
if (selectedIcon_ == null) {
iPlatformAppContext app = Platform.getAppContext();
if (ColorUtils.getForeground().isDarkColor()) {
selectedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.light");
deselectedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.light");
selectedPressedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.pressed.light");
deselectedPressedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.pressed.light");
selectedIconDisabled_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.disabled.light");
deselectedIconDisabled_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.disabled.light");
} else {
selectedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.dark");
deselectedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.dark");
selectedPressedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.pressed.dark");
deselectedPressedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.pressed.dark");
selectedIconDisabled_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.disabled.dark");
deselectedIconDisabled_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.disabled.dark");
}
}
setSelectedIcon(selectedIcon_);
setDisabledIcon(deselectedIconDisabled_);
setPressedIcon(deselectedPressedIcon_);
setIcon(deselectedIcon_);
setDisabledSelectedIcon(selectedIconDisabled_);
}
@Override
public Icon getDisabledIcon() {
Icon icon = super.getDisabledIcon();
if (icon == null) {
icon = getIcon();
if (icon instanceof iPlatformIcon) {
return ((iPlatformIcon) icon).getDisabledVersion();
}
}
return icon;
}
public Icon getDisabledSelectedIcon() {
Icon icon = super.getDisabledSelectedIcon();
if (icon == null) {
icon = getSelectedIcon();
if (icon == null) {
icon = getIcon();
}
if (icon instanceof iPlatformIcon) {
return ((iPlatformIcon) icon).getDisabledVersion();
}
}
return icon;
}
private static UIDimension size = new UIDimension();
@Override
public Dimension getPreferredSize() {
if (size == null) {
size = new UIDimension();
}
Number num = (Number) getClientProperty(iConstants.RARE_WIDTH_FIXED_VALUE);
int maxWidth = 0;
if ((num != null) && (num.intValue() > 0)) {
maxWidth = num.intValue();
}
getPreferredSize(size, maxWidth);
return new Dimension(size.intWidth(), size.intHeight());
}
@Override
public void getPreferredSize(UIDimension size, int maxWidth) {
Dimension d = super.getPreferredSize();
size.width = d.width;
size.height = d.height;
if (isFontSet() && getFont().isItalic()) {
if (getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey) == null) {
size.width += 4;
}
}
}
}
| Java |
package de.roskenet.simplecms.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import de.roskenet.simplecms.entity.Attribute;
public interface AttributeRepository extends PagingAndSortingRepository<Attribute, Integer> {
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.2"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Sequoia: Member List</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Sequoia
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.2 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
var searchBox = new SearchBox("searchBox", "../../search",'Search','.html');
/* @license-end */
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
$(function() {
initMenu('../../',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>sequoia</b></li><li class="navelem"><b>testing</b></li><li class="navelem"><a class="el" href="../../d3/dcb/classsequoia_1_1testing_1_1shell__commands__free__test.html">shell_commands_free_test</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle"><div class="title">sequoia::testing::shell_commands_free_test Member List</div></div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="../../d3/dcb/classsequoia_1_1testing_1_1shell__commands__free__test.html">sequoia::testing::shell_commands_free_test</a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>auxiliary_materials</b>() const noexcept (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="odd"><td class="entry"><b>basic_test</b>(std::string name) (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">explicit</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>basic_test</b>(const basic_test &)=delete (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="odd"><td class="entry"><b>basic_test</b>(basic_test &&) noexcept=default (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>caught_exceptions_output_filename</b>() const noexcept (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="odd"><td class="entry"><b>diagnostics_output_filename</b>() const noexcept (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>duration</b> typedef (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="odd"><td class="entry"><b>execute</b>(std::optional< std::size_t > index) (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>mode</b> (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr bgcolor="#f0f0f0" class="odd"><td class="entry"><b>name</b>() const noexcept (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>operator=</b>(const basic_test &)=delete (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="odd"><td class="entry"><b>operator=</b>(basic_test &&) noexcept=default (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>predictive_materials</b>() const noexcept (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="odd"><td class="entry"><b>report_line</b>(const std::filesystem::path &file, int line, std::string_view message) (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>set_filesystem_data</b>(std::filesystem::path testRepo, const std::filesystem::path &outputDir, std::string_view familyName) (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="odd"><td class="entry"><b>set_materials</b>(std::filesystem::path workingMaterials, std::filesystem::path predictiveMaterials, std::filesystem::path auxiliaryMaterials) (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>set_recovery_paths</b>(recovery_paths paths) (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="odd"><td class="entry"><b>source_filename</b>() const noexcept (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html#a74f379026bb979d1253c5660a70530cb">summarize</a>(duration delta) const</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span><span class="mlabel">virtual</span></td></tr>
<tr bgcolor="#f0f0f0" class="odd"><td class="entry"><b>test_repository</b>() const noexcept (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>working_materials</b>() const noexcept (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="odd"><td class="entry"><b>~basic_test</b>()=default (defined in <a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a>)</td><td class="entry"><a class="el" href="../../d0/d16/classsequoia_1_1testing_1_1basic__test.html">sequoia::testing::basic_test< Checker ></a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by <a href="https://www.doxygen.org/index.html"><img class="footer" src="../../doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.9.2
</small></address>
</body>
</html>
| Java |
require('dotenv').config({ silent: true });
var Express = require('express');
var path = require('path');
var fs = require('fs');
var merge = require('lodash/merge');
var proxy = require('proxy-middleware');
var ejs = require('ejs');
var config = require('./config');
var server = new Express();
server.set('port', config.PORT);
server.engine('html', require('ejs').renderFile);
server.set('view engine', 'ejs');
server.set('views', path.resolve(__dirname, '../www'));
server.locals.CONFIG = escape(JSON.stringify(config));
server.use(config.API_PROXY_PATH, proxy(config.API_ENDPOINT));
server.get('/', function (req, res) {
res.render('index.html');
});
server.use(Express.static(path.resolve(__dirname, '../www')));
server.get('/404', function (req, res) {
res.render('404.html');
});
server.listen(server.get('port'), function (err) {
if (err) {
console.log('error while starting server', err);
}
console.log('Gandalf is started to listen at localhost:' + server.get('port'));
});
| Java |
/* This file is part of the 'orilib' software. */
/* Copyright (C) 2007-2009, 2012 Romain Quey */
/* see the COPYING file in the top-level directory.*/
#ifdef __cplusplus
extern "C"
{
#endif
#ifndef OL_DIS_DEP_H
#define OL_DIS_DEP_H
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<float.h>
#define isNaN(x) ((x) != (x))
#include"ut.h"
#include"../ol_set.h"
#endif /* OL_DIS_DEP_H */
#ifdef __cplusplus
}
#endif
| Java |
/**
*
* Copyright (C) 2004-2008 FhG Fokus
*
* This file is part of the FhG Fokus UPnP stack - an open source UPnP implementation
* with some additional features
*
* You can redistribute the FhG Fokus UPnP stack and/or modify it
* under the terms of the GNU General Public License Version 3 as published by
* the Free Software Foundation.
*
* For a license to use the FhG Fokus UPnP stack software under conditions
* other than those described here, or to purchase support for this
* software, please contact Fraunhofer FOKUS by e-mail at the following
* addresses:
* upnpstack@fokus.fraunhofer.de
*
* The FhG Fokus UPnP stack is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>
* or write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package de.fraunhofer.fokus.upnp.core;
import java.util.Hashtable;
import java.util.Vector;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import de.fraunhofer.fokus.upnp.util.SAXTemplateHandler;
/**
* This class is used to parse UPnPDoc messages.
*
* @author Alexander Koenig
*
*
*/
public class UPnPDocParser extends SAXTemplateHandler
{
/** Doc entries for the current service type */
private Vector currentDocEntryList = new Vector();
private boolean isAction = false;
private boolean isStateVariable = false;
private String currentServiceType = null;
private String currentArgumentName = null;
private String currentArgumentDescription = null;
private UPnPDocEntry currentDocEntry = null;
/** Hashtable containing the UPnP doc entry list for one service type */
private Hashtable docEntryFromServiceTypeTable = new Hashtable();
/*
* (non-Javadoc)
*
* @see de.fraunhofer.fokus.upnp.util.SAXTemplateHandler#processStartElement(java.lang.String,
* java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void processStartElement(String uri, String name, String name2, Attributes atts) throws SAXException
{
if (getTagCount() == 2)
{
for (int i = 0; i < atts.getLength(); i++)
{
if (atts.getQName(i).equalsIgnoreCase("serviceType"))
{
currentServiceType = atts.getValue(i);
currentDocEntryList = new Vector();
}
}
}
if (getTagCount() == 3 && currentServiceType != null)
{
isAction = getCurrentTag().equalsIgnoreCase("actionList");
isStateVariable = getCurrentTag().equalsIgnoreCase("serviceStateTable");
}
if (getTagCount() == 4 && currentServiceType != null)
{
currentDocEntry = new UPnPDocEntry(currentServiceType);
}
}
/*
* (non-Javadoc)
*
* @see de.fraunhofer.fokus.upnp.util.SAXTemplateHandler#processEndElement(java.lang.String,
* java.lang.String, java.lang.String)
*/
public void processEndElement(String uri, String localName, String name) throws SAXException
{
if (getTagCount() == 6 && isAction && currentDocEntry != null && currentArgumentName != null &&
currentArgumentDescription != null)
{
currentDocEntry.addArgumentDescription(currentArgumentName, currentArgumentDescription);
currentArgumentName = null;
currentArgumentDescription = null;
}
if (getTagCount() == 4)
{
if (currentDocEntry != null && currentDocEntry.getActionName() != null && isAction)
{
// TemplateService.printMessage(" Add doc entry for action " +
// currentDocEntry.getActionName());
currentDocEntryList.add(currentDocEntry);
}
if (currentDocEntry != null && currentDocEntry.getStateVariableName() != null && isStateVariable)
{
// TemplateService.printMessage(" Add doc entry for state variable " +
// currentDocEntry.getStateVariableName());
currentDocEntryList.add(currentDocEntry);
}
currentDocEntry = null;
}
if (getTagCount() == 3)
{
isAction = false;
isStateVariable = false;
}
if (getTagCount() == 2)
{
// store list with doc entries for one service type
docEntryFromServiceTypeTable.put(currentServiceType, currentDocEntryList);
currentServiceType = null;
currentDocEntryList = null;
}
}
/*
* (non-Javadoc)
*
* @see de.fraunhofer.fokus.upnp.util.SAXTemplateHandler#processContentElement(java.lang.String)
*/
public void processContentElement(String content) throws SAXException
{
if (getTagCount() == 5 && currentDocEntry != null)
{
if (getCurrentTag().equalsIgnoreCase("name") && isAction)
{
currentDocEntry.setActionName(content.trim());
}
if (getCurrentTag().equalsIgnoreCase("name") && isStateVariable)
{
currentDocEntry.setStateVariableName(content.trim());
}
if (getCurrentTag().equalsIgnoreCase("description"))
{
currentDocEntry.setDescription(content.trim());
}
}
if (getTagCount() == 7 && currentDocEntry != null)
{
if (getCurrentTag().equalsIgnoreCase("name"))
{
currentArgumentName = content.trim();
}
if (getCurrentTag().equalsIgnoreCase("description"))
{
currentArgumentDescription = content.trim();
}
}
}
/**
* Retrieves the upnpDocEntryTable.
*
* @return The upnpDocEntryTable
*/
public Hashtable getDocEntryFormServiceTypeTable()
{
return docEntryFromServiceTypeTable;
}
}
| Java |
/*
* (C) 2003-2006 Gabest
* (C) 2006-2013 see Authors.txt
*
* This file is part of MPC-HC.
*
* MPC-HC is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* MPC-HC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
#include <d3dx9shader.h>
class CPixelShaderCompiler
{
typedef HRESULT(WINAPI* D3DXCompileShaderPtr)(
LPCSTR pSrcData,
UINT SrcDataLen,
CONST D3DXMACRO* pDefines,
LPD3DXINCLUDE pInclude,
LPCSTR pFunctionName,
LPCSTR pProfile,
DWORD Flags,
LPD3DXBUFFER* ppShader,
LPD3DXBUFFER* ppErrorMsgs,
LPD3DXCONSTANTTABLE* ppConstantTable);
typedef HRESULT(WINAPI* D3DXDisassembleShaderPtr)(
CONST DWORD* pShader,
bool EnableColorCode,
LPCSTR pComments,
LPD3DXBUFFER* ppDisassembly);
D3DXCompileShaderPtr m_pD3DXCompileShader;
D3DXDisassembleShaderPtr m_pD3DXDisassembleShader;
CComPtr<IDirect3DDevice9> m_pD3DDev;
public:
CPixelShaderCompiler(IDirect3DDevice9* pD3DDev, bool fStaySilent = false);
virtual ~CPixelShaderCompiler();
HRESULT CompileShader(
LPCSTR pSrcData,
LPCSTR pFunctionName,
LPCSTR pProfile,
DWORD Flags,
IDirect3DPixelShader9** ppPixelShader,
CString* disasm = nullptr,
CString* errmsg = nullptr);
};
| Java |
<!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://www.npmjs.org/doc/cli/npm-rm.html">
<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>
| Java |
#!/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
| Java |
--
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local _detalhes = _G._detalhes
local Loc = LibStub ("AceLocale-3.0"):GetLocale ( "Details" )
local _
_detalhes.network = {}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> local pointers
local _UnitName = UnitName
local _GetRealmName = GetRealmName
local _select = select
local _table_wipe = table.wipe
local _math_min = math.min
local _string_gmatch = string.gmatch
local _pairs = pairs
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> constants
DETAILS_PREFIX_NETWORK = "DTLS"
local CONST_HIGHFIVE_REQUEST = "HI"
local CONST_HIGHFIVE_DATA = "HF"
local CONST_VERSION_CHECK = "CV"
local CONST_ITEMLEVEL_DATA = "IL"
local CONST_WIPE_CALL = "WI"
local CONST_GUILD_SYNC = "GS"
local CONST_CLOUD_REQUEST = "CR"
local CONST_CLOUD_FOUND = "CF"
local CONST_CLOUD_DATARQ = "CD"
local CONST_CLOUD_DATARC = "CE"
local CONST_CLOUD_EQUALIZE = "EQ"
local CONST_CLOUD_SHAREDATA = "SD"
local CONST_PVP_ENEMY = "PP"
local CONST_ROGUE_SR = "SR" --soul rip from akaari's soul (LEGION ONLY)
DETAILS_PREFIX_COACH = "CO" --coach feature
DETAILS_PREFIX_TBC_DATA = "BC" --tbc data
_detalhes.network.ids = {
["HIGHFIVE_REQUEST"] = CONST_HIGHFIVE_REQUEST,
["HIGHFIVE_DATA"] = CONST_HIGHFIVE_DATA,
["VERSION_CHECK"] = CONST_VERSION_CHECK,
["ITEMLEVEL_DATA"] = CONST_ITEMLEVEL_DATA,
["CLOUD_REQUEST"] = CONST_CLOUD_REQUEST,
["CLOUD_FOUND"] = CONST_CLOUD_FOUND,
["CLOUD_DATARQ"] = CONST_CLOUD_DATARQ,
["CLOUD_DATARC"] = CONST_CLOUD_DATARC,
["CLOUD_EQUALIZE"] = CONST_CLOUD_EQUALIZE,
["WIPE_CALL"] = CONST_WIPE_CALL,
["GUILD_SYNC"] = CONST_GUILD_SYNC,
["PVP_ENEMY"] = CONST_PVP_ENEMY,
["MISSDATA_ROGUE_SOULRIP"] = CONST_ROGUE_SR, --soul rip from akaari's soul (LEGION ONLY)
["CLOUD_SHAREDATA"] = CONST_CLOUD_SHAREDATA,
["COACH_FEATURE"] = DETAILS_PREFIX_COACH, --ask the raid leader is the coach is enbaled
["TBC_DATA"] = DETAILS_PREFIX_TBC_DATA, --get basic information about the player
}
local plugins_registred = {}
local temp = {}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> comm functions
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> item level
function _detalhes:SendCharacterData()
--> only send if in group
if (not IsInGroup() and not IsInRaid()) then
return
end
if (DetailsFramework.IsTimewalkWoW()) then
if (DetailsFramework.IsTBCWow()) then
--detect my spec
end
return
end
--> check the player level
local playerLevel = UnitLevel ("player")
if (not playerLevel) then
return
elseif (playerLevel < 60) then
return
end
--> delay to sent information again
if (_detalhes.LastPlayerInfoSync and _detalhes.LastPlayerInfoSync+10 > GetTime()) then
--do not send info if recently sent
return
end
--> get player item level
local overall, equipped = GetAverageItemLevel()
--> get player talents
local talents = {}
for i = 1, 7 do
for o = 1, 3 do
local talentID, name, texture, selected, available = GetTalentInfo (i, o, 1)
if (selected) then
tinsert (talents, talentID)
break
end
end
end
--> get the spec ID
local spec = DetailsFramework.GetSpecialization()
local currentSpec
if (spec) then
local specID = DetailsFramework.GetSpecializationInfo (spec)
if (specID and specID ~= 0) then
currentSpec = specID
end
end
--> get the character serial number
local serial = UnitGUID ("player")
if (IsInRaid()) then
_detalhes:SendRaidData (CONST_ITEMLEVEL_DATA, serial, equipped, talents, currentSpec)
if (_detalhes.debug) then
_detalhes:Msg ("(debug) sent ilevel data to Raid")
end
elseif (IsInGroup()) then
_detalhes:SendPartyData (CONST_ITEMLEVEL_DATA, serial, equipped, talents, currentSpec)
if (_detalhes.debug) then
_detalhes:Msg ("(debug) sent ilevel data to Party")
end
end
_detalhes.LastPlayerInfoSync = GetTime()
end
function _detalhes.network.ItemLevel_Received (player, realm, core_version, serial, itemlevel, talents, spec)
_detalhes:IlvlFromNetwork (player, realm, core_version, serial, itemlevel, talents, spec)
end
--high five
function _detalhes.network.HighFive_Request()
return _detalhes:SendRaidData (CONST_HIGHFIVE_DATA, _detalhes.userversion)
end
function _detalhes.network.HighFive_DataReceived (player, realm, core_version, user_version)
if (_detalhes.sent_highfive and _detalhes.sent_highfive + 30 > GetTime()) then
_detalhes.users [#_detalhes.users+1] = {player, realm, (user_version or "") .. " (" .. core_version .. ")"}
end
end
function _detalhes.network.Update_VersionReceived (player, realm, core_version, build_number)
if (_detalhes.debug) then
_detalhes:Msg ("(debug) received version alert ", build_number)
end
if (_detalhes.streamer_config.no_alerts) then
return
end
build_number = tonumber (build_number)
if (not _detalhes.build_counter or not _detalhes.lastUpdateWarning or not build_number) then
return
end
if (build_number > _detalhes.build_counter) then
if (time() > _detalhes.lastUpdateWarning + 72000) then
local lower_instance = _detalhes:GetLowerInstanceNumber()
if (lower_instance) then
lower_instance = _detalhes:GetInstance (lower_instance)
if (lower_instance) then
lower_instance:InstanceAlert ("Update Available!", {[[Interface\GossipFrame\AvailableQuestIcon]], 16, 16, false}, _detalhes.update_warning_timeout, {_detalhes.OpenUpdateWindow})
end
end
_detalhes:Msg (Loc ["STRING_VERSION_AVAILABLE"])
_detalhes.lastUpdateWarning = time()
end
end
end
function _detalhes.network.Cloud_Request (player, realm, core_version, ...)
--deprecated | need to remove
if (true) then return end
if (_detalhes.debug) then
_detalhes:Msg ("(debug)", player, _detalhes.host_of, _detalhes:CaptureIsAllEnabled(), core_version == _detalhes.realversion)
end
if (player ~= _detalhes.playername) then
if (not _detalhes.host_of and _detalhes:CaptureIsAllEnabled() and core_version == _detalhes.realversion) then
if (realm ~= _GetRealmName()) then
player = player .."-"..realm
end
_detalhes.host_of = player
if (_detalhes.debug) then
_detalhes:Msg ("(debug) sent 'okey' answer for a cloud parser request.")
end
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (_detalhes.network.ids.CLOUD_FOUND, _UnitName ("player"), _GetRealmName(), _detalhes.realversion), "WHISPER", player)
end
end
end
function _detalhes.network.Cloud_Found (player, realm, core_version, ...)
--deprecated | need to remove
if (true) then return end
if (_detalhes.host_by) then
return
end
if (realm ~= _GetRealmName()) then
player = player .."-"..realm
end
_detalhes.host_by = player
if (_detalhes.debug) then
_detalhes:Msg ("(debug) cloud found for disabled captures.")
end
_detalhes.cloud_process = _detalhes:ScheduleRepeatingTimer ("RequestCloudData", 10)
_detalhes.last_data_requested = _detalhes._tempo
end
function _detalhes.network.Cloud_DataRequest (player, realm, core_version, ...)
--deprecated | need to remove
if (true) then return end
if (not _detalhes.host_of) then
return
end
local atributo, subatributo = player, realm
local data
local atributo_name = _detalhes:GetInternalSubAttributeName (atributo, subatributo)
if (atributo == 1) then
data = _detalhes.atributo_damage:RefreshWindow ({}, _detalhes.tabela_vigente, nil, { key = atributo_name, modo = _detalhes.modos.group })
elseif (atributo == 2) then
data = _detalhes.atributo_heal:RefreshWindow ({}, _detalhes.tabela_vigente, nil, { key = atributo_name, modo = _detalhes.modos.group })
elseif (atributo == 3) then
data = _detalhes.atributo_energy:RefreshWindow ({}, _detalhes.tabela_vigente, nil, { key = atributo_name, modo = _detalhes.modos.group })
elseif (atributo == 4) then
data = _detalhes.atributo_misc:RefreshWindow ({}, _detalhes.tabela_vigente, nil, { key = atributo_name, modo = _detalhes.modos.group })
else
return
end
if (data) then
local export = temp
local container = _detalhes.tabela_vigente [atributo]._ActorTable
for i = 1, _math_min (6, #container) do
local actor = container [i]
if (actor.grupo) then
export [#export+1] = {actor.nome, actor [atributo_name]}
end
end
if (_detalhes.debug) then
_detalhes:Msg ("(debug) requesting data from the cloud.")
end
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (CONST_CLOUD_DATARC, atributo, atributo_name, export), "WHISPER", _detalhes.host_of)
_table_wipe (temp)
end
end
function _detalhes.network.Cloud_DataReceived (player, realm, core_version, ...)
--deprecated | need to remove
if (true) then return end
local atributo, atributo_name, data = player, realm, core_version
local container = _detalhes.tabela_vigente [atributo]
if (_detalhes.debug) then
_detalhes:Msg ("(debug) received data from the cloud.")
end
for i = 1, #data do
local _this = data [i]
local name = _this [1]
local actor = container:PegarCombatente (nil, name)
if (not actor) then
if (IsInRaid()) then
for i = 1, GetNumGroupMembers() do
if (name:find ("-")) then --> other realm
local nname, server = _UnitName ("raid"..i)
if (server and server ~= "") then
nname = nname.."-"..server
end
if (nname == name) then
actor = container:PegarCombatente (UnitGUID ("raid"..i), name, 0x514, true)
break
end
else
if (_UnitName ("raid"..i) == name) then
actor = container:PegarCombatente (UnitGUID ("raid"..i), name, 0x514, true)
break
end
end
end
elseif (IsInGroup()) then
for i = 1, GetNumGroupMembers()-1 do
if (name:find ("-")) then --> other realm
local nname, server = _UnitName ("party"..i)
if (server and server ~= "") then
nname = nname.."-"..server
end
if (nname == name) then
actor = container:PegarCombatente (UnitGUID ("party"..i), name, 0x514, true)
break
end
else
if (_UnitName ("party"..i) == name or _detalhes.playername == name) then
actor = container:PegarCombatente (UnitGUID ("party"..i), name, 0x514, true)
break
end
end
end
end
end
if (actor) then
actor [atributo_name] = _this [2]
container.need_refresh = true
else
if (_detalhes.debug) then
_detalhes:Msg ("(debug) actor not found on cloud data received", name, atributo_name)
end
end
end
end
function _detalhes.network.Cloud_Equalize (player, realm, core_version, data)
--deprecated | need to remove
if (true) then return end
if (not _detalhes.in_combat) then
if (core_version ~= _detalhes.realversion) then
return
end
_detalhes:MakeEqualizeOnActor (player, realm, data)
end
end
function _detalhes.network.Wipe_Call (player, realm, core_version, ...)
local chr_name = Ambiguate(player, "none")
if (UnitIsGroupLeader (chr_name)) then
if (UnitIsInMyGuild (chr_name)) then
_detalhes:CallWipe()
end
end
end
--received an entire segment data from a user that is sharing with the 'player'
function _detalhes.network.Cloud_SharedData (player, realm, core_version, data)
if (core_version ~= _detalhes.realversion) then
if (core_version > _detalhes.realversion) then
--_detalhes:Msg ("your Details! is out dated and cannot perform the action, please update it.")
end
return false
end
end
function _detalhes.network.TBCData(player, realm, coreVersion, data)
if (not IsInRaid() and not IsInGroup()) then
return
end
local LibDeflate = _G.LibStub:GetLibrary("LibDeflate")
local dataCompressed = LibDeflate:DecodeForWoWAddonChannel(data)
local dataSerialized = LibDeflate:DecompressDeflate(dataCompressed)
local dataTable = {Details:Deserialize(dataSerialized)}
tremove(dataTable, 1)
local dataTable = dataTable[1]
local playerRole = dataTable[1]
local spec = dataTable[2]
local itemLevel = dataTable[3]
local talents = dataTable[4]
local guid = dataTable[5]
--[=[
print("Details! Received TBC Comm Data:")
print("From:", player)
print("spec:", spec)
print("role:", playerRole)
print("item level:", itemLevel)
print("guid:", guid)
--]=]
_detalhes.cached_talents[guid] = talents
if (spec and spec ~= 0) then
_detalhes.cached_specs[guid] = spec
end
_detalhes.cached_roles[guid] = playerRole
_detalhes.item_level_pool[guid] = {
name = player,
ilvl = itemLevel,
time = time()
}
end
--"CIEA" Coach Is Enabled Ask (client > server)
--"CIER" Coach Is Enabled Response (server > client)
--"CCS" Coach Combat Start (client > server)
function _detalhes.network.Coach(player, realm, core_version, msgType, data)
if (not IsInRaid()) then
return
end
if (_detalhes.debug) then
print("Details Coach Received Comm", player, realm, core_version, msgType, data)
end
local sourcePlayer = Ambiguate(player, "none")
local playerName = UnitName("player")
if (playerName == sourcePlayer) then
if (_detalhes.debug) then
print("Details Coach Received Comm | RETURN | playerName == sourcePlayer", playerName , sourcePlayer)
end
return
end
if (msgType == "CIEA") then --Is Coach Enabled Ask (regular player asked to raid leader)
Details.Coach.Server.CoachIsEnabled_Answer(sourcePlayer)
elseif (msgType == "CIER") then --Coach Is Enabled Response (regular player received a raid leader response)
local isEnabled = data
Details.Coach.Client.CoachIsEnabled_Response(isEnabled, sourcePlayer)
elseif (msgType == "CCS") then --Coach Combat Start (raid assistant told the raid leader a combat started)
Details.Coach.Server.CombatStarted()
elseif (msgType == "CCE") then --Coach Combat End (raid assistant told the raid leader a combat ended)
Details.Coach.Server.CombatEnded()
elseif (msgType == "CS") then --Coach Start (raid leader notifying other members of the group)
if (_detalhes.debug) then
print("Details Coach received 'CE' a new coach is active, coach name:", sourcePlayer)
end
Details.Coach.Client.EnableCoach(sourcePlayer)
elseif (msgType == "CE") then --Coach End (raid leader notifying other members of the group)
Details.Coach.Client.CoachEnd()
elseif (msgType == "CDT") then --Coach Data (a player in the raid sent to raid leader combat data)
if (Details.Coach.Server.IsEnabled()) then
--update the current combat with new information
Details.packFunctions.DeployPackedCombatData(data)
end
elseif (msgType == "CDD") then --Coach Death (a player in the raid sent to raid leader his death log)
if (Details.Coach.Server.IsEnabled()) then
Details.Coach.Server.AddPlayerDeath(sourcePlayer, data)
end
end
end
--guild sync R = someone pressed the sync button
--guild sync L = list of fights IDs
--guild sync G = requested a list of encounters
--guild sync A = received missing encounters, add them
function _detalhes.network.GuildSync (player, realm, core_version, type, data)
local chr_name = Ambiguate(player, "none")
if (UnitName ("player") == chr_name) then
return
end
if (core_version ~= _detalhes.realversion) then
if (core_version > _detalhes.realversion) then
--_detalhes:Msg ("your Details! is out dated and cannot perform the action, please update it.")
end
return false
end
if (type == "R") then --RoS - somebody requested IDs of stored encounters
_detalhes.LastGuildSyncDataTime1 = _detalhes.LastGuildSyncDataTime1 or 0
--build our table and send to the player
if (_detalhes.LastGuildSyncDataTime1 > GetTime()) then
--return false
end
local IDs = _detalhes.storage:GetIDsToGuildSync()
if (IDs and IDs [1]) then
local from = UnitName ("player")
local realm = GetRealmName()
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (CONST_GUILD_SYNC, from, realm, _detalhes.realversion, "L", IDs), "WHISPER", chr_name)
end
_detalhes.LastGuildSyncDataTime1 = GetTime() + 60
return true
elseif (type == "L") then --RoC - the player received the IDs list and send back which IDs he doesn't have
local MissingIDs = _detalhes.storage:CheckMissingIDsToGuildSync (data)
if (MissingIDs and MissingIDs [1]) then
local from = UnitName ("player")
local realm = GetRealmName()
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (CONST_GUILD_SYNC, from, realm, _detalhes.realversion, "G", MissingIDs), "WHISPER", chr_name)
end
return true
elseif (type == "G") then --RoS - the 'server' send the encounter dps table to the player which requested
local EncounterData = _detalhes.storage:BuildEncounterDataToGuildSync (data)
if (EncounterData and EncounterData [1]) then
local task = C_Timer.NewTicker (4, function (task)
task.TickID = task.TickID + 1
local data = task.EncounterData [task.TickID]
if (not data) then
task:Cancel()
return
end
local from = UnitName ("player")
local realm = GetRealmName()
--todo: need to check if the target is still online
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (CONST_GUILD_SYNC, from, realm, _detalhes.realversion, "A", data), "WHISPER", task.Target)
if (_detalhes.debug) then
_detalhes:Msg ("(debug) [RoS-EncounterSync] send-task sending data #" .. task.TickID .. ".")
end
end)
task.TickID = 0
task.EncounterData = EncounterData
task.Target = chr_name
end
return true
elseif (type == "A") then --RoC - the player received the dps table and should now add it to the db
_detalhes.storage:AddGuildSyncData (data, player)
return true
end
end
function _detalhes.network.HandleMissData (player, realm, core_version, data)
-- [1] - container
-- [2] - spellid
-- [3] - spell total
-- [4] - spell counter
core_version = tonumber (core_version) or 0
if (core_version ~= _detalhes.realversion) then
if (core_version > _detalhes.realversion) then
_detalhes:Msg ("your Details! is out dated and cannot communicate with other players.")
end
return
end
if (type (player) ~= "string") then
return
end
local playerName = _detalhes:GetCLName (player)
if (playerName) then
_detalhes.HandleMissData (playerName, data)
end
end
function _detalhes.network.ReceivedEnemyPlayer (player, realm, core_version, data)
-- ["PVP_ENEMY"] = CONST_PVP_ENEMY,
end
_detalhes.network.functions = {
[CONST_HIGHFIVE_REQUEST] = _detalhes.network.HighFive_Request,
[CONST_HIGHFIVE_DATA] = _detalhes.network.HighFive_DataReceived,
[CONST_VERSION_CHECK] = _detalhes.network.Update_VersionReceived,
[CONST_ITEMLEVEL_DATA] = _detalhes.network.ItemLevel_Received,
[CONST_CLOUD_REQUEST] = _detalhes.network.Cloud_Request,
[CONST_CLOUD_FOUND] = _detalhes.network.Cloud_Found,
[CONST_CLOUD_DATARQ] = _detalhes.network.Cloud_DataRequest,
[CONST_CLOUD_DATARC] = _detalhes.network.Cloud_DataReceived,
[CONST_CLOUD_EQUALIZE] = _detalhes.network.Cloud_Equalize,
[CONST_WIPE_CALL] = _detalhes.network.Wipe_Call,
[CONST_GUILD_SYNC] = _detalhes.network.GuildSync,
[CONST_ROGUE_SR] = _detalhes.network.HandleMissData, --soul rip from akaari's soul (LEGION ONLY)
[CONST_PVP_ENEMY] = _detalhes.network.ReceivedEnemyPlayer,
[DETAILS_PREFIX_COACH] = _detalhes.network.Coach, --coach feature
[DETAILS_PREFIX_TBC_DATA] = _detalhes.network.TBCData
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> register comm
function _detalhes:CommReceived (commPrefix, data, channel, source)
local prefix, player, realm, dversion, arg6, arg7, arg8, arg9 = _select (2, _detalhes:Deserialize (data))
player = source
if (_detalhes.debug) then
_detalhes:Msg ("(debug) network received:", prefix, "length:", string.len (data))
end
--event
_detalhes:SendEvent ("COMM_EVENT_RECEIVED", nil, string.len (data), prefix, player, realm, dversion, arg6, arg7, arg8, arg9)
--print ("comm received", prefix, _detalhes.network.functions [prefix])
local func = _detalhes.network.functions [prefix]
if (func) then
--todo: this call should be safe
func (player, realm, dversion, arg6, arg7, arg8, arg9)
else
func = plugins_registred [prefix]
--print ("plugin comm?", func, player, realm, dversion, arg6, arg7, arg8, arg9)
if (func) then
--todo: this call should be safe
func (player, realm, dversion, arg6, arg7, arg8, arg9)
else
if (_detalhes.debug) then
_detalhes:Msg ("comm prefix not found:", prefix)
end
end
end
end
_detalhes:RegisterComm ("DTLS", "CommReceived")
--> hook the send comm message so we can trigger events when sending data
--> this adds overhead, but easily catches all outgoing comm messages
hooksecurefunc (Details, "SendCommMessage", function (context, addonPrefix, serializedData, channel)
--unpack data
local prefix, player, realm, dversion, arg6, arg7, arg8, arg9 = _select (2, _detalhes:Deserialize (serializedData))
--send the event
_detalhes:SendEvent ("COMM_EVENT_SENT", nil, string.len (serializedData), prefix, player, realm, dversion, arg6, arg7, arg8, arg9)
end)
function _detalhes:RegisterPluginComm (prefix, func)
assert (type (prefix) == "string" and string.len (prefix) >= 2 and string.len (prefix) <= 4, "RegisterPluginComm expects a string with 2-4 characters on #1 argument.")
assert (type (func) == "function" or (type (func) == "string" and type (self [func]) == "function"), "RegisterPluginComm expects a function or function name on #2 argument.")
assert (plugins_registred [prefix] == nil, "Prefix " .. prefix .. " already in use 1.")
assert (_detalhes.network.functions [prefix] == nil, "Prefix " .. prefix .. " already in use 2.")
if (type (func) == "string") then
plugins_registred [prefix] = self [func]
else
plugins_registred [prefix] = func
end
return true
end
function _detalhes:UnregisterPluginComm (prefix)
plugins_registred [prefix] = nil
return true
end
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> send functions
function _detalhes:GetChannelId (channel)
for id = 1, GetNumDisplayChannels() do
local name, _, _, room_id = GetChannelDisplayInfo (id)
if (name == channel) then
return room_id
end
end
end
--[
function _detalhes.parser_functions:CHAT_MSG_CHANNEL (...)
local message, _, _, _, _, _, _, _, channelName = ...
if (channelName == "Details") then
local prefix, data = strsplit ("_", message, 2)
local func = plugins_registred [prefix]
if (func) then
func (_select (2, _detalhes:Deserialize (data)))
else
if (_detalhes.debug) then
_detalhes:Msg ("comm prefix not found:", prefix)
end
end
end
end
--]]
function _detalhes:SendPluginCommMessage(prefix, channel, ...)
if (channel == "RAID") then
if (IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and IsInInstance()) then
_detalhes:SendCommMessage (prefix, _detalhes:Serialize (self.__version, ...), "INSTANCE_CHAT")
else
_detalhes:SendCommMessage (prefix, _detalhes:Serialize (self.__version, ...), "RAID")
end
elseif (channel == "PARTY") then
if (IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and IsInInstance()) then
_detalhes:SendCommMessage(prefix, _detalhes:Serialize (self.__version, ...), "INSTANCE_CHAT")
else
_detalhes:SendCommMessage(prefix, _detalhes:Serialize (self.__version, ...), "PARTY")
end
else
_detalhes:SendCommMessage(prefix, _detalhes:Serialize (self.__version, ...), channel)
end
return true
end
--> send as
function _detalhes:SendRaidDataAs(type, player, realm, ...)
if (not realm) then
--> check if realm is already inside player name
for _name, _realm in _string_gmatch(player, "(%w+)-(%w+)") do
if (_realm) then
player = _name
realm = _realm
end
end
end
if (not realm) then
--> doesn't have realm at all, so we assume the actor is in same realm as player
realm = _GetRealmName()
end
_detalhes:SendCommMessage(DETAILS_PREFIX_NETWORK, _detalhes:Serialize (type, player, realm, _detalhes.realversion, ...), "RAID")
end
function _detalhes:SendHomeRaidData(type, ...)
if (IsInRaid(LE_PARTY_CATEGORY_HOME) and IsInInstance()) then
_detalhes:SendCommMessage(DETAILS_PREFIX_NETWORK, _detalhes:Serialize (type, _UnitName("player"), _GetRealmName(), _detalhes.realversion, ...), "RAID")
end
end
function _detalhes:SendRaidData (type, ...)
local isInInstanceGroup = IsInRaid (LE_PARTY_CATEGORY_INSTANCE)
if (isInInstanceGroup) then
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (type, _UnitName("player"), _GetRealmName(), _detalhes.realversion, ...), "INSTANCE_CHAT")
if (_detalhes.debug) then
_detalhes:Msg ("(debug) sent comm to INSTANCE raid group")
end
else
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (type, _UnitName("player"), _GetRealmName(), _detalhes.realversion, ...), "RAID")
if (_detalhes.debug) then
_detalhes:Msg ("(debug) sent comm to LOCAL raid group")
end
end
end
function _detalhes:SendPartyData (type, ...)
local isInInstanceGroup = IsInGroup (LE_PARTY_CATEGORY_INSTANCE)
if (isInInstanceGroup) then
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (type, _UnitName ("player"), _GetRealmName(), _detalhes.realversion, ...), "INSTANCE_CHAT")
if (_detalhes.debug) then
_detalhes:Msg ("(debug) sent comm to INSTANCE party group")
end
else
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (type, _UnitName ("player"), _GetRealmName(), _detalhes.realversion, ...), "PARTY")
if (_detalhes.debug) then
_detalhes:Msg ("(debug) sent comm to LOCAL party group")
end
end
end
function _detalhes:SendRaidOrPartyData (type, ...)
if (IsInRaid()) then
_detalhes:SendRaidData (type, ...)
elseif (IsInGroup()) then
_detalhes:SendPartyData (type, ...)
end
end
function _detalhes:SendGuildData (type, ...)
if not IsInGuild() then return end --> fix from Tim@WoWInterface
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (type, _UnitName ("player"), _GetRealmName(), _detalhes.realversion, ...), "GUILD")
end
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> cloud
function _detalhes:SendCloudRequest()
_detalhes:SendRaidData (_detalhes.network.ids.CLOUD_REQUEST)
end
function _detalhes:ScheduleSendCloudRequest()
_detalhes:ScheduleTimer ("SendCloudRequest", 1)
end
function _detalhes:RequestCloudData()
_detalhes.last_data_requested = _detalhes._tempo
if (not _detalhes.host_by) then
return
end
for index = 1, #_detalhes.tabela_instancias do
local instancia = _detalhes.tabela_instancias [index]
if (instancia.ativa) then
local atributo = instancia.atributo
if (atributo == 1 and not _detalhes:CaptureGet ("damage")) then
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (CONST_CLOUD_DATARQ, atributo, instancia.sub_atributo), "WHISPER", _detalhes.host_by)
break
elseif (atributo == 2 and (not _detalhes:CaptureGet ("heal") or _detalhes:CaptureGet ("aura"))) then
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (CONST_CLOUD_DATARQ, atributo, instancia.sub_atributo), "WHISPER", _detalhes.host_by)
break
elseif (atributo == 3 and not _detalhes:CaptureGet ("energy")) then
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (CONST_CLOUD_DATARQ, atributo, instancia.sub_atributo), "WHISPER", _detalhes.host_by)
break
elseif (atributo == 4 and not _detalhes:CaptureGet ("miscdata")) then
_detalhes:SendCommMessage (DETAILS_PREFIX_NETWORK, _detalhes:Serialize (CONST_CLOUD_DATARQ, atributo, instancia.sub_atributo), "WHISPER", _detalhes.host_by)
break
end
end
end
end
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--> update
function _detalhes:CheckVersion (send_to_guild)
if (IsInRaid()) then
_detalhes:SendRaidData (_detalhes.network.ids.VERSION_CHECK, _detalhes.build_counter)
elseif (IsInGroup()) then
_detalhes:SendPartyData (_detalhes.network.ids.VERSION_CHECK, _detalhes.build_counter)
end
if (send_to_guild) then
_detalhes:SendGuildData (_detalhes.network.ids.VERSION_CHECK, _detalhes.build_counter)
end
end
| Java |
# htspan
## Dependencies
* gcc >= 4.8
* gsl >= 2.4.1
### Included dependencies
* htslib >= 1.8
* mlat >= 0.1
## Install
```{bash}
make
```
| Java |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Andrew Kofink <ajkofink@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: subscription_manifest
version_added: 1.0.0
short_description: Manage Subscription Manifests
description:
- Upload, refresh and delete Subscription Manifests
author: "Andrew Kofink (@akofink)"
options:
manifest_path:
description:
- Path to the manifest zip file
- This parameter will be ignored if I(state=absent) or I(state=refreshed)
type: path
state:
description:
- The state of the manifest
default: present
choices:
- absent
- present
- refreshed
type: str
repository_url:
description:
- URL to retrieve content from
aliases: [ redhat_repository_url ]
type: str
extends_documentation_fragment:
- theforeman.foreman.foreman
- theforeman.foreman.foreman.organization
'''
EXAMPLES = '''
- name: "Upload the RHEL developer edition manifest"
theforeman.foreman.subscription_manifest:
username: "admin"
password: "changeme"
server_url: "https://foreman.example.com"
organization: "Default Organization"
state: present
manifest_path: "/tmp/manifest.zip"
'''
RETURN = ''' # '''
from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule
def main():
module = KatelloEntityAnsibleModule(
argument_spec=dict(
manifest_path=dict(type='path'),
state=dict(default='present', choices=['absent', 'present', 'refreshed']),
repository_url=dict(aliases=['redhat_repository_url']),
),
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 = {'redhat_repository_url': module.foreman_params['repository_url']}
org_spec = dict(id=dict(), redhat_repository_url=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()
| Java |
#!/usr/bin/env bash
# Copyright © 2019 by The qTox Project Contributors
#
# This file is part of qTox, a Qt-based graphical interface for Tox.
# qTox is libre software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qTox is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qTox. If not, see <http://www.gnu.org/licenses/>
# 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
# before reporting issues like “qTox doesn't compile”.
#
# 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
################ parameters ################
# 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 ############
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 . -DCMAKE_INSTALL_PREFIX=${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() {
########## parse input parameters ##########
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
############### prepare step ###############
# 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 step ###############
install_toxcore
install_sqlcipher
############### cleanup step ###############
# remove cloned repositories
if [[ $KEEP_BUILD_FILES = "false" ]]
then
remove_build_dirs
fi
}
main $@
| Java |
[(#REM)
Affiche la liste des auteurs d'un objet, séparés par des virgules
Modele pour la balise #LESAUTEURS, dans le cas des auteurs d'un objet
(pour un objet ayant un champ lesauteurs dans la base, la balise affiche directement la valeur du champ)
]
<BOUCLE_auteurs(AUTEURS){id_objet}{objet}{par nom}{", "}>
<span class="author"><a class="url fn spip_in" href="#URL_AUTEUR">#NOM</a></span></BOUCLE_auteurs>
| Java |
import moment from 'moment';
import PublicationsController from './controller/publications.controller.js';
import AuthorsController from './controller/authors.controller.js';
import PublishersController from './controller/publishers.controller.js';
/*
* Application routing
*/
function routing($routeProvider) {
$routeProvider
.when('/publications', {
template: require('./view/publications.html'),
controller: PublicationsController,
controllerAs: 'vm'
})
.when('/authors', {
template: require('./view/authors.html'),
controller: AuthorsController,
controllerAs: 'vm'
})
.when('/publishers', {
template: require('./view/publishers.html'),
controller: PublishersController,
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($mdDateLocaleProvider) {
const dateFmt = 'YYYY-MM-DD';
$mdDateLocaleProvider.formatDate = (date) => {
return moment(date).format(dateFmt);
};
$mdDateLocaleProvider.parseDate = (str) => {
const m = moment(str, dateFmt);
return m.isValid() ? m.toDate() : new Date(NaN);
};
}
dateLocalization.$inject = ['$mdDateLocaleProvider'];
export { routing, theming, dateLocalization };
| Java |
#include "disablenonworkingunits.h"
#include "wololo/datPatch.h"
namespace wololo {
void disableNonWorkingUnitsPatch(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 disableNonWorkingUnits = {
&disableNonWorkingUnitsPatch,
"Hide units in the scenario editor"
};
}
| Java |
<!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);
border-bottom-left-radius:1vw;
border-bottom-right-radius: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;
border-bottom-left-radius:1.2vw;
border-bottom-right-radius: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://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyDxGzBuvFA2qrOZZPBdTmIjsXAgWpcrmcs",
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://us-central1-crblackjack-9e220.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.FacebookAuthProvider();
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>
| Java |
import styled from "./Theme";
export const Content = styled.div`
margin: 2rem 0;
padding: 5px;
`;
| Java |
<?php
namespace Chamilo\Core\Repository\Selector;
/**
* A category of options in a ContentObjectTypeSelector
*
* @author Hans De Bisschop <hans.de.bisschop@ehb.be>
*/
class TypeSelectorCategory
{
/**
*
* @var string
*/
private $type;
/**
*
* @var string
*/
private $name;
/**
*
* @var \core\repository\ContentObjectTypeSelectorOption[]
*/
private $options;
/**
*
* @param string $type
* @param string $name
* @param \core\repository\ContentObjectTypeSelectorOption[] $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\ContentObjectTypeSelectorOption[]
*/
public function set_options($options)
{
$this->options = $options;
}
/**
*
* @param \core\repository\ContentObjectTypeSelectorOption $option
*/
public function add_option($option)
{
$this->options[] = $option;
}
/**
* Sort the ContentObjectTypeSelectorOption 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 get_unique_content_object_template_ids()
{
$types = array();
foreach ($this->get_options() as $option)
{
if (! in_array($option->get_template_registration_id(), $types))
{
$types[] = $option->get_template_registration_id();
}
}
return $types;
}
} | Java |
# coding: utf-8
# Copyright (C) 2017 Open Path View, Maison Du Libre
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
# 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]),
('fetcher_next_indexes', List[int]),
('break_reason', str),
('number_of_incomplete_sets', int),
('number_of_complete_sets', int),
('max_consecutive_incomplete_sets', int)
]
)
| Java |
<?php
/**
* @version $Id: search.class.php v1.0 $
* @package PBDigg
* @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
* @license PBDigg is free software and use is subject to license terms
*/
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);;
}
}
}
?> | Java |
using System;
namespace ForumSystem.Data.Models.BaseEntities
{
public interface IDeletableEntity
{
bool IsDeleted { get; set; }
DateTime? DeletedOn { get; set; }
}
}
| Java |
#ifndef HANOI_TOWER_SOLVER_H
#define HANOI_TOWER_SOLVER_H
#include <list>
#include <map>
#include "goap/iplanner.h"
#include "goap/istate.h"
#include "goap/iscopetimer.h"
#include "goap/ifunctionstatemeter.h"
#include "goap/iplanningstatecomparer.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() {
IPlanningStateComparer::Ptr comparer = NewPtr<IPlanningStateComparer>(EXACTSTATEMETER_SINGLETON);
if (!_planningStateMeter || *_planningStateMeter->goalState() != *_goalState) {
auto functionStateMeter = Goap::newFunctionStateMeter(_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-- == 1) {
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 // HANOI_TOWER_SOLVER_H
| Java |
<?php
/**
* Nombre del archivo: RegionSicaController.php
* Descripción:Contiene las funciones del controlador
* Fecha de creación:18/11/2017
* Creado por: Juan Carlos Centeno Borja
*/
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\region_sica;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class RegionSicaController 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)
{
//
}
}
| Java |
/*
* Copyright (C) 2013 Huub de Beer
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
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:
//
// (∀m: 0 ≤ m ≤ |`moments`|: `moment_computed`(`moments`[m]))
//
// 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:
//
// `t2m`(`T_START`) ≤ `now` ≤ `t2m`(`T_END`) → `moment_computed`(`now`)
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
//
// (∀m: 0 ≤ m < |`moments`|: `val`(m) <= `val`(m+1))
//
// Therefore,
//
// (∃m, n: 0 ≤ m < n ≤ |`moments`|:
// `val`(m) ≤ value ≤ `val`(n) ⋀
// (∀p: m < p < n: `val`(p) = value))
//
// `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;
//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);
}
// q.minimum ≤ value ≤ 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;
| Java |
/////////////////////////////////////////////////////////////////////////////
// C# Version Copyright (c) 2003 CenterSpace Software, LLC //
// //
// This code is free software under the Artistic license. //
// //
// CenterSpace Software //
// 2098 NW Myrtlewood Way //
// Corvallis, Oregon, 97330 //
// USA //
// http://www.centerspace.net //
/////////////////////////////////////////////////////////////////////////////
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Any feedback is very welcome.
http://www.math.keio.ac.jp/matumoto/emt.html
email: matumoto@math.keio.ac.jp
*/
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
{
#region Constants -------------------------------------------------------
// 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
#region Instance Variables ----------------------------------------------
// 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
#region Constructors ----------------------------------------------------
/// <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
#region Properties ------------------------------------------------------
/// <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
#region Member Functions ------------------------------------------------
/// <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 );
}
#region Methods ported from C -------------------------------------------
// 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[].
// 2002/01/09 modified by Makoto Matsumoto
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
}
}
| Java |
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 !fileExistsAndNotExpired(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("Content-Security-Policy", Config.fileContentSecurityPolicy)
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 fileExistsAndNotExpired(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
}
| Java |
/******************************************************************************
*******************************************************************************
*******************************************************************************
libferris
Copyright (C) 2001 Ben Martin
libferris is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
libferris is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with libferris. If not, see <http://www.gnu.org/licenses/>.
For more details see the COPYING file in the root directory of this
distribution.
$Id: libferrispostgresqlshared.cpp,v 1.2 2006/12/07 06:49:42 ben Exp $
*******************************************************************************
*******************************************************************************
******************************************************************************/
#include "config.h"
#include "libferrisgoogle_shared.hh"
#include <Ferris/Configuration_private.hh>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QBuffer>
#include <Ferris/FerrisQt_private.hh>
#include <Ferris/FerrisKDE.hh>
#include <Ferris/FerrisDOM.hh>
#include <Ferris/FerrisBoost.hh>
#include <Ferris/Iterator.hh>
#include <Ferris/FerrisKDE.hh>
#include <qjson/parser.h>
#define DEBUG LG_GOOGLE_D
namespace Ferris
{
using namespace XML;
using namespace std;
static const string DBNAME = FDB_SECURE;
string prettyprintxml( const std::string& s )
{
try
{
fh_domdoc dom = Factory::StringToDOM( s );
fh_stringstream ss = tostream( dom );
return ss.str();
}
catch( exception& e )
{
return s;
}
}
FERRISEXP_EXPORT userpass_t getGoogleUserPass(
const std::string& server )
{
string user;
string pass;
string Key = ""; // server;
{
stringstream ss;
ss << "google" << Key << "-username";
user = getConfigString( DBNAME, tostr(ss), "" );
}
{
stringstream ss;
ss << "google" << Key << "-password";
pass = getConfigString( DBNAME, tostr(ss), "" );
}
return make_pair( user, pass );
}
FERRISEXP_EXPORT void setGoogleUserPass(
const std::string& server,
const std::string& user, const std::string& pass )
{
string Key = ""; // server;
{
stringstream ss;
ss << "google" << Key << "-username";
setConfigString( DBNAME, tostr(ss), user );
}
{
stringstream ss;
ss << "google" << Key << "-password";
setConfigString( DBNAME, tostr(ss), pass );
}
}
FERRISEXP_EXPORT std::string
columnNumberToName( int col )
{
stringstream ss;
int aval = 'a';
--aval;
ss << (char)(aval + col);
string v = ss.str();
return v;
}
/********************************************************************************/
/********************************************************************************/
/********************************************************************************/
// GoogleClientResponseWaiter::GoogleClientResponseWaiter()
// {
// m_loop = g_main_loop_new( 0, 0 );
// }
// void
// GoogleClientResponseWaiter::block()
// {
// LG_GOOGLE_D << "GoogleClientResponseWaiter::block(top)" << endl;
// g_main_loop_run( m_loop );
// LG_GOOGLE_D << "GoogleClientResponseWaiter::block(done)" << endl;
// }
// void
// GoogleClientResponseWaiter::unblock()
// {
// g_main_loop_quit( m_loop );
// }
/********************************************************************************/
/********************************************************************************/
/********************************************************************************/
GoogleClient::GoogleClient()
:
m_qmanager( 0 )
{
}
QNetworkAccessManager*
GoogleClient::getQManager()
{
return ::Ferris::getQManager();
// return new QNetworkAccessManager(0);
// if( !m_qmanager )
// {
// m_qmanager = new QNetworkAccessManager(0);
// }
// return m_qmanager;
}
void
GoogleClient::addAuth( QNetworkRequest& r, const std::string& service )
{
if( m_authTokens[ service ].empty() )
Authenticate_ClientLogin( service );
DEBUG << "Auth token service:" << service << " token:" << m_authTokens[service] << endl;
r.setRawHeader("Authorization", m_authTokens[service].c_str() );
}
void
GoogleClient::dumpReplyToConsole(QNetworkReply* reply )
{
m_waiter.unblock( reply );
cerr << "GoogleClient::dumpReplyToConsole()" << endl;
cerr << "error:" << reply->error() << endl;
cerr << "earl:" << tostr(reply->url().toString()) << endl;
QByteArray ba = reply->readAll();
cerr << "ba.sz:" << ba.size() << endl;
cerr << "ba:" << (string)ba << endl;
cerr << "-------------" << endl;
}
void
GoogleClient::dumpReplyToConsole()
{
QNetworkReply* reply = (QNetworkReply*)sender();
m_waiter.unblock( reply );
cerr << "GoogleClient::dumpReplyToConsole()" << endl;
cerr << "error:" << reply->error() << endl;
cerr << "earl:" << tostr(reply->url().toString()) << endl;
QByteArray ba = reply->readAll();
cerr << "ba.sz:" << ba.size() << endl;
cerr << "ba:" << (string)ba << endl;
cerr << "-------------" << endl;
}
std::string responseToAuthToken( const std::string& data )
{
string ret;
stringstream ss;
ss << data;
string s;
while( getline(ss,s) )
{
// LG_GOOGLE_D << "s:" << s << endl;
if( starts_with( s, "Auth=" ))
{
ret = "GoogleLogin " + s;
ret = Util::replace_all( ret, "Auth=", "auth=" );
}
}
return ret;
}
void
GoogleClient::replyFinished(QNetworkReply* reply )
{
m_waiter.unblock( reply );
LG_GOOGLE_D << "-------------" << endl;
LG_GOOGLE_D << "GoogleClient::replyFinished(3)" << endl;
// m_authToken = responseToAuthToken( (string)reply->readAll() );
// stringstream ss;
// ss << reply->readAll().data();
// string s;
// while( getline(ss,s) )
// {
// // LG_GOOGLE_D << "s:" << s << endl;
// if( starts_with( s, "Auth=" ))
// {
// m_authToken = "GoogleLogin " + s;
// }
// }
// listSheets();
}
void
GoogleClient::handleFinished()
{
QNetworkReply* r = dynamic_cast<QNetworkReply*>(sender());
m_waiter.unblock(r);
LG_GOOGLE_D << "GoogleClient::handleFinished()" << endl;
}
void
GoogleClient::handleFinished( QNetworkReply* r )
{
m_waiter.unblock(r);
LG_GOOGLE_D << "GoogleClient::handleFinished(QNR)" << endl;
}
void
GoogleClient::localtest()
{
QNetworkAccessManager* qm = getQManager();
QNetworkRequest request;
request.setUrl(QUrl("http://alkid"));
request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
cerr << "getting reply..." << endl;
connect( qm, SIGNAL(finished(QNetworkReply*)), SLOT(dumpReplyToConsole(QNetworkReply*)));
QNetworkReply *reply = qm->get(request);
QUrl postdata("https://www.google.com/accounts/ClientLogin");
postdata.addQueryItem("accountType", "HOSTED_OR_GOOGLE");
// connect( reply, SIGNAL( finished() ), SLOT( dumpReplyToConsole() ) );
m_waiter.block(reply);
}
void
GoogleClient::Authenticate_ClientLogin( const std::string& service )
{
userpass_t up = getGoogleUserPass();
std::string username = up.first;
std::string password = up.second;
QNetworkAccessManager* qm = getQManager();
QNetworkRequest request;
QUrl postdata("https://www.google.com/accounts/ClientLogin");
postdata.addQueryItem("accountType", "HOSTED_OR_GOOGLE");
postdata.addQueryItem("Email", username.c_str() );
postdata.addQueryItem("Passwd", password.c_str() );
postdata.addQueryItem("service", service.c_str() );
postdata.addQueryItem("source", "libferris" FERRIS_VERSION);
request.setUrl(postdata);
connect( qm, SIGNAL(finished(QNetworkReply*)), SLOT(handleFinished(QNetworkReply*)));
LG_GOOGLE_D << "postdata.toEncoded():" << tostr(QString(postdata.toEncoded())) << endl;
LG_GOOGLE_D << "getting reply...2" << endl;
QByteArray empty;
QNetworkReply *reply = qm->post( request, empty );
m_waiter.block(reply);
string token = responseToAuthToken( (string)reply->readAll() );
LG_GOOGLE_D << "service:" << service << " token:" << token << endl;
m_authTokens[service] = token;
}
QNetworkReply*
GoogleClient::get( QNetworkRequest req )
{
QNetworkAccessManager* qm = getQManager();
QNetworkReply* reply = qm->get( req );
connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) );
m_waiter.block(reply);
return reply;
}
QNetworkReply*
GoogleClient::put( QNetworkRequest req, QByteArray& ba )
{
QNetworkAccessManager* qm = getQManager();
QNetworkReply* reply = qm->put( req, ba );
connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) );
m_waiter.block(reply);
return reply;
}
QNetworkReply*
GoogleClient::put( QNetworkRequest req, const std::string& data )
{
QByteArray ba( data.data(), data.size() );
return put( req, ba );
}
QNetworkReply*
GoogleClient::post( QNetworkRequest req, const std::string& data )
{
QNetworkAccessManager* qm = getQManager();
QNetworkReply* reply = qm->post( req, data.c_str() );
connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) );
m_waiter.block(reply);
return reply;
}
QNetworkRequest
GoogleClient::createRequest( QUrl& u, const std::string& service, const std::string& gversion )
{
QNetworkRequest req;
addAuth( req, service );
if( !gversion.empty() )
req.setRawHeader("GData-Version", gversion.c_str() );
req.setUrl(u);
return req;
}
std::string
GoogleClient::getYoutubeDevKey()
{
return getStrSubCtx( "~/.ferris/youtube-dev-key.txt", "" );
}
FERRISEXP_API std::list< DOMElement* >
getAllChildrenElementsWithAttribute( DOMNode* node,
const std::string& name,
const std::string& attr,
const std::string& value,
bool recurse = true );
FERRISEXP_API DOMElement*
getFirstChildElementsWithAttribute( DOMNode* node,
const std::string& name,
const std::string& attrname,
const std::string& value,
bool recurse = true );
FERRISEXP_API std::list< DOMElement* >
getAllChildrenElementsWithAttribute( DOMNode* node,
const std::string& name,
const std::string& attrname,
const std::string& value,
bool recurse )
{
typedef std::list< DOMElement* > LIST;
LIST l = getAllChildrenElements( node,
name,
recurse );
LIST ret;
for( LIST::iterator li = l.begin(); li != l.end(); ++li )
{
DOMElement* e = *li;
std::string s = getAttribute( e, attrname );
// cerr << "value:" << value << " s:" << s << endl;
if( s == value )
{
// cerr << "match!" << endl;
ret.push_back( e );
}
}
// cerr << "ret.sz:" << ret.size() << endl;
return ret;
}
FERRISEXP_API DOMElement*
getFirstChildElementsWithAttribute( DOMNode* node,
const std::string& name,
const std::string& attrname,
const std::string& value,
bool recurse )
{
DOMElement* ret = 0;
std::list< DOMElement* > l = getAllChildrenElementsWithAttribute( node, name, attrname, value, recurse );
if( !l.empty() )
ret = l.front();
return ret;
}
std::string getMatchingAttribute( DOMNode* node,
const std::string& name,
const std::string& attrname,
const std::string& value,
const std::string& desiredAttribute )
{
DOMElement* e = getFirstChildElementsWithAttribute( node, name, attrname, value );
if( e )
{
return getAttribute( e, desiredAttribute );
}
return "";
}
typedef std::list< DOMElement* > entries_t;
GoogleSpreadSheets_t
GoogleClient::listSheets()
{
LG_GOOGLE_D << "running listSheets...." << endl;
QUrl u("http://spreadsheets.google.com/feeds/spreadsheets/private/full");
QNetworkRequest request = createRequest( u );
QNetworkReply *reply = get( request );
LG_GOOGLE_D << "after running listSheets...." << endl;
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "spreadsheets error:" << reply->error() << endl;
LG_GOOGLE_D << "spreadsheets reply:" << (string)ba << endl;
fh_domdoc dom = Factory::StringToDOM( (string)ba );
entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false );
GoogleSpreadSheets_t ret;
for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei )
{
fh_GoogleSpreadSheet t = new GoogleSpreadSheet( this, dom, *ei );
ret.push_back(t);
}
return ret;
}
fh_GoogleDocumentFolder
GoogleClient::getRootFolder()
{
DEBUG << "GoogleClient::getRootFolder...." << endl;
fh_GoogleDocumentFolder ret = new GoogleDocumentFolder( this, "" );
return ret;
}
GoogleDocuments_t
GoogleClient::listDocuments()
{
LG_GOOGLE_D << "running listDocuments...." << endl;
QUrl u("http://docs.google.com/feeds/documents/private/full");
QNetworkRequest request = createRequest( u, "writely" );
request.setRawHeader("GData-Version", " 2.0");
QNetworkReply *reply = get( request );
LG_GOOGLE_D << "after running listDocuments...." << endl;
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "docs error:" << reply->error() << endl;
LG_GOOGLE_D << "docs reply:" << (string)ba << endl;
fh_domdoc dom = Factory::StringToDOM( (string)ba );
m_documentsETag = getAttribute( dom->getDocumentElement(), "gd:etag" );
entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false );
if( LG_GOOGLE_D_ACTIVE )
{
fh_stringstream ss = tostream( dom );
LG_GOOGLE_D << "Documents:" << ss.str() << endl;
LG_GOOGLE_D << "m_documentsETag:" << m_documentsETag << endl;
}
GoogleDocuments_t ret;
for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei )
{
fh_GoogleDocument t = new GoogleDocument( this, dom, *ei );
ret.push_back(t);
}
//
// Have to get all the folder names to get the top level ones :(
// GET /feeds/documents/private/full/-/folder?showfolders=true
//
{
request.setUrl( QUrl( "http://docs.google.com/feeds/documents/private/full/-/folder?showfolders=true" ));
QNetworkReply *reply = get( request );
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "docs folders error:" << reply->error() << endl;
LG_GOOGLE_D << "docs folders reply:" << (string)ba << endl;
fh_domdoc dom = Factory::StringToDOM( (string)ba );
entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false );
for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei )
{
fh_GoogleDocument t = new GoogleDocument( this, dom, *ei );
ret.push_back(t);
}
}
// // GET /feeds/documents/private/full/-/folder?showfolders=true
// {
// QUrl u("http://docs.google.com/feeds/documents/private/full/-/folder?showfolders=true");
// QNetworkRequest request = createRequest( u, "writely" );
// request.setRawHeader("GData-Version", " 2.0");
// QNetworkReply *reply = get( request );
// LG_GOOGLE_D << "after running listDocuments...." << endl;
// QByteArray ba = reply->readAll();
// LG_GOOGLE_D << "docs error:" << reply->error() << endl;
// fh_domdoc dom = Factory::StringToDOM( (string)ba );
// fh_stringstream ss = tostream( dom );
// LG_GOOGLE_D << "Folders:" << ss.str() << endl;
// }
// GET http://docs.google.com/feeds/folders/private/full/folder%3Afolder_id
{
LG_GOOGLE_D << "------------------------------------------------------------------------" << endl;
// QUrl u("http://docs.google.com/feeds/folders/private/full/folder%3A1d90eb20-cad4-4bf3-b4d7-0ff8ddf3448d");
QUrl u("http://docs.google.com/feeds/folders/private/full/folder%3Abe4824a5-8b8f-4129-9b33-5c5f3c1cdb57?showfolders=true");
QNetworkRequest request = createRequest( u, "writely" );
request.setRawHeader("GData-Version", " 2.0");
QNetworkReply* reply = get( request );
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "x error:" << reply->error() << endl;
LG_GOOGLE_D << "x reply:" << (string)ba << endl;
fh_domdoc dom = Factory::StringToDOM( (string)ba );
fh_stringstream ss = tostream( dom );
LG_GOOGLE_D << "DATA:" << ss.str() << endl;
}
return ret;
}
fh_YoutubeUpload
GoogleClient::createYoutubeUpload()
{
return new YoutubeUpload( this );
}
/****************************************/
/****************************************/
/****************************************/
// This is for the root directory...
GoogleDocumentFolder::GoogleDocumentFolder( fh_GoogleClient gc, const std::string& folderID )
:
m_gc( gc ),
m_haveRead( false ),
m_folderID( folderID )
{
}
GoogleDocumentFolder::GoogleDocumentFolder( fh_GoogleClient gc, fh_domdoc dom, DOMElement* e )
:
m_gc( gc ),
m_haveRead( false )
{
m_title = getStrSubCtx( e, "title" );
m_editURL = getMatchingAttribute( e, "link",
"rel", "edit",
"href" );
m_folderID = getStrSubCtx( e, "id" );
m_folderID = m_folderID.substr( m_folderID.length() - strlen("fac1125b-6dc7-4e79-8ef2-7dc1c8b4c9b8"));
// m_folderID = Util::replace_all( m_folderID,
// "http://docs.google.com/feeds/documents/private/full/folder%3A",
// "" );
}
// <category label="spreadsheet" scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/docs/2007#spreadsheet"/>
void
GoogleDocumentFolder::addItem( fh_domdoc dom, DOMElement* e )
{
string kind = getMatchingAttribute( e, "category",
"scheme", "http://schemas.google.com/g/2005#kind",
"label" );
DEBUG << "kind:" << kind << endl;
if( kind == "folder" )
{
fh_GoogleDocumentFolder f = new GoogleDocumentFolder( m_gc, dom, e );
m_folders.push_back(f);
}
else
{
fh_GoogleDocument d = new GoogleDocument( m_gc, dom, e );
m_docs.push_back(d);
}
}
void
GoogleDocumentFolder::read( bool force )
{
DEBUG << "read() title:" << m_title << " folderID:" << m_folderID << endl;
GoogleDocumentFolders_t ret;
if( m_haveRead )
return;
m_haveRead = true;
//
// Have to get all the folder names to get the top level ones :(
// GET /feeds/documents/private/full/-/folder?showfolders=true
//
if( m_folderID.empty() )
{
QUrl u("http://docs.google.com/feeds/documents/private/full?showfolders=true");
QNetworkRequest request = m_gc->createRequest( u, "writely" );
request.setRawHeader("GData-Version", " 2.0");
QNetworkReply *reply = m_gc->get( request );
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "docs folders error:" << reply->error() << endl;
LG_GOOGLE_D << "docs folders reply:" << (string)ba << endl;
if( reply->error() == 0 )
{
fh_domdoc dom = Factory::StringToDOM( (string)ba );
entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false );
for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei )
{
DOMElement* e = *ei;
string p = getMatchingAttribute( e, "link",
"rel", "http://schemas.google.com/docs/2007#parent",
"href" );
if( p.empty() )
{
addItem( dom, *ei );
}
}
if( LG_GOOGLE_D_ACTIVE )
{
fh_stringstream ss = tostream( dom );
LG_GOOGLE_D << "TOP FOLDER....:" << ss.str() << endl;
}
}
}
else
{
stringstream uss;
uss << "http://docs.google.com/feeds/folders/private/full/folder%3A" << m_folderID << "?showfolders=true";
QUrl u(uss.str().c_str());
QNetworkRequest request = m_gc->createRequest( u, "writely" );
request.setRawHeader("GData-Version", " 2.0");
QNetworkReply* reply = m_gc->get( request );
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "x error:" << reply->error() << endl;
LG_GOOGLE_D << "x reply:" << (string)ba << endl;
if( reply->error() == 0 )
{
fh_domdoc dom = Factory::StringToDOM( (string)ba );
fh_stringstream ss = tostream( dom );
LG_GOOGLE_D << "DATA:" << ss.str() << endl;
entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false );
for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei )
{
addItem( dom, *ei );
}
}
}
}
GoogleDocumentFolders_t
GoogleDocumentFolder::getSubFolders()
{
read();
return m_folders;
}
GoogleDocuments_t
GoogleDocumentFolder::getDocuments()
{
read();
return m_docs;
}
std::string
GoogleDocumentFolder::getEditURL()
{
return m_editURL;
}
std::string
GoogleDocumentFolder::getTitle()
{
return m_title;
}
fh_GoogleDocument
GoogleDocumentFolder::createDocument( const std::string& data,
const std::string& slug,
const std::string& format )
{
fh_GoogleDocument ret = new GoogleDocument( m_gc, data, slug, format );
return ret;
}
/****************************************/
/****************************************/
/****************************************/
GoogleDocument::GoogleDocument( fh_GoogleClient gc, fh_domdoc dom, DOMElement* e )
:
m_gc( gc ),
m_haveRead( false )
{
m_title = getStrSubCtx( e, "title" );
m_editURL = getMatchingAttribute( e, "link",
"rel", "edit",
"href" );
m_docID = getStrSubCtx( e, "gd:resourceId" );
m_docID = Util::replace_all( m_docID, "document:", "" );
}
GoogleDocument::GoogleDocument( fh_GoogleClient gc,
const std::string& data,
const std::string& slug,
const std::string& format )
:
m_gc(gc),
m_haveRead( false )
{
QNetworkRequest request = prepareCreateOrReplace( data, slug, format, true );
QNetworkReply* reply = m_gc->post( request, data.c_str() );
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "create doc error code:" << reply->error() << endl;
LG_GOOGLE_D << "create doc reply:" << (string)ba << endl;
}
std::string
GoogleDocument::getEditURL()
{
return m_editURL;
}
std::string
GoogleDocument::getTitle()
{
return m_title;
}
fh_istream
GoogleDocument::exportToFormat( const std::string& format )
{
DEBUG << "exportToFormat() m_docID:" << m_docID << endl;
QUrl u( "http://docs.google.com/feeds/download/documents/Export" );
u.addQueryItem("docID", m_docID.c_str() );
u.addQueryItem("exportFormat", format.c_str() );
LG_GOOGLE_D << "export args:" << tostr(QString(u.toEncoded())) << endl;
QNetworkRequest request = m_gc->createRequest( u, "writely", "" );
QNetworkReply *reply = m_gc->get( request );
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "export error:" << reply->error() << endl;
LG_GOOGLE_D << "export reply:" << (string)ba << endl;
fh_stringstream ret;
ret.write( ba.data(), ba.size() );
ret->clear();
ret->seekg(0, ios::beg);
ret->seekp(0, ios::beg);
ret->clear();
return ret;
}
string filenameToContentType( const std::string& slug_const,
const std::string& format,
const std::string& data = "" )
{
string slug = tolowerstr()( slug_const );
// 299, update reply:Content-Type application/vnd.oasis.opendocument.spreadsheet is not a valid input type.
string ret = "text/plain";
if( format == "xx" || ends_with( slug, "xx" ) )
ret = "application/vnd.ms-excel";
else if( format == "xls" || ends_with( slug, "xls" ) )
ret = "application/vnd.ms-excel";
else if( format == "doc" || ends_with( slug, "doc" ) )
ret = "application/msword";
else if( format == "odt" || ends_with( slug, "odt" ) )
ret = "application/vnd.oasis.opendocument.text";
else if( format == "ods" || ends_with( slug, "ods" ) )
ret = "application/vnd.oasis.opendocument.spreadsheet";
else if( ends_with( slug, "png" ) )
ret = "image/png";
else if( ends_with( slug, "pdf" ) )
ret = "application/pdf";
else
{
string mt = regex_match_single( data, ".*mimetypeapplication/([^P]+)PK.*" );
if( !mt.empty() )
ret = "application/" + mt;
}
return ret;
}
QNetworkRequest
GoogleDocument::prepareCreateOrReplace( const std::string& data,
const std::string& slug,
const std::string& format,
bool create )
{
string ctype = filenameToContentType( slug, format, data );
stringstream uss;
if( create )
uss << "http://docs.google.com/feeds/documents/private/full";
else
{
if( contains( m_docID, "spreadshee" ))
uss << "http://docs.google.com/feeds/media/private/full/" << m_docID;
else
uss << "http://docs.google.com/feeds/media/private/full/document:" << m_docID;
}
QUrl u( uss.str().c_str() );
QNetworkRequest request = m_gc->createRequest( u, "writely", "" );
request.setHeader( QNetworkRequest::ContentTypeHeader, ctype.c_str() );
request.setHeader( QNetworkRequest::ContentLengthHeader, tostr(data.length()).c_str() );
request.setRawHeader("Content-Type", ctype.c_str() );
// request.setRawHeader("Content-Length", tostr(data.length()).c_str() );
request.setRawHeader("Slug", slug.c_str() );
if( !create )
request.setRawHeader("If-Match", "*" );
DEBUG << "import url:" << tostr(QString(u.toEncoded())) << endl;
DEBUG << "slug:" << slug << endl;
DEBUG << "ctype:" << ctype << endl;
DEBUG << "format:" << format << endl;
return request;
}
void
GoogleDocument::importFromFormat( fh_istream iss, const std::string& format )
{
DEBUG << "importFromFormat() m_title:" << m_title << endl;
string data = StreamToString(iss);
QNetworkRequest request = prepareCreateOrReplace( data, m_title, format, false );
DEBUG << "importFromFormat() Calling put..." << endl;
QNetworkReply* reply = m_gc->put( request, data );
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "update error code:" << reply->error() << endl;
LG_GOOGLE_D << "update reply:" << (string)ba << endl;
}
/****************************************/
/****************************************/
/****************************************/
GoogleSpreadSheet::GoogleSpreadSheet( fh_GoogleClient gc, fh_domdoc dom, DOMElement* e )
:
m_gc( gc ),
m_haveRead( false )
{
m_title = getStrSubCtx( e, "title" );
m_feedURL = getMatchingAttribute( e, "content",
"type", "application/atom+xml;type=feed",
"src" );
// non versioned data header
// m_feedURL = getMatchingAttribute( e, "link",
// "rel", "http://schemas.google.com/spreadsheets/2006#worksheetsfeed",
// "href" );
}
std::string
GoogleSpreadSheet::getFeedURL()
{
return m_feedURL;
}
std::string
GoogleSpreadSheet::getTitle()
{
return m_title;
}
GoogleWorkSheets_t
GoogleSpreadSheet::listSheets()
{
LG_GOOGLE_D << "running list WORK Sheets...." << endl;
if( m_haveRead )
return m_sheets;
QUrl u( getFeedURL().c_str() );
QNetworkRequest request = m_gc->createRequest( u );
QNetworkReply* reply = m_gc->get( request );
LG_GOOGLE_D << "after running list WORK Sheets...." << endl;
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "worksheets error:" << reply->error() << endl;
LG_GOOGLE_D << "worksheets reply:" << (string)ba << endl;
fh_domdoc dom = Factory::StringToDOM( (string)ba );
entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false );
for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei )
{
fh_GoogleWorkSheet t = new GoogleWorkSheet( m_gc, dom, *ei );
m_sheets.push_back(t);
}
return m_sheets;
}
// void
// GoogleSpreadSheet::addDocsAPIAuth_reply(QNetworkReply* reply )
// {
// m_gc->m_waiter.unblock(reply);
// }
// void
// GoogleSpreadSheet::addDocsAPIAuth( QNetworkRequest& r )
// {
// if( m_docsAPIAuth.empty() )
// {
// QNetworkAccessManager* qm = m_gc->getQManager();
// QNetworkRequest request;
// userpass_t up = getGoogleUserPass();
// string username = up.first;
// string password = up.second;
// QUrl postdata("https://www.google.com/accounts/ClientLogin");
// postdata.addQueryItem("accountType", "HOSTED_OR_GOOGLE");
// postdata.addQueryItem("Email", username.c_str() );
// postdata.addQueryItem("Passwd", password.c_str() );
// postdata.addQueryItem("service", "writely");
// postdata.addQueryItem("source", "libferris" FERRIS_VERSION);
// request.setUrl(postdata);
// connect( qm, SIGNAL(finished(QNetworkReply*)), SLOT(addDocsAPIAuth_reply(QNetworkReply*)));
// LG_GOOGLE_D << "GoogleSpreadSheet::addDocsAPIAuth():" << tostr(QString(postdata.toEncoded())) << endl;
// LG_GOOGLE_D << "getting reply...2" << endl;
// QByteArray empty;
// QNetworkReply *reply = qm->post( request, empty );
// LG_GOOGLE_D << "calling block()" << endl;
// m_gc->m_waiter.block(reply);
// LG_GOOGLE_D << "after block()" << endl;
// m_docsAPIAuth = responseToAuthToken( (string)reply->readAll() );
// LG_GOOGLE_D << "m_docsAPIAuth:" << m_docsAPIAuth << endl;
// }
// r.setRawHeader("Authorization", m_docsAPIAuth.c_str() );
// }
string
GoogleSpreadSheet::getDocIDFromTitle( const std::string& title )
{
// cerr << "FIXME GoogleSpreadSheet::getDocIDFromTitle() " << endl;
// return "tz96EupEQKYKTbu3m0GpqTw";
// QUrl u( "http://docs.google.com/feeds/documents/private/full/-/spreadsheet" );
// QNetworkRequest request = m_gc->createRequest( u );
// request.setRawHeader("GData-Version", " 2.0");
QUrl u("http://docs.google.com/feeds/documents/private/full");
QNetworkRequest request;
// m_gc->addAuth( request, "wise" );
m_gc->addAuth( request, "writely" );
request.setRawHeader("GData-Version", " 2.0");
request.setUrl(u);
LG_GOOGLE_D << "about to issue google docs request..." << endl;
QNetworkReply *reply = m_gc->get( request );
LG_GOOGLE_D << "done with google docs request..." << endl;
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "getDocIDFromTitle error:" << reply->error() << endl;
LG_GOOGLE_D << "getDocIDFromTitle reply:" << (string)ba << endl;
string ret;
fh_domdoc dom = Factory::StringToDOM( (string)ba );
string etag = getAttribute( dom->getDocumentElement(), "gd:etag" );
entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false );
for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei )
{
DOMElement* e = *ei;
string t = getStrSubCtx( e, "title" );
if( t == title )
{
ret = getStrSubCtx( e, "id" );
break;
}
}
LG_GOOGLE_D << "docid ret:" << ret << endl;
return ret;
}
fh_GoogleDocument
GoogleSpreadSheet::getDocument()
{
// getDocIDFromTitle
// ( fh_GoogleClient gc, fh_domdoc dom, DOMElement* e );
stringstream uss;
uss << "http://docs.google.com/feeds/documents/private/full?"
<< "title-exact=true&title=" << getTitle();
QUrl u( uss.str().c_str() );
DEBUG << "GoogleSpreadSheet::getDocument() earl:" << uss.str() << endl;
QNetworkRequest request = m_gc->createRequest( u, "writely" );
request.setRawHeader("GData-Version", " 2.0");
QNetworkReply *reply = m_gc->get( request );
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "docs error:" << reply->error() << endl;
LG_GOOGLE_D << "docs reply:" << (string)ba << endl;
fh_domdoc dom = Factory::StringToDOM( (string)ba );
entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false );
if( LG_GOOGLE_D_ACTIVE )
{
fh_stringstream ss = tostream( dom );
LG_GOOGLE_D << "Documents:" << ss.str() << endl;
}
for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei )
{
fh_GoogleDocument t = new GoogleDocument( m_gc, dom, *ei );
return t;
}
return 0;
}
void
GoogleSpreadSheet::importFromFormat( fh_istream iss, const std::string& format )
{
LG_GOOGLE_D << "GoogleSpreadSheet::importFromFormat() format:" << format << endl;
string docid = getDocIDFromTitle( m_title );
LG_GOOGLE_D << "getDocIDFromTitle() title:" << m_title << " docid:" << docid << endl;
fh_GoogleDocument doc = getDocument();
doc->importFromFormat( iss, format );
}
fh_istream
GoogleSpreadSheet::exportToFormat( const std::string& format )
{
LG_GOOGLE_D << "GoogleSpreadSheet::exportToFormat() format:" << format << endl;
string docid = getDocIDFromTitle( m_title );
LG_GOOGLE_D << "getDocIDFromTitle() title:" << m_title << " docid:" << docid << endl;
QUrl u( "http://spreadsheets.google.com/feeds/download/spreadsheets/Export" );
u.addQueryItem("key", docid.c_str() );
u.addQueryItem("exportFormat", format.c_str() );
LG_GOOGLE_D << "exportToFormat, args:" << tostr(QString(u.toEncoded())) << endl;
QNetworkRequest request = m_gc->createRequest( u );
QNetworkReply *reply = m_gc->get( request );
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "exportToFormat error:" << reply->error() << endl;
if( !reply->error() )
LG_GOOGLE_D << "exportToFormat reply.len:" << ba.size() << endl;
else
LG_GOOGLE_D << "exportToFormat reply:" << (string)ba << endl;
{
QVariant qv = reply->header( QNetworkRequest::ContentTypeHeader );
DEBUG << "Got ctype:" << tostr(qv.toString()) << endl;
// application/vnd.oasis.opendocument.spreadsheet; charset=UTF-8
}
fh_stringstream ret;
ret.write( ba.data(), ba.size() );
return ret;
}
fh_GoogleWorkSheet
GoogleSpreadSheet::createWorkSheet( const std::string& name )
{
LG_GOOGLE_D << "createWorkSheet() top" << endl;
stringstream ss;
ss << "<entry xmlns=\"http://www.w3.org/2005/Atom\"" << endl
<< " xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\">" << endl
<< " <title>" << name << "</title>" << endl
<< " <gs:rowCount>100</gs:rowCount>" << endl
<< " <gs:colCount>100</gs:colCount>" << endl
<< "</entry>" << endl;
QUrl u( getFeedURL().c_str() );
QNetworkRequest request = m_gc->createRequest( u );
request.setHeader( QNetworkRequest::ContentTypeHeader, "application/atom+xml" );
QNetworkReply *reply = m_gc->post( request, ss.str() );
QByteArray ba = reply->readAll();
LG_GOOGLE_D << "createWorkSheet() reply:" << (string)ba << endl;
fh_domdoc dom = Factory::StringToDOM( (string)ba );
DOMElement* e = dom->getDocumentElement();
fh_GoogleWorkSheet t = new GoogleWorkSheet( m_gc, dom, e );
m_sheets.push_back(t);
return t;
}
/****************************************/
/****************************************/
/****************************************/
GoogleWorkSheet::GoogleWorkSheet( fh_GoogleClient gc, fh_domdoc dom, DOMElement* e )
:
m_gc( gc ),
m_cellsFetched( false ),
m_delayCellSync( false )
{
m_etag = getAttribute( e, "gd:etag" );
m_title = getStrSubCtx( e, "title" );
m_cellFeedURL = getMatchingAttribute( e, "link",
"rel", "http://schemas.google.com/spreadsheets/2006#cellsfeed",
"href" );
m_editURL = getMatchingAttribute( e, "link",
"rel", "edit",
"href" );
if( LG_GOOGLE_D_ACTIVE )
{
fh_stringstream ss = tostream( *e );
LG_GOOGLE_D << "WorkSheet:" << ss.str() << endl;
}
}
std::string
GoogleWorkSheet::getCellFeedURL()
{
return m_cellFeedURL;
}
std::string
GoogleWorkSheet::getTitle()
{
return m_title;
}
void
GoogleWorkSheet::fetchCells()
{
QUrl u( getCellFeedURL().c_str() );
QNetworkRequest request = m_gc->createRequest( u );
// If-None-Match: W/"D08FQn8-eil7ImA9WxZbFEw."
if( !m_cellFeedETag.empty() )
request.setRawHeader("If-None-Match", m_cellFeedETag.c_str() );
QNetworkReply* reply = m_gc->get( request );
QByteArray ba = reply->readAll();
// cerr << "CELL DATA:" << (string)ba << endl;
fh_domdoc dom = Factory::StringToDOM( (string)ba );
m_cellFeedETag = getAttribute( dom->getDocumentElement(), "gd:etag" );
entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false );
int cellURLLength = getCellFeedURL().length();
int header_rownum = 1;
int max_headerrow_colnum = 0;
for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei )
{
DOMElement* e = *ei;
fh_GoogleWorkSheetCell cell = new GoogleWorkSheetCell( m_gc, dom, *ei, this, cellURLLength );
LG_GOOGLE_D << "have cell at row:" << cell->row() << " col:" << cell->col() << endl;
m_cells_t::iterator ci = m_cells.find( make_pair( cell->row(), cell->col() ));
if( ci != m_cells.end() )
{
fh_GoogleWorkSheetCell cell = ci->second;
cell->update( dom, e, cellURLLength );
}
else
{
m_cells[ make_pair( cell->row(), cell->col() ) ] = cell;
}
if( cell->row() == header_rownum )
{
max_headerrow_colnum = max( max_headerrow_colnum, cell->col() );
}
}
m_colnames.clear();
LG_GOOGLE_D << "max_headerrow_colnum:" << max_headerrow_colnum << endl;
for( int col=1; col <= max_headerrow_colnum; ++col )
{
m_cells_t::iterator ci = m_cells.find( make_pair( header_rownum, col ));
if( ci != m_cells.end() )
{
string v = ci->second->value();
m_colnames[ v ] = col;
}
string v = columnNumberToName( col );
m_colnames[ v ] = col;
LG_GOOGLE_D << " setting col:" << col << " to name:" << v << endl;
}
for( int col=1; col < 26; ++col )
{
string v = columnNumberToName( col );
m_colnames[ v ] = col;
}
m_cellsFetched = true;
}
std::list< std::string >
GoogleWorkSheet::getColumnNames()
{
ensureCellsFetched();
std::list< std::string > ret;
copy( map_domain_iterator( m_colnames.begin() ),
map_domain_iterator( m_colnames.end() ),
back_inserter( ret ) );
return ret;
}
void
GoogleWorkSheet::ensureCellsFetched()
{
if( !m_cellsFetched )
fetchCells();
}
fh_GoogleWorkSheetCell
GoogleWorkSheet::getCell( int row, int col )
{
ensureCellsFetched();
m_cells_t::iterator ci = m_cells.find( make_pair( row, col ));
if( ci == m_cells.end() )
{
LG_GOOGLE_D << "Creating new cell at row:" << row << " col:" << col << endl;
fh_GoogleWorkSheetCell cell = new GoogleWorkSheetCell( m_gc, this, row, col, "" );
m_cells[ make_pair( cell->row(), cell->col() ) ] = cell;
return cell;
}
return ci->second;
}
fh_GoogleWorkSheetCell
GoogleWorkSheet::getCell( int row, const std::string& colName )
{
ensureCellsFetched();
int c = m_colnames[ colName ];
LG_GOOGLE_D << "m_colnames.sz:" << m_colnames.size() << " colName:" << colName << " has number:" << c << endl;
for( m_colnames_t::iterator ci = m_colnames.begin(); ci != m_colnames.end(); ++ci )
{
LG_GOOGLE_D << "ci.first:" << ci->first << " sec:" << ci->second << endl;
}
return getCell( row, c );
}
int
GoogleWorkSheet::getLargestRowNumber()
{
ensureCellsFetched();
int ret = 0;
for( m_cells_t::iterator ci = m_cells.begin(); ci != m_cells.end(); ++ci )
{
fh_GoogleWorkSheetCell c = ci->second;
ret = max( ret, c->row() );
}
return ret;
}
bool
GoogleWorkSheet::getDelayCellSync()
{
return m_delayCellSync;
}
void
GoogleWorkSheet::setDelayCellSync( bool v )
{
m_delayCellSync = v;
}
void
GoogleWorkSheet::sync()
{
if( !getDelayCellSync() )
return;
string baseURL = getCellFeedURL();
string fullEditURL = baseURL + "/batch";
stringstream updatess;
updatess << "<feed xmlns=\"http://www.w3.org/2005/Atom\"" << endl
<< " xmlns:batch=\"http://schemas.google.com/gdata/batch\" " << endl
<< " xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\" " << endl
<< " >" << endl
<< endl
<< "<id>" << getCellFeedURL() << "</id> " << endl
<< endl;
for( m_cells_t::iterator ci = m_cells.begin(); ci != m_cells.end(); ++ci )
{
fh_GoogleWorkSheetCell c = ci->second;
// if( c->isCreated() )
// {
// c->sync();
// }
// else
{
c->writeUpdateBlock( updatess );
}
}
updatess << "</feed>" << endl;
QUrl u(fullEditURL.c_str());
QNetworkRequest request = m_gc->createRequest( u );
request.setHeader( QNetworkRequest::ContentTypeHeader, "application/atom+xml" );
if( !m_etag.empty() )
request.setRawHeader("If-Match", "*" );
QNetworkReply* reply = m_gc->post( request, updatess.str() );
cerr << "-------------" << endl;
cerr << "m_etag:" << m_etag << endl;
cerr << "m_cellFeedETag:" << m_cellFeedETag << endl;
cerr << "DST URL:" << fullEditURL << endl;
cerr << "SENT2" << endl;
cerr << updatess.str() << endl;
cerr << "error:" << reply->error() << endl;
QByteArray ba = reply->readAll();
cerr << "ba.sz:" << ba.size() << endl;
cerr << "ba:" << prettyprintxml( (string)ba ) << endl;
cerr << "-------------" << endl;
fh_domdoc dom = Factory::StringToDOM( (string)ba );
entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "atom:entry", false );
int cellURLLength = getCellFeedURL().length();
GoogleSpreadSheets_t ret;
for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei )
{
DOMElement* e = *ei;
cerr << "have entry..." << endl;
DOMElement* x = XML::getChildElement( e, "gs:cell" );
if( x )
{
cerr << "have entry/x..." << endl;
int row = toint( getAttribute( x, "row" ) );
int col = toint( getAttribute( x, "col" ) );
cerr << "row:" << row << " col:" << col << endl;
if( fh_GoogleWorkSheetCell cell = m_cells[ make_pair( row, col ) ] )
cell->update( dom, e, cellURLLength );
}
}
//
// now, update any formula cells
// this shouldn't need to be explicit with ETags and feeds
//
fetchCells();
// for( m_cells_t::iterator ci = m_cells.begin(); ci != m_cells.end(); ++ci )
// {
// fh_GoogleWorkSheetCell c = ci->second;
// if( c->isFormula() )
// {
// }
// }
}
/****************************************/
/****************************************/
/****************************************/
GoogleWorkSheetCell::GoogleWorkSheetCell( fh_GoogleClient gc,
fh_domdoc dom,
DOMElement* e,
fh_GoogleWorkSheet ws,
int cellURLLength )
:
m_gc( gc ),
m_ws( ws ),
m_dirty( false ),
m_created( false ),
m_etag("")
{
update( dom, e, cellURLLength );
// string editURL = getMatchingAttribute( e, "link",
// "rel", "edit",
// "href" );
// DOMElement* x = XML::getChildElement( e, "gs:cell" );
// m_value = getStrSubCtx( e, "gs:cell" );
// m_row = toint( getAttribute( x, "row" ) );
// m_col = toint( getAttribute( x, "col" ) );
// m_cellURL = editURL.substr( cellURLLength );
{
fh_stringstream ss = tostream( *e );
LG_GOOGLE_D << "CELL:" << ss.str() << endl;
}
}
void
GoogleWorkSheetCell::update( fh_domdoc dom, DOMElement* e, int cellURLLength )
{
string editURL = getMatchingAttribute( e, "link",
"rel", "edit",
"href" );
if( editURL.empty() )
editURL = getMatchingAttribute( e, "atom:link",
"rel", "edit",
"href" );
m_etag = getAttribute( e, "gd:etag" );
DOMElement* x = XML::getChildElement( e, "gs:cell" );
m_value = getStrSubCtx( e, "gs:cell" );
m_row = toint( getAttribute( x, "row" ) );
m_col = toint( getAttribute( x, "col" ) );
m_cellURL = editURL.substr( cellURLLength );
m_isFormula = starts_with( getAttribute( x, "inputValue" ), "=" );
LG_GOOGLE_D << "editURL:" << editURL << endl;
LG_GOOGLE_D << "etag:" << m_etag << endl;
LG_GOOGLE_D << "m_value:" << m_value << endl;
LG_GOOGLE_D << "m_isFormula:" << m_isFormula << endl;
}
GoogleWorkSheetCell::GoogleWorkSheetCell( fh_GoogleClient gc, fh_GoogleWorkSheet ws,
int r, int c, const std::string& v )
:
m_gc( gc ),
m_ws( ws ),
m_created( true ),
m_etag("")
{
m_row = r;
m_col = c;
m_value = v;
{
stringstream ss;
ss << "/R" << r << "C" << c;
m_cellURL = ss.str();
}
}
bool
GoogleWorkSheetCell::isCreated()
{
return m_created;
}
bool
GoogleWorkSheetCell::isFormula()
{
return m_isFormula;
}
int
GoogleWorkSheetCell::row()
{
return m_row;
}
int
GoogleWorkSheetCell::col()
{
return m_col;
}
std::string
GoogleWorkSheetCell::value()
{
LG_GOOGLE_D << "reading cell at row:" << m_row << " col:" << m_col << " result:" << m_value << endl;
return m_value;
}
void
GoogleWorkSheetCell::writeUpdateBlock( stringstream& ss )
{
if( !m_dirty )
return;
string fullEditURL = editURL();
if( m_created )
fullEditURL += "/latest";
cerr << "m_etag:" << m_etag << endl;
ss << "" << endl
<< "<entry "
// << " xmlns:gd=\"http://schemas.google.com/g/2005\" "
// << " gd:etag=\"" << Util::replace_all( m_etag, "\"", """ ) << "\" "
<< " >" << endl
<< " <batch:id>A" << toVoid(this) << "</batch:id> " << endl
<< " <batch:operation type=\"update\"/> " << endl
<< " <id>" << fullEditURL << "</id> " << endl
<< " <link rel=\"edit\" type=\"application/atom+xml\" " << endl
<< " href=\"" << fullEditURL << "\"/>" << endl
<< " <gs:cell row=\"" << row() << "\" col=\"" << col() << "\" inputValue=\"" << m_value << "\"/>" << endl
<< "</entry> " << endl
<< endl;
}
void
GoogleWorkSheetCell::sync()
{
string fullEditURL = editURL();
if( m_created )
fullEditURL += "/latest";
cerr << "SENDING VALUE:" << m_value << endl;
stringstream updatess;
updatess << "" << endl
<< "<entry xmlns=\"http://www.w3.org/2005/Atom\"" << endl
<< " xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\">" << endl
<< " <id>" << "http://spreadsheets.google.com/feeds/cells/key/worksheetId/private/full/cellId" << "</id>" << endl
<< " <link rel=\"edit\" type=\"application/atom+xml\"" << endl
<< " href=\"" << fullEditURL << "\"/>" << endl
<< " <gs:cell row=\"" << row() << "\" col=\"" << col() << "\" inputValue=\"" << m_value << "\" />" << endl
<< "</entry>" << endl
<<"" << endl;
QUrl u(fullEditURL.c_str());
QNetworkRequest request = m_gc->createRequest( u );
request.setHeader( QNetworkRequest::ContentTypeHeader, "application/atom+xml" );
QNetworkReply* reply = m_gc->put( request, updatess.str() );
cerr << "-------------" << endl;
cerr << "SENT to:" << fullEditURL << endl;
cerr << updatess.str() << endl;
cerr << "error:" << reply->error() << endl;
QByteArray ba = reply->readAll();
cerr << "ba.sz:" << ba.size() << endl;
cerr << "ba:" << prettyprintxml( (string)ba ) << endl;
cerr << "-------------" << endl;
fh_domdoc dom = Factory::StringToDOM( (string)ba );
DOMElement* e = dom->getDocumentElement();
string editURL = getMatchingAttribute( e, "link",
"rel", "edit",
"href" );
cerr << "have updated editURL:" << editURL << endl;
int cellURLLength = m_ws->getCellFeedURL().length();
m_value = getStrSubCtx( e, "gs:cell" );
m_cellURL = editURL.substr( cellURLLength );
}
void
GoogleWorkSheetCell::value( const std::string& s )
{
if( m_ws->getDelayCellSync() )
{
m_dirty = true;
m_value = s;
return;
}
m_value = s;
sync();
}
std::string
GoogleWorkSheetCell::editURL()
{
return m_ws->getCellFeedURL() + m_cellURL;
}
/****************************************/
/****************************************/
/****************************************/
YoutubeUpload::YoutubeUpload( fh_GoogleClient gc )
:
m_gc( gc )
{
}
YoutubeUpload::~YoutubeUpload()
{
// cerr << "~YoutubeUpload()" << endl;
// BackTrace();
}
void
YoutubeUpload::streamingUploadComplete()
{
cerr << "YoutubeUpload::streamingUploadComplete() m_streamToQIO:" << GetImpl(m_streamToQIO)
<< " blocking for reply" << endl;
DEBUG << "YoutubeUpload::streamingUploadComplete() blocking for reply" << endl;
QNetworkReply* reply = m_reply;
cerr << "YoutubeUpload::streamingUploadComplete() m_streamToQIO:" << GetImpl(m_streamToQIO) << " wc1" << endl;
m_streamToQIO->writingComplete();
cerr << "YoutubeUpload::streamingUploadComplete() m_streamToQIO:" << GetImpl(m_streamToQIO) << " wc2" << endl;
DEBUG << "YoutubeUpload::streamingUploadComplete() reading data..." << endl;
QByteArray ba = m_streamToQIO->readResponse();
// QByteArray ba = reply->readAll();
cerr << "YoutubeUpload::streamingUploadComplete() m_streamToQIO:" << GetImpl(m_streamToQIO)
<< " reply:" << reply->error() << endl;
DEBUG << "streamingUploadComplete() reply.err:" << reply->error() << endl;
DEBUG << "streamingUploadComplete() got reply:" << tostr(ba) << endl;
fh_domdoc dom = Factory::StringToDOM( tostr(ba) );
DOMElement* e = dom->getDocumentElement();
m_url = getMatchingAttribute( e, "link",
"rel", "self",
"href" );
m_id = XML::getChildText( firstChild( e, "yt:videoid" ));
// <?xml version="1.0" encoding="UTF-8"?>
// <entry xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns:media="http://search.yahoo.com/mrss/" xmlns:gd="http://schemas.google.com/g/2005" xmlns:yt="http://gdata.youtube.com/schemas/2007" gd:etag="W/"C0YMQXoycCp7ImA9WxNTFEU."">
// <id>tag:youtube.com,2008:video:jKY6tYD5s0U</id>
// <published>2009-08-16T20:53:00.498-07:00</published>
// <updated>2009-08-16T20:53:00.498-07:00</updated>
// <app:edited>2009-08-16T20:53:00.498-07:00</app:edited>
// <app:control>
// <app:draft>yes</app:draft>
// <yt:state name="processing"/>
// </app:control>
// <category scheme="http://schemas.google.com/g/2005#kind" term="http://gdata.youtube.com/schemas/2007#video"/>
// <category scheme="http://gdata.youtube.com/schemas/2007/categories.cat" term="People" label="People & Blogs"/>
// <category scheme="http://gdata.youtube.com/schemas/2007/keywords.cat" term="nothing"/>
// <title>nothing</title>
// <link rel="alternate" type="text/html" href="http://www.youtube.com/watch?v=jKY6tYD5s0U"/>
// <link rel="http://gdata.youtube.com/schemas/2007#video.responses" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/videos/jKY6tYD5s0U/responses"/>
// <link rel="http://gdata.youtube.com/schemas/2007#video.ratings" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/videos/jKY6tYD5s0U/ratings"/>
// <link rel="http://gdata.youtube.com/schemas/2007#video.complaints" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/videos/jKY6tYD5s0U/complaints"/>
// <link rel="http://gdata.youtube.com/schemas/2007#video.related" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/videos/jKY6tYD5s0U/related"/>
// <link rel="http://gdata.youtube.com/schemas/2007#video.captionTracks" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/videos/jKY6tYD5s0U/captions" yt:hasEntries="false"/>
// <link rel="http://gdata.youtube.com/schemas/2007#insight.views" type="text/html" href="http://insight.youtube.com/video-analytics/csvreports?query=jKY6tYD5s0U&type=v&starttime=1249862400000&endtime=1250467200000&region=world&token=yyT3Wb4oxV4D5VKuz1sLnroReKR8MTI1MDQ4Mjk4MA%3D%3D&hl=en_US"/>
// <link rel="self" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/users/monkeyiqtesting/uploads/jKY6tYD5s0U"/>
// <link rel="edit" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/users/monkeyiqtesting/uploads/jKY6tYD5s0U"/>
// <author>
// <name>monkeyiqtesting</name>
// <uri>http://gdata.youtube.com/feeds/api/users/monkeyiqtesting</uri>
// </author>
// <gd:comments>
// <gd:feedLink href="http://gdata.youtube.com/feeds/api/videos/jKY6tYD5s0U/comments" countHint="0"/>
// </gd:comments>
// <media:group>
// <media:category label="People & Blogs" scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People</media:category>
// <media:content url="http://www.youtube.com/v/jKY6tYD5s0U&f=user_uploads&d=DeKCSMvhFol1x0mvu9wlZWD9LlbsOl3qUImVMV6ramM&app=youtube_gdata" type="application/x-shockwave-flash" medium="video" isDefault="true" expression="full" yt:format="5"/>
// <media:credit role="uploader" scheme="urn:youtube">monkeyiqtesting</media:credit>
// <media:description type="plain">nothing</media:description>
// <media:keywords>nothing</media:keywords>
// <media:player url="http://www.youtube.com/watch?v=jKY6tYD5s0U"/>
// <media:title type="plain">nothing</media:title>
// <yt:uploaded>2009-08-16T20:53:00.498-07:00</yt:uploaded>
// <yt:videoid>jKY6tYD5s0U</yt:videoid>
// </media:group>
// </entry>
}
fh_iostream
YoutubeUpload::createStreamingUpload( const std::string& ContentType )
{
m_url = "";
m_id = "";
// NO X-GData-Client: <client_id>
// OK X-GData-Key: key=<developer_key>
// OK Slug: <video_filename>
// OK Authorization: AuthSub token="<authentication_token>"
// OK GData-Version: 2
// OK Content-Length: <content_length>
string devkey = (string)"key=" + m_gc->getYoutubeDevKey();
QUrl u( "http://uploads.gdata.youtube.com/feeds/api/users/default/uploads");
// u.addQueryItem("Slug", m_uploadFilename.c_str());
// u.addQueryItem("X-GData-Key", devkey.c_str());
QNetworkRequest req = m_gc->createRequest( u, "youtube", "2" );
req.setRawHeader("Slug", m_uploadFilename.c_str());
req.setRawHeader("X-GData-Key", devkey.c_str());
DEBUG << "X-GData-Key START|" << devkey << "|END" << endl;
req.setHeader(QNetworkRequest::ContentLengthHeader, tostr(m_uploadSize).c_str() );
m_streamToQIO = Factory::createStreamToQIODevice();
{
string desc = m_desc;
string title = m_title;
string keywords = m_keywords;
if( keywords.empty() )
keywords = "none";
stringstream ss;
ss << "Content-Type: application/atom+xml; charset=UTF-8\n";
ss << "\n";
ss << "<?xml version=\"1.0\"?>";
ss << "<entry xmlns=\"http://www.w3.org/2005/Atom\"\n";
ss << " xmlns:media=\"http://search.yahoo.com/mrss/\"\n";
ss << " xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">\n";
ss << " <media:group>\n";
// if( m_uploadDefaultsToPrivate )
// ss << " <yt:private/>\n";
ss << " <media:title type=\"plain\">" << title << "</media:title>\n";
ss << " <media:description type=\"plain\">\n";
ss << " " << desc << "\n";
ss << " </media:description>\n";
ss << " <media:category\n";
ss << " scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">People\n";
ss << " </media:category>\n";
ss << " <media:keywords>" << keywords << "</media:keywords>\n";
ss << " </media:group>\n";
ss << "</entry>\n";
string API_XML_request;
API_XML_request = ss.str();
m_streamToQIO->addExtraDataChunk( API_XML_request );
}
stringstream blobss;
blobss << "Content-Type: " << ContentType << "\n"
<< "Content-Transfer-Encoding: binary;";
m_streamToQIO->setContentType( "multipart/related" );
QNetworkReply* reply = m_streamToQIO->post( ::Ferris::getQNonCachingManager(),
req, blobss.str() );
m_reply = reply;
fh_iostream ret = m_streamToQIO->getStream();
return ret;
}
/****************************************/
/****************************************/
/****************************************/
namespace Factory
{
fh_GoogleClient createGoogleClient()
{
Main::processAllPendingEvents();
KDE::ensureKDEApplication();
return new GoogleClient();
}
};
/******************************************************/
/******************************************************/
/******************************************************/
GDriveFile::GDriveFile( fh_GDriveClient gd, QVariantMap dm )
: m_gd( gd )
, m_id(tostr(dm["id"]))
, m_etag(tostr(dm["etag"]))
, m_rdn(tostr(dm["originalFilename"]))
, m_mime(tostr(dm["mimeType"]))
, m_title(tostr(dm["title"]))
, m_desc(tostr(dm["description"]))
, m_earl(tostr(dm["downloadUrl"]))
, m_earlview(tostr(dm["webViewLink"]))
, m_ext(tostr(dm["fileExtension"]))
, m_md5(tostr(dm["md5checksum"]))
, m_sz(toint(tostr(dm["fileSize"])))
{
m_ctime = parseTime(tostr(dm["createdDate"]));
m_mtime = parseTime(tostr(dm["modifiedDate"]));
m_mmtime = parseTime(tostr(dm["modifiedByMeDate"]));
}
time_t
GDriveFile::parseTime( const std::string& v_const )
{
string v = v_const;
try
{
// 2013-07-26T03:51:28.238Z
v = replaceg( v, "\\.[0-9]*Z", "Z" );
return Time::toTime(Time::ParseTimeString( v ));
}
catch( ... )
{
return 0;
}
}
QNetworkRequest
GDriveFile::createRequest( const std::string& earl )
{
QNetworkRequest req( QUrl(earl.c_str()) );
req.setRawHeader("Authorization", string(string("Bearer ") + m_gd->m_accessToken).c_str() );
return req;
}
fh_istream
GDriveFile::getIStream()
{
m_gd->ensureAccessTokenFresh();
QNetworkAccessManager* qm = getQManager();
QNetworkRequest req = createRequest(m_earl);
DEBUG << "getIStream()...url:" << tostr(QString(req.url().toEncoded())) << endl;
QNetworkReply *reply = qm->get( req );
fh_istream ret = Factory::createIStreamFromQIODevice( reply );
return ret;
}
void
GDriveFile::OnStreamClosed( fh_istream& ss, std::streamsize tellp, ferris_ios::openmode m )
{
DEBUG << "GDriveFile::OnStreamClosed(top)" << endl;
m_streamToQIO->writingComplete();
QByteArray ba = m_streamToQIO->readResponse();
DEBUG << "RESULT:" << tostr(ba) << endl;
}
fh_iostream
GDriveFile::getIOStream()
{
DEBUG << "GDriveFile::getIOStream(top)" << endl;
// PUT https://www.googleapis.com/upload/drive/v2/files/fileId
stringstream earlss;
earlss << "https://www.googleapis.com/upload/drive/v2/files/" << m_id << "?"
<< "uploadType=media&"
<< "fileId=" << m_id;
QNetworkRequest req = createRequest(tostr(earlss));
req.setRawHeader( "Accept", "*/*" );
req.setRawHeader( "Connection", "" );
req.setRawHeader( "Accept-Encoding", "" );
req.setRawHeader( "Accept-Language", "" );
req.setRawHeader( "User-Agent", "" );
DEBUG << "PUT()ing main request..." << endl;
m_streamToQIO = Factory::createStreamToQIODevice();
QNetworkReply* reply = m_streamToQIO->put( ::Ferris::getQNonCachingManager(), req );
m_streamToQIO_reply = reply;
DEBUG << "preparing iostream for user..." << endl;
fh_iostream ret = m_streamToQIO->getStream();
ferris_ios::openmode m = 0;
ret->getCloseSig().connect( sigc::bind( sigc::mem_fun(*this, &_Self::OnStreamClosed ), m ));
DEBUG << "GDriveFile::getIOStream(end)" << endl;
return ret;
}
bool
GDriveFile::isDir() const
{
return m_mime == "application/vnd.google-apps.folder";
}
string
GDriveFile::DRIVE_BASE()
{
return "https://www.googleapis.com/drive/v2/";
}
QNetworkRequest
GDriveFile::addAuth( QNetworkRequest req )
{
return m_gd->addAuth( req );
}
QNetworkReply*
GDriveFile::wait(QNetworkReply* reply )
{
return getDrive()->wait( reply );
}
void
GDriveFile::updateMetadata( const std::string& key, const std::string& value )
{
stringmap_t update;
update[ key ] = value;
updateMetadata( update );
}
fh_GDriveFile
GDriveFile::createFile( const std::string& title )
{
QNetworkRequest req = createRequest(DRIVE_BASE() + "files");
req.setRawHeader("Content-Type", "application/json" );
stringmap_t update;
update["fileId"] = "";
update["title"] = title;
update["description"] = "new";
update["data"] = "";
update["mimeType"] = KDE::guessMimeType( title );
string body = stringmapToJSON( update );
DEBUG << "createFile() url:" << tostr( req.url().toEncoded() ) << endl;
DEBUG << "createFile() body:" << body << endl;
QNetworkReply* reply = getDrive()->callPost( req, stringmap_t(), body );
wait( reply );
QByteArray ba = reply->readAll();
DEBUG << "REST error code:" << reply->error() << endl;
DEBUG << "HTTP response :" << httpResponse(reply) << endl;
QVariantMap dm = JSONToQVMap( tostr(ba) );
fh_GDriveFile f = new GDriveFile( getDrive(), dm );
return f;
}
void
GDriveFile::updateMetadata( stringmap_t& update )
{
getDrive()->ensureAccessTokenFresh();
// PATCH https://www.googleapis.com/drive/v2/files/fileId
QUrl u( string(DRIVE_BASE() + "files/" + m_id).c_str() );
QNetworkRequest req;
req.setUrl( u );
DEBUG << "u1.str::" << tostr(req.url().toString()) << endl;
req.setRawHeader("Content-Type", "application/json" );
req = addAuth( req );
DEBUG << "u2.str::" << tostr(req.url().toString()) << endl;
std::string json = stringmapToJSON( update );
DEBUG << " json:" << json << endl;
QBuffer* buf = new QBuffer(new QByteArray(json.c_str()));
QNetworkReply* reply = getQManager()->sendCustomRequest( req, "PATCH", buf );
wait( reply );
QByteArray ba = reply->readAll();
DEBUG << "REST error code:" << reply->error() << endl;
DEBUG << "HTTP response :" << httpResponse(reply) << endl;
DEBUG << "result:" << tostr(ba) << endl;
stringmap_t sm = JSONToStringMap( tostr(ba) );
fh_stringstream ess;
for( stringmap_t::iterator iter = update.begin(); iter != update.end(); ++iter )
{
DEBUG << "iter->first:" << iter->first << endl;
DEBUG << "iter->second:" << iter->second << endl;
DEBUG << " got:" << sm[iter->first] << endl;
if( sm[iter->first] != iter->second )
{
ess << "attribute " << iter->first << " not correct." << endl;
ess << "expected:" << iter->second << endl;
ess << " got:" << sm[iter->first] << endl;
}
}
string e = tostr(ess);
DEBUG << "e:" << e << endl;
if( !e.empty() )
{
Throw_WebAPIException( e, 0 );
}
}
GDrivePermissions_t
GDriveFile::readPermissions()
{
GDrivePermissions_t ret;
QNetworkRequest req = createRequest(DRIVE_BASE() + "files/" + m_id + "/permissions");
req.setRawHeader("Content-Type", "application/json" );
stringmap_t args;
args["fileId"] = m_id;
QNetworkReply* reply = getDrive()->callMeth( req, args );
QByteArray ba = reply->readAll();
DEBUG << "readPermissions() REST error code:" << reply->error() << endl;
DEBUG << "readPermissions() HTTP response :" << httpResponse(reply) << endl;
DEBUG << "readPermissions() RESULT:" << tostr(ba) << endl;
QVariantMap qm = JSONToQVMap( tostr(ba) );
QVariantList l = qm["items"].toList();
foreach (QVariant ding, l)
{
QVariantMap dm = ding.toMap();
int perm = GDrivePermission::NONE;
if( dm["role"] == "reader" )
perm = GDrivePermission::READ;
if( dm["role"] == "writer" || dm["role"] == "owner" )
perm = GDrivePermission::WRITE;
fh_GDrivePermission p = new GDrivePermission( perm, tostr(dm["name"]));
ret.push_back(p);
}
return ret;
}
void
GDriveFile::sharesAdd( std::string email )
{
stringlist_t emails;
emails.push_back( email );
return sharesAdd( emails );
}
void
GDriveFile::sharesAdd( stringlist_t& emails )
{
// POST https://www.googleapis.com/drive/v2/files/fileId/permissions
for( stringlist_t::iterator si = emails.begin(); si != emails.end(); ++si )
{
string email = *si;
QNetworkRequest req = createRequest(DRIVE_BASE() + "files/" + m_id + "/permissions");
req.setRawHeader("Content-Type", "application/json" );
stringmap_t args;
args["fileId"] = m_id;
args["emailMessage"] = "Life moves pretty fast. If you don't stop and look around once in a while, you could miss it.";
stringstream bodyss;
bodyss << "{" << endl
<< " \"kind\": \"drive#permission\", " << endl
<< " \"value\": \"" << email << "\" , " << endl
<< " \"role\": \"writer\"," << endl
<< " \"type\": \"user\"" << endl
<< " } " << endl;
DEBUG << "body:" << tostr(bodyss) << endl;
QNetworkReply* reply = getDrive()->callPost( req, args, tostr(bodyss) );
QByteArray ba = reply->readAll();
DEBUG << "sharesAdd() REST error code:" << reply->error() << endl;
DEBUG << "sharesAdd() HTTP response :" << httpResponse(reply) << endl;
DEBUG << "sharesAdd() RESULT:" << tostr(ba) << endl;
stringmap_t sm = JSONToStringMap( tostr(ba) );
if( !sm["etag"].empty() && !sm["id"].empty() )
continue;
// Failed
stringstream ess;
ess << "Failed to create permission for user:" << email << endl
<< " reply:" << tostr(ba) << endl;
Throw_WebAPIException( tostr(ess), 0 );
}
}
/********************/
GDriveClient::GDriveClient()
: m_clientID( "881964254376.apps.googleusercontent.com" )
, m_secret( "UH9zxZ8k_Fj3actLPRVPVG8Q" )
{
readAuthTokens();
}
void
GDriveClient::readAuthTokens()
{
m_accessToken = getConfigString( FDB_SECURE, "gdrive-access-token", "" );
m_refreshToken = getConfigString( FDB_SECURE, "gdrive-refresh-token", "" );
m_accessToken_expiretime = toType<time_t>(
getConfigString( FDB_SECURE,
"gdrive-access-token-expires-timet", "0"));
}
std::string
GDriveClient::AUTH_BASE()
{
return "https://accounts.google.com/o/oauth2/";
}
fh_GDriveClient
GDriveClient::getGDriveClient()
{
Main::processAllPendingEvents();
KDE::ensureKDEApplication();
static fh_GDriveClient ret = new GDriveClient();
return ret;
}
bool
GDriveClient::haveAPIKey() const
{
return !m_clientID.empty() && !m_secret.empty();
}
bool
GDriveClient::isAuthenticated() const
{
return !m_accessToken.empty() && !m_refreshToken.empty();
}
void
GDriveClient::handleFinished()
{
QNetworkReply* r = dynamic_cast<QNetworkReply*>(sender());
m_waiter.unblock(r);
DEBUG << "handleFinished() r:" << r << endl;
}
QNetworkReply*
GDriveClient::wait(QNetworkReply* reply )
{
connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) );
m_waiter.block(reply);
return reply;
}
QNetworkReply*
GDriveClient::post( QNetworkRequest req )
{
QUrl u = req.url();
DEBUG << "u.str::" << tostr(u.toString()) << endl;
string body = tostr(u.encodedQuery());
DEBUG << "body:" << body << endl;
u.setEncodedQuery(QByteArray());
// u.setUrl( "http://localhost/testing" );
req.setHeader( QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded" );
req.setHeader(QNetworkRequest::ContentLengthHeader, tostr(body.size()).c_str() );
QNetworkReply* reply = getQManager()->post( req, body.c_str() );
connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) );
m_waiter.block(reply);
DEBUG << "REST error code:" << reply->error() << endl;
return reply;
}
std::string
GDriveClient::requestToken( stringmap_t args )
{
QUrl u( string(AUTH_BASE() + "auth").c_str() );
u.addQueryItem("response_type", "code" );
u.addQueryItem("client_id", m_clientID.c_str() );
u.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob" );
u.addQueryItem("scope", "https://www.googleapis.com/auth/drive.file "
"https://www.googleapis.com/auth/drive "
"https://www.googleapis.com/auth/drive.scripts "
"https://www.googleapis.com/auth/drive.appdata " );
u.addQueryItem("state", "anyone... anyone?" );
std::string authURL = tostr( u.toEncoded() );
return authURL;
}
void
GDriveClient::accessToken( const std::string& code, stringmap_t args )
{
QUrl u( string(AUTH_BASE() + "token").c_str() );
QNetworkRequest req;
req.setUrl( u );
args["code"] = code;
args["client_id"] = m_clientID;
args["client_secret"] = m_secret;
args["redirect_uri"] = "urn:ietf:wg:oauth:2.0:oob";
args["grant_type"] = "authorization_code";
DEBUG << "u1.str::" << tostr(req.url().toString()) << endl;
req = setArgs( req, args );
DEBUG << "u2.str::" << tostr(req.url().toString()) << endl;
QNetworkReply* reply = post( req );
QByteArray ba = reply->readAll();
cerr << "result:" << tostr(ba) << endl;
stringmap_t sm = JSONToStringMap( tostr(ba) );
time_t expiretime = Time::getTime() + toint(sm["expires_in"]);
setConfigString( FDB_SECURE, "gdrive-access-token", sm["access_token"] );
setConfigString( FDB_SECURE, "gdrive-refresh-token", sm["refresh_token"] );
setConfigString( FDB_SECURE, "gdrive-access-token-expires-timet", tostr(expiretime) );
readAuthTokens();
}
void
GDriveClient::ensureAccessTokenFresh( int force )
{
if( !isAuthenticated() )
return;
if( !force )
{
if( Time::getTime() + 30 < m_accessToken_expiretime )
return;
}
DEBUG << "ensureAccessTokenFresh() really doing it!" << endl;
QUrl u( string(AUTH_BASE() + "token").c_str() );
QNetworkRequest req;
req.setUrl( u );
stringmap_t args;
args["refresh_token"] = m_refreshToken;
args["client_id"] = m_clientID;
args["client_secret"] = m_secret;
args["grant_type"] = "refresh_token";
req = setArgs( req, args );
QNetworkReply* reply = post( req );
cerr << "ensureAccessTokenFresh() have reply..." << endl;
QByteArray ba = reply->readAll();
cerr << "ensureAccessTokenFresh(b) m_accessToken:" << m_accessToken << endl;
cerr << "ensureAccessTokenFresh() result:" << tostr(ba) << endl;
stringmap_t sm = JSONToStringMap( tostr(ba) );
time_t expiretime = Time::getTime() + toint(sm["expires_in"]);
setConfigString( FDB_SECURE, "gdrive-access-token", sm["access_token"] );
setConfigString( FDB_SECURE, "gdrive-access-token-expires-timet", tostr(expiretime) );
readAuthTokens();
cerr << "ensureAccessTokenFresh(e) m_accessToken:" << m_accessToken << endl;
}
QNetworkRequest
GDriveClient::addAuth( QNetworkRequest req )
{
req.setRawHeader("Authorization", string(string("Bearer ") + m_accessToken).c_str() );
return req;
}
QNetworkReply*
GDriveClient::callMeth( QNetworkRequest req, stringmap_t args )
{
ensureAccessTokenFresh();
req = setArgs( req, args );
req = addAuth( req );
QUrl u = req.url();
DEBUG << "callMeth U:" << tostr(QString(u.toEncoded())) << endl;
// u.setUrl( "http://localhost/testing" );
// req.setUrl(u);
QNetworkReply* reply = getQManager()->get( req );
connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) );
m_waiter.block(reply);
DEBUG << "REST error code:" << reply->error() << endl;
return reply;
}
QNetworkReply*
GDriveClient::callPost( QNetworkRequest req, stringmap_t args, const std::string& body )
{
ensureAccessTokenFresh();
req = setArgs( req, args );
req = addAuth( req );
QUrl u = req.url();
DEBUG << "callPost U:" << tostr(QString(u.toEncoded())) << endl;
DEBUG << " body:" << body << endl;
QBuffer* buf = new QBuffer(new QByteArray(body.c_str()));
QNetworkReply* reply = getQManager()->post( req, buf );
connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) );
m_waiter.block(reply);
DEBUG << "REST error code:" << reply->error() << endl;
return reply;
}
string
GDriveClient::DRIVE_BASE()
{
return "https://www.googleapis.com/drive/v2/";
}
QNetworkRequest
GDriveClient::createRequest( const std::string& earlTail )
{
QUrl u( string(DRIVE_BASE() + earlTail).c_str() );
QNetworkRequest req;
req.setUrl( u );
return req;
}
files_t
GDriveClient::filesList( const std::string& q_const, const std::string& pageToken )
{
string q = q_const;
if( q.empty() )
{
q = "hidden = false and trashed = false";
}
files_t ret;
// QNetworkRequest req = createRequest("files/root/children");
QNetworkRequest req = createRequest("files");
stringmap_t args;
args["maxResults"] = tostr(1000);
if( !pageToken.empty() )
args["pageToken"] = pageToken;
if( !q.empty() )
args["q"] = q;
QNetworkReply* reply = callMeth( req, args );
QByteArray ba = reply->readAll();
DEBUG << "filesList() result:" << tostr(ba) << endl;
stringmap_t sm = JSONToStringMap( tostr(ba) );
DEBUG << "etag:" << sm["etag"] << endl;
QVariantMap qm = JSONToQVMap( tostr(ba) );
QVariantList l = qm["items"].toList();
foreach (QVariant ding, l)
{
QVariantMap dm = ding.toMap();
string rdn = tostr(dm["originalFilename"]);
long sz = toint(tostr(dm["fileSize"]));
QVariantMap labels = dm["labels"].toMap();
if( labels["hidden"].toInt() || labels["trashed"].toInt() )
continue;
bool skipThisOne = false;
QVariantList parents = dm["parents"].toList();
foreach (QVariant pv, parents)
{
QVariantMap pm = pv.toMap();
if( !pm["isRoot"].toInt() )
{
skipThisOne = 1;
break;
}
}
if( dm["userPermission"].toMap()["role"] != "owner" )
skipThisOne = true;
if( skipThisOne )
continue;
DEBUG << "sz:" << sz << " fn:" << rdn << endl;
fh_GDriveFile f = new GDriveFile( this, dm );
ret.push_back(f);
}
return ret;
}
/****************************************/
/****************************************/
/****************************************/
};
| Java |
//
// This file is part of Return To The Roots.
//
// Return To The Roots is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Return To The Roots is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Return To The Roots. If not, see <http://www.gnu.org/licenses/>.
#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;
}
| Java |
<?php
/*
publicacion_miniatura.php
Una publicacion en miniatura
*/
/*
Created on : 23/04/2015, 14:40:40
Author : Juan Manuel Scarciofolo
License : GPLv3
*/
?>
<div class="publicacion_miniatura">
<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> | Java |
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 'f9421047519d2af9a7a466e4336f6e6ea55206b356cd33c8bd18cb626bf2ce91'
binary_url ({
aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/aspell_fr-0.50-3-chromeos-armv7l.tar.xz',
armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/aspell_fr-0.50-3-chromeos-armv7l.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.50-3-chromeos-x86_64.tar.xz',
})
binary_sha256 ({
aarch64: 'c109f726e0a3a7e708a6c8fb4cb1cd7f84d0486fa352c141ce5f70817651efc7',
armv7l: 'c109f726e0a3a7e708a6c8fb4cb1cd7f84d0486fa352c141ce5f70817651efc7',
i686: '3a466ebca6ea8267b2ba5e5bcda9b1e15869f11d144b2c282dc5ff40a37d7364',
x86_64: '8ffcc409bf5c6e4a142b68d027498942788535f8025927de23efa477e1a7d2c1',
})
depends_on 'aspell'
def self.build
system './configure'
system 'make'
end
def self.install
system "make", "DESTDIR=#{CREW_DEST_DIR}", "install"
end
end
| Java |
require_relative '../core_ext/array'
require_relative '../core_ext/hash'
require_relative 'host'
require_relative 'command'
require_relative 'command_map'
require_relative 'configuration'
require_relative 'coordinator'
require_relative 'logger'
require_relative 'log_message'
require_relative 'formatters/abstract'
require_relative 'formatters/black_hole'
require_relative 'formatters/pretty'
require_relative 'formatters/dot'
require_relative 'runners/abstract'
require_relative 'runners/sequential'
require_relative 'runners/parallel'
require_relative 'runners/group'
require_relative 'runners/null'
require_relative 'backends/abstract'
require_relative 'backends/printer'
require_relative 'backends/netssh'
require_relative 'backends/local'
require_relative 'backends/skipper'
| Java |
#!/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, RawDescriptionHelpFormatter
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=RawDescriptionHelpFormatter)
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)
| Java |
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stt.data.jpa.service;
import com.stt.data.jpa.domain.City;
import com.stt.data.jpa.domain.Hotel;
import com.stt.data.jpa.domain.HotelSummary;
import com.stt.data.jpa.domain.RatingCount;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import java.util.List;
interface HotelRepository extends Repository<Hotel, Long> {
Hotel findByCityAndName(City city, String name);
@Query("select h.city as city, h.name as name, avg(r.rating) as averageRating "
+ "from Hotel h left outer join h.reviews r where h.city = ?1 group by h")
Page<HotelSummary> findByCity(City city, Pageable pageable);
@Query("select r.rating as rating, count(r) as count "
+ "from Review r where r.hotel = ?1 group by r.rating order by r.rating DESC")
List<RatingCount> findRatingCounts(Hotel hotel);
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<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 href="index__pixel_8hpp.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/*</span>
<a name="l00002"></a>00002 <span class="comment"> * Copyright (C) 2007,2008 Alex Shulgin</span>
<a name="l00003"></a>00003 <span class="comment"> *</span>
<a name="l00004"></a>00004 <span class="comment"> * This file is part of png++ the C++ wrapper for libpng. PNG++ is free</span>
<a name="l00005"></a>00005 <span class="comment"> * software; the exact copying conditions are as follows:</span>
<a name="l00006"></a>00006 <span class="comment"> *</span>
<a name="l00007"></a>00007 <span class="comment"> * Redistribution and use in source and binary forms, with or without</span>
<a name="l00008"></a>00008 <span class="comment"> * modification, are permitted provided that the following conditions are met:</span>
<a name="l00009"></a>00009 <span class="comment"> *</span>
<a name="l00010"></a>00010 <span class="comment"> * 1. Redistributions of source code must retain the above copyright notice,</span>
<a name="l00011"></a>00011 <span class="comment"> * this list of conditions and the following disclaimer.</span>
<a name="l00012"></a>00012 <span class="comment"> *</span>
<a name="l00013"></a>00013 <span class="comment"> * 2. Redistributions in binary form must reproduce the above copyright</span>
<a name="l00014"></a>00014 <span class="comment"> * notice, this list of conditions and the following disclaimer in the</span>
<a name="l00015"></a>00015 <span class="comment"> * documentation and/or other materials provided with the distribution.</span>
<a name="l00016"></a>00016 <span class="comment"> *</span>
<a name="l00017"></a>00017 <span class="comment"> * 3. The name of the author may not be used to endorse or promote products</span>
<a name="l00018"></a>00018 <span class="comment"> * derived from this software without specific prior written permission.</span>
<a name="l00019"></a>00019 <span class="comment"> *</span>
<a name="l00020"></a>00020 <span class="comment"> * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR</span>
<a name="l00021"></a>00021 <span class="comment"> * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES</span>
<a name="l00022"></a>00022 <span class="comment"> * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN</span>
<a name="l00023"></a>00023 <span class="comment"> * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,</span>
<a name="l00024"></a>00024 <span class="comment"> * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED</span>
<a name="l00025"></a>00025 <span class="comment"> * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR</span>
<a name="l00026"></a>00026 <span class="comment"> * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF</span>
<a name="l00027"></a>00027 <span class="comment"> * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING</span>
<a name="l00028"></a>00028 <span class="comment"> * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS</span>
<a name="l00029"></a>00029 <span class="comment"> * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</span>
<a name="l00030"></a>00030 <span class="comment"> */</span>
<a name="l00031"></a>00031 <span class="preprocessor">#ifndef PNGPP_INDEX_PIXEL_HPP_INCLUDED</span>
<a name="l00032"></a>00032 <span class="preprocessor"></span><span class="preprocessor">#define PNGPP_INDEX_PIXEL_HPP_INCLUDED</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="classpng_1_1index__pixel.html">00044</a> <span class="keyword">class </span><a class="code" href="classpng_1_1index__pixel.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="classpng_1_1index__pixel.html#a16519149701f54c24cc9e09ac033d1b6">00047</a> <a class="code" href="classpng_1_1index__pixel.html#a16519149701f54c24cc9e09ac033d1b6">index_pixel</a>(<a class="code" href="namespacepng.html#ac0e0e2e09bdd9a287618bfdc5f31ca52">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="classpng_1_1index__pixel.html#acbd240869e0002e145ed1dc1ad11ab52">00052</a> <a class="code" href="classpng_1_1index__pixel.html#acbd240869e0002e145ed1dc1ad11ab52">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#ac0e0e2e09bdd9a287618bfdc5f31ca52">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="classpng_1_1packed__index__pixel.html">00066</a> <span class="keyword">class </span><a class="code" href="classpng_1_1packed__index__pixel.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="classpng_1_1packed__pixel.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="classpng_1_1packed__index__pixel.html#af2998b19cb86caaf0c02c0718638cfa9">00070</a> <a class="code" href="classpng_1_1packed__index__pixel.html#af2998b19cb86caaf0c02c0718638cfa9">packed_index_pixel</a>(<a class="code" href="namespacepng.html#ac0e0e2e09bdd9a287618bfdc5f31ca52">byte</a> value = 0)
<a name="l00071"></a>00071 : <a class="code" href="classpng_1_1packed__pixel.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#ad9bcd36130a08ef57f572cd8f5589ba5">00079</a> <span class="keyword">typedef</span> <a class="code" href="classpng_1_1packed__index__pixel.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#ad9bcd36130a08ef57f572cd8f5589ba5" 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#ab8275ae7a6deacae66e45e38a6493b7f">00084</a> <span class="keyword">typedef</span> <a class="code" href="classpng_1_1packed__index__pixel.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#ab8275ae7a6deacae66e45e38a6493b7f" 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#a303ec6fdaacd846547a7992d3bd84c29">00089</a> <span class="keyword">typedef</span> <a class="code" href="classpng_1_1packed__index__pixel.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#a303ec6fdaacd846547a7992d3bd84c29" 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="structpng_1_1pixel__traits_3_01index__pixel_01_4.html">00095</a> <span class="keyword">struct </span>pixel_traits< <a class="code" href="classpng_1_1index__pixel.html" title="The 8-bit Indexed (colormap) pixel type.">index_pixel</a> >
<a name="l00096"></a>00096 : <a class="code" href="structpng_1_1basic__pixel__traits.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="structpng_1_1pixel__traits_3_01packed__index__pixel_3_01bits_01_4_01_4.html">00104</a> <span class="keyword">struct </span>pixel_traits< <a class="code" href="classpng_1_1packed__index__pixel.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="structpng_1_1basic__pixel__traits.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 // PNGPP_INDEX_PIXEL_HPP_INCLUDED</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://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.4 </small></address>
</body>
</html>
| Java |
---------------------------------------------
-- Pleiades Ray
--
-- Description: Fires a magical ray at nearby targets. Additional effects: Paralysis + Blind + Poison + Plague + Bind + Silence + Slow
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: Unknown
-- Notes: Only used by Gurfurlur the Menacing with health below 20%.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local duration = 120;
MobStatusEffectMove(mob, target, EFFECT_PARALYSIS, 40, 3, duration);
MobStatusEffectMove(mob, target, EFFECT_AMNESIA, 40, 3, duration);
MobStatusEffectMove(mob, target, EFFECT_ADDLE, 10, 3, duration);
MobStatusEffectMove(mob, target, EFFECT_PLAGUE, 5, 3, duration);
MobStatusEffectMove(mob, target, EFFECT_CURSE_I, 1, 3, duration);
MobStatusEffectMove(mob, target, EFFECT_SILENCE, 1, 3, duration);
MobStatusEffectMove(mob, target, EFFECT_SLOW, 128, 3, duration);
local dmgmod = 1.2;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*7,ELE_FIRE,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_FIRE,MOBPARAM_WIPE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| Java |
# Copyright © 2016 Lars Peter Søndergaard <lps@chireiden.net>
# Copyright © 2016 FichteFoll <fichtefoll2@googlemail.com>
#
# This file is part of Shanghai, an asynchronous multi-server IRC bot.
#
# Shanghai is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shanghai is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Shanghai. If not, see <http://www.gnu.org/licenses/>.
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 TestPrioritizedSetList:
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 test_add_already_added(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 test_core_event_deco(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 test_from_not_handler(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 test_register_plugin(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 test_dispatch_priority(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 test_dispatch_disabled(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 test_dispatch_exception(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 test_dispatch_unknown_return(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 test_dispatch_nested_insert(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
| Java |
/************************************************************************
* Copyright (C) 2019 Spatial Information Systems Research Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
************************************************************************/
#include <Action/ActionToggleCameraActorInteraction.h>
#include <FaceModelViewer.h>
#include <FaceModel.h>
using FaceTools::Action::ActionToggleCameraActorInteraction;
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;
ActionToggleCameraActorInteraction::ActionToggleCameraActorInteraction( 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::onDoubleClickedSelected, this, &ActionToggleCameraActorInteraction::_doDoubleClicked);
connect( sn, &Interactor::SelectNotifier::onLeftButtonUp, this, &ActionToggleCameraActorInteraction::_doLeftButtonUp);
_moveNotifier = std::shared_ptr<ActorMoveNotifier>( new ActorMoveNotifier);
connect( &*_moveNotifier, &ActorMoveNotifier::onActorStart, this, &ActionToggleCameraActorInteraction::_doOnActorStart);
connect( &*_moveNotifier, &ActorMoveNotifier::onActorStop, this, &ActionToggleCameraActorInteraction::_doOnActorStop);
setCheckable( true, false);
} // end ctor
QString ActionToggleCameraActorInteraction::toolTip() const
{
return "When on, click and drag the selected model to change its position or orientation.";
} // end toolTip
QString ActionToggleCameraActorInteraction::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 ActionToggleCameraActorInteraction::checkState( Event)
{
return MS::interactionMode() == IMode::ACTOR_INTERACTION;
} // end checkState
bool ActionToggleCameraActorInteraction::checkEnable( Event)
{
const FM* fm = MS::selectedModel();
return fm || isChecked();
} // end checkEnabled
void ActionToggleCameraActorInteraction::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 ActionToggleCameraActorInteraction::_doOnActorStart()
{
storeUndo( this, Event::AFFINE_CHANGE);
} // end _doOnActorStart
void ActionToggleCameraActorInteraction::_doOnActorStop()
{
emit onEvent( Event::AFFINE_CHANGE);
} // end _doOnActorStop
// Called only when user double clicks on an already selected model.
void ActionToggleCameraActorInteraction::_doDoubleClicked()
{
_dblClickDrag = true;
setChecked( true);
execute( Event::USER);
} // end _doDoubleClicked
void ActionToggleCameraActorInteraction::_doLeftButtonUp()
{
if ( _dblClickDrag)
{
_dblClickDrag = false;
setChecked( false);
execute( Event::USER);
} // end if
} // end _doLeftButtonUp
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<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>
| Java |
#!/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)
| Java |
#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;
}
| Java |
/*
** ###################################################################
** This code is generated by the Device Initialization Tool.
** It is overwritten during code generation.
** USER MODIFICATION ARE NOT PRESERVED IN THIS FILE.
**
** Project : s08qe128
** Processor : MCF51QE128CLK
** Version : Bean 01.001, Driver 01.03, CPU db: 3.00.000
** Datasheet : MCF51QE128RM Rev. 1.0 Draft F
** Date/Time : 06/03/2009, 10:04 a.m.
** Abstract :
** This module contains device initialization code
** for selected on-chip peripherals.
** Contents :
** Function "MCU_init" initializes selected peripherals
**
** (c) Copyright UNIS, spol. s r.o. 1997-2006
** UNIS, spol s r.o.
** Jundrovska 33
** 624 00 Brno
** Czech Republic
** http : www.processorexpert.com
** mail : info@processorexpert.com
** ###################################################################
*/
#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 );
| Java |
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! 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::{MiningBlockChainClient, 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, ExternalMinerService};
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 pending_nonce_from_queue: bool,
/// Returns receipt from pending blocks
pub allow_pending_receipt_query: bool,
/// Send additional block number when asking for work
pub send_block_number_in_get_work: 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 {
pending_nonce_from_queue: false,
allow_pending_receipt_query: true,
send_block_number_in_get_work: true,
}
}
}
/// Eth rpc implementation.
pub struct EthClient<C, SN: ?Sized, S: ?Sized, M, EM> where
C: MiningBlockChainClient,
SN: SnapshotService,
S: SyncProvider,
M: MinerService,
EM: ExternalMinerService {
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: MiningBlockChainClient,
SN: SnapshotService,
S: SyncProvider,
M: MinerService,
EM: ExternalMinerService {
/// 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.block_total_difficulty(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().localized_transactions().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.block_total_difficulty(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: MiningBlockChainClient {
use ethcore::block_status::BlockStatus;
match client.block_status(number.into()) {
BlockStatus::InChain => Ok(()),
BlockStatus::Pending => Ok(()),
_ => Err(errors::unknown_block()),
}
}
const MAX_QUEUE_SIZE_TO_MINE_ON: 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: MiningBlockChainClient + 'static,
SN: SnapshotService + 'static,
S: SyncProvider + 'static,
M: MinerService + 'static,
EM: ExternalMinerService + '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, warp_chunks_processed) = 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.highest_block_number.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),
warp_chunks_processed: warp_chunks_processed.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.is_currently_sealing())
}
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.pending_nonce_from_queue => {
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 block_transaction_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(self.client.block(BlockId::Hash(hash.into()))
.map(|block| block.transactions_count().into())))
}
fn block_transaction_count_by_number(&self, num: BlockNumber) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(match num {
BlockNumber::Pending => Some(
self.miner.status().transactions_in_pending_block.into()
),
_ =>
self.client.block(num.into())
.map(|block| block.transactions_count().into())
}))
}
fn block_uncles_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> {
Box::new(future::ok(self.client.block(BlockId::Hash(hash.into()))
.map(|block| block.uncles_count().into())))
}
fn block_uncles_count_by_number(&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 transaction_by_block_hash_and_index(&self, hash: RpcH256, index: Index) -> BoxFuture<Option<Transaction>> {
Box::new(future::done(
self.transaction(TransactionId::Location(BlockId::Hash(hash.into()), index.value()))
))
}
fn transaction_by_block_number_and_index(&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.allow_pending_receipt_query) {
(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 uncle_by_block_hash_and_index(&self, hash: RpcH256, index: Index) -> BoxFuture<Option<RichBlock>> {
Box::new(future::done(self.uncle(UncleId {
block: BlockId::Hash(hash.into()),
position: index.value()
})))
}
fn uncle_by_block_number_and_index(&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.can_produce_work_package() {
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() > MAX_QUEUE_SIZE_TO_MINE_ON {
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::difficulty_to_boundary(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.send_block_number_in_get_work {
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.can_produce_work_package() {
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 send_raw_transaction(&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::dispatch_transaction(
&*self.client,
&*self.miner,
signed_transaction.into(),
)
})
.map(Into::into)
}
fn submit_transaction(&self, raw: Bytes) -> Result<RpcH256> {
self.send_raw_transaction(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()))
}
}
| Java |
/**********************************************************************
** smepowercad
** Copyright (C) 2015 Smart Micro Engineering GmbH
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************/
#ifndef CAD_HEATCOOL_RADIATORVALVE_H
#define CAD_HEATCOOL_RADIATORVALVE_H
#include "caditem.h"
#include "items/cad_basic_box.h"
class CAD_HeatCool_RadiatorValve : public CADitem
{
public:
CAD_HeatCool_RadiatorValve();
virtual ~CAD_HeatCool_RadiatorValve();
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 // CAD_HEATCOOL_RADIATORVALVE_H
| Java |
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);
}
} | Java |
""" 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")
| Java |
# Makefile.in generated by automake 1.14.1 from Makefile.am.
# compat/jansson/Makefile. Generated from Makefile.in by configure.
# Copyright (C) 1994-2013 Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
am__make_running_with_option = \
case $${target_option-} in \
?) ;; \
*) echo "am__make_running_with_option: 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 ]*//g"`;; \
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; $(am__make_running_with_option))
am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
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 = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = x86_64-unknown-linux-gnu
host_triplet = x86_64-unknown-linux-gnu
target_triplet = x86_64-unknown-linux-gnu
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) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(install_sh) -d
CONFIG_HEADER = $(top_builddir)/ccminer-config.h
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
LIBRARIES = $(noinst_LIBRARIES)
AR = ar
ARFLAGS = cru
AM_V_AR = $(am__v_AR_$(V))
am__v_AR_ = $(am__v_AR_$(AM_DEFAULT_VERBOSITY))
am__v_AR_0 = @echo " AR " $@;
am__v_AR_1 =
libjansson_a_AR = $(AR) $(ARFLAGS)
libjansson_a_LIBADD =
am_libjansson_a_OBJECTS = dump.$(OBJEXT) error.$(OBJEXT) \
hashtable.$(OBJEXT) load.$(OBJEXT) memory.$(OBJEXT) \
pack_unpack.$(OBJEXT) strbuffer.$(OBJEXT) strconv.$(OBJEXT) \
utf.$(OBJEXT) value.$(OBJEXT)
libjansson_a_OBJECTS = $(am_libjansson_a_OBJECTS)
AM_V_P = $(am__v_P_$(V))
am__v_P_ = $(am__v_P_$(AM_DEFAULT_VERBOSITY))
am__v_P_0 = false
am__v_P_1 = :
AM_V_GEN = $(am__v_GEN_$(V))
am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY))
am__v_GEN_0 = @echo " GEN " $@;
am__v_GEN_1 =
AM_V_at = $(am__v_at_$(V))
am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY))
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_$(AM_DEFAULT_VERBOSITY))
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_$(AM_DEFAULT_VERBOSITY))
am__v_CCLD_0 = @echo " CCLD " $@;
am__v_CCLD_1 =
SOURCES = $(libjansson_a_SOURCES)
DIST_SOURCES = $(libjansson_a_SOURCES)
am__can_run_installinfo = \
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.
am__define_uniq_tagged_files = \
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}
AM_DEFAULT_VERBOSITY = 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}
INSTALL_STRIP_PROGRAM = $(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 = x86_64-unknown-linux-gnu
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 = x86_64-unknown-linux-gnu
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
program_transform_name = s,x,x,
psdir = ${docdir}
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
srcdir = .
sysconfdir = ${prefix}/etc
target = x86_64-unknown-linux-gnu
target_alias =
target_cpu = x86_64
target_os = linux-gnu
target_vendor = unknown
top_build_prefix = ../../
top_builddir = ../..
top_srcdir = ../..
noinst_LIBRARIES = libjansson.a
libjansson_a_SOURCES = \
jansson_private_config.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 $(CONFIG_STATUS_DEPENDENCIES)
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):
clean-noinstLIBRARIES:
-test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES)
libjansson.a: $(libjansson_a_OBJECTS) $(libjansson_a_DEPENDENCIES) $(EXTRA_libjansson_a_DEPENDENCIES)
$(AM_V_at)-rm -f libjansson.a
$(AM_V_AR)$(libjansson_a_AR) libjansson.a $(libjansson_a_OBJECTS) $(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)
$(am__define_uniq_tagged_files); mkid -fID $$unique
tags: tags-am
TAGS: tags
tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
set x; \
here=`pwd`; \
$(am__define_uniq_tagged_files); \
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)
$(am__define_uniq_tagged_files); \
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="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
install; \
else \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" 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 "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
maintainer-clean-generic:
@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 clean-noinstLIBRARIES 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 maintainer-clean-generic
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 \
clean-noinstLIBRARIES 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 \
maintainer-clean-generic 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:
| Java |
/* $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 $ */
/*-
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)stdlib.h 5.13 (Berkeley) 6/4/91
*/
#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 arc4random_addrandom __P((unsigned char *, int));
int getbaudval __P((int ));
int getbaudrate __P((char *));
#endif /* !_ANSI_SOURCE && !_POSIX_SOURCE */
__END_DECLS
#endif /* _STDLIB_H_ */
| Java |
<?php
/* Copyright (C) 2014 Daniel Preussker <f0o@devilcode.org>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. */
/**
* Custom Frontpage
* @author f0o <f0o@devilcode.org>
* @copyright 2014 f0o, LibreNMS
* @license GPL
*/
use Illuminate\Support\Facades\Auth;
use LibreNMS\Alert\AlertUtil;
use LibreNMS\Config;
$install_dir = Config::get('install_dir');
if (Config::get('map.engine', 'leaflet') == 'leaflet') {
$temp_output = '
<script src="js/leaflet.js"></script>
<script src="js/leaflet.markercluster.js"></script>
<script src="js/leaflet.awesome-markers.min.js"></script>
<div id="leaflet-map"></div>
<script>
';
$init_lat = Config::get('leaflet.default_lat', 51.48);
$init_lng = Config::get('leaflet.default_lng', 0);
$init_zoom = Config::get('leaflet.default_zoom', 5);
$group_radius = Config::get('leaflet.group_radius', 80);
$tile_url = Config::get('leaflet.tile_url', '{s}.tile.openstreetmap.org');
$show_status = [0, 1];
$map_init = '[' . $init_lat . ', ' . $init_lng . '], ' . sprintf('%01.1f', $init_zoom);
$temp_output .= 'var map = L.map(\'leaflet-map\', { zoomSnap: 0.1 } ).setView(' . $map_init . ');
L.tileLayer(\'//' . $tile_url . '/{z}/{x}/{y}.png\', {
attribution: \'© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors\'
}).addTo(map);
var markers = L.markerClusterGroup({
maxClusterRadius: ' . $group_radius . ',
iconCreateFunction: function (cluster) {
var markers = cluster.getAllChildMarkers();
var n = 0;
color = "green"
newClass = "Cluster marker-cluster marker-cluster-small leaflet-zoom-animated leaflet-clickable";
for (var i = 0; i < markers.length; i++) {
if (markers[i].options.icon.options.markerColor == "blue" && color != "red") {
color = "blue";
}
if (markers[i].options.icon.options.markerColor == "red") {
color = "red";
}
}
return L.divIcon({ html: cluster.getChildCount(), className: color+newClass, iconSize: L.point(40, 40) });
},
});
var redMarker = L.AwesomeMarkers.icon({
icon: \'server\',
markerColor: \'red\', prefix: \'fa\', iconColor: \'white\'
});
var blueMarker = L.AwesomeMarkers.icon({
icon: \'server\',
markerColor: \'blue\', prefix: \'fa\', iconColor: \'white\'
});
var greenMarker = L.AwesomeMarkers.icon({
icon: \'server\',
markerColor: \'green\', prefix: \'fa\', iconColor: \'white\'
});
';
// Checking user permissions
if (Auth::user()->hasGlobalRead()) {
// Admin or global read-only - show all devices
$sql = "SELECT DISTINCT(`device_id`),`location`,`sysName`,`hostname`,`os`,`status`,`lat`,`lng` FROM `devices`
LEFT JOIN `locations` ON `devices`.`location_id`=`locations`.`id`
WHERE `disabled`=0 AND `ignore`=0 AND ((`lat` != '' AND `lng` != '') OR (`location` REGEXP '\[[0-9\.\, ]+\]'))
AND `status` IN " . dbGenPlaceholders(count($show_status)) .
' ORDER BY `status` ASC, `hostname`';
$param = $show_status;
} else {
// Normal user - grab devices that user has permissions to
$device_ids = Permissions::devicesForUser()->toArray() ?: [0];
$sql = "SELECT DISTINCT(`devices`.`device_id`) as `device_id`,`location`,`sysName`,`hostname`,`os`,`status`,`lat`,`lng`
FROM `devices`
LEFT JOIN `locations` ON `devices`.location_id=`locations`.`id`
WHERE `disabled`=0 AND `ignore`=0 AND ((`lat` != '' AND `lng` != '') OR (`location` REGEXP '\[[0-9\.\, ]+\]'))
AND `devices`.`device_id` IN " . dbGenPlaceholders(count($device_ids)) .
' AND `status` IN ' . dbGenPlaceholders(count($show_status)) .
' ORDER BY `status` ASC, `hostname`';
$param = array_merge($device_ids, $show_status);
}
foreach (dbFetchRows($sql, $param) as $map_devices) {
$icon = 'greenMarker';
$z_offset = 0;
$tmp_loc = parse_location($map_devices['location']);
if (is_numeric($tmp_loc['lat']) && is_numeric($tmp_loc['lng'])) {
$map_devices['lat'] = $tmp_loc['lat'];
$map_devices['lng'] = $tmp_loc['lng'];
}
if ($map_devices['status'] == 0) {
if (AlertUtil::isMaintenance($map_devices['device_id'])) {
if ($show_status == 0) { // Don't show icon if only down devices should be shown
continue;
} else {
$icon = 'blueMarker';
$z_offset = 5000;
}
} else {
$icon = 'redMarker';
$z_offset = 10000; // move marker to foreground
}
}
$temp_output .= "var title = '<a href=\"" . \LibreNMS\Util\Url::deviceUrl((int) $map_devices['device_id']) . '"><img src="' . getIcon($map_devices) . '" width="32" height="32" alt=""> ' . format_hostname($map_devices) . "</a>';
var tooltip = '" . format_hostname($map_devices) . "';
var marker = L.marker(new L.LatLng(" . $map_devices['lat'] . ', ' . $map_devices['lng'] . "), {title: tooltip, icon: $icon, zIndexOffset: $z_offset});
marker.bindPopup(title);
markers.addLayer(marker);\n";
}
if (Config::get('network_map_show_on_worldmap')) {
if (Auth::user()->hasGlobalRead()) {
$sql = "
SELECT
ll.id AS left_id,
ll.lat AS left_lat,
ll.lng AS left_lng,
rl.id AS right_id,
rl.lat AS right_lat,
rl.lng AS right_lng,
sum(lp.ifHighSpeed) AS link_capacity,
sum(lp.ifOutOctets_rate) * 8 / sum(lp.ifSpeed) * 100 as link_out_usage_pct,
sum(lp.ifInOctets_rate) * 8 / sum(lp.ifSpeed) * 100 as link_in_usage_pct
FROM
devices AS ld,
devices AS rd,
links AS l,
locations AS ll,
locations AS rl,
ports as lp
WHERE
l.local_device_id = ld.device_id
AND l.remote_device_id = rd.device_id
AND ld.location_id != rd.location_id
AND ld.location_id = ll.id
AND rd.location_id = rl.id
AND lp.device_id = ld.device_id
AND lp.port_id = l.local_port_id
AND lp.ifType = 'ethernetCsmacd'
AND ld.disabled = 0
AND ld.ignore = 0
AND rd.disabled = 0
AND rd.ignore = 0
AND lp.ifOutOctets_rate != 0
AND lp.ifInOctets_rate != 0
AND lp.ifOperStatus = 'up'
AND ll.lat IS NOT NULL
AND ll.lng IS NOT NULL
AND rl.lat IS NOT NULL
AND rl.lng IS NOT NULL
AND ld.status IN " . dbGenPlaceholders(count($show_status)) . '
AND rd.status IN ' . dbGenPlaceholders(count($show_status)) . '
GROUP BY
left_id, right_id, ll.lat, ll.lng, rl.lat, rl.lng
';
$param = array_merge($show_status, $show_status);
} else {
$device_ids = Permissions::devicesForUser()->toArray() ?: [0];
$sql = "
SELECT
ll.id AS left_id,
ll.lat AS left_lat,
ll.lng AS left_lng,
rl.id AS right_id,
rl.lat AS right_lat,
rl.lng AS right_lng,
sum(lp.ifHighSpeed) AS link_capacity,
sum(lp.ifOutOctets_rate) * 8 / sum(lp.ifSpeed) * 100 as link_out_usage_pct,
sum(lp.ifInOctets_rate) * 8 / sum(lp.ifSpeed) * 100 as link_in_usage_pct
FROM
devices AS ld,
devices AS rd,
links AS l,
locations AS ll,
locations AS rl,
ports as lp
WHERE
l.local_device_id = ld.device_id
AND l.remote_device_id = rd.device_id
AND ld.location_id != rd.location_id
AND ld.location_id = ll.id
AND rd.location_id = rl.id
AND lp.device_id = ld.device_id
AND lp.port_id = l.local_port_id
AND lp.ifType = 'ethernetCsmacd'
AND ld.disabled = 0
AND ld.ignore = 0
AND rd.disabled = 0
AND rd.ignore = 0
AND lp.ifOutOctets_rate != 0
AND lp.ifInOctets_rate != 0
AND lp.ifOperStatus = 'up'
AND ll.lat IS NOT NULL
AND ll.lng IS NOT NULL
AND rl.lat IS NOT NULL
AND rl.lng IS NOT NULL
AND ld.status IN " . dbGenPlaceholders(count($show_status)) . '
AND rd.status IN ' . dbGenPlaceholders(count($show_status)) . '
AND ld.device_id IN ' . dbGenPlaceholders(count($device_ids)) . '
AND rd.device_id IN ' . dbGenPlaceholders(count($device_ids)) . '
GROUP BY
left_id, right_id, ll.lat, ll.lng, rl.lat, rl.lng
';
$param = array_merge($show_status, $show_status, $device_ids, $device_ids);
}
foreach (dbFetchRows($sql, $param) as $link) {
$icon = 'greenMarker';
$z_offset = 0;
$speed = $link['link_capacity'] / 1000;
if ($speed > 500000) {
$width = 20;
} else {
$width = round(0.77 * pow($speed, 0.25));
}
$link_used = max($link['link_out_usage_pct'], $link['link_in_usage_pct']);
$link_used = round(2 * $link_used, -1) / 2;
if ($link_used > 100) {
$link_used = 100;
}
if (is_nan($link_used)) {
$link_used = 0;
}
$link_color = Config::get("network_map_legend.$link_used");
$temp_output .= 'var marker = new L.Polyline([new L.LatLng(' . $link['left_lat'] . ', ' . $link['left_lng'] . '), new L.LatLng(' . $link['right_lat'] . ', ' . $link['right_lng'] . ")], {
color: '" . $link_color . "',
weight: " . $width . ',
opacity: 0.8,
smoothFactor: 1
});
markers.addLayer(marker);
';
}
}
$temp_output .= 'map.addLayer(markers);
map.scrollWheelZoom.disable();
$(document).ready(function(){
$("#leaflet-map").on("click", function(event) {
map.scrollWheelZoom.enable();
});
$("#leaflet-map").mouseleave(function(event) {
map.scrollWheelZoom.disable();
});
});
</script>';
} else {
$temp_output = 'Mapael engine not supported here';
}
unset($common_output);
$common_output[] = $temp_output;
| Java |
package com.bruce.android.knowledge.custom_view.scanAnimation;
/**
* @author zhenghao.qi
* @version 1.0
* @time 2015年11月09日14:45:32
*/
public class ScanAnimaitonStrategy implements IAnimationStrategy {
/**
* 起始X坐标
*/
private int startX;
/**
* 起始Y坐标
*/
private int startY;
/**
* 起始点到终点的Y轴位移。
*/
private int shift;
/**
* X Y坐标。
*/
private double currentX, currentY;
/**
* 动画开始时间。
*/
private long startTime;
/**
* 循环时间
*/
private long cyclePeriod;
/**
* 动画正在进行时值为true,反之为false。
*/
private boolean doing;
/**
* 进行动画展示的view
*/
private AnimationSurfaceView animationSurfaceView;
public ScanAnimaitonStrategy(AnimationSurfaceView animationSurfaceView, int shift, long cyclePeriod) {
this.animationSurfaceView = animationSurfaceView;
this.shift = shift;
this.cyclePeriod = cyclePeriod;
initParams();
}
public void start() {
startTime = System.currentTimeMillis();
doing = true;
}
/**
* 设置起始位置坐标
*/
private void initParams() {
int[] position = new int[2];
animationSurfaceView.getLocationInWindow(position);
this.startX = position[0];
this.startY = position[1];
}
/**
* 根据当前时间计算小球的X/Y坐标。
*/
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;
}
} | Java |
Wordpress 4.5.3 = 8fdd30960a4499c4e96caf8c5f43d6a2
Wordpress 4.1.13 = 9db7f2e6f8e36b05f7ced5f221e6254b
Wordpress 3.8.16 = 9ebe6182b84d541634ded7e953aec282
Wordpress 3.4.2 = d59b6610752b975950f30735688efc36
Wordpress 5.1.1 = 2cde4ea09e0a8414786efdcfda5b9ae4
Wordpress 5.3.1 = 3f2b1e00c430271c6b9e901cc0857800
| Java |
// 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 defaultHelpHoverTitle = "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("postBlockquoteCreation"); // 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.setUndoRedoButtonStates();
}, panels);
this.textOperation = function (f) {
undoManager.setCommandMode();
f();
that.refreshPreview();
}
}
uiManager = new UIManager(idPostfix, panels, undoManager, previewManager, commandManager, help);
uiManager.setUndoRedoButtonStates();
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/blockquote-glitch-in-editor-in-chrome-6-and-7/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) {
// IE
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.setInputAreaSelectionStartEnd();
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.setInputAreaSelection = 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.setInputAreaSelectionStartEnd = 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.setInputAreaSelection();
}
};
// Restore this state into the input area.
this.restore = function () {
if (stateObj.text != undefined && stateObj.text != inputArea.value) {
inputArea.value = stateObj.text;
}
this.setInputAreaSelection();
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, previewRefreshCallback) {
var managerObj = this;
var timeout;
var elapsedTime;
var oldInputText;
var maxDelay = 3000;
var startType = "delayed"; // The other legal value is "manual"
// 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 nonSuckyBrowserPreviewSet = function (text) {
panels.preview.innerHTML = text;
}
var previewSetter;
var previewSet = function (text) {
if (previewSetter)
return previewSetter(text);
try {
nonSuckyBrowserPreviewSet(text);
previewSetter = nonSuckyBrowserPreviewSet;
} catch (e) {
previewSetter = ieSafePreviewSet;
previewSetter(text);
}
};
var pushPreviewHtml = function (text) {
var emptyTop = position.getTop(panels.input) - getDocScrollTop();
if (panels.preview) {
previewSet(text);
previewRefreshCallback();
}
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 = "wmd-prompt-background";
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):\/\//, '$1://');
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.
makeSpritedButtonRow();
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.getElementsByTagName("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 makeSpritedButtonRow() {
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 || defaultHelpHoverTitle;
helpButton.onclick = helpOptions.handler;
setupButton(helpButton, true);
buttonRow.appendChild(helpButton);
buttons.help = helpButton;
}
setUndoRedoButtonStates();
}
function setUndoRedoButtonStates() {
if (undoManager) {
setupButton(buttons.undo, undoManager.canUndo());
setupButton(buttons.redo, undoManager.canRedo());
}
};
this.setUndoRedoButtonStates = setUndoRedoButtonStates;
}
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+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
// 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) {
// ( $1
// [^\\] 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;
// see e.g. http://meta.stackoverflow.com/questions/9807.
//
// 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)) { // a)
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)) { // b)
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)) { // d)
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.postBlockquoteCreation(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 = "----------\n";
chunk.selection = "";
chunk.skipLines(2, 1, true);
}
})();
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- 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>
<!-- ========= START OF TOP NAVBAR ======= -->
<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="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<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>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<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="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015. All rights reserved.</small></p>
</body>
</html>
| Java |
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 = -8825447220839372572L;
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("#", 0);
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;
}
}
| Java |
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');
});
| Java |
/*
* GNU LESSER GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*
* You can view LICENCE file for details.
*
* @author The Dragonet Team
*/
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;
}
}
| Java |
// BOINC Sentinels.
// https://projects.romwnet.org/boincsentinels
// Copyright (C) 2009-2014 Rom Walton
//
// BOINC Sentinels is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC Sentinels is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with BOINC Sentinels. If not, see <http://www.gnu.org/licenses/>.
//
#ifndef _NOTIFICATIONMANAGER_H_
#define _NOTIFICATIONMANAGER_H_
class CNotificationManager: public wxObject
{
DECLARE_NO_COPY_CLASS(CNotificationManager)
public:
CNotificationManager();
virtual ~CNotificationManager();
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
| Java |
/*
* LBFGS.java
*
* Copyright (C) 2016 Pavel Prokhorov (pavelvpster@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
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;
/**
* Limited-memory BFGS.
*
* https://en.wikipedia.org/wiki/Limited-memory_BFGS
*
* Liu, D. C.; Nocedal, J. (1989). "On the Limited Memory Method for Large Scale Optimization".
* Mathematical Programming B. 45 (3): 503–528. doi:10.1007/BF01589116.
*
*/
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 maxLineSearchIterations = 100;
/**
* Continue optimization if line search returns {@code MAX_ITERATION_REACHED}.
*/
private boolean continueOnMaxLineSearchIterations = 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 getMaxLineSearchIterations() {
return maxLineSearchIterations;
}
public void setMaxLineSearchIterations(int maxLineSearchIterations) {
this.maxLineSearchIterations = maxLineSearchIterations;
}
public boolean isContinueOnMaxLineSearchIterations() {
return continueOnMaxLineSearchIterations;
}
public void setContinueOnMaxLineSearchIterations(boolean continueOnMaxLineSearchIterations) {
this.continueOnMaxLineSearchIterations = continueOnMaxLineSearchIterations;
}
@Override
public OptimizationResult optimize() {
LOG.debug("Limited-memory BFGS optimize...");
final BacktrackingLineSearch lineSearch = new BacktrackingLineSearch(function);
lineSearch.setMaxIterations(maxLineSearchIterations);
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 = MAX_ITERATION_REACHED;
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 continueOptimization =
(lineSearchResult.getStatus() == MAX_ITERATION_REACHED) && continueOnMaxLineSearchIterations;
if (!continueOptimization) {
// 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;
}
}
| Java |
package cn.bjsxt.oop.staticInitBlock;
public class Parent001 /*extends Object*/ {
static int aa;
static {
System.out.println(" 静态初始化Parent001");
aa=200;
}
}
| Java |
using Fallout4Checklist.Entities;
namespace Fallout4Checklist.ViewModels
{
public class WeaponStatsViewModel
{
public WeaponStatsViewModel(Weapon weapon)
{
Weapon = weapon;
}
public Weapon Weapon { get; set; }
}
}
| Java |
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 pytest_collection_modifyitems(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
# https://github.com/pytest-dev/pytest/issues/1373 Will make this way easier
# 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)
| Java |
/*********************************************************
*********************************************************
** DO NOT EDIT **
** **
** THIS FILE AS BEEN GENERATED AUTOMATICALLY **
** BY UPA PORTABLE GENERATOR **
** (c) vpc **
** **
*********************************************************
********************************************************/
namespace Net.TheVpc.Upa.Impl.Uql
{
/**
* @author Taha BEN SALAH <taha.bensalah@gmail.com>
* @creationdate 11/19/12 7:22 PM
*/
public interface ExpressionDeclarationList {
System.Collections.Generic.IList<Net.TheVpc.Upa.Impl.Uql.ExpressionDeclaration> GetExportedDeclarations();
void ExportDeclaration(string name, Net.TheVpc.Upa.Impl.Uql.DecObjectType type, object referrerName, object referrerParentId);
System.Collections.Generic.IList<Net.TheVpc.Upa.Impl.Uql.ExpressionDeclaration> GetDeclarations(string alias);
Net.TheVpc.Upa.Impl.Uql.ExpressionDeclaration GetDeclaration(string name);
}
}
| Java |
/*
* Copyright (C) 2018 Johan Dykstrom
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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 AbstractJumpStatement extends AbstractNode implements Statement {
private final String jumpLabel;
protected AbstractJumpStatement(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;
AbstractJumpStatement that = (AbstractJumpStatement) o;
return Objects.equals(jumpLabel, that.jumpLabel);
}
@Override
public int hashCode() {
return Objects.hash(jumpLabel);
}
}
| Java |
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);
}
}
| Java |
/*
* Copyright (C) 2012 MineStar.de
*
* This file is part of Contao.
*
* Contao is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* Contao is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Contao. If not, see <http://www.gnu.org/licenses/>.
*/
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.getMinecraftNickname().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.getMinecraftNickname());
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.getMinecraftNickname());
if (mPlayer != null) {
mPlayer.setGroup(newGroup.getMinestarGroup());
}
}
public boolean canBeFree(User probeUser) {
// TODO: Implement requirements
return false;
}
}
| Java |
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 MasterSecretRequirementProvider implements RequirementProvider {
private final BroadcastReceiver newKeyReceiver;
private RequirementListener listener;
public MasterSecretRequirementProvider(Context context) {
this.newKeyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (listener != null) {
listener.onRequirementStatusChanged();
}
}
};
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;
}
}
| Java |
/*
* Copyright (C) 2017 Josua Frank
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
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 {
}
| Java |
<?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();
} | Java |
//------------------------------------------------------------------------------
// <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 CMSModules_Workflows_Workflow_Step_General {
/// <summary>
/// editElem control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMSModules_Workflows_Controls_UI_WorkflowStep_Edit editElem;
}
| Java |
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
}
}
| Java |
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: 'persona-personaPnombre',
error: 'El primer nombre es un campo obligatorio.'
};
}
if (_.isUndefined(attrs.persona.personaApaterno) || _.isEmpty(attrs.persona.personaApaterno.trim())) {
return {
field: 'persona-personaApaterno',
error: 'El apellido paterno es un campo obligatorio.'
};
}
if (_.isUndefined(attrs.persona.personaAmaterno) || _.isEmpty(attrs.persona.personaAmaterno.trim())) {
return {
field: 'persona-personaAmaterno',
error: 'El apellido materno es un campo obligatorio.'
};
}
}
});
}); | Java |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#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 scalar_product_traits<typename Lhs::Scalar, typename Rhs::Scalar>::ReturnType Scalar;
typedef typename promote_storage_type<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,
MaxRowsAtCompileTime = traits<Lhs>::MaxRowsAtCompileTime,
MaxColsAtCompileTime = traits<Rhs>::MaxColsAtCompileTime,
Flags = (MaxRowsAtCompileTime==1 ? RowMajorBit : 0)
| EvalBeforeNestingBit | EvalBeforeAssigningBit | NestByRefBit,
// Note that EvalBeforeNestingBit and NestByRefBit
// are not used in practice because nested is overloaded for products
CoeffReadCost = 0 // FIXME why is it needed ?
};
};
}
#define EIGEN_PRODUCT_PUBLIC_INTERFACE(Derived) \
typedef ProductBase<Derived, Lhs, Rhs > Base; \
EIGEN_DENSE_PUBLIC_INTERFACE(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;
EIGEN_DENSE_PUBLIC_INTERFACE(ProductBase)
typedef typename Lhs::Nested LhsNested;
typedef typename internal::remove_all<LhsNested>::type _LhsNested;
typedef internal::blas_traits<_LhsNested> LhsBlasTraits;
typedef typename LhsBlasTraits::DirectLinearAccessType 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::DirectLinearAccessType 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> FullyLazyCoeffBaseProductType;
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 FullyLazyCoeffBaseProductType,0> diagonal() const
{ return FullyLazyCoeffBaseProductType(m_lhs, m_rhs); }
template<int Index>
const Diagonal<FullyLazyCoeffBaseProductType,Index> diagonal() const
{ return FullyLazyCoeffBaseProductType(m_lhs, m_rhs); }
const Diagonal<FullyLazyCoeffBaseProductType,Dynamic> diagonal(Index index) const
{ return FullyLazyCoeffBaseProductType(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
EIGEN_STATIC_ASSERT_SIZE_1x1(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
{
EIGEN_STATIC_ASSERT_SIZE_1x1(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
{
EIGEN_STATIC_ASSERT_SIZE_1x1(Derived)
eigen_assert(this->rows() == 1 && this->cols() == 1);
return derived().coeffRef(row,col);
}
const Scalar& coeffRef(Index i) const
{
EIGEN_STATIC_ASSERT_SIZE_1x1(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;
// EIGEN_PRODUCT_PUBLIC_INTERFACE(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
| Java |
package de.unikiel.inf.comsys.neo4j.inference.sail;
/*
* #%L
* neo4j-sparql-extension
* %%
* Copyright (C) 2014 Niclas Hoyer
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
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.SailRepositoryConnection;
/**
* 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 SailBooleanExprQuery extends SailBooleanQuery {
public SailBooleanExprQuery(ParsedBooleanQuery booleanQuery, SailRepositoryConnection sailConnection) {
super(booleanQuery, sailConnection);
}
}
| Java |
#!/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.
# Copyright (C) 2009-2015 Grupo de desarrollo de Meran CeSPI-UNLP
# <desarrollo@cespi.unlp.edu.ar>
#
# This file is part of Meran.
#
# Meran is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Meran is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Meran. If not, see <http://www.gnu.org/licenses/>.
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->get_cat_registro_marc_n3(
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; | Java |
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 | Java |
#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"
// ▲ 攻击优先级1:攻击范围内,距离伙伴最近的正在攻击主人的所有目标>远一些的正在攻击主人的所有目标>距离伙伴最近的正在攻击伙伴自身的所有目标>远一些的正在攻击伙伴自身的所有目标>主人正在攻击的目标
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 < MAX_PARTNER_ATTACK_UNIT; ++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 < MAX_PARTNER_ATTACK_UNIT; ++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 < MAX_PARTNER_ATTACK_UNIT; ++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 (!check_distance_in_range(my_pos, his_pos, config->SkillRange))
// {
// //追击
// partner->reset_pos();
// if (get_circle_random_position_v2(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->cast_skill_to_target(skill_id, target);
// return 1;
// }
// }
// partner->reset_pos();
// partner->cast_immediate_skill_to_target(skill_id, target);
// //被反弹死了
// if (!partner->data)
// return 1;
// partner->data->skill_id = 0;
// //计算硬直时间
// partner->data->ontick_time += count_skill_delay_time(config);
// return 1;
}
struct partner_ai_interface partner_ai_1_interface =
{
.on_tick = partner_ai_tick_1,
.choose_target = choose_target,
};
| Java |
#!/bin/sh
yum update
| Java |
package redsgreens.Pigasus;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
/**
* Handle events for all Player related events
* @author redsgreens
*/
public class PigasusPlayerListener implements Listener {
private final Pigasus plugin;
public PigasusPlayerListener(Pigasus instance) {
plugin = instance;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event)
// catch player+entity events, looking for wand usage on an entity
{
Entity entity = event.getRightClicked();
// return if something not allowed was clicked
if(plugin.Config.getHoveringChance(entity) == -1) return;
Player player = event.getPlayer();
// return if the click was with something other than the wand
if(player.getItemInHand().getType() != plugin.Config.WandItem) return;
// check for permission
if(!plugin.isAuthorized(player, "wand") && !plugin.isAuthorized(player, "wand." + PigasusFlyingEntity.getType(entity).name().toLowerCase()))
{
if(plugin.Config.ShowErrorsInClient)
player.sendMessage("§cErr: " + plugin.Name + ": you don't have permission.");
return;
}
// checks passed, make this pig fly!
plugin.Manager.addEntity(entity);
}
}
| Java |
\section{Discussão}
\begin{itemize}
\item Consideração sobre comportamento e peculiaridades do Clang
\item Pressuposto uma vulnerabilidade por arquivo
\item Percentual baixo, porém comum
\item Maioria dos arquivos não obtiveram report
\end{itemize}
As vulnerabilidades e suas nomenclaturas identificadas pela ferramenta \"scan-build\" (presente na ferramenta Clang)
não estão alinhadas com as determinadas pelo NIST, sendo necessária, para este trabalho, uma aproximação. Foi levantada
a hipotése de existência de apenas uma vulnerabilidade por arquivo de teste. Deste modo, há a possibilidade de que
a quantidade de ocorrências de vulnerabilidades esperadas não corresponda à real. Entretanto, o modo de abordagem utilizado
diminui o impacto dessa possível discrepância.
O percentual de vulnerabilidades encontradas equivalentes as esperadas foi relativamente baixo, contudo, não foi
uma surpresa, já que a grande maioria das ferramentas possuem tal desempenho. O fato de não ter encontrado nenhuma
vulnerabilidade na grande maioria dos casos de teste influenciou bastante para o baixo percentual obtido, não estando, este fato,
relacionado a uma interpretação errônea, realmente apresentando um mal desempenho da ferramenta. No contexto dos casos de testes
que foram identificadas vulnerabilidades, pode ou não ter inconsistências, dependendo da acurácia da
hipótese levantada. No espaço amostral das arquivos que foram encontradas vulnerabilidades, cerca de um quinto das vulnerabilidades
encontradas foram equivalentes as esperadas, o que pode-se dizer satisfatório.
| Java |
/*
Original code by Lee Thomason (www.grinninglizard.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#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 --break-closing-brackets --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)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); }
# else
# include <assert.h>
# define TIXMLASSERT assert
# endif
#else
# define TIXMLASSERT( x ) {}
#endif
/* Versioning, past 1.0.14:
http://semver.org/
*/
static const int TIXML2_MAJOR_VERSION = 4;
static const int TIXML2_MINOR_VERSION = 0;
static const int TIXML2_PATCH_VERSION = 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 {
NEEDS_ENTITY_PROCESSING = 0x01,
NEEDS_NEWLINE_NORMALIZATION = 0x02,
NEEDS_WHITESPACE_COLLAPSING = 0x04,
TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION,
ATTRIBUTE_NAME = 0,
ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION,
COMMENT = NEEDS_NEWLINE_NORMALIZATION
};
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,
XML_WRONG_ATTRIBUTE_TYPE,
XML_ERROR_FILE_NOT_FOUND,
XML_ERROR_FILE_COULD_NOT_BE_OPENED,
XML_ERROR_FILE_READ_ERROR,
XML_ERROR_ELEMENT_MISMATCH,
XML_ERROR_PARSING_ELEMENT,
XML_ERROR_PARSING_ATTRIBUTE,
XML_ERROR_IDENTIFYING_TAG,
XML_ERROR_PARSING_TEXT,
XML_ERROR_PARSING_CDATA,
XML_ERROR_PARSING_COMMENT,
XML_ERROR_PARSING_DECLARATION,
XML_ERROR_PARSING_UNKNOWN,
XML_ERROR_EMPTY_DOCUMENT,
XML_ERROR_MISMATCHED_ELEMENT,
XML_ERROR_PARSING,
XML_CAN_NOT_CONVERT_TEXT,
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* PreviousSiblingElement( const char* name = 0 ) const ;
XMLElement* PreviousSiblingElement( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->PreviousSiblingElement( 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;
/** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the
XML tree will be conditionally visited and the host will be called back
via the XMLVisitor interface.
This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse
the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this
interface versus any other.)
The interface has been based on ideas from:
- http://www.saxproject.org/
- http://c2.com/cgi/wiki?HierarchicalVisitorPattern
Which are both good references for "visiting".
An example of using Accept():
@verbatim
XMLPrinter printer;
tinyxmlDoc.Accept( &printer );
const char* xmlcstr = printer.CStr();
@endverbatim
*/
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 XML_WRONG_ATTRIBUTE_TYPE 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;
QueryUnsignedAttribute( 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;
QueryDoubleAttribute( 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, XML_WRONG_ATTRIBUTE_TYPE 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 QueryUnsignedAttribute( 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 QueryDoubleAttribute( 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, XML_WRONG_ATTRIBUTE_TYPE 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 QueryUnsignedAttribute( 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 QueryDoubleAttribute( 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 = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, int value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, unsigned value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute(const char* name, int64_t value) {
XMLAttribute* a = FindOrCreateAttribute(name);
a->SetAttribute(value);
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, bool value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, double value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, float value ) {
XMLAttribute* a = FindOrCreateAttribute( 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, XML_CAN_NOT_CONVERT_TEXT 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* FindOrCreateAttribute( 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 PreviousSiblingElement( const char* name = 0 ) {
return XMLHandle( _node ? _node->PreviousSiblingElement( 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 PreviousSiblingElement( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node->PreviousSiblingElement( 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 SealElementIfJustOpened();
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 _restrictedEntityFlag[ENTITY_RANGE];
DynArray< char, 20 > _buffer;
};
} // tinyxml2
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // TINYXML2_INCLUDED
| Java |
package fi.metatavu.edelphi.jsons.queries;
import java.util.Locale;
import fi.metatavu.edelphi.smvcj.SmvcRuntimeException;
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.QueryPageHandlerFactory;
import fi.metatavu.edelphi.utils.ActionUtils;
import fi.metatavu.edelphi.utils.QueryDataUtils;
public class SaveQueryAnswersJSONRequestController extends JSONController {
public SaveQueryAnswersJSONRequestController() {
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 SmvcRuntimeException(EdelfoiStatusCode.CANNOT_SAVE_REPLY_QUERY_CLOSED, messages.getText(locale, "exception.1027.cannotSaveReplyQueryClosed"));
if (query.getState() == QueryState.EDIT) {
if (!ActionUtils.hasPanelAccess(jsonRequestContext, DelfoiActionName.MANAGE_DELFOI_MATERIALS.toString()))
throw new SmvcRuntimeException(EdelfoiStatusCode.CANNOT_SAVE_REPLY_QUERY_IN_EDIT_STATE, messages.getText(locale, "exception.1028.cannotSaveReplyQueryInEditState"));
}
else {
User loggedUser = null;
if (jsonRequestContext.isLoggedIn())
loggedUser = userDAO.findById(jsonRequestContext.getLoggedUserId());
QueryReply queryReply = QueryDataUtils.findQueryReply(jsonRequestContext, loggedUser, query);
if (queryReply == null) {
throw new SmvcRuntimeException(EdelfoiStatusCode.UNKNOWN_REPLICANT, messages.getText(locale, "exception.1026.unknownReplicant"));
}
queryReplyDAO.updateLastModified(queryReply, loggedUser);
QueryDataUtils.storeQueryReplyId(jsonRequestContext.getRequest().getSession(), queryReply);
QueryPageHandler queryPageHandler = QueryPageHandlerFactory.getInstance().buildPageHandler(queryPage.getPageType());
queryPageHandler.saveAnswers(jsonRequestContext, queryPage, queryReply);
}
}
}
| Java |
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 {
}
}
| Java |
## Versioning
All core-utils will remain `0.1.0` until the entirety of core-utils reaches
`1.0.0`.
## Issues
If a particular utility is at issue please prepend with issue with its name as
such: `"dd: not implemented"`
## Style
Standard Rust indentation is used. No use of globs, and use of namespaces must
be explicit, this rule does not apply for structures or enumerations, returns
must be explicit. External crates must be imported before any `use`s. For
example:
```Rust
// Bad (set_exit_status is a function)
use std::env::*
use std::env::{set_exit_status};
extern crate common;
use common::{Status};
// Good
extern crate common;
use common::{Status};
use std::env;
use std::path::{PathBuf};
```
Feel free to take a look at some of the source for the general structure of a
util
## Help, Versions
When writing help menus for any util, use the following structure:
```
$ util --help
Usage: util [OPTION...] [FILE...]
Useful utilitiy for doing things
Options:
-v --verbose Print things
-f --function Do things
Example:
util -vf file.txt Does and prints a thing
```
Append an elipses if the program takes more than one option/file
For printing versions use [`Prog.copyright`](lib/lib.rs).
## Commits
Commits must be well documented, and signed off on. See
[commits](https://github.com/0X1A/core-utils/commits/master) for examples
## License
All files must be prepended with:
```
// Copyright (C) YEAR, CONTRIBUTER <CONTRIBUTER EMAIL>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
```
| Java |
// -*- C++ -*-
//
// 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 DIALOGEVTCMDCHANGELEVEL_H
#define DIALOGEVTCMDCHANGELEVEL_H
#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 DialogEvtCmdChangeLevel: public wxDialog {
public:
// begin wxGlade: DialogEvtCmdChangeLevel::ids
// end wxGlade
DialogEvtCmdChangeLevel(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos=wxDefaultPosition, const wxSize& size=wxDefaultSize, long style=wxDEFAULT_DIALOG_STYLE);
private:
// begin wxGlade: DialogEvtCmdChangeLevel::methods
void set_properties();
void do_layout();
// end wxGlade
protected:
// begin wxGlade: DialogEvtCmdChangeLevel::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 // DIALOGEVTCMDCHANGELEVEL_H
| Java |
/***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera (herrera@decsai.ugr.es)
L. Sánchez (luciano@uniovi.es)
J. Alcalá-Fdez (jalcala@decsai.ugr.es)
S. GarcÃa (sglopez@ujaen.es)
A. Fernández (alberto.fernandez@ujaen.es)
J. Luengo (julianlm@decsai.ugr.es)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
**********************************************************************/
package keel.Algorithms.Genetic_Rule_Learning.RMini;
import java.util.StringTokenizer;
import org.core.Fichero;
import java.util.StringTokenizer;
/**
* <p>Title: Main Class of the Program</p>
*
* <p>Description: It reads the configuration file (data-set files and parameters) and launch the algorithm</p>
*
* <p>Company: KEEL</p>
*
* @author Jesús Jiménez
* @version 1.0
*/
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.parseConfigurationFile(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]);
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.