answer
stringlengths 15
1.25M
|
|---|
import sys, random
import re, collections, time
TXT_FILE='';
BUF_DIR='';
NWORDS=None;
def words(text): return re.findall('[a-z]+', text)
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
alphabet = '<API key>'
def edits1(word):
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in splits if b]
transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b]
inserts = [a + c + b for a, b in splits for c in alphabet]
return set(deletes + transposes + replaces + inserts)
def known_edits2(word):
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)
def known(words): return set(w for w in words if w in NWORDS)
def correct(word):
candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
return max(candidates, key=NWORDS.get)
if __name__ == '__main__':
TXT_FILE = sys.argv[1]
t0 = time.clock()
o_words = words(file(TXT_FILE).read())
NWORDS = train(o_words)
#print time.clock() - t0, " seconds build time"
#print "dictionary size: %d" %len(NWORDS)
et1 = time.clock() - t0
t_count = 10
rl = o_words[0:t_count] #random.sample(o_words, t_count)
orl = [''.join(random.sample(word, len(word))) for word in o_words]
t1 = time.clock()
r_count = 10
for i in range(0, r_count):
for w1, w2 in zip(rl, orl):
correct(w1); correct(w2)
et2 = (time.clock() - t1)/t_count/r_count/2
print '%d\t%f\t%f' %(len(NWORDS), et1, et2)
print 'Done'
|
<B_lastforums><div id="derniers-forums" class="listagebloc">
<h2><:derniers_forums:></h2>
<ul class="listageconteneur">
<BOUCLE_lastforums(FORUMS){!par date}{0,#ENV{parametre}}{plat}>
<li>
<h4 class="listagetitre"><a href="#URL_ARTICLE#forums">#TITRE</a></h4>
<div class="listageinfo">[(#DATE|affdate)][, <:par_auteur:> <a href="mailto:#EMAIL">(#NOM)</a>]</div>
<p class="listagetexte">[(#TEXTE|couper{220})]</p>
</li>
</BOUCLE_lastforums>
</ul>
</div></B_lastforums>
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>sensekey</title>
<link rel="stylesheet" type="text/css" href="csound.css" />
<link rel="stylesheet" type="text/css" href="syntax-highlighting.css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1" />
<link rel="home" href="index.html" title="The Canonical Csound Reference Manual" />
<link rel="up" href="OpcodesTop.html" title="Orchestra Opcodes and Operators" />
<link rel="prev" href="sense.html" title="sense" />
<link rel="next" href="serialBegin.html" title="serialBegin" />
</head>
<body>
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">sensekey</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="sense.html">Prev</a> </td>
<th width="60%" align="center">Orchestra Opcodes and Operators</th>
<td width="20%" align="right"> <a accesskey="n" href="serialBegin.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="refentry">
<a id="sensekey"></a>
<div class="titlepage"></div>
<a id="IndexSensekey" class="indexterm"></a>
<div class="refnamediv">
<h2>
<span class="refentrytitle">sensekey</span>
</h2>
<p>sensekey —
Returns the ASCII code of a key that has been pressed.
</p>
</div>
<div class="refsect1">
<a id="idm431456309440"></a>
<h2>Description</h2>
<p>
Returns the ASCII code of a key that has been pressed, or -1 if no key has been pressed.
</p>
</div>
<div class="refsect1">
<a id="idm431456308048"></a>
<h2>Syntax</h2>
<pre class="synopsis">kres[, kkeydown] <span class="command"><strong>sensekey</strong></span></pre>
</div>
<div class="refsect1">
<a id="idm431456306080"></a>
<h2>Performance</h2>
<p>
<span class="emphasis"><em>kres</em></span> - returns the ASCII value of a key which is pressed or released.
</p>
<p>
<span class="emphasis"><em>kkeydown</em></span> - returns 1 if the key was pressed, 0 if it was released or if there is no key event.
</p>
<p>
<span class="emphasis"><em>kres</em></span> can be used to read keyboard events from stdin and returns the ASCII value of any key that is pressed or released, or it returns -1 when there is no keyboard activity. The value of <span class="emphasis"><em>kkeydown</em></span> is 1 when a key was pressed, or 0 otherwise. This behavior is emulated by default, so a key release is generated immediately after every key press. To have full functionality, FLTK can be used to capture keyboard events. <a class="link" href="FLpanel.html" title="FLpanel"><em class="citetitle">FLpanel</em></a> can be used to capture keyboard events and send them to the sensekey opcode, by adding an additional optional argument. See <a class="link" href="FLpanel.html" title="FLpanel"><em class="citetitle">FLpanel</em></a> for more information.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<table border="0" summary="Note: Note">
<tr>
<td rowspan="2" align="center" valign="top" width="25">
<img alt="[Note]" src="images/note.png" />
</td>
<th align="left">Note</th>
</tr>
<tr>
<td align="left" valign="top">
<p>
This opcode can also be written as <a class="link" href="sense.html" title="sense"><em class="citetitle">sense</em></a>.
</p>
</td>
</tr>
</table>
</div>
</div>
<div class="refsect1">
<a id="idm431456297728"></a>
<h2>Examples</h2>
<p>
Here is an example of the sensekey opcode. It uses the file <a class="ulink" href="examples/sensekey.csd" target="_top"><em class="citetitle">sensekey.csd</em></a>.
</p>
<div class="example">
<a id="idm431456295920"></a>
<p class="title">
<strong>Example 884. Example of the sensekey opcode.</strong>
</p>
<div class="example-contents">
<p>See the sections <a class="link" href="UsingRealTime.html" title="Real-Time Audio"><em class="citetitle">Real-time Audio</em></a> and <a class="link" href="CommandFlags.html" title="Csound command line"><em class="citetitle">Command Line Flags</em></a> for more information on using command line flags.</p>
<div class="refsect1">
<a id="idm431823003600"></a>
<pre class="programlisting">
<span class="nt"><CsoundSynthesizer></span>
<span class="nt"><CsOptions></span>
<span class="c1">; Select audio/midi flags here according to platform</span>
<span class="c1">; Audio out Audio in</span>
-odac -iadc <span class="c1">;;;RT audio I/O</span>
<span class="c1">; For Non-realtime ouput leave only the line below:</span>
<span class="c1">; -o sensekey.wav -W ;;; for file output any platform</span>
<span class="nt"></CsOptions></span>
<span class="nt"><CsInstruments></span>
<span class="c1">; Initialize the global variables.</span>
<span class="vg">sr</span> <span class="o">=</span> <span class="mi">44100</span>
<span class="vg">kr</span> <span class="o">=</span> <span class="mi">4410</span>
<span class="vg">ksmps</span> <span class="o">=</span> <span class="mi">10</span>
<span class="vg">nchnls</span> <span class="o">=</span> <span class="mi">1</span>
<span class="c1">; Instrument #1.</span>
<span class="kd">instr</span> <span class="nf">1</span>
k<span class="n">1</span> <span class="nb">sensekey</span>
<span class="nb">printk2</span> k<span class="n">1</span>
<span class="kd">endin</span>
<span class="nt"></CsInstruments></span>
<span class="nt"><CsScore></span>
<span class="c1">; Play Instrument #1 for thirty seconds.</span>
<span class="nb">i</span> <span class="mi">1</span> <span class="mi">0</span> <span class="mi">30</span>
<span class="nb">e</span>
<span class="nt"></CsScore></span>
<span class="nt"></CsoundSynthesizer></span>
</pre>
</div>
</div>
</div>
<p><br class="example-break" />
Here is what the output should look like when the "q" button is pressed...
</p>
<pre class="screen">
q i1 113.00000
</pre>
<p>
</p>
<p>
Here is an example of the sensekey opcode in conjucntion with <a class="link" href="FLpanel.html" title="FLpanel"><em class="citetitle">FLpanel</em></a>. It uses the file <a class="ulink" href="examples/FLpanel-sensekey.csd" target="_top"><em class="citetitle">FLpanel-sensekey.csd</em></a>.
</p>
<div class="example">
<a id="idm431456289216"></a>
<p class="title">
<strong>Example 885. Example of the sensekey opcode using keyboard capture from an FLpanel.</strong>
</p>
<div class="example-contents">
<div class="refsect1">
<a id="idm431823457456"></a>
<pre class="programlisting">
<span class="nt"><CsoundSynthesizer></span>
<span class="nt"><CsOptions></span>
<span class="c1">; Select audio/midi flags here according to platform</span>
<span class="c1">; Audio out Audio in No messages</span>
-odac -iadc -d <span class="c1">;;;RT audio I/O</span>
<span class="c1">; For Non-realtime ouput leave only the line below:</span>
<span class="c1">; -o FLpanel-sensekey.wav -W ;;; for file output any platform</span>
<span class="nt"></CsOptions></span>
<span class="nt"><CsInstruments></span>
<span class="c1">; Example by Johnathan Murphy</span>
<span class="vg">sr</span> <span class="o">=</span> <span class="mi">44100</span>
<span class="vg">ksmps</span> <span class="o">=</span> <span class="mi">128</span>
<span class="vg">nchnls</span> <span class="o">=</span> <span class="mi">2</span>
<span class="c1">; ikbdcapture flag set to 1</span>
i<span class="n">key</span> <span class="nb">init</span> <span class="mi">1</span>
<span class="nb">FLpanel</span> <span class="s">"sensekey"</span><span class="p">,</span> <span class="mi">740</span><span class="p">,</span> <span class="mi">340</span><span class="p">,</span> <span class="mi">100</span><span class="p">,</span> <span class="mi">250</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> i<span class="n">key</span>
gk<span class="n">asc</span><span class="p">,</span> gi<span class="n">asc</span> <span class="nb">FLbutBank</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">16</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">700</span><span class="p">,</span> <span class="mi">300</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span>
<span class="nb">FLpanelEnd</span>
<span class="nb">FLrun</span>
<span class="kd">instr</span> <span class="nf">1</span>
k<span class="n">key</span> <span class="nb">sensekey</span>
k<span class="n">print</span> <span class="nb">changed</span> k<span class="n">key</span>
<span class="nb">FLsetVal</span> k<span class="n">print</span><span class="p">,</span> k<span class="n">key</span><span class="p">,</span> gi<span class="n">asc</span>
<span class="kd">endin</span>
<span class="nt"></CsInstruments></span>
<span class="nt"><CsScore></span>
<span class="nb">i</span><span class="mi">1</span> <span class="mi">0</span> <span class="mi">60</span>
<span class="nb">e</span>
<span class="nt"></CsScore></span>
<span class="nt"></CsoundSynthesizer></span>
</pre>
</div>
</div>
</div>
<p><br class="example-break" />
The lit button in the FLpanel window shows the last key pressed.
</p>
<p>
Here is a more complex example of the sensekey opcode in conjucntion with <a class="link" href="FLpanel.html" title="FLpanel"><em class="citetitle">FLpanel</em></a>. It uses the file <a class="ulink" href="examples/FLpanel-sensekey.csd" target="_top"><em class="citetitle">FLpanel-sensekey2.csd</em></a>.
</p>
<div class="example">
<a id="idm431456285456"></a>
<p class="title">
<strong>Example 886. Example of the sensekey opcode using keyboard capture from an FLpanel.</strong>
</p>
<div class="example-contents">
<div class="refsect1">
<a id="idm431823458336"></a>
<pre class="programlisting">
<span class="nt"><CsoundSynthesizer></span>
<span class="nt"><CsOptions></span>
<span class="c1">; Select audio/midi flags here according to platform</span>
<span class="c1">; Audio out Audio in No messages</span>
-odac <span class="c1">; -iadc -d ;;;RT audio I/O</span>
<span class="c1">; For Non-realtime ouput leave only the line below:</span>
<span class="c1">; -o FLpanel-sensekey2.wav -W ;;; for file output any platform</span>
<span class="nt"></CsOptions></span>
<span class="nt"><CsInstruments></span>
<span class="vg">sr</span> <span class="o">=</span> <span class="mi">48000</span>
<span class="vg">ksmps</span> <span class="o">=</span> <span class="mi">32</span>
<span class="vg">nchnls</span> <span class="o">=</span> <span class="mi">1</span>
<span class="c1">; Example by Istvan Varga</span>
<span class="c1">; if the FLTK opcodes are commented out, sensekey will read keyboard</span>
<span class="c1">; events from stdin</span>
<span class="nb">FLpanel</span> <span class="s">""</span><span class="p">,</span> <span class="mi">150</span><span class="p">,</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
<span class="nb">FLlabel</span> <span class="mi">18</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span>
<span class="nb">FLgroup</span> <span class="s">"Keyboard Input"</span><span class="p">,</span> <span class="mi">150</span><span class="p">,</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span>
<span class="nb">FLgroupEnd</span>
<span class="nb">FLpanelEnd</span>
<span class="nb">FLrun</span>
<span class="kd">instr</span> <span class="nf">1</span>
k<span class="n">trig1</span> <span class="nb">init</span> <span class="mi">1</span>
k<span class="n">trig2</span> <span class="nb">init</span> <span class="mi">1</span>
<span class="nl">nxtKey1</span><span class="p">:</span>
k<span class="n">1</span><span class="p">,</span> k<span class="n">2</span> <span class="nb">sensekey</span>
<span class="k">if</span> <span class="p">(</span>k<span class="n">1</span> <span class="o">!=</span> <span class="o">-</span><span class="mi">1</span> <span class="o">||</span> k<span class="n">2</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span> <span class="k">then</span>
<span class="nb">printf</span> <span class="s">"Key code = </span><span class="si">%02X</span><span class="s">, state = </span><span class="si">%d</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> k<span class="n">trig1</span><span class="p">,</span> k<span class="n">1</span><span class="p">,</span> k<span class="n">2</span>
k<span class="n">trig1</span> <span class="o">=</span> <span class="mi">3</span> <span class="o">-</span> k<span class="n">trig1</span>
<span class="k">kgoto</span> <span class="nl">nxtKey1</span>
<span class="k">endif</span>
<span class="nl">nxtKey2</span><span class="p">:</span>
k<span class="n">3</span> <span class="nb">sensekey</span>
<span class="k">if</span> <span class="p">(</span>k<span class="n">3</span> <span class="o">!=</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="k">then</span>
<span class="nb">printf</span> <span class="s">"Character = '</span><span class="si">%c</span><span class="s">'</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> k<span class="n">trig2</span><span class="p">,</span> k<span class="n">3</span>
k<span class="n">trig2</span> <span class="o">=</span> <span class="mi">3</span> <span class="o">-</span> k<span class="n">trig2</span>
<span class="k">kgoto</span> <span class="nl">nxtKey2</span>
<span class="k">endif</span>
<span class="kd">endin</span>
<span class="nt"></CsInstruments></span>
<span class="nt"><CsScore></span>
<span class="nb">i</span> <span class="mi">1</span> <span class="mi">0</span> <span class="mi">3600</span>
<span class="nb">e</span>
<span class="nt"></CsScore></span>
<span class="nt"></CsoundSynthesizer></span>
</pre>
</div>
</div>
</div>
<p><br class="example-break" />
The console output will look something like:
</p>
<div class="literallayout">
<p><br />
new alloc for instr 1:<br />
Key code = 65, state = 1<br />
Character = 'e'<br />
Key code = 65, state = 0<br />
Key code = 72, state = 1<br />
Character = 'r'<br />
Key code = 72, state = 0<br />
Key code = 61, state = 1<br />
Character = 'a'<br />
Key code = 61, state = 0<br />
</p>
</div>
<p>
</p>
</div>
<div class="refsect1">
<a id="idm431456282496"></a>
<h2>See also</h2>
<p>
<a class="link" href="FLpanel.html" title="FLpanel"><em class="citetitle">FLpanel</em></a>,
<a class="link" href="FLkeyIn.html" title="FLkeyIn"><em class="citetitle">FLkeyIn</em></a>
</p>
</div>
<div class="refsect1">
<a id="idm431456279552"></a>
<h2>Credits</h2>
<p>
</p>
<table border="0" summary="Simple list" class="simplelist">
<tr>
<td>Author: John ffitch</td>
</tr>
<tr>
<td>University of Bath, Codemist. Ltd.</td>
</tr>
<tr>
<td>Bath, UK</td>
</tr>
<tr>
<td>October 2000</td>
</tr>
</table>
<p>
</p>
<p>Examples written by Kevin Conder, Johnathan Murphy and Istvan Varga.</p>
<p>New in Csound version 4.09. Renamed in Csound version 4.10.</p>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="sense.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="OpcodesTop.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="serialBegin.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">sense </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> serialBegin</td>
</tr>
</table>
</div>
</body>
</html>
|
package com.baeldung.webflux;
import static java.time.LocalDateTime.now;
import static java.util.UUID.randomUUID;
import java.time.Duration;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import com.fasterxml.jackson.core.<API key>;
import com.fasterxml.jackson.databind.ObjectMapper;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component("<API key>")
public class <API key> implements WebSocketHandler {
ObjectMapper om = new ObjectMapper();
@Override
public Mono<Void> handle(WebSocketSession webSocketSession) {
Flux<String> <API key> = Flux.generate(sink -> {
<API key> event = new <API key>(randomUUID().toString(), now().toString());
try {
sink.next(om.writeValueAsString(event));
} catch (<API key> e) {
sink.error(e);
}
});
return webSocketSession.send(<API key>
.map(webSocketSession::textMessage)
.delayElements(Duration.ofSeconds(1)));
}
}
|
#ifndef <API key>
#define <API key>
#include "<API key>.h"
#include "<API key>.h"
/**
* greebo: A MultiState mover is an extension to the vanilla D3 movers.
*
* In contrast to the idElevator class, this multistate mover draws the floor
* information from the <API key> entities which are targetted
* by this class.
*
* The MultiStateMover will start moving when it's triggered (e.g. by buttons),
* where the information where to go is contained on the triggering button.
*
* Furthermore, the MultiStateMover provides a public interface for AI to
* help them figuring out which buttons to use, where to go, etc.
*/
class CMultiStateMover :
public idMover
{
idList<MoverPositionInfo> positionInfo;
idVec3 forwardDirection;
// The lists of buttons, AI entities need them to get the elevator moving
idList< idEntityPtr<<API key>> > fetchButtons;
idList< idEntityPtr<<API key>> > rideButtons;
// grayman #3050 - to help reduce jostling on the elevator
bool masterAtRideButton; // is the master in position to push the ride button?
UserManager riderManager; // manage a list of riders (which is different than users)
public:
CLASS_PROTOTYPE( CMultiStateMover );
CMultiStateMover();
void Spawn();
void Save(idSaveGame *savefile) const;
void Restore(idRestoreGame *savefile);
void Activate(idEntity* activator);
// Returns the list of position infos, populates the list if none are assigned yet.
const idList<MoverPositionInfo>& GetPositionInfoList();
/**
* greebo: Returns TRUE if this mover is at the given position.
* Note: NULL arguments always return false.
*/
bool IsAtPosition(<API key>* position);
/**
* greebo: This is called by the <API key> class exclusively to
* register the button with this Mover, so that the mover knows which buttons
* can be used to get it moving.
*
* @button: The button entity
* @type: The "use type" of the entity, e.g. "fetch" or "ride"
*/
void RegisterButton(<API key>* button, EMMButtonType type);
/**
* greebo: Returns the closest button entity for the given position and the given "use type".
*
* @toPosition: the position the elevator needs to go to (to be "fetched" to, to "ride" to).
* @fromPosition: the position the button needs to be accessed from (can be NULL for type == RIDE).
* @type: the desired type of button (fetch or ride)
* @riderOrg: the origin of the AI using the button (grayman #3029)
*
* @returns: NULL if nothing found.
*/
<API key>* GetButton(<API key>* toPosition, <API key>* fromPosition, EMMButtonType type, idVec3 riderOrg); // grayman #3029
// grayman #3050 - for ride management
bool <API key>();
void <API key>(bool atButton);
inline UserManager& GetRiderManager()
{
return riderManager;
}
protected:
// override idMover's DoneMoving() to trigger targets
virtual void DoneMoving();
private:
// greebo: Controls the direction of targetted rotaters, depending on the given moveTargetPosition
void SetGearDirection(const idVec3& targetPos);
// Returns the index of the named position info or -1 if not found
int <API key>(const idStr& name) const;
// Returns the index of the position info at the given position (using epsilon comparison)
int <API key>(const idVec3& pos) const;
// Returns the positioninfo entity of the given location or NULL if no suitable position found
<API key>* GetPositionEntity(const idVec3& pos) const;
// Extracts all position entities from the targets
void <API key>();
void Event_Activate(idEntity* activator);
void Event_PostSpawn();
/**
* grayman #4370: "Override" the TeamBlocked event to detect collisions with the player.
*/
virtual void OnTeamBlocked(idEntity* blockedEntity, idEntity* blockingEntity);
};
#endif /* <API key> */
|
describe SearchController, type: :controller do
it { is_expected.to route(:get, '/search').to(action: :basic) }
it { is_expected.to route(:get, '/search/entity').to(action: :entity_search) }
describe "GET #entity_search" do
login_user
let(:org) { build(:org) }
def <API key>
instance_double('EntitySearchService').tap do |d|
d.<API key>(:@search, [org])
end
end
it 'returns http status bad_request if missing param q' do
get :entity_search
expect(response).to have_http_status(:bad_request)
end
it "returns http success" do
allow(Entity).to receive(:search).with("@(name,aliases) name", any_args).and_return([org])
get :entity_search, params: { :q => 'name' }
expect(response).to have_http_status(:success)
end
it "hash includes url by default" do
allow(Entity).to receive(:search).with("@(name,aliases) name", any_args).and_return([org])
get :entity_search, params: { :q => 'name' }
expect(JSON.parse(response.body)[0]['url']).to include "/org/#{org.id}"
expect(JSON.parse(response.body)[0]).not_to have_key "is_parent"
end
it "hash can optionally include parent" do
allow(Entity).to receive(:search).with("@(name,aliases) name", any_args).and_return([org])
expect(org).to receive(:parent?).once.and_return(false)
get :entity_search, params: { :q => 'name', include_parent: true }
expect(JSON.parse(response.body)[0]['is_parent']).to eq false
end
end
end
|
<?php
namespace App\Model;
use PDO;
use Exception;
use App\Model;
use App\Config;
use App\Exceptions\ServerException;
use App\Exceptions\<API key>;
class Account extends Model
{
public $id;
public $name;
public $email;
public $service;
public $password;
public $is_active;
public $imap_host;
public $imap_port;
public $smtp_host;
public $smtp_port;
public $imap_flags;
public $created_at;
public function getData()
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'service' => $this->service,
'password' => $this->password,
'is_active' => $this->is_active,
'imap_host' => $this->imap_host,
'imap_port' => $this->imap_port,
'smtp_host' => $this->smtp_host,
'smtp_port' => $this->smtp_port,
'imap_flags' => $this->imap_flags,
'created_at' => $this->created_at
];
}
public function getActive()
{
return $this->db()
->select()
->from('accounts')
->where('is_active', '=', 1)
->execute()
->fetchAll(PDO::FETCH_CLASS, get_class());
}
public function getFirstActive()
{
$active = $this->getActive();
return $active
? current($active)
: null;
}
public function getByEmail(string $email)
{
$account = $this->db()
->select()
->from('accounts')
->where('email', '=', $email)
->execute()
->fetchObject();
return $account
? new self($account)
: null;
}
public function fromAddress()
{
return $this->name
? sprintf('%s <%s>', $this->name, $this->email)
: $this->email;
}
public function hasFolders()
{
return (new Folder)->countByAccount($this->id) > 0;
}
/**
* Updates the account configuration.
*/
public function update(
string $email,
string $password,
string $name,
string $imapHost,
int $imapPort,
string $smtpHost,
int $smtpPort
) {
if (! $this->exists()) {
return false;
}
$updated = $this->db()
->update([
'name' => trim($name),
'email' => trim($email),
'password' => trim($password),
'imap_host' => trim($imapHost),
'imap_port' => trim($imapPort),
'smtp_host' => trim($smtpHost),
'smtp_port' => trim($smtpPort)
])
->table('accounts')
->where('id', '=', $this->id)
->execute();
return is_numeric($updated) ? $updated : false;
}
/**
* Creates a new account with the class data. This is done only
* after the IMAP credentials are tested to be working.
*
* @throws ServerException
*
* @return Account
*/
public function create()
{
// Exit if it already exists!
if ($this->exists()) {
return false;
}
$service = Config::getEmailService($this->email);
list($imapHost, $imapPort) = Config::getImapSettings($this->email);
if ($imapHost) {
$this->imap_host = $imapHost;
$this->imap_port = $imapPort;
}
$data = [
'is_active' => 1,
'service' => $service,
'name' => trim($this->name),
'email' => trim($this->email),
'password' => trim($this->password),
'imap_host' => trim($this->imap_host),
'imap_port' => trim($this->imap_port),
'smtp_host' => trim($this->smtp_host),
'smtp_port' => trim($this->smtp_port),
'created_at' => $this->utcDate()->format(DATE_DATABASE)
];
try {
// Start a transaction to prevent storing bad data
$this->db()->beginTransaction();
$newAccountId = $this->db()
->insert(array_keys($data))
->into('accounts')
->values(array_values($data))
->execute();
if (! $newAccountId) {
throw new <API key>;
}
$this->db()->commit();
// Saved to the database
} catch (Exception $e) {
$this->db()->rollback();
throw new ServerException(
'Failed creating new account. '.$e->getMessage()
);
}
$this->id = $newAccountId;
return $this;
}
}
|
package org.vaadin.addons.guice.server;
import org.vaadin.addons.guice.servlet.<API key>;
import com.google.inject.servlet.ServletModule;
/**
*
* @author Will Temperley
*
*/
public class <API key> extends ServletModule {
@Override
protected void configureServlets() {
|
class <API key>
{
idd=-1;
movingenable=false;
class controls
{
class <API key>: RscFrame
{
idc = -1;
x = 0.365937 * safezoneW + safezoneX;
y = 0.379 * safezoneH + safezoneY;
w = 0.170156 * safezoneW;
h = 0.143 * safezoneH;
};
class <API key>: Box
{
idc = -1;
x = 0.365937 * safezoneW + safezoneX;
y = 0.379 * safezoneH + safezoneY;
w = 0.170156 * safezoneW;
h = 0.143 * safezoneH;
};
class <API key>: RscText
{
idc = -1;
text = "Waffenauswahl";
x = 0.365937 * safezoneW + safezoneX;
y = 0.39 * safezoneH + safezoneY;
w = 0.0773437 * safezoneW;
h = 0.022 * safezoneH;
};
class <API key>: RscCombo
{
idc = 2100;
x = 0.371094 * safezoneW + safezoneX;
y = 0.445 * safezoneH + safezoneY;
w = 0.159844 * safezoneW;
h = 0.022 * safezoneH;
};
class <API key>: RscButton
{
idc = 2101;
text = "OK";
x = 0.371094 * safezoneW + safezoneX;
y = 0.489 * safezoneH + safezoneY;
w = 0.0773437 * safezoneW;
h = 0.022 * safezoneH;
action = "(lbText [2100, lbCurSel 2100]) execVM ""Ammo\Dialog.sqf"";closeDialog 1;";
};
class <API key>: RscButton
{
idc = 2102;
text = "Abbruch";
x = 0.453594 * safezoneW + safezoneX;
y = 0.489 * safezoneH + safezoneY;
w = 0.0773437 * safezoneW;
h = 0.022 * safezoneH;
action = "closeDialog 2;";
};
};
};
|
CREATE TABLE "<API key>" (
"contributor" text,
"aggregate_donation" text
);
|
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class <API key> : <API key>
{
[Ordinal(1)] [RED("playerId")] public <API key> PlayerId { get; set; }
[Ordinal(2)] [RED("<API key>")] public <API key> <API key> { get; set; }
[Ordinal(3)] [RED("<API key>")] public inkWidgetReference <API key> { get; set; }
[Ordinal(4)] [RED("<API key>")] public CBool <API key> { get; set; }
public <API key>(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
|
#include "argList.H"
#include "Time.H"
#include "mirrorFvMesh.H"
#include "mapPolyMesh.H"
#include "hexRef8Data.H"
using namespace Foam;
int main(int argc, char *argv[])
{
#include "addOverwriteOption.H"
#include "addDictOption.H"
#include "setRootCase.H"
#include "createTime.H"
const bool overwrite = args.optionFound("overwrite");
const word dictName
(
args.<API key><word>("dict", "mirrorMeshDict")
);
mirrorFvMesh mesh
(
IOobject
(
mirrorFvMesh::defaultRegion,
runTime.constant(),
runTime
),
dictName
);
hexRef8Data refData
(
IOobject
(
"dummy",
mesh.facesInstance(),
polyMesh::meshSubDir,
mesh,
IOobject::READ_IF_PRESENT,
IOobject::NO_WRITE,
false
)
);
if (!overwrite)
{
runTime++;
mesh.setInstance(runTime.timeName());
}
// Set the precision of the points data to 10
IOstream::defaultPrecision(max(10u, IOstream::defaultPrecision()));
// Generate the mirrored mesh
const fvMesh& mMesh = mesh.mirrorMesh();
const_cast<fvMesh&>(mMesh).setInstance(mesh.facesInstance());
Info<< "Writing mirrored mesh" << endl;
mMesh.write();
// Map the hexRef8 data
mapPolyMesh map
(
mesh,
mesh.nPoints(), // nOldPoints,
mesh.nFaces(), // nOldFaces,
mesh.nCells(), // nOldCells,
mesh.pointMap(), // pointMap,
List<objectMap>(0), // pointsFromPoints,
labelList(0), // faceMap,
List<objectMap>(0), // facesFromPoints,
List<objectMap>(0), // facesFromEdges,
List<objectMap>(0), // facesFromFaces,
mesh.cellMap(), // cellMap,
List<objectMap>(0), // cellsFromPoints,
List<objectMap>(0), // cellsFromEdges,
List<objectMap>(0), // cellsFromFaces,
List<objectMap>(0), // cellsFromCells,
labelList(0), // reversePointMap,
labelList(0), // reverseFaceMap,
labelList(0), // reverseCellMap,
labelHashSet(0), // flipFaceFlux,
labelListList(0), // patchPointMap,
labelListList(0), // pointZoneMap,
labelListList(0), // faceZonePointMap,
labelListList(0), // faceZoneFaceMap,
labelListList(0), // cellZoneMap,
pointField(0), // preMotionPoints,
labelList(0), // oldPatchStarts,
labelList(0), // oldPatchNMeshPoints,
autoPtr<scalarField>() // oldCellVolumesPtr
);
refData.updateMesh(map);
refData.write();
Info<< "End" << endl;
return 0;
}
|
-- PostgreSQL database dump
-- Dumped from database version 10.6
-- Dumped by pg_dump version 10.6
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET <API key> = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET <API key> = false;
SET client_min_messages = warning;
ALTER TABLE IF EXISTS ONLY public.own_television DROP CONSTRAINT IF EXISTS pk_own_television;
DROP TABLE IF EXISTS public.own_television;
SET default_tablespace = '';
SET default_with_oids = false;
-- Name: own_television; Type: TABLE; Schema: public; Owner: -
CREATE TABLE public.own_television (
geo_level character varying(15) NOT NULL,
geo_code character varying(10) NOT NULL,
geo_version character varying(100) DEFAULT ''::character varying NOT NULL,
own_television character varying(128) NOT NULL,
total integer
);
-- Data for Name: own_television; Type: TABLE DATA; Schema: public; Owner: -
COPY public.own_television (geo_level, geo_code, geo_version, own_television, total) FROM stdin;
region 1 2009 No, don't own 91
region 1 2009 Yes, do own 29
region 2 2009 No, don't own 79
region 2 2009 Yes, do own 194
region 3 2009 No, don't own 91
region 3 2009 Yes, do own 5
region 4 2009 No, don't own 59
region 4 2009 Yes, do own 12
region 5 2009 No, don't own 41
region 5 2009 Yes, do own 7
region 6 2009 No, don't own 56
region 6 2009 Yes, do own 16
region 7 2009 No, don't own 38
region 7 2009 Yes, do own 18
region 8 2009 No, don't own 23
region 8 2009 Yes, do own 17
region 9 2009 No, don't own 16
region 9 2009 Yes, do own 8
region 10 2009 No, don't own 90
region 10 2009 Yes, do own 6
region 11 2009 No, don't own 54
region 11 2009 Yes, do own 34
region 12 2009 No, don't own 6
region 12 2009 Yes, do own 2
region 13 2009 No, don't own 18
region 13 2009 Yes, do own 6
region 14 2009 No, don't own 48
region 15 2009 No, don't own 53
region 15 2009 Yes, do own 11
region 16 2009 No, don't own 64
region 16 2009 Yes, do own 16
region 17 2009 No, don't own 38
region 17 2009 Yes, do own 26
region 30 2009 No, don't own 33
region 30 2009 Yes, do own 79
region 18 2009 No, don't own 104
region 18 2009 Yes, do own 16
region 19 2009 No, don't own 61
region 19 2009 Yes, do own 10
region 20 2009 No, don't own 103
region 20 2009 Yes, do own 21
region 21 2009 No, don't own 30
region 21 2009 Yes, do own 10
region 22 2009 No, don't own 61
region 22 2009 Yes, do own 11
region 23 2009 No, don't own 34
region 23 2009 Yes, do own 5
region 24 2009 No, don't own 68
region 24 2009 Yes, do own 4
region 25 2009 No, don't own 60
region 25 2009 Yes, do own 12
region 26 2009 No, don't own 61
region 26 2009 Yes, do own 3
region 27 2009 No, don't own 55
region 27 2009 Yes, do own 9
region 31 2009 Don't know 1
region 31 2009 No, don't own 59
region 31 2009 Yes, do own 12
region 29 2009 No, don't own 93
region 29 2009 Yes, do own 11
region 28 2009 No, don't own 59
region 28 2009 Yes, do own 29
country TZ 2009 Yes, do own 639
country TZ 2009 No, don't own 1746
country TZ 2009 Don't know 1
\.
-- Name: own_television pk_own_television; Type: CONSTRAINT; Schema: public; Owner: -
ALTER TABLE ONLY public.own_television
ADD CONSTRAINT pk_own_television PRIMARY KEY (geo_level, geo_code, geo_version, own_television);
-- PostgreSQL database dump complete
|
function c21520110.initial_effect(c)
--summon & set with no tribute
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(21520110,0))
e1:SetProperty(<API key>+<API key>)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SUMMON_PROC)
e1:SetCondition(c21520110.ntcon)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetDescription(aux.Stringid(21520110,2))
e2:SetCode(EFFECT_SET_PROC)
c:RegisterEffect(e2)
--recover
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(21520110,1))
e3:SetCategory(CATEGORY_RECOVER)
e3:SetType(EFFECT_TYPE_SINGLE+<API key>)
e3:SetCode(EVENT_BATTLE_DAMAGE)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(c21520110.reccon)
e3:SetTarget(c21520110.rectg)
e3:SetOperation(c21520110.recop)
c:RegisterEffect(e3)
end
function c21520110.filter(c)
return c:IsSetCard(0x491) and c:IsFaceup()
end
function c21520110.ntcon(e,c,minc)
if c==nil then return true end
return minc==0 and c:GetLevel()>4 and Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
and Duel.<API key>(c21520110.filter,tp,LOCATION_MZONE,0,1,nil)
end
function c21520110.reccon(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp
end
function c21520110.rectg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(ev)
Duel.SetOperationInfo(0,CATEGORY_RECOVER,0,0,tp,ev)
end
function c21520110.recop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,<API key>,<API key>)
Duel.Recover(p,d,REASON_EFFECT)
end
|
#include "Data/datadescriptor.h"
#include <type_traits>
#include <QDebug>
unsigned int DataDescriptor::_uid_ctr = 0;
DataDescriptor::DataDescriptor(QString name, QString unit, double factor, Type t) :
_name(name), _unit(unit), _factor(factor), _type(t)
{
_uuid = getUUID();
}
DataDescriptor::DataDescriptor(const QJsonObject &jo) {
_uuid = getUUID();
_name = jo["name"].toString();
_unit = jo["unit"].toString();
_factor = jo["factor"].toDouble();
_type = static_cast<Type>(jo["type"].toInt());
}
DataDescriptor::Type DataDescriptor::typeFromId(quint8 id) {
switch (id) {
case 0: return Type::CHAR;
case 1: return Type::FLOAT;
case 2: return Type::UINT16T;
case 3: return Type::BIGLITTLE;
default: return Type::UINT32T;
}
}
QString DataDescriptor::str() const {
QString test("%1 [%2] * %3");
return test.arg(_name,_unit,QString::number(_factor));
}
unsigned int DataDescriptor::getUUID() {
return _uid_ctr++;
}
QJsonObject DataDescriptor::json() const {
QJsonObject json;
json["name"] = _name;
json["unit"] = _unit;
json["factor"] = _factor;
json["type"] = static_cast<std::underlying_type<Type>::type>(_type);
return json;
}
|
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import collections
import six
from .comminfo import CommissionInfo
from .position import Position
from .metabase import MetaParams
from .order import Order, BuyOrder, SellOrder
class BrokerBack(six.with_metaclass(MetaParams, object)):
params = (('cash', 10000.0), ('commission', CommissionInfo()),)
def __init__(self):
self.comminfo = dict()
self.init()
def init(self):
if None not in self.comminfo.keys():
self.comminfo = dict({None: self.p.commission})
self.startingcash = self.cash = self.p.cash
self.orders = list() # will only be appending
self.pending = collections.deque() # popleft and append(right)
self.positions = collections.defaultdict(Position)
self.notifs = collections.deque()
def getcash(self):
return self.cash
def setcash(self, cash):
self.startingcash = self.cash = self.p.cash = cash
def getcommissioninfo(self, data):
if data._name in self.comminfo:
return self.comminfo[data._name]
return self.comminfo[None]
def setcommission(self, commission=0.0, margin=None, mult=1.0, name=None):
comm = CommissionInfo(commission=commission, margin=margin, mult=mult)
self.comminfo[name] = comm
def addcommissioninfo(self, comminfo, name=None):
self.comminfo[name] = comminfo
def start(self):
self.init()
def stop(self):
pass
def cancel(self, order):
try:
self.pending.remove(order)
except ValueError:
# If the list didn't have the element we didn't cancel anything
return False
order.cancel()
self.notify(order)
return True
def getvalue(self, datas=None):
pos_value = 0.0
for data in datas or self.positions.keys():
comminfo = self.getcommissioninfo(data)
position = self.positions[data]
pos_value += comminfo.getvalue(position, data.close[0])
return self.cash + pos_value
def getposition(self, data):
return self.positions[data]
def submit(self, order):
# FIXME: When an order is submitted, a margin check
# requirement has to be done before it can be accepted. This implies
# going over the entire list of pending orders for all datas and
# existing positions, simulating order execution and ending up
# with a "cash" figure that can be used to check the margin requirement
# of the order. If not met, the order can be immediately rejected
order.pannotated = None
order.plen = len(order.data)
order.accept()
self.orders.append(order)
self.pending.append(order)
self.notify(order)
return order
def buy(self, owner, data,
size, price=None, plimit=None,
exectype=None, valid=None):
order = BuyOrder(owner=owner, data=data,
size=size, price=price, pricelimit=plimit,
exectype=exectype, valid=valid)
return self.submit(order)
def sell(self, owner, data,
size, price=None, plimit=None,
exectype=None, valid=None):
order = SellOrder(owner=owner, data=data,
size=size, price=price, pricelimit=plimit,
exectype=exectype, valid=valid)
return self.submit(order)
def _execute(self, order, dt, price):
# Orders are fully executed, get operation size
size = order.executed.remsize
# Get comminfo object for the data
comminfo = self.getcommissioninfo(order.data)
# Adjust position with operation size
position = self.positions[order.data]
oldpprice = position.price
psize, pprice, opened, closed = position.update(size, price)
abopened, abclosed = abs(opened), abs(closed)
# if part/all of a position has been closed, then there has been
# a profitandloss ... record it
pnl = comminfo.profitandloss(abclosed, oldpprice, price)
if closed:
# Adjust to returned value for closed items & acquired opened items
closedvalue = comminfo.getoperationcost(abclosed, price)
self.cash += closedvalue
# Calculate and substract commission
closedcomm = comminfo.getcomm_pricesize(abclosed, price)
self.cash -= closedcomm
# Re-adjust cash according to future-like movements
# Restore cash which was already taken at the start of the day
self.cash -= comminfo.cashadjust(abclosed,
price,
order.data.close[0])
# pnl = comminfo.profitandloss(oldpsize, oldpprice, price)
else:
closedvalue = closedcomm = 0.0
if opened:
openedvalue = comminfo.getoperationcost(abopened, price)
self.cash -= openedvalue
openedcomm = comminfo.getcomm_pricesize(abopened, price)
self.cash -= openedcomm
# Remove cash for the new opened contracts
self.cash += comminfo.cashadjust(abopened,
price,
order.data.close[0])
else:
openedvalue = openedcomm = 0.0
# Execute and notify the order
order.execute(dt, size, price,
closed, closedvalue, closedcomm,
opened, openedvalue, openedcomm,
comminfo.margin, pnl,
psize, pprice)
self.notify(order)
def notify(self, order):
self.notifs.append(order.clone())
def next(self):
for data, pos in self.positions.items():
# futures change cash in the broker in every bar
# to ensure margin requirements are met
comminfo = self.getcommissioninfo(data)
self.cash += comminfo.cashadjust(pos.size,
data.close[-1],
data.close[0])
# Iterate once over all elements of the pending queue
for i in range(len(self.pending)):
order = self.pending.popleft()
if order.expire():
self.notify(order)
continue
popen = order.data.tick_open or order.data.open[0]
phigh = order.data.tick_high or order.data.high[0]
plow = order.data.tick_low or order.data.low[0]
pclose = order.data.tick_close or order.data.close[0]
pcreated = order.created.price
plimit = order.created.pricelimit
if order.exectype == Order.Market:
self._execute(order, order.data.datetime[0], price=popen)
elif order.exectype == Order.Close:
self._try_exec_close(order, pclose)
elif order.exectype == Order.Limit:
self._try_exec_limit(order, popen, phigh, plow, pcreated)
elif order.exectype == Order.StopLimit and order.triggered:
self._try_exec_limit(order, popen, phigh, plow, plimit)
elif order.exectype == Order.Stop:
self._try_exec_stop(order, popen, phigh, plow, pcreated)
elif order.exectype == Order.StopLimit:
self._try_exec_stoplimit(order,
popen, phigh, plow, pclose,
pcreated, plimit)
if order.alive():
self.pending.append(order)
def _try_exec_close(self, order, pclose):
if len(order.data) > order.plen:
dt0 = order.data.datetime[0]
if dt0 > order.dteos:
if order.pannotated:
execdt = order.data.datetime[-1]
execprice = pannotated
else:
execdt = dt0
execprice = pclose
self._execute(order, execdt, price=execprice)
return
# If no exexcution has taken place ... annotate the closing price
order.pannotated = pclose
def _try_exec_limit(self, order, popen, phigh, plow, plimit):
if order.isbuy():
if plimit >= popen:
# open smaller/equal than requested - buy cheaper
self._execute(order, order.data.datetime[0], price=popen)
elif plimit >= plow:
# day low below req price ... match limit price
self._execute(order, order.data.datetime[0], price=plimit)
else: # Sell
if plimit <= popen:
# open greater/equal than requested - sell more expensive
self._execute(order, order.data.datetime[0], price=popen)
elif plimit <= phigh:
# day high above req price ... match limit price
self._execute(order, order.data.datetime[0], price=plimit)
def _try_exec_stop(self, order, popen, phigh, plow, pcreated):
if order.isbuy():
if popen >= pcreated:
# price penetrated with an open gap - use open
self._execute(order, order.data.datetime[0], price=popen)
elif phigh >= pcreated:
# price penetrated during the session - use trigger price
self._execute(order, order.data.datetime[0], price=pcreated)
else: # Sell
if popen <= pcreated:
# price penetrated with an open gap - use open
self._execute(order, order.data.datetime[0], price=popen)
elif plow <= pcreated:
# price penetrated during the session - use trigger price
self._execute(order, order.data.datetime[0], price=pcreated)
def _try_exec_stoplimit(self, order,
popen, phigh, plow, pclose,
pcreated, plimit):
if order.isbuy():
if popen >= pcreated:
order.triggered = True
# price penetrated with an open gap
if plimit >= popen:
self._execute(order, order.data.datetime[0], price=popen)
elif plimit >= plow:
# execute in same bar
self._execute(order, order.data.datetime[0], price=plimit)
elif phigh >= pcreated:
# price penetrated upwards during the session
order.triggered = True
# can calculate execution for a few cases - datetime is fixed
dt = order.data.datetime[0]
if popen > pclose:
if plimit >= pcreated:
self._execute(order, dt, price=pcreated)
elif plimit >= pclose:
self._execute(order, dt, price=plimit)
else: # popen < pclose
if plimit >= pcreated:
self._execute(order, dt, price=pcreated)
else: # Sell
if popen <= pcreated:
# price penetrated downwards with an open gap
order.triggered = True
if plimit <= open:
self._execute(order, order.data.datetime[0], price=popen)
elif plimit <= phigh:
# execute in same bar
self._execute(order, order.data.datetime[0], price=plimit)
elif plow <= pcreated:
# price penetrated downwards during the session
order.triggered = True
# can calculate execution for a few cases - datetime is fixed
dt = order.data.datetime[0]
if popen <= pclose:
if plimit <= pcreated:
self._execute(order, dt, price=pcreated)
elif plimit <= pclose:
self._execute(order, dt, price=plimit)
else:
# popen > pclose
if plimit <= pcreated:
self._execute(order, dt, price=pcreated)
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.mariotaku.twidere.util.http;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.SecurityInfo;
import javax.microedition.io.SocketConnection;
import javax.microedition.io.StreamConnection;
import repackaged.com.sun.midp.pki.X509Certificate;
import repackaged.com.sun.midp.ssl.SSLStreamConnection;
/**
*
* @author mariotaku
*/
public final class UnsafeSSLConnection implements StreamConnection {
private final SSLStreamConnection sc;
UnsafeSSLConnection(final String host, final int port) throws IOException {
final SocketConnection tcp = (SocketConnection) Connector.open("socket://" + host + ":" + port);
tcp.setSocketOption(SocketConnection.DELAY, 0);
final InputStream tcpIn = tcp.openInputStream();
final OutputStream tcpOut = tcp.openOutputStream();
sc = new SSLStreamConnection(host, port, tcpIn, tcpOut);
}
public synchronized OutputStream openOutputStream() throws IOException {
return sc.openOutputStream();
}
public synchronized InputStream openInputStream() throws IOException {
return sc.openInputStream();
}
public DataOutputStream <API key>() throws IOException {
return sc.<API key>();
}
public DataInputStream openDataInputStream() throws IOException {
return sc.openDataInputStream();
}
public X509Certificate <API key>() {
return sc.<API key>();
}
public SecurityInfo getSecurityInfo() throws IOException {
return sc.getSecurityInfo();
}
public synchronized void close() throws IOException {
sc.close();
}
public static UnsafeSSLConnection open(final String host, final int port) throws IOException {
if (host == null && port < 0) {
return new UnsafeSSLConnection("127.0.0.1", 443);
} else if (host != null) {
return new UnsafeSSLConnection(host, 443);
}
return new UnsafeSSLConnection(host, port);
}
}
|
using System;
using System.Collections.Generic;
public class GraphDemo {
bool[] IsVisited;
// We are using Adjacency List instead of adjacency matrix to save space,
// for sparse graphs which is average case
List<int>[] AdjList;
// Nodes in the path being visited so far
int[] Path;
// Number of nodes so far encountered during the visit
int PathHopCount;
int PathCount = 0;
// Number of Vertices in the graph
int nV;
// Number of Edges
int nE;
int Source;
int Destination;
/*
* Takes input
* Build adjacency list graph representation
* Does input validation
*/
public void TakeInput() {
Console.WriteLine("Please enter number of vertices in the graph:");
nV = int.Parse(Console.ReadLine());
if (nV < 1)
throw new ArgumentException();
// As number of vertices is know at this point,
// Initialize (another way to do is to move this block to constructor)
Path = new int[nV];
PathHopCount = 0;
PathCount = 0;
AdjList = new List<int>[nV];
// by default C# compiler sets values in array to false
IsVisited = new bool[nV];
for (int i = 0; i < nV; i++)
AdjList[i] = new List<int>();
// Build adjacency list from given points
Console.WriteLine("Please enter number of edges:");
nE = int.Parse(Console.ReadLine());
if (nE < 0)
throw new ArgumentException();
Console.WriteLine("Please enter {0} of edges, one edge per line \"u v\" " +
"where 1 <= u <= {1} and 1 <= v <= {1}", nE, nV);
string[] tokens = null;
for (int i=0; i<nE; i++) {
tokens = Console.ReadLine().Split();
int u = int.Parse(tokens[0]) - 1;
int v = int.Parse(tokens[1]) - 1;
if (u < 0 || u >= nV || v < 0 || v >= nV)
throw new ArgumentException();
AdjList[u].Add(v);
AdjList[v].Add(u);
}
Console.WriteLine("Please provide source and destination:");
// reuse tokens variable, if it were reducing readability we would a new
// variable
tokens = Console.ReadLine().Split();
Source = int.Parse(tokens[0]) - 1;
Destination = int.Parse(tokens[1]) - 1;
if (Source < 0 || Source >= nV || Destination < 0 || Destination >= nV)
throw new ArgumentException();
}
/*
* Depth first search algorithm to find path from source to destination
* for the node of the graph passed as argument
* 1. We check if it's destination node (we avoid cycle)
* 2. If not then if the node is not visited in the same path then we visit
* its adjacent nodes
* To allow visiting same node in a different path we set visited to false
* for the node when we backtrack to a different path
*
* We store the visited paths for the node in Path variable and keep count
* of nodes in the path using variable PathHopCount. Path variable is
* reused for finding other paths.
*
* If we want to return list of all paths we can use a list of list to store
* all of them from this variable
*/
private void DFSVisit(int u) {
IsVisited[u] = true;
Path[PathHopCount++] = u;
if (u == Destination)
PrintPath();
else
foreach (int v in AdjList[u])
if (IsVisited[v] == false)
DFSVisit(v);
PathHopCount
IsVisited[u] = false;
}
/*
* Simply print nodes from array Path
* PathCount increments every time a new path is found.
*/
private void PrintPath() {
Console.WriteLine("Path {0}:", ++PathCount);
for (int i = 0; i < PathHopCount; i++)
if (i==0)
Console.Write(" {0}", Path[i] + 1);
else
Console.Write(" -> {0}", Path[i]+1);
Console.WriteLine();
}
public void ShowResult() {
Console.WriteLine("Listing paths from {0} to {1}.", Source+1, Destination+1);
DFSVisit(Source);
}
}
class Program {
static void Main(string[] args) {
GraphDemo graph_demo = new GraphDemo();
graph_demo.TakeInput();
graph_demo.ShowResult();
}
}
|
package keel.Algorithms.RE_SL_Methods.LEL_TSK;
import java.io.*;
import org.core.*;
import java.util.*;
import java.lang.Math;
class Simplif {
public double semilla;
public long cont_soluciones;
public long Gen, n_genes, n_reglas, n_generaciones;
public int n_soluciones;
public String fich_datos_chequeo, fich_datos_tst, fich_datos_val;
public String fichero_conf, ruta_salida;
public String fichero_br, fichero_reglas, fich_tra_obli, fich_tst_obli;
public String datos_inter = "";
public String cadenaReglas = "";
public MiDataset tabla, tabla_tst, tabla_val;
public BaseR_TSK base_reglas;
public BaseR_TSK base_total;
public Adap_Sel fun_adap;
public AG alg_gen;
public Simplif(String f_e) {
fichero_conf = f_e;
}
private String Quita_blancos(String cadena) {
StringTokenizer sT = new StringTokenizer(cadena, "\t ", false);
return (sT.nextToken());
}
/** Reads the data of the configuration file */
public void leer_conf() {
int i, j;
String cadenaEntrada, valor;
double cruce, mutacion, porc_radio_reglas, porc_min_reglas, alfa, tau;
int tipo_fitness, long_poblacion;
// we read the file in a String
cadenaEntrada = Fichero.leeFichero(fichero_conf);
StringTokenizer sT = new StringTokenizer(cadenaEntrada, "\n\r=", false);
// we read the algorithm's name
sT.nextToken();
sT.nextToken();
// we read the name of the training and test files
sT.nextToken();
valor = sT.nextToken();
StringTokenizer ficheros = new StringTokenizer(valor, "\t ", false);
fich_datos_chequeo = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
fich_datos_val = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
fich_datos_tst = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
// we read the name of the output files
sT.nextToken();
valor = sT.nextToken();
ficheros = new StringTokenizer(valor, "\t ", false);
fich_tra_obli = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
fich_tst_obli = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
String aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //Br inicial
aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
fichero_br = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de MAN2TSK
fichero_reglas = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de Select
aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de Tuning
ruta_salida = fich_tst_obli.substring(0, fich_tst_obli.lastIndexOf('/') + 1);
// we read the seed of the random generator
sT.nextToken();
valor = sT.nextToken();
semilla = Double.parseDouble(valor.trim());
Randomize.setSeed( (long) semilla); ;
for (i = 0; i < 19; i++) {
sT.nextToken(); //variable
sT.nextToken(); //valor
}
// we read the Number of Iterations
sT.nextToken();
valor = sT.nextToken();
n_generaciones = Long.parseLong(valor.trim());
// we read the Population Size
sT.nextToken();
valor = sT.nextToken();
long_poblacion = Integer.parseInt(valor.trim());
// we read the Tau parameter for the minimun maching degree required to the KB
sT.nextToken();
valor = sT.nextToken();
tau = Double.parseDouble(valor.trim());
// we read the Rate of Rules that don't are eliminated
sT.nextToken();
valor = sT.nextToken();
porc_min_reglas = Double.parseDouble(valor.trim());
// we read the Rate of rules to estimate the niche radio
sT.nextToken();
valor = sT.nextToken();
porc_radio_reglas = Double.parseDouble(valor.trim());
// we read the Alfa parameter for the Power Law
sT.nextToken();
valor = sT.nextToken();
alfa = Double.parseDouble(valor.trim());
// we read the Type of Fitness Function
sT.nextToken();
valor = sT.nextToken();
tipo_fitness = Integer.parseInt(valor.trim());
// we select the numero de soluciones
n_soluciones = 1;
// we read the Cross Probability
sT.nextToken();
valor = sT.nextToken();
cruce = Double.parseDouble(valor.trim());
// we read the Mutation Probability
sT.nextToken();
valor = sT.nextToken();
mutacion = Double.parseDouble(valor.trim());
// we create all the objects
tabla = new MiDataset(fich_datos_chequeo, false);
if (tabla.salir == false) {
tabla_val = new MiDataset(fich_datos_val, false);
tabla_tst = new MiDataset(fich_datos_tst, false);
base_total = new BaseR_TSK(fichero_br, tabla, true);
base_reglas = new BaseR_TSK(base_total.n_reglas, tabla);
fun_adap = new Adap_Sel(tabla, tabla_tst, base_reglas, base_total,
base_total.n_reglas, porc_radio_reglas,
porc_min_reglas, n_soluciones, tau, alfa,
tipo_fitness);
alg_gen = new AG(long_poblacion, base_total.n_reglas, cruce, mutacion,
fun_adap);
}
}
public void run() {
int i, j;
double ec, el, min_CR, ectst, eltst;
/* We read the configutate file and we initialize the structures and variables */
leer_conf();
if (tabla.salir == false) {
/* Inicializacion del contador de soluciones ya generadas */
cont_soluciones = 0;
System.out.println("Simplif-TSK");
do {
/* Generation of the initial population */
alg_gen.Initialize();
Gen = 0;
/* Evaluation of the initial population */
alg_gen.Evaluate();
Gen++;
/* Main of the genetic algorithm */
do {
/* Interchange of the new and old population */
alg_gen.Intercambio();
/* Selection by means of Baker */
alg_gen.Select();
/* Crossover */
alg_gen.Cruce_Multipunto();
/* Mutation */
alg_gen.Mutacion_Uniforme();
/* Elitist selection */
alg_gen.Elitist();
/* Evaluation of the current population */
alg_gen.Evaluate();
/* we increment the counter */
Gen++;
}
while (Gen <= n_generaciones);
/* we store the RB in the Tabu list */
if (Aceptar(alg_gen.solucion()) == 1) {
fun_adap.guardar_solucion(alg_gen.solucion());
/* we increment the number of solutions */
cont_soluciones++;
fun_adap.Decodifica(alg_gen.solucion());
fun_adap.Cubrimientos_Base();
/* we calcule the MSEs */
fun_adap.Error_tra();
ec = fun_adap.EC;
el = fun_adap.EL;
fun_adap.tabla_tst = tabla_tst;
fun_adap.Error_tst();
ectst = fun_adap.EC;
eltst = fun_adap.EL;
/* we calculate the minimum and maximum matching */
min_CR = 1.0;
for (i = 0; i < tabla.long_tabla; i++) {
min_CR = Adap.Minimo(min_CR, tabla.datos[i].maximo_cubrimiento);
}
/* we write the RB */
cadenaReglas = base_reglas.BRtoString();
cadenaReglas += "\n\nMinimum of C_R: " + min_CR +
" Minimum covering degree: " + fun_adap.mincb +
"\nAverage covering degree: " + fun_adap.medcb + " MLE: " + el +
"\nMSEtra: " + ec + " , MSEtst: " + ectst + "\n";
Fichero.escribeFichero(fichero_reglas, cadenaReglas);
/* we write the obligatory output files*/
String salida_tra = tabla.getCabecera();
salida_tra += fun_adap.getSalidaObli(tabla_val);
Fichero.escribeFichero(fich_tra_obli, salida_tra);
String salida_tst = tabla_tst.getCabecera();
salida_tst += fun_adap.getSalidaObli(tabla_tst);
Fichero.escribeFichero(fich_tst_obli, salida_tst);
/* we write the MSEs in specific files */
Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunR.txt", "" + base_reglas.n_reglas + "\n");
Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunTRA.txt", "" + ec + "\n");
Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunTST.txt", "" + ectst + "\n");
}
/* the multimodal GA finish when the condition is true */
}
while (Parada() == 0);
}
}
/** Criterion of stop */
public int Parada() {
if (cont_soluciones == n_soluciones) {
return (1);
}
else {
return (0);
}
}
/** Criterion to accept the solutions */
int Aceptar(char[] cromosoma) {
return (1);
}
}
|
package com.orcinuss.reinforcedtools.item.tools;
import com.google.common.collect.Sets;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import java.util.Set;
public class ItemRTMHarvester extends ItemTool{
private static final Set blocksToBreak = Sets.newHashSet(new Block[]{Blocks.glowstone});
public EnumRarity rarity;
public ItemRTMHarvester(Item.ToolMaterial material)
{
this(material, EnumRarity.common);
}
public ItemRTMHarvester(Item.ToolMaterial material, EnumRarity rarity ){
super(0.0F, material, blocksToBreak);
this.rarity = rarity;
this.maxStackSize = 1;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
namespace Admin.Models
{
public class FacilityClient
{
private string BASE_URL = "http://localhost:52249/api/";
public IEnumerable<Facility> findAll()
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.<API key>.Accept.Add(
new System.Net.Http.Headers.<API key>("application/json"));
HttpResponseMessage response = client.GetAsync("Facility").Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<IEnumerable<Facility>>().Result;
}
else
{
return null;
}
}
catch
{
return null;
}
}
public Facility find(int id)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.<API key>.Accept.Add(
new System.Net.Http.Headers.<API key>("application/json"));
HttpResponseMessage response = client.GetAsync("Facility/" + id).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<Facility>().Result;
}
else
{
return null;
}
}
catch
{
return null;
}
}
public bool Create(Facility Facility)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.<API key>.Accept.Add(
new System.Net.Http.Headers.<API key>("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("Facility", Facility).Result;
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
public bool Edit(Facility Facility)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.<API key>.Accept.Add(
new System.Net.Http.Headers.<API key>("application/json"));
HttpResponseMessage response = client.PutAsJsonAsync("Facility/" + Facility.facilityNumber, Facility).Result;
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
public bool Delete(int id)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.<API key>.Accept.Add(
new System.Net.Http.Headers.<API key>("application/json"));
HttpResponseMessage response = client.DeleteAsync("Facility/" + id).Result;
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
}
}
|
#include <Foundation/Foundation.h>
@interface MDLMemoryMappedData : NSObject
@end
|
/* <API key> handles all aspects of searching */
#ifndef <API key>
#define <API key>
#include <gtk/gtk.h>
#include <mucharmap/mucharmap.h>
#include "mucharmap-window.h"
G_BEGIN_DECLS
//class <API key>
#define <API key> (<API key> ())
#define <API key>(o) (<API key> ((o), <API key>, <API key>))
#define <API key>(k) (<API key>((k), <API key>, <API key>))
#define <API key>(o) (<API key> ((o), <API key>))
#define <API key>(k) (<API key> ((k), <API key>))
#define <API key>(o) (<API key> ((o), <API key>, <API key>))
typedef struct <API key> <API key>;
typedef struct <API key> <API key>;
struct <API key>
{
GtkDialog parent;
};
struct <API key>
{
GtkDialogClass parent_class;
/* signals */
void (* search_start) (void);
void (* search_finish) (gunichar found_char);
};
typedef enum
{
<API key> = -1,
<API key> = 1
}
MucharmapDirection;
GType <API key> (void);
GtkWidget * <API key> (MucharmapWindow *parent);
void <API key> (<API key> *search_dialog);
void <API key> (<API key> *search_dialog,
MucharmapDirection direction);
gdouble <API key> (<API key> *search_dialog);
G_END_DECLS
#endif /* #ifndef <API key> */
|
#include "XmlSerializer.h"
namespace dnc {
namespace Xml {
XmlSerializer::XmlSerializer() {}
XmlSerializer::~XmlSerializer() {}
std::string XmlSerializer::ToString() {
return std::string("System.Xml.XmlSerializer");
}
std::string XmlSerializer::GetTypeString() {
return std::string("XmlSerializer");
}
String XmlSerializer::ToXml(Serializable* obj, Collections::Generic::List<unsigned long long>& _childPtrs) {
unsigned long long hash = 0;
String res;
size_t len;
//Serializable* seri = nullptr;
/*if(std::is_same<T, Serializable*>::value) {
seri = (Serializable*) obj;
} else {
seri = static_cast<Serializable*>(&obj);
}*/
len = obj->AttrLen();
res = "<" + obj->Name() + " ID=\"" + obj->getHashCode() + "\">";
for(size_t i = 0; i < len; i++) {
<API key>& t = obj->Attribute(i);
// Get Values
String attrName = t.AttributeName();
Object& val = t.Member();
// Check Serializable
Serializable* child = dynamic_cast<Serializable*>(&val);
if(child == nullptr) {
// Just serialize
res += "<" + attrName + " type=\"" + val.GetTypeString() + "\">";
res += val.ToString();
res += "</" + attrName + ">";
} else {
// Is Serializable
hash = child->getHashCode();
if(_childPtrs.Contains(hash)) {
// Just add a reference
res += "<" + attrName + " ref=\"" + hash + "\"/>";
} else {
// Call serialize
_childPtrs.Add(hash);
res += "<" + attrName + " type=\"" + val.GetTypeString() + "\">";
res += ToXml(child, _childPtrs);
res += "</" + attrName + ">";
}
}
}
res += "</" + obj->Name() + ">\r\n";
return res;
}
}
}
|
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>AgeDetectedIssueCodeJava
*
* <p>
* <p>
* <pre>
* <simpleType name="<API key>">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="AGE"/>
* <enumeration value="DOSEHINDA"/>
* <enumeration value="DOSELINDA"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "<API key>")
@XmlEnum
public enum <API key> {
AGE,
DOSEHINDA,
DOSELINDA;
public String value() {
return name();
}
public static <API key> fromValue(String v) {
return valueOf(v);
}
}
|
<?php
defined('JPATH_PLATFORM') or die;
/**
* JDataSet is a collection class that allows the developer to operate on a set of JData objects as if they were in a
* typical PHP array.
*
* @since 12.3
*/
class JDataSet implements JDataDumpable, ArrayAccess, Countable, Iterator
{
/**
* The current position of the iterator.
*
* @var integer
* @since 12.3
*/
private $_current = false;
/**
* The iterator objects.
*
* @var array
* @since 12.3
*/
private $_objects = array();
/**
* The class constructor.
*
* @param array $objects An array of JData objects to bind to the data set.
*
* @since 12.3
* @throws <API key> if an object is not an instance of JData.
*/
public function __construct(array $objects = array())
{
// Set the objects.
$this->_initialise($objects);
}
/**
* The magic call method is used to call object methods using the iterator.
*
* Example: $array = $objectList->foo('bar');
*
* The object list will iterate over its objects and see if each object has a callable 'foo' method.
* If so, it will pass the argument list and assemble any return values. If an object does not have
* a callable method no return value is recorded.
* The keys of the objects and the result array are maintained.
*
* @param string $method The name of the method called.
* @param array $arguments The arguments of the method called.
*
* @return array An array of values returned by the methods called on the objects in the data set.
*
* @since 12.3
*/
public function __call($method, $arguments = array())
{
$return = array();
// Iterate through the objects.
foreach ($this->_objects as $key => $object)
{
// Create the object callback.
$callback = array($object, $method);
// Check if the callback is callable.
if (is_callable($callback))
{
// Call the method for the object.
$return[$key] = <API key>($callback, $arguments);
}
}
return $return;
}
/**
* The magic get method is used to get a list of properties from the objects in the data set.
*
* Example: $array = $dataSet->foo;
*
* This will return a column of the values of the 'foo' property in all the objects
* (or values determined by custom property setters in the individual JData's).
* The result array will contain an entry for each object in the list (compared to __call which may not).
* The keys of the objects and the result array are maintained.
*
* @param string $property The name of the data property.
*
* @return array An associative array of the values.
*
* @since 12.3
*/
public function __get($property)
{
$return = array();
// Iterate through the objects.
foreach ($this->_objects as $key => $object)
{
// Get the property.
$return[$key] = $object->$property;
}
return $return;
}
/**
* The magic isset method is used to check the state of an object property using the iterator.
*
* Example: $array = isset($objectList->foo);
*
* @param string $property The name of the property.
*
* @return boolean True if the property is set in any of the objects in the data set.
*
* @since 12.3
*/
public function __isset($property)
{
$return = array();
// Iterate through the objects.
foreach ($this->_objects as $object)
{
// Check the property.
$return[] = isset($object->$property);
}
return in_array(true, $return, true) ? true : false;
}
/**
* The magic set method is used to set an object property using the iterator.
*
* Example: $objectList->foo = 'bar';
*
* This will set the 'foo' property to 'bar' in all of the objects
* (or a value determined by custom property setters in the JData).
*
* @param string $property The name of the property.
* @param mixed $value The value to give the data property.
*
* @return void
*
* @since 12.3
*/
public function __set($property, $value)
{
// Iterate through the objects.
foreach ($this->_objects as $object)
{
// Set the property.
$object->$property = $value;
}
}
/**
* The magic unset method is used to unset an object property using the iterator.
*
* Example: unset($objectList->foo);
*
* This will unset all of the 'foo' properties in the list of JData's.
*
* @param string $property The name of the property.
*
* @return void
*
* @since 12.3
*/
public function __unset($property)
{
// Iterate through the objects.
foreach ($this->_objects as $object)
{
unset($object->$property);
}
}
/**
* Gets the number of data objects in the set.
*
* @return integer The number of objects.
*
* @since 12.3
*/
public function count()
{
return count($this->_objects);
}
/**
* Clears the objects in the data set.
*
* @return JDataSet Returns itself to allow chaining.
*
* @since 12.3
*/
public function clear()
{
$this->_objects = array();
$this->rewind();
return $this;
}
/**
* Get the current data object in the set.
*
* @return JData The current object, or false if the array is empty or the pointer is beyond the end of the elements.
*
* @since 12.3
*/
public function current()
{
return is_scalar($this->_current) ? $this->_objects[$this->_current] : false;
}
/**
* Dumps the data object in the set, recursively if appropriate.
*
* @param integer $depth The maximum depth of recursion (default = 3).
* For example, a depth of 0 will return a stdClass with all the properties in native
* form. A depth of 1 will recurse into the first level of properties only.
* @param SplObjectStorage $dumped An array of already serialized objects that is used to avoid infinite loops.
*
* @return array An associative array of the date objects in the set, dumped as a simple PHP stdClass object.
*
* @see JData::dump()
* @since 12.3
*/
public function dump($depth = 3, SplObjectStorage $dumped = null)
{
// Check if we should initialise the recursion tracker.
if ($dumped === null)
{
$dumped = new SplObjectStorage;
}
// Add this object to the dumped stack.
$dumped->attach($this);
$objects = array();
// Make sure that we have not reached our maximum depth.
if ($depth > 0)
{
// Handle JSON serialization recursively.
foreach ($this->_objects as $key => $object)
{
$objects[$key] = $object->dump($depth, $dumped);
}
}
return $objects;
}
/**
* Gets the data set in a form that can be serialised to JSON format.
*
* Note that this method will not return an associative array, otherwise it would be encoded into an object.
* JSON decoders do not consistently maintain the order of associative keys, whereas they do maintain the order of arrays.
*
* @param mixed $serialized An array of objects that have already been serialized that is used to infinite loops
* (null on first call).
*
* @return array An array that can be serialised by json_encode().
*
* @since 12.3
*/
public function jsonSerialize($serialized = null)
{
// Check if we should initialise the recursion tracker.
if ($serialized === null)
{
$serialized = array();
}
// Add this object to the serialized stack.
$serialized[] = spl_object_hash($this);
$return = array();
// Iterate through the objects.
foreach ($this->_objects as $object)
{
// Call the method for the object.
$return[] = $object->jsonSerialize($serialized);
}
return $return;
}
/**
* Gets the key of the current object in the iterator.
*
* @return scalar The object key on success; null on failure.
*
* @since 12.3
*/
public function key()
{
return $this->_current;
}
/**
* Gets the array of keys for all the objects in the iterator (emulates array_keys).
*
* @return array The array of keys
*
* @since 12.3
*/
public function keys()
{
return array_keys($this->_objects);
}
/**
* Advances the iterator to the next object in the iterator.
*
* @return void
*
* @since 12.3
*/
public function next()
{
// Get the object offsets.
$keys = $this->keys();
// Check if _current has been set to false but offsetUnset.
if ($this->_current === false && isset($keys[0]))
{
// This is a special case where offsetUnset was used in a foreach loop and the first element was unset.
$this->_current = $keys[0];
}
else
{
// Get the current key.
$position = array_search($this->_current, $keys);
// Check if there is an object after the current object.
if ($position !== false && isset($keys[$position + 1]))
{
// Get the next id.
$this->_current = $keys[$position + 1];
}
else
{
// That was the last object or the internal properties have become corrupted.
$this->_current = null;
}
}
}
/**
* Checks whether an offset exists in the iterator.
*
* @param mixed $offset The object offset.
*
* @return boolean True if the object exists, false otherwise.
*
* @since 12.3
*/
public function offsetExists($offset)
{
return isset($this->_objects[$offset]);
}
/**
* Gets an offset in the iterator.
*
* @param mixed $offset The object offset.
*
* @return JData The object if it exists, null otherwise.
*
* @since 12.3
*/
public function offsetGet($offset)
{
return isset($this->_objects[$offset]) ? $this->_objects[$offset] : null;
}
/**
* Sets an offset in the iterator.
*
* @param mixed $offset The object offset.
* @param JData $object The object object.
*
* @return void
*
* @since 12.3
* @throws <API key> if an object is not an instance of JData.
*/
public function offsetSet($offset, $object)
{
// Check if the object is a JData object.
if (!($object instanceof JData))
{
throw new <API key>(sprintf('%s("%s", *%s*)', __METHOD__, $offset, gettype($object)));
}
// Set the offset.
$this->_objects[$offset] = $object;
}
/**
* Unsets an offset in the iterator.
*
* @param mixed $offset The object offset.
*
* @return void
*
* @since 12.3
*/
public function offsetUnset($offset)
{
if (!$this->offsetExists($offset))
{
// Do nothing if the offset does not exist.
return;
}
// Check for special handling of unsetting the current position.
if ($offset == $this->_current)
{
// Get the current position.
$keys = $this->keys();
$position = array_search($this->_current, $keys);
// Check if there is an object before the current object.
if ($position > 0)
{
// Move the current position back one.
$this->_current = $keys[$position - 1];
}
else
{
// We are at the start of the keys AND let's assume we are in a foreach loop and `next` is going to be called.
$this->_current = false;
}
}
unset($this->_objects[$offset]);
}
/**
* Rewinds the iterator to the first object.
*
* @return void
*
* @since 12.3
*/
public function rewind()
{
// Set the current position to the first object.
if (empty($this->_objects))
{
$this->_current = false;
}
else
{
$keys = $this->keys();
$this->_current = array_shift($keys);
}
}
/**
* Validates the iterator.
*
* @return boolean True if valid, false otherwise.
*
* @since 12.3
*/
public function valid()
{
// Check the current position.
if (!is_scalar($this->_current) || !isset($this->_objects[$this->_current]))
{
return false;
}
return true;
}
/**
* Initialises the list with an array of objects.
*
* @param array $input An array of objects.
*
* @return void
*
* @since 12.3
* @throws <API key> if an object is not an instance of JData.
*/
private function _initialise(array $input = array())
{
foreach ($input as $key => $object)
{
if (!is_null($object))
{
$this->offsetSet($key, $object);
}
}
$this->rewind();
}
}
|
package medium_challenges;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class BenderSolution {
public static void main(String args[]) {
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int R = in.nextInt();
int C = in.nextInt();
in.nextLine();
List<Node> teleports = new ArrayList<>();
Node start = null;
// Create (x,y) map and store starting point
char[][] map = new char[C][R];
for (int y = 0; y < R; y++) {
String row = in.nextLine();
for (int x = 0; x < C; x++){
char item = row.charAt(x);
map[x][y] = item;
if (item == '@') {
start = new Node(x,y);
}
if (item == 'T') {
teleports.add(new Node(x,y));
}
}
}
// Create new robot with map
Bender bender = new Bender(start, map, teleports);
// Limit iterations
boolean circular = false;
final int MAX_ITERATIONS = 200;
// Collect all moves.
List<String> moves = new ArrayList<>();
while (bender.alive && !circular) {
moves.add(bender.move());
circular = moves.size() > MAX_ITERATIONS;
}
// Output Result
if (circular) System.out.println("LOOP");
else {
for (String s: moves) System.out.println(s);
}
}
/** Simple object to store coordinate pair */
private static class Node {
final int x, y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
/** Object to store state and behavior of Bender */
private static class Bender {
Node position;
char[][] map;
boolean directionToggle;
boolean alive;
Direction facing;
boolean beerToggle;
List<Node> teleports;
/** Direction enum includes the ability to find next node based on direction Bender is facing.
*/
private enum Direction {
SOUTH(0, 1), EAST(1, 0), NORTH(0, -1), WEST(-1, 0);
private int dx;
private int dy;
Direction (int dx, int dy) {
this.dx = dx;
this.dy = dy;
}
public Node newNode(Node original) {
return new Node(original.x + dx, original.y + dy);
}
public Direction nextDirection(boolean toggle) {
if (toggle) {
switch (this) {
case SOUTH: return EAST;
case EAST: return NORTH;
default: return WEST;
}
} else {
switch (this) {
case WEST: return NORTH;
case NORTH: return EAST;
default: return SOUTH;
}
}
}
}
public Bender(Node start, char[][] map, List<Node> teleports) {
this.position = start;
this.map = map;
this.alive = true;
this.facing = Direction.SOUTH;
this.directionToggle = true;
this.beerToggle = false;
this.teleports = teleports;
}
/** Updates the state of bender.
Returns direction of the move.
*/
public String move() {
char currentContent = map[position.x][position.y];
// Check for Teleporters
if (currentContent == 'T') {
position = (teleports.get(0).equals(position)) ? teleports.get(1) : teleports.get(0);
}
// Check for immediate move command
if ((""+currentContent).matches("[NESW]")) {
switch (currentContent) {
case 'N': facing = Direction.NORTH; position = facing.newNode(position); return Direction.NORTH.toString();
case 'W': facing = Direction.WEST; position = facing.newNode(position); return Direction.WEST.toString();
case 'S': facing = Direction.SOUTH; position = facing.newNode(position); return Direction.SOUTH.toString();
default: facing = Direction.EAST; position = facing.newNode(position); return Direction.EAST.toString();
}
}
// Check for inversion
if (currentContent == 'I') {
directionToggle = !directionToggle;
}
// Check for beer
if (currentContent == 'B') {
beerToggle = !beerToggle;
}
// Trial next possibility
Node trial = facing.newNode(position);
char content = map[trial.x][trial.y];
// Check if Bender dies
if (content == '$') {
alive = false;
return facing.toString();
}
// Check for beer power to remove X barrier
if (beerToggle && content == 'X') {
content = ' ';
map[trial.x][trial.y] = ' ';
}
// Check for Obstacles
boolean initialCheck = true;
while (content == 'X' || content == '
// Check for obstacles
if (content == 'X' || content == '
if (initialCheck) {
facing = directionToggle ? Direction.SOUTH : Direction.WEST;
initialCheck = false;
} else {
facing = facing.nextDirection(directionToggle);
}
}
// Update position and facing
trial = facing.newNode(position);
content = map[trial.x][trial.y];
}
// If we made it to this point, it's okay to move bender
position = facing.newNode(position);
if (content == '$') alive = false;
return facing.toString();
}
}
}
|
package me.zsj.moment.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.<API key>;
/**
* @author zsj
*/
public class CircleTransform extends <API key> {
public CircleTransform(Context context) {
super(context);
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squared.recycle();
return result;
}
@Override public String getId() {
return getClass().getName();
}
}
|
#ifndef OUTDOOR_PVP_HP_
#define OUTDOOR_PVP_HP_
#include "OutdoorPvP.h"
#define <API key> 6
// HP, citadel, ramparts, blood furnace, shattered halls, mag's lair
const uint32 <API key>[<API key>] = { 3483, 3563, 3562, 3713, 3714, 3836 };
enum OutdoorPvPHPSpells
{
<API key> = 32155,
<API key> = 32158,
AllianceBuff = 32071,
HordeBuff = 32049
};
enum <API key>
{
<API key> = 0,
HP_TOWER_OVERLOOK = 1,
HP_TOWER_STADIUM = 2,
HP_TOWER_NUM = 3
};
const uint32 HP_CREDITMARKER[HP_TOWER_NUM] = {19032, 19028, 19029};
const uint32 <API key>[HP_TOWER_NUM] = {11404, 11396, 11388};
const uint32 <API key>[HP_TOWER_NUM] = {11403, 11395, 11387};
enum <API key>
{
<API key> = 0x9ba,
<API key> = 0x9b9,
HP_UI_TOWER_COUNT_H = 0x9ae,
HP_UI_TOWER_COUNT_A = 0x9ac,
<API key> = 2475,
<API key> = 2474,
<API key> = 2473
};
const uint32 HP_MAP_N[HP_TOWER_NUM] = {0x9b5, 0x9b2, 0x9a8};
const uint32 HP_MAP_A[HP_TOWER_NUM] = {0x9b3, 0x9b0, 0x9a7};
const uint32 HP_MAP_H[HP_TOWER_NUM] = {0x9b4, 0x9b1, 0x9a6};
const uint32 HP_TowerArtKit_A[HP_TOWER_NUM] = {65, 62, 67};
const uint32 HP_TowerArtKit_H[HP_TOWER_NUM] = {64, 61, 68};
const uint32 HP_TowerArtKit_N[HP_TOWER_NUM] = {66, 63, 69};
const go_type HPCapturePoints[HP_TOWER_NUM] =
{
{182175, 530, -471.462f, 3451.09f, 34.6432f, 0.174533f, 0.0f, 0.0f, 0.087156f, 0.996195f}, // 0 - Broken Hill
{182174, 530, -184.889f, 3476.93f, 38.205f, -0.017453f, 0.0f, 0.0f, 0.008727f, -0.999962f}, // 1 - Overlook
{182173, 530, -290.016f, 3702.42f, 56.6729f, 0.034907f, 0.0f, 0.0f, 0.017452f, 0.999848f} // 2 - Stadium
};
const go_type HPTowerFlags[HP_TOWER_NUM] =
{
{183514, 530, -467.078f, 3528.17f, 64.7121f, 3.14159f, 0.0f, 0.0f, 1.0f, 0.0f}, // 0 broken hill
{182525, 530, -187.887f, 3459.38f, 60.0403f, -3.12414f, 0.0f, 0.0f, 0.999962f, -0.008727f}, // 1 overlook
{183515, 530, -289.610f, 3696.83f, 75.9447f, 3.12414f, 0.0f, 0.0f, 0.999962f, 0.008727f} // 2 stadium
};
class OPvPCapturePointHP : public OPvPCapturePoint
{
public:
OPvPCapturePointHP(OutdoorPvP* pvp, <API key> type);
void ChangeState();
void SendChangePhase();
void <API key>(WorldPacket & data);
// used when player is activated/inactivated in the area
bool HandlePlayerEnter(Player* player);
void HandlePlayerLeave(Player* player);
private:
<API key> m_TowerType;
};
class OutdoorPvPHP : public OutdoorPvP
{
public:
OutdoorPvPHP();
bool SetupOutdoorPvP();
void <API key>(Player* player, uint32 zone);
void <API key>(Player* player, uint32 zone);
bool Update(uint32 diff);
void <API key>(WorldPacket &data);
void <API key>(Player* player);
void HandleKillImpl(Player* player, Unit* killed);
uint32 <API key>() const;
void <API key>(uint32 count);
uint32 <API key>() const;
void <API key>(uint32 count);
private:
// how many towers are controlled
uint32 <API key>;
uint32 <API key>;
};
#endif
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>reordc_c</TITLE>
</HEAD>
<BODY style="color: rgb(0, 0, 0); background-color: rgb(255, 255, 255);">
<A name="TOP"></A>
<table style="text-align: left; margin-left: auto; margin-right: auto; width: 800px;"
border="0" cellpadding="5" cellspacing="2">
<tbody>
<tr>
<td style="background-color: rgb(153, 153, 153); vertical-align: middle; text-align: center;">
<div align="right">
<small><small><a href="index.html">Index Page</a></small></small>
</div>
<b>reordc_c</b> </td>
</tr>
<tr>
<td style="vertical-align: top;">
<small><div align="center">
<A HREF="index.html#A">A</A>
<A HREF="index.html#B">B</A>
<A HREF="index.html#C">C</A>
<A HREF="index.html#D">D</A>
<A HREF="index.html#E">E</A>
<A HREF="index.html#F">F</A>
<A HREF="index.html#G">G</A>
<A HREF="index.html#H">H</A>
<A HREF="index.html#I">I</A>
<A HREF="index.html#J">J</A>
<A HREF="index.html#K">K</A>
<A HREF="index.html#L">L</A>
<A HREF="index.html#M">M</A>
<A HREF="index.html#N">N</A>
<A HREF="index.html#O">O</A>
<A HREF="index.html#P">P</A>
<A HREF="index.html#Q">Q</A>
<A HREF="index.html#R">R</A>
<A HREF="index.html#S">S</A>
<A HREF="index.html#T">T</A>
<A HREF="index.html#U">U</A>
<A HREF="index.html#V">V</A>
<A HREF="index.html#W">W</A>
<A HREF="index.html#X">X</A>
</div></small>
<br>
<table style="text-align: left; width: 60%; margin-left: auto; margin-right: auto;"
border="0" cellspacing="2" cellpadding="2">
<tbody>
<tr>
<td style="width: 33%; text-align: center;">
<small>
<a href="#Procedure">Procedure<br></a>
<a href="#Abstract">Abstract<br></a>
<a href="#Required_Reading">Required_Reading<br></a>
<a href="#Keywords">Keywords<br></a>
<a href="#Brief_I/O">Brief_I/O<br></a>
<a href="#Detailed_Input">Detailed_Input<br></a>
</small>
</td>
<td style="vertical-align: top; width: 33%; text-align: center;">
<small> <a href="#Detailed_Output">Detailed_Output<br></a>
<a href="#Parameters">Parameters<br></a>
<a href="#Exceptions">Exceptions<br></a>
<a href="#Files">Files<br></a>
<a href="#Particulars">Particulars<br></a>
<a href="#Examples">Examples<br></a>
</small>
</td>
<td style="vertical-align: top; width: 33%; text-align: center;">
<small> <a href="#Restrictions">Restrictions<br></a>
<a href="#<API key>"><API key><br></a>
<a href="#<API key>><API key><br></a>
<a href="#Version">Version<br></a>
<a href="#Index_Entries">Index_Entries<br></a>
</small>
</td>
</tr>
</tbody>
</table>
<h4><a name="Procedure">Procedure</a></h4>
<PRE>
void reordc_c ( ConstSpiceInt * iorder,
SpiceInt ndim,
SpiceInt lenvals,
void * array )
</PRE>
<h4><a name="Abstract">Abstract</a></h4>
<PRE>
Re-order the elements of an array of character strings
according to a given order vector.
</PRE>
<h4><a name="Required_Reading">Required_Reading</a></h4>
<PRE>
None.
</PRE>
<h4><a name="Keywords">Keywords</a></h4>
<PRE>
ARRAY, SORT
</PRE>
<h4><a name="Brief_I/O">Brief_I/O</a></h4>
<PRE>
VARIABLE I/O DESCRIPTION
iorder I Order vector to be used to re-order array.
ndim I Dimension of array.
lenvals I String length.
array I/O Array to be re-ordered.
</PRE>
<h4><a name="Detailed_Input">Detailed_Input</a></h4>
<PRE>
iorder is the order vector to be used to re-order the input
array. The first element of iorder is the index of
the first item of the re-ordered array, and so on.
Note that the order imposed by <b>reordc_c</b> is not the
same order that would be imposed by a sorting
routine. In general, the order vector will have
been created (by one of the order routines) for
a related array, as illustrated in the example below.
The elements of iorder range from zero to ndim-1.
ndim is the number of elements in the input array.
lenvals is the declared length of the strings in the input
string array, including null terminators. The input
array should be declared with dimension
[ndim][lenvals]
array on input, is an array containing some number of
elements in unspecified order.
</PRE>
<h4><a name="Detailed_Output">Detailed_Output</a></h4>
<PRE>
array on output, is the same array, with the elements
in re-ordered as specified by iorder.
</PRE>
<h4><a name="Parameters">Parameters</a></h4>
<PRE>
None.
</PRE>
<h4><a name="Exceptions">Exceptions</a></h4>
<PRE>
1) If the input string array pointer is null, the error
SPICE(NULLPOINTER) will be signaled.
2) If the input array string's length is less than 2, the error
SPICE(STRINGTOOSHORT) will be signaled.
3) If memory cannot be allocated to create a Fortran-style version of
the input order vector, the error SPICE(MALLOCFAILED) is signaled.
4) If ndim < 2, this routine executes a no-op. This case is
not an error.
</PRE>
<h4><a name="Files">Files</a></h4>
<PRE>
None.
</PRE>
<h4><a name="Particulars">Particulars</a></h4>
<PRE>
<b>reordc_c</b> uses a cyclical algorithm to re-order the elements of
the array in place. After re-ordering, element iorder[0] of
the input array is the first element of the output array,
element iorder[1] of the input array is the second element of
the output array, and so on.
The order vector used by <b>reordc_c</b> is typically created for
a related array by one of the order*_c routines, as shown in
the example below.
</PRE>
<h4><a name="Examples">Examples</a></h4>
<PRE>
In the following example, the order*_c and reord*_c routines are
used to sort four related arrays (containing the names,
masses, integer ID codes, and visual magnitudes for a group
of satellites). This is representative of the typical use of
these routines.
#include "SpiceUsr.h"
.
.
.
/.
Sort the object arrays by name.
./
<a href="orderc_c.html">orderc_c</a> ( namlen, names, n, iorder );
<b>reordc_c</b> ( iorder, n, namlen, names );
<a href="reordd_c.html">reordd_c</a> ( iorder, n, masses );
<a href="reordi_c.html">reordi_c</a> ( iorder, n, codes );
<a href="reordd_c.html">reordd_c</a> ( iorder, n, vmags );
</PRE>
<h4><a name="Restrictions">Restrictions</a></h4>
<PRE>
None.
</PRE>
<h4><a name="<API key>"><API key></a></h4>
<PRE>
None.
</PRE>
<h4><a name="<API key>><API key></a></h4>
<PRE>
N.J. Bachman (JPL)
W.L. Taber (JPL)
I.M. Underwood (JPL)
</PRE>
<h4><a name="Version">Version</a></h4>
<PRE>
-CSPICE Version 1.0.0, 10-JUL-2002 (NJB) (WLT) (IMU)
</PRE>
<h4><a name="Index_Entries">Index_Entries</a></h4>
<PRE>
reorder a character array
</PRE>
</td>
</tr>
</tbody>
</table>
<pre>Tue Jul 15 14:31:41 2014</pre>
</body>
</html>
|
#ifndef __bidibidentdlg__
#define __bidibidentdlg__
/**
@file
Subclass of BidibIdentDlgGen, which is generated by wxFormBuilder.
*/
#include "bidibidendlggen.h"
#include "rocs/public/node.h"
#include "rocs/public/list.h"
#include "rocs/public/map.h"
#include "rocs/public/mutex.h"
/ end generated include
/** Implementing BidibIdentDlgGen */
class BidibIdentDlg : public BidibIdentDlgGen
{
iONode node;
iONode bidibnode;
iOList nodeList;
iOMap nodeMap;
iOMap nodePathMap;
iONode m_SelectedBidibNode;
iONode m_ProductsNode;
iOMap m_ProductsMap;
int macro;
int macroline;
int macrosize;
int macrolevel;
int macroparam;
bool macrosave;
bool macroapply;
int configL;
int configR;
int configV;
int configS;
int uid;
char* www;
iOMutex servoSetMutex;
bool eventUpdate;
wxTreeItemId findTreeItem( const wxTreeItemId& root, const wxString& text);
int getLevel(const char* path, int* n, int* o, int* p, char** key, char** parentkey);
wxTreeItemId addTreeChild( const wxTreeItemId& root, iONode bidibnode);
void handleFeature(iONode node);
void clearFeatureList();
void handleMacro(iONode node);
void handleAccessory(iONode node);
iONode findNodeByUID( const char* uid);
protected:
// Handlers for BidibIdentDlgGen events.
void onClose( wxCloseEvent& event );
void onCancel( wxCommandEvent& event );
void onOK( wxCommandEvent& event );
void onHelp( wxCommandEvent& event );
void onTreeSelChanged( wxTreeEvent& event );
void onBeginDrag( wxTreeEvent& event );
void onItemActivated( wxTreeEvent& event );
void onItemRightClick( wxTreeEvent& event );
void onMenu( wxCommandEvent& event );
void onFeatureSelect( wxCommandEvent& event );
void onFeaturesGet( wxCommandEvent& event );
void onFeatureSet( wxCommandEvent& event );
void onServoLeft( wxScrollEvent& event );
void onServoRight( wxScrollEvent& event );
void onServoSpeed( wxScrollEvent& event );
void onServoPort( wxSpinEvent& event );
void onServoLeftTest( wxCommandEvent& event );
void onServoRightTest( wxCommandEvent& event );
void onServoGet( wxCommandEvent& event );
void onPortSet( wxCommandEvent& event );
void onConfigL( wxSpinEvent& event );
void onConfigR( wxSpinEvent& event );
void onConfigV( wxSpinEvent& event );
void onConfigS( wxSpinEvent& event );
void onServoReserved( wxScrollEvent& event );
void onPortType( wxCommandEvent& event );
void onConfigLtxt( wxCommandEvent& event );
void onConfigRtxt( wxCommandEvent& event );
void onConfigVtxt( wxCommandEvent& event );
void onConfigStxt( wxCommandEvent& event );
void onSelectUpdateFile( wxCommandEvent& event );
void onUpdateStart( wxCommandEvent& event );
void onServoSet(bool overwrite=false);
void onPageChanged( wxNotebookEvent& event );
void onMacroList( wxCommandEvent& event );
void onMacroLineSelected( wxGridEvent& event );
void onMacroApply( wxCommandEvent& event );
void onMacroReload( wxCommandEvent& event );
void onMacroSave( wxCommandEvent& event );
void onMacroEveryMinute( wxCommandEvent& event );
void onMacroExport( wxCommandEvent& event );
void onMacroImport( wxCommandEvent& event );
void onMacroSaveMacro( wxCommandEvent& event );
void onMacroDeleteMacro( wxCommandEvent& event );
void onMacroRestoreMacro( wxCommandEvent& event );
void onMacroTest( wxCommandEvent& event );
void onVendorCVEnable( wxCommandEvent& event );
void onVendorCVDisable( wxCommandEvent& event );
void onVendorCVGet( wxCommandEvent& event );
void onVendorCVSet( wxCommandEvent& event );
void onAccessoryOnTest( wxCommandEvent& event );
void onAccessoryOffTest( wxCommandEvent& event );
void <API key>( wxCommandEvent& event );
void <API key>( wxCommandEvent& event );
void <API key>( wxCommandEvent& event );
void <API key>( wxCommandEvent& event );
void onLeftLogo( wxMouseEvent& event );
void onProductName( wxMouseEvent& event );
int getProductID(int uid);
void onReport( wxCommandEvent& event );
void onUsernameSet( wxCommandEvent& event );
public:
/** Constructor */
BidibIdentDlg( wxWindow* parent );
/ end generated class members
BidibIdentDlg( wxWindow* parent, iONode node );
~BidibIdentDlg();
void event(iONode node);
void initLabels();
void initValues();
void initProducts();
const char* GetProductName(int vid, int pid, char** www);
};
#endif // __bidibidentdlg__
|
package clientdata.visitors;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.HashMap;
import java.util.Map;
import org.apache.mina.core.buffer.IoBuffer;
import clientdata.VisitorInterface;
public class <API key> implements VisitorInterface {
public static class SlotDefinition {
public String slotName;
public byte global;
public byte canMod;
public byte exclusive;
public String hardpointName;
public int unk1;
}
public <API key>() {
definitions = new HashMap<String, SlotDefinition>();
}
private Map<String, SlotDefinition> definitions;
public Map<String, SlotDefinition> getDefinitions() {
return definitions;
}
@Override
public void parseData(String nodename, IoBuffer data, int depth, int size) throws Exception {
if(nodename.endsWith("DATA")) {
CharsetDecoder cd = Charset.forName("US-ASCII").newDecoder();
while(data.hasRemaining()) {
SlotDefinition next = new SlotDefinition();
next.slotName = data.getString(cd);
cd.reset();
next.global = data.get();
next.canMod = data.get();
next.exclusive = data.get();
next.hardpointName = data.getString(cd);
cd.reset();
next.unk1 = data.getInt();
definitions.put(next.slotName, next);
}
}
}
@Override
public void notifyFolder(String nodeName, int depth) throws Exception {}
}
|
package fr.eurecom.senml.entity;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;
@PersistenceCapable
public class ContactTest {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private String firstName;
@Persistent
private String lastName;
@Persistent
private String email;
public ContactTest(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public String getirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getEmail() {return email;}
public Key getKey() {return key;}
}
|
<ion-header>
<ion-navbar color="secondary">
<button ion-button menuToggle>
<ion-icon color="primary" name="menu"></ion-icon>
</button>
<ion-title color="primary">Gourmet Calculator</ion-title>
</ion-navbar>
</ion-header>
<ion-content class="calc">
<form #calcForm="ngForm" (ngSubmit)="onSubmit()">
<ion-item padding-top class="noBg">
<ion-label color="secondary" stacked class="amountLabel">Enter the amount (x100) <span padding-left class="preview" [hidden]="!amount>0 || calcForm.form.invalid" stacked>{{amount/100 | currency:currency:true:'1.2'}}</span></ion-label>
<!-- better tel because it allows to set maxlength -->
<ion-input type="tel" pattern="[0-9]+" placeholder="2500" maxlength="4" name="amount" required [(ngModel)]="amount" (ngModelChange)="amountChange($event)" [disabled]="gotResults"></ion-input>
</ion-item>
<ion-item text-center class="noBg" [hidden]="gotResults">
<button type="submit" ion-button large [outline]="calcForm.form.invalid" [disabled]="calcForm.form.invalid || isLoading" color="light">
<ion-icon padding-right name="calculator" [hidden]="isLoading" ></ion-icon>
<ion-spinner padding-right [hidden]="!isLoading" ></ion-spinner>
Calc
</button>
</ion-item>
</form>
<div padding *ngIf="gotResults">
<ion-list-header no-margin class="noBg">
Option 1 <ion-icon name="arrow-down" color="warning"></ion-icon>
</ion-list-header>
<ion-item padding class="semiBg calcResults">
<ion-label no-margin color="secondary" stacked>{{results.Option1Ticket1}} x {{ticket1/100 | currency:currency:true:'1.2'}}</ion-label>
<ion-label color="secondary" stacked>{{results.Option1Ticket2}} x {{ticket2/100 | currency:currency:true:'1.2'}}</ion-label>
<ion-label color="light" stacked>To pay: {{results.Option1Cash/100 | currency:currency:true:'1.2'}}</ion-label>
</ion-item>
<ion-list-header no-margin class="noBg">
Option 2 <ion-icon name="arrow-up" color="warning"></ion-icon>
</ion-list-header>
<ion-item padding class="semiBg calcResults">
<ion-label no-margin color="secondary" stacked>{{results.Option2Ticket1}} x {{ticket1/100 | currency:currency:true:'1.2'}}</ion-label>
<ion-label color="secondary" stacked>{{results.Option2Ticket2}} x {{ticket2/100 | currency:currency:true:'1.2'}}</ion-label>
<ion-label color="light" stacked>To receive: {{results.Option2Cash/100 | currency:currency:true:'1.2'}}</ion-label>
</ion-item>
<ion-item text-center padding-top class="noBg">
<button ion-button large outline (click)="reset()" [disabled]="calcForm.form.invalid" color="light">
<ion-icon padding-right name="refresh"></ion-icon> Reset
</button>
</ion-item>
</div>
<div padding *ngIf="gotFacts && !gotResults">
<ion-list-header no-margin class="noBg">
<ion-icon padding-right name="bulb" color="warning"></ion-icon> Did you know?
</ion-list-header>
<ion-item padding class="semiBg" text-wrap>
{{fact}}
</ion-item>
</div>
</ion-content>
|
package me.anthonybruno.soccerSim.team.member;
import me.anthonybruno.soccerSim.models.Range;
/**
* Player is a class that contains information about a player.
*/
public class Player extends TeamMember {
private final Range shotRange;
private final int goal;
/**
* Creates a new player with a name, shot range (how likely a shot will be attributed to the player) and a goal
* rating (how likely they are to score a goal).
*
* @param name The name of the player
* @param shotRange Shot range of player. Defines how likely a shot on goal will be attributed to this player (see
* rule files for more information. Is the maximum value when lower and upper bounds given by the
* rules.
* @param goal How likely a shot from the player will go in. When shot is taken, a number from 1-10 is generated.
* If the generated number is above or equal to goal rating, the player scores.
*/
public Player(String name, Range shotRange, int goal, int multiplier) {
super(name, multiplier);
this.shotRange = shotRange;
this.goal = goal;
}
/**
* Returns the shot range of player.
*
* @return the player's shot range.
*/
public Range getShotRange() {
return shotRange;
}
/**
* Returns the goal rating of the player.
*
* @return the player's goal range.
*/
public int getGoal() {
return goal;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Newtonsoft.Json;
using SmartStore.Core.Infrastructure;
namespace SmartStore.Collections
{
public abstract class TreeNodeBase<T> where T : TreeNodeBase<T>
{
private T _parent;
private List<T> _children = new List<T>();
private int? _depth = null;
private int _index = -1;
protected object _id;
private IDictionary<object, TreeNodeBase<T>> _idNodeMap;
protected IDictionary<string, object> _metadata;
private readonly static ContextState<Dictionary<string, object>> _contextState = new ContextState<Dictionary<string, object>>("TreeNodeBase.ThreadMetadata");
public TreeNodeBase()
{
}
#region Id
public object Id
{
get
{
return _id;
}
set
{
_id = value;
if (_parent != null)
{
var map = GetIdNodeMap();
if (_id != null && map.ContainsKey(_id))
{
// Remove old id from map
map.Remove(_id);
}
if (value != null)
{
map[value] = this;
}
}
}
}
public T SelectNodeById(object id)
{
if (id == null || IsLeaf)
return null;
var map = GetIdNodeMap();
var node = (T)map?.Get(id);
if (node != null && !this.IsAncestorOfOrSelf(node))
{
// Found node is NOT a child of this node
return null;
}
return node;
}
private IDictionary<object, TreeNodeBase<T>> GetIdNodeMap()
{
var map = this.Root._idNodeMap;
if (map == null)
{
map = this.Root._idNodeMap = new Dictionary<object, TreeNodeBase<T>>();
}
return map;
}
#endregion
#region Metadata
public IDictionary<string, object> Metadata
{
get
{
return _metadata ?? (_metadata = new Dictionary<string, object>());
}
set
{
_metadata = value;
}
}
public void SetMetadata(string key, object value)
{
Guard.NotEmpty(key, nameof(key));
Metadata[key] = value;
}
public void SetThreadMetadata(string key, object value)
{
Guard.NotEmpty(key, nameof(key));
var state = _contextState.GetState();
if (state == null)
{
state = new Dictionary<string, object>();
_contextState.SetState(state);
}
state[GetContextKey(this, key)] = value;
}
public TMetadata GetMetadata<TMetadata>(string key, bool recursive = true)
{
Guard.NotEmpty(key, nameof(key));
object metadata;
if (!recursive)
{
return <API key>(this, key, out metadata) ? (TMetadata)metadata : default(TMetadata);
}
// recursively search for the metadata value in current node and ancestors
var current = this;
while (!<API key>(current, key, out metadata))
{
current = current.Parent;
if (current == null)
break;
}
if (metadata != null)
{
return (TMetadata)metadata;
}
return default(TMetadata);
}
private bool <API key>(TreeNodeBase<T> node, string key, out object metadata)
{
metadata = null;
var state = _contextState.GetState();
if (state != null)
{
var contextKey = GetContextKey(node, key);
if (state.ContainsKey(contextKey))
{
metadata = state[contextKey];
return true;
}
}
if (node._metadata != null && node._metadata.ContainsKey(key))
{
metadata = node._metadata[key];
return true;
}
return false;
}
private static string GetContextKey(TreeNodeBase<T> node, string key)
{
return node.GetHashCode().ToString() + key;
}
#endregion
private List<T> ChildrenInternal
{
get
{
if (_children == null)
{
_children = new List<T>();
}
return _children;
}
}
private void AddChild(T node, bool clone, bool append = true)
{
var newNode = node;
if (clone)
{
newNode = node.Clone(true);
}
newNode.AttachTo((T)this, append ? (int?)null : 0);
}
private void AttachTo(T newParent, int? index)
{
Guard.NotNull(newParent, nameof(newParent));
var prevParent = _parent;
if (_parent != null)
{
// Detach from parent
_parent.Remove((T)this);
}
if (index == null)
{
newParent.ChildrenInternal.Add((T)this);
_index = newParent.ChildrenInternal.Count - 1;
}
else
{
newParent.ChildrenInternal.Insert(index.Value, (T)this);
_index = index.Value;
FixIndexes(newParent._children, _index + 1, 1);
}
_parent = newParent;
FixIdNodeMap(prevParent, newParent);
}
<summary>
Responsible for propagating node ids when detaching/attaching nodes
</summary>
private void FixIdNodeMap(T prevParent, T newParent)
{
ICollection<TreeNodeBase<T>> keyedNodes = null;
if (prevParent != null)
{
// A node is moved. We need to detach first.
keyedNodes = new List<TreeNodeBase<T>>();
// Detach ids from prev map
var prevMap = prevParent.GetIdNodeMap();
Traverse(x =>
{
// Collect all child node's ids
if (x._id != null)
{
keyedNodes.Add(x);
if (prevMap.ContainsKey(x._id))
{
// Remove from map
prevMap.Remove(x._id);
}
}
}, true);
}
if (keyedNodes == null && _idNodeMap != null)
{
// An orphan/root node is attached
keyedNodes = _idNodeMap.Values;
}
if (newParent != null)
{
// Get new *root map
var map = newParent.GetIdNodeMap();
// Merge *this map with *root map
if (keyedNodes != null)
{
foreach (var node in keyedNodes)
{
map[node._id] = node;
}
// Get rid of *this map after memorizing keyed nodes
if (_idNodeMap != null)
{
_idNodeMap.Clear();
_idNodeMap = null;
}
}
if (prevParent == null && _id != null)
{
// When *this was a root, but is keyed, then *this id
// was most likely missing in the prev id-node-map.
map[_id] = (T)this;
}
}
}
[JsonIgnore]
public T Parent
{
get
{
return _parent;
}
}
public T this[int i]
{
get
{
return _children?[i];
}
}
public IReadOnlyList<T> Children
{
get
{
return ChildrenInternal;
}
}
[JsonIgnore]
public IEnumerable<T> LeafNodes
{
get
{
return _children != null
? _children.Where(x => x.IsLeaf)
: Enumerable.Empty<T>();
}
}
[JsonIgnore]
public IEnumerable<T> NonLeafNodes
{
get
{
return _children != null
? _children.Where(x => !x.IsLeaf)
: Enumerable.Empty<T>();
}
}
[JsonIgnore]
public T FirstChild
{
get
{
return _children?.FirstOrDefault();
}
}
[JsonIgnore]
public T LastChild
{
get
{
return _children?.LastOrDefault();
}
}
[JsonIgnore]
public bool IsLeaf
{
get
{
return _children == null || _children.Count == 0;
}
}
[JsonIgnore]
public bool HasChildren
{
get
{
return _children == null || _children.Count > 0;
}
}
[JsonIgnore]
public bool IsRoot
{
get
{
return _parent == null;
}
}
[JsonIgnore]
public int Index
{
get
{
return _index;
}
}
<summary>
Root starts with 0
</summary>
[JsonIgnore]
public int Depth
{
get
{
if (!_depth.HasValue)
{
var node = this;
int depth = 0;
while (node != null && !node.IsRoot)
{
depth++;
node = node.Parent;
}
_depth = depth;
}
return _depth.Value;
}
}
[JsonIgnore]
public T Root
{
get
{
var root = this;
while (root._parent != null)
{
root = root._parent;
}
return (T)root;
}
}
[JsonIgnore]
public T First
{
get
{
return _parent?._children?.FirstOrDefault();
}
}
[JsonIgnore]
public T Last
{
get
{
return _parent?._children?.LastOrDefault();
}
}
[JsonIgnore]
public T Next
{
get
{
return _parent?._children?.ElementAtOrDefault(_index + 1);
}
}
[JsonIgnore]
public T Previous
{
get
{
return _parent?._children?.ElementAtOrDefault(_index - 1);
}
}
public bool IsDescendantOf(T node)
{
var parent = _parent;
while (parent != null)
{
if (parent == node)
{
return true;
}
parent = parent._parent;
}
return false;
}
public bool <API key>(T node)
{
if (node == (T)this)
return true;
return IsDescendantOf(node);
}
public bool IsAncestorOf(T node)
{
return node.IsDescendantOf((T)this);
}
public bool IsAncestorOfOrSelf(T node)
{
if (node == (T)this)
return true;
return node.IsDescendantOf((T)this);
}
[JsonIgnore]
public IEnumerable<T> Trail
{
get
{
var trail = new List<T>();
var node = (T)this;
do
{
trail.Insert(0, node);
node = node._parent;
} while (node != null);
return trail;
}
}
<summary>
Gets the first element that matches the predicate by testing the node itself
and traversing up through its ancestors in the tree.
</summary>
<param name="predicate">predicate</param>
<returns>The closest node</returns>
public T Closest(Expression<Func<T, bool>> predicate)
{
Guard.NotNull(predicate, nameof(predicate));
var test = predicate.Compile();
if (test((T)this))
{
return (T)this;
}
var parent = _parent;
while (parent != null)
{
if (test(parent))
{
return parent;
}
parent = parent._parent;
}
return null;
}
public T Append(T value)
{
this.AddChild(value, false, true);
return value;
}
public void AppendRange(IEnumerable<T> values)
{
values.Each(x => Append(x));
}
public void AppendChildrenOf(T node)
{
if (node?._children != null)
{
node._children.Each(x => this.AddChild(x, true, true));
}
}
public T Prepend(T value)
{
this.AddChild(value, false, false);
return value;
}
public void InsertAfter(int index)
{
var refNode = _children?.ElementAtOrDefault(index);
if (refNode != null)
{
InsertAfter(refNode);
}
throw new <API key>(nameof(index));
}
public void InsertAfter(T refNode)
{
this.Insert(refNode, true);
}
public void InsertBefore(int index)
{
var refNode = _children?.ElementAtOrDefault(index);
if (refNode != null)
{
InsertBefore(refNode);
}
throw new <API key>(nameof(index));
}
public void InsertBefore(T refNode)
{
this.Insert(refNode, false);
}
private void Insert(T refNode, bool after)
{
Guard.NotNull(refNode, nameof(refNode));
var refParent = refNode._parent;
if (refParent == null)
{
throw Error.Argument("refNode", "The reference node cannot be a root node and must be attached to the tree.");
}
AttachTo(refParent, refNode._index + (after ? 1 : 0));
}
public T SelectNode(Expression<Func<T, bool>> predicate, bool includeSelf = false)
{
Guard.NotNull(predicate, nameof(predicate));
return this.FlattenNodes(predicate, includeSelf).FirstOrDefault();
}
<summary>
Selects all nodes (recursively) witch match the given <c>predicate</c>
</summary>
<param name="predicate">The predicate to match against</param>
<returns>A readonly collection of node matches</returns>
public IEnumerable<T> SelectNodes(Expression<Func<T, bool>> predicate, bool includeSelf = false)
{
Guard.NotNull(predicate, nameof(predicate));
return this.FlattenNodes(predicate, includeSelf);
}
private void FixIndexes(IList<T> list, int startIndex, int summand = 1)
{
if (startIndex < 0 || startIndex >= list.Count)
return;
for (var i = startIndex; i < list.Count; i++)
{
list[i]._index += summand;
}
}
public void Remove(T node)
{
Guard.NotNull(node, nameof(node));
if (!node.IsRoot)
{
var list = node._parent?._children;
if (list.Remove(node))
{
node.FixIdNodeMap(node._parent, null);
FixIndexes(list, node._index, -1);
node._index = -1;
node._parent = null;
node.Traverse(x => x._depth = null, true);
}
}
}
public void Clear()
{
Traverse(x => x._depth = null, false);
if (_children != null)
{
_children.Clear();
}
FixIdNodeMap(_parent, null);
}
public void Traverse(Action<T> action, bool includeSelf = false)
{
Guard.NotNull(action, nameof(action));
if (includeSelf)
action((T)this);
if (_children != null)
{
foreach (var child in _children)
child.Traverse(action, true);
}
}
public void TraverseParents(Action<T> action, bool includeSelf = false)
{
Guard.NotNull(action, nameof(action));
if (includeSelf)
action((T)this);
var parent = _parent;
while (parent != null)
{
action(parent);
parent = parent._parent;
}
}
public IEnumerable<T> FlattenNodes(bool includeSelf = true)
{
return this.FlattenNodes(null, includeSelf);
}
protected IEnumerable<T> FlattenNodes(Expression<Func<T, bool>> predicate, bool includeSelf = true)
{
IEnumerable<T> list;
if (includeSelf)
{
list = new[] { (T)this };
}
else
{
list = Enumerable.Empty<T>();
}
if (_children == null)
return list;
var result = list.Union(_children.SelectMany(x => x.FlattenNodes()));
if (predicate != null)
{
result = result.Where(predicate.Compile());
}
return result;
}
public T Clone()
{
return Clone(true);
}
public virtual T Clone(bool deep)
{
var clone = CreateInstance();
if (deep)
{
clone.AppendChildrenOf((T)this);
}
return clone;
}
protected abstract T CreateInstance();
}
}
|
package vizardous.delegate.dataFilter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import vizardous.util.Converter;
/**
* Filter class that provides filter functionality for data structures with comparable content
*
* @author Johannes Seiffarth <j.seiffarth@fz-juelich.de>
*/
public class ComparableFilter {
/**
* Filters a map. All values (not keys!) that equal kick will be removed
* @param map to filter
* @param kick Value to kick out
*/
public static <T extends Comparable<T>, K> void filter(Map<K,T> map, T kick) {
Set<Map.Entry<K, T>> entrySet = map.entrySet();
for(Iterator<Map.Entry<K,T>> it = entrySet.iterator(); it.hasNext();) {
Map.Entry<K, T> entry = it.next();
if(entry.getValue().equals(kick))
it.remove();
}
}
/**
* Filters a list. All values that equal kick will be removed
* @param list to filter
* @param kick Value to kick out
* @return a reference to list (no new list!)
*/
public static <T extends Comparable<T>> List<T> filter(List<T> list, T kick) {
for(Iterator<T> it = list.iterator(); it.hasNext();) {
T val = it.next();
if(val.equals(kick))
it.remove();
}
return list;
}
/**
* Filters a double array. All values that equal kick will be removed
* @param data array to filter
* @param kick Value to kick out
* @return a new filtered array
*/
public static double[] filter(double[] data, double kick) {
LinkedList<Double> list = new LinkedList<Double>();
for(double value : data) {
if(value != kick)
list.add(value);
}
return Converter.listToArray(list);
}
}
|
#ifndef _AST_SMT_PP_H_
#define _AST_SMT_PP_H_
#include"ast.h"
#include<string>
#include"map.h"
class smt_renaming {
typedef map<symbol, symbol, symbol_hash_proc, symbol_eq_proc> symbol2symbol;
symbol2symbol m_translate;
symbol2symbol m_rev_translate;
symbol fix_symbol(symbol s, int k);
bool is_legal(char c);
bool is_special(char const* s);
bool is_numerical(char const* s);
bool all_is_legal(char const* s);
public:
smt_renaming();
symbol get_symbol(symbol s0);
symbol operator()(symbol const & s) { return get_symbol(s); }
};
class ast_smt_pp {
public:
class is_declared {
public:
virtual bool operator()(func_decl* d) const { return false; }
virtual bool operator()(sort* s) const { return false; }
};
private:
ast_manager& m_manager;
expr_ref_vector m_assumptions;
expr_ref_vector m_assumptions_star;
symbol m_benchmark_name;
symbol m_source_info;
symbol m_status;
symbol m_category;
symbol m_logic;
std::string m_attributes;
family_id m_dt_fid;
is_declared <API key>;
is_declared* m_is_declared;
bool m_simplify_implies;
public:
ast_smt_pp(ast_manager& m);
void set_benchmark_name(const char* bn) { if (bn) m_benchmark_name = bn; }
void set_source_info(const char* si) { if (si) m_source_info = si; }
void set_status(const char* s) { if (s) m_status = s; }
void set_category(const char* c) { if (c) m_category = c; }
void set_logic(const char* l) { if (l) m_logic = l; }
void add_attributes(const char* s) { if (s) m_attributes += s; }
void add_assumption(expr* n) { m_assumptions.push_back(n); }
void add_assumption_star(expr* n) { m_assumptions_star.push_back(n); }
void <API key>(bool f) { m_simplify_implies = f; }
void set_is_declared(is_declared* id) { m_is_declared = id; }
void display(std::ostream& strm, expr* n);
void display_smt2(std::ostream& strm, expr* n);
void display_expr(std::ostream& strm, expr* n);
void display_expr_smt2(std::ostream& strm, expr* n, unsigned indent = 0, unsigned num_var_names = 0, char const* const* var_names = 0);
};
struct mk_smt_pp {
expr * m_expr;
ast_manager& m_manager;
unsigned m_indent;
unsigned m_num_var_names;
char const* const* m_var_names;
mk_smt_pp(expr* e, ast_manager & m, unsigned indent = 0, unsigned num_var_names = 0, char const* const* var_names = 0) :
m_expr(e), m_manager(m), m_indent(indent), m_num_var_names(num_var_names), m_var_names(var_names) {}
};
inline std::ostream& operator<<(std::ostream& out, const mk_smt_pp & p) {
ast_smt_pp pp(p.m_manager);
pp.display_expr_smt2(out, p.m_expr, p.m_indent, p.m_num_var_names, p.m_var_names);
return out;
}
#endif
|
#!/bin/bash
set -e
echo "$(whoami)"
if [ "$(whoami)" == "root" ]; then
chown -R scrapy:scrapy /home/scrapy/backup
chown --dereference scrapy "/proc/$$/fd/1" "/proc/$$/fd/2" || :
exec gosu scrapy "$@"
fi
|
<!DOCTYPE html>
<html>
<head>
<title>!AntiShout demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<form action="/">
<p>
<label>Type: text</label>
<input type="text" placeholder="Try me">
</p>
<p>
<label>Textarea</label>
<textarea placeholder="And me too"></textarea>
</p>
<div class="message"></div>
<button type="submit" disabled>send</button>
</form>
<!-- load scripts -->
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
<script src="antishout.js"></script>
<!-- antishout init -->
<script>
$(function(){
$('form').antishout();
});
</script>
</body>
</html>
|
# Tutorials
## Table of contents
- [Make a server from scratch](https://github.com/Komrod/web-servo/blob/master/tutorials.md#<API key>)
- [Create a HTTPS server](https://github.com/Komrod/web-servo/blob/master/tutorials.md#make-a-https-server)
## Make a server from scratch
Assuming you start from nothing, install Node (https://nodejs.org/en/download/) and open a console. Then create a directory for your project and install the web-servo module:
mkdir myProject
cd myProject
npm install web-servo
Create the script "server.js" to launch the server in "myProject/":
require('web-servo').start();
If you run the server now, it will show an error because the configuration is not set in the script and the server is supposed to use the file "config.json" that doesn't exist yet. It is also recommanded to create the WWW root directory and log directory so everything works fine.
mkdir www
mkdir log
Now create "config.json" in "myProject/":
{
"server": {
"port": "9000",
"dir": "www/"
},
"log": {
"access": {
"enabled": true,
"path": "log/access.log",
"console": true
},
"error": {
"enabled": true,
"path": "log/error.log",
"console": true,
"debug": true
}
}
}
In this file, we defined the server to run on port 9000 and the WWW directory to "www/". I also add the log parameters to show access and errors in the console.
If you omit a parameter in this file, it will take the default value. For example, the default page is set by default to "index.html".
Now launch the server and it should run properly:
node server.js
The console will output:
Using config file "C:\Users\me\git\myProject\config.json"
Using WWW directory "C:\Users\me\git\myProject\www"
Server listening on: http://localhost:9000
Create a simple "index.html" file and put it in "myProject/www/":
<!doctype html>
<html>
<head>
<title>Hello world!</title>
</head>
<body>
This is the Hello world page!
</body>
</html>
Now open a browser and request http://localhost:9000/ you should see the Hello world page. You can now build a whole website inside the WWW directory with images, CSS, JS ...
## Make a HTTPS server
You can run a web server over HTTPS protocol. You will need the SSL key file and the SSL certificate file.
If you want to run your server locally, you can generate those files on your computer with some commands, it will require OpenSSL installed.
Generate local SSL files by script
There is a shell script in the root directory that can do it for you. How to use it :
./generateSSL.sh example/ssl/ example
This will generate the files in the "example/ssl/" directory.
After succefull execution, the generated files are "example/ssl/example.key" and "example/ssl/example.crt".
Generate local SSL files manually
You can generate manually those files by typing the commands yourself. You can go to the directory you want to create the SSL files "example.crt" and "example.key".
cd example/ssl/
openssl genrsa -des3 -passout pass:x -out example.pass.key 2048
openssl rsa -passin pass:x -in example.pass.key -out example.key
You must know your local hostname or else your certificate will not work.
hostname
Your host name is the response to field Common Name (CN or FQDN).
openssl x509 -req -days 365 -in example.csr -signkey example.key -out example.crt
Cleanup temporary files.
rm example.pass.key example.csr
If everything runs properly, you now have the 2 files "example.crt" and "example.key". They are ready to use with the example HTTPS server. They must be in the directory "example/ssl/".
If you use them in another project, you can also rename them.
Configure the server
You now have the 2 SSL files. You need to configure the files in the config file of Web-servo, it may looks like this (in config.json):
{
"server": {
"port": "443",
"ssl": {
"enabled": true,
"key": "ssl/example.key",
"cert": "ssl/example.crt"
}
}
}
If you are using the example server, the config file is already ready in "example/config_https.json".
Then, you have to run your server with a simple line in a node script.
require('web-servo').start();
The script is also ready in "example/server_https.js". You can run "node example/server_https.js".
Executing the example HTTPS server will have this result :
Using config file "C:\Users\PR033\git\web-servo\example\config_https.json"
Using WWW directory "C:\Users\PR033\git\web-servo\example\www"
Server listening on: https://localhost:443
Finally
You can now access the server on https://localhost/. If you are using a locally generated certificate, you may have a warning because your certificate is not validated by a trusted source. But it will run properly.
Way to disable the warning:
- [For Internet Explorer](https:
- [For Chrome](https://support.google.com/chrome/answer/99020)
- [For Firefox](http://ccm.net/faq/<API key>)
If your certificate files are invalid or corrupted, there might be no errors while running the server but your browser will prevent you to process the requests.
|
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: ../pdfreporter-core/src/org/oss/pdfreporter/crosstabs/fill/calculation/<API key>.java
#include "J2ObjC_header.h"
#pragma push_macro("<API key>")
#ifdef <API key>
#define <API key> 0
#else
#define <API key> 1
#endif
#undef <API key>
#if !defined (<API key>) && (<API key> || defined(<API key>))
#define <API key>
@class IOSObjectArray;
@protocol <API key>;
@protocol <API key>;
@protocol <API key>;
@protocol <API key> < NSObject, JavaObject >
- (id<<API key>>)<API key>;
- (id<<API key>>)<API key>;
- (id)<API key>:(id<<API key>>)expression
<API key>:(IOSObjectArray *)measureValues;
@end
<API key>(<API key>)
<API key>(<API key>)
#endif
#pragma pop_macro("<API key>")
|
<?php
return array(
'title' => 'Publicaciones',
'parent' => 'Contenido',
'name' => 'publicación|publicaciones',
'table' =>
array(
'id' => 'ID',
'action' => 'Acción',
'title' => 'Título',
'category_id' => 'Categoría',
'author_id' => 'Autor',
'url_alias' => 'Alias de la URL',
'author_alias' => 'Alias del autor',
'image_file' => 'Imagen',
'description' => 'Descripción',
'content' => 'Contenido',
'created_at' => 'Creado',
'status' => 'Estado',
),
);
|
package com.albion.common.graph.algorithms;
import com.albion.common.graph.core.v1.Edge;
import com.albion.common.graph.core.v1.Graph;
import com.albion.common.graph.core.v1.Vertex;
import java.util.ArrayList;
import java.util.List;
public class BreathFirstSearch {
public static Vertex locate(Graph graph, Integer source, Integer target){
List<Vertex> queue = new ArrayList<>();
Vertex root = graph.getVertex(source);
queue.add(root);
while(!queue.isEmpty()){
Vertex v = queue.remove(0);
if(v.getId() == target.intValue()){
v.setVisited(true);
return v;
}
List<Edge> edgeList = v.getEdgeList();
for(Edge edge : edgeList){
int vertexId = edge.getY();
Vertex w = graph.getVerticesMap().get(vertexId);
if(w.isVisited() == false){
w.setVisited(true);
queue.add(w);
}
}
}
return null;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Athame.PluginAPI.Service
{
<summary>
Represents a collection of items that are retrieved as pages from a service.
</summary>
<typeparam name="T">The type of each item.</typeparam>
public abstract class PagedMethod<T> : PagedList<T>
{
<summary>
Default constructor.
</summary>
<param name="itemsPerPage">The amount of items per page to load.</param>
protected PagedMethod(int itemsPerPage)
{
ItemsPerPage = itemsPerPage;
}
<summary>
Retrieves the next page asynchronously and appends the result to <see cref="AllItems"/>.
</summary>
<returns>The next page's contents.</returns>
public abstract Task<IList<T>> GetNextPageAsync();
<summary>
Retrieves each page sequentially until there are none left.
</summary>
public virtual async Task LoadAllPagesAsync()
{
while (HasMoreItems)
{
await GetNextPageAsync();
}
}
}
}
|
namespace Animals.Animals
{
public class Kitten : Cat
{
public Kitten(string name, int age) : base(name, age, "Female")
{
}
public override string ProduceSound()
{
return "Meow";
}
}
}
|
// Platform-specific code for FreeBSD goes here. For the POSIX-compatible
// parts, the implementation is in platform-posix.cc.
#include <osconfig.h>
#ifdef FreeBSD
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/ucontext.h>
#include <stdlib.h>
#include <sys/types.h> // mmap & munmap
#include <sys/mman.h> // mmap & munmap
#include <sys/stat.h> // open
#include <sys/fcntl.h> // open
#include <unistd.h> // getpagesize
// If you don't have execinfo.h then you need devel/libexecinfo from ports.
#include <strings.h> // index
#include <errno.h>
#include <stdarg.h>
#include <limits.h>
#undef MAP_TYPE
#include "v8.h"
#include "v8threads.h"
#include "platform.h"
namespace v8 {
namespace internal {
const char* OS::LocalTimezone(double time, TimezoneCache* cache) {
if (std::isnan(time)) return "";
time_t tv = static_cast<time_t>(std::floor(time/msPerSecond));
struct tm* t = localtime(&tv);
if (NULL == t) return "";
return t->tm_zone;
}
double OS::LocalTimeOffset(TimezoneCache* cache) {
time_t tv = time(NULL);
struct tm* t = localtime(&tv);
// tm_gmtoff includes any daylight savings offset, so subtract it.
return static_cast<double>(t->tm_gmtoff * msPerSecond -
(t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
}
void* OS::Allocate(const size_t requested,
size_t* allocated,
bool executable) {
const size_t msize = RoundUp(requested, getpagesize());
int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANON, -1, 0);
if (mbase == MAP_FAILED) {
LOG(Isolate::Current(), StringEvent("OS::Allocate", "mmap failed"));
return NULL;
}
*allocated = msize;
return mbase;
}
class <API key> : public OS::MemoryMappedFile {
public:
<API key>(FILE* file, void* memory, int size)
: file_(file), memory_(memory), size_(size) { }
virtual ~<API key>();
virtual void* memory() { return memory_; }
virtual int size() { return size_; }
private:
FILE* file_;
void* memory_;
int size_;
};
OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
FILE* file = fopen(name, "r+");
if (file == NULL) return NULL;
fseek(file, 0, SEEK_END);
int size = ftell(file);
void* memory =
mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
return new <API key>(file, memory, size);
}
OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
void* initial) {
FILE* file = fopen(name, "w+");
if (file == NULL) return NULL;
int result = fwrite(initial, size, 1, file);
if (result < 1) {
fclose(file);
return NULL;
}
void* memory =
mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
return new <API key>(file, memory, size);
}
<API key>::~<API key>() {
if (memory_) munmap(memory_, size_);
fclose(file_);
}
static unsigned StringToLong(char* buffer) {
return static_cast<unsigned>(strtol(buffer, NULL, 16)); // NOLINT
}
void OS::<API key>(Isolate* isolate) {
static const int MAP_LENGTH = 1024;
int fd = open("/proc/self/maps", O_RDONLY);
if (fd < 0) return;
while (true) {
char addr_buffer[11];
addr_buffer[0] = '0';
addr_buffer[1] = 'x';
addr_buffer[10] = 0;
int result = read(fd, addr_buffer + 2, 8);
if (result < 8) break;
unsigned start = StringToLong(addr_buffer);
result = read(fd, addr_buffer + 2, 1);
if (result < 1) break;
if (addr_buffer[2] != '-') break;
result = read(fd, addr_buffer + 2, 8);
if (result < 8) break;
unsigned end = StringToLong(addr_buffer);
char buffer[MAP_LENGTH];
int bytes_read = -1;
do {
bytes_read++;
if (bytes_read >= MAP_LENGTH - 1)
break;
result = read(fd, buffer + bytes_read, 1);
if (result < 1) break;
} while (buffer[bytes_read] != '\n');
buffer[bytes_read] = 0;
// Ignore mappings that are not executable.
if (buffer[3] != 'x') continue;
char* start_of_path = index(buffer, '/');
// There may be no filename in this line. Skip to next.
if (start_of_path == NULL) continue;
buffer[bytes_read] = 0;
LOG(isolate, SharedLibraryEvent(start_of_path, start, end));
}
close(fd);
}
void OS::SignalCodeMovingGC() {
}
// Constants used for mmap.
static const int kMmapFd = -1;
static const int kMmapFdOffset = 0;
VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
VirtualMemory::VirtualMemory(size_t size)
: address_(ReserveRegion(size)), size_(size) { }
VirtualMemory::VirtualMemory(size_t size, size_t alignment)
: address_(NULL), size_(0) {
ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
size_t request_size = RoundUp(size + alignment,
static_cast<intptr_t>(OS::AllocateAlignment()));
void* reservation = mmap(OS::GetRandomMmapAddr(),
request_size,
PROT_NONE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
kMmapFd,
kMmapFdOffset);
if (reservation == MAP_FAILED) return;
Address base = static_cast<Address>(reservation);
Address aligned_base = RoundUp(base, alignment);
ASSERT_LE(base, aligned_base);
// Unmap extra memory reserved before and after the desired block.
if (aligned_base != base) {
size_t prefix_size = static_cast<size_t>(aligned_base - base);
OS::Free(base, prefix_size);
request_size -= prefix_size;
}
size_t aligned_size = RoundUp(size, OS::AllocateAlignment());
ASSERT_LE(aligned_size, request_size);
if (aligned_size != request_size) {
size_t suffix_size = request_size - aligned_size;
OS::Free(aligned_base + aligned_size, suffix_size);
request_size -= suffix_size;
}
ASSERT(aligned_size == request_size);
address_ = static_cast<void*>(aligned_base);
size_ = aligned_size;
}
VirtualMemory::~VirtualMemory() {
if (IsReserved()) {
bool result = ReleaseRegion(address(), size());
ASSERT(result);
USE(result);
}
}
bool VirtualMemory::IsReserved() {
return address_ != NULL;
}
void VirtualMemory::Reset() {
address_ = NULL;
size_ = 0;
}
bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
return CommitRegion(address, size, is_executable);
}
bool VirtualMemory::Uncommit(void* address, size_t size) {
return UncommitRegion(address, size);
}
bool VirtualMemory::Guard(void* address) {
OS::Guard(address, OS::CommitPageSize());
return true;
}
void* VirtualMemory::ReserveRegion(size_t size) {
void* result = mmap(OS::GetRandomMmapAddr(),
size,
PROT_NONE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
kMmapFd,
kMmapFdOffset);
if (result == MAP_FAILED) return NULL;
return result;
}
bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
if (MAP_FAILED == mmap(base,
size,
prot,
MAP_PRIVATE | MAP_ANON | MAP_FIXED,
kMmapFd,
kMmapFdOffset)) {
return false;
}
return true;
}
bool VirtualMemory::UncommitRegion(void* base, size_t size) {
return mmap(base,
size,
PROT_NONE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED,
kMmapFd,
kMmapFdOffset) != MAP_FAILED;
}
bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
return munmap(base, size) == 0;
}
bool VirtualMemory::HasLazyCommits() {
// TODO(alph): implement for the platform.
return false;
}
} } // namespace v8::internal
#endif
|
#! /usr/bin/env python
import logging, logtool
from .page import Page
from .xlate_frame import XlateFrame
LOG = logging.getLogger (__name__)
class Contents:
@logtool.log_call
def __init__ (self, canvas, objects):
self.canvas = canvas
self.objects = objects
@logtool.log_call
def render (self):
with Page (self.canvas) as pg:
for obj in self.objects:
coords = pg.next (obj.asset)
with XlateFrame (self.canvas, obj.tile_type, *coords,
inset_by = "margin"):
# print ("Obj: ", obj.asset)
obj.render ()
|
class CfgWeapons {
// Base classes
class ItemCore;
class H_HelmetB;
class H_Cap_red;
class H_Bandanna_khk;
class <API key>;
// RHSSAF
class rhssaf_helmet_base : H_HelmetB{
rgoc_canAcceptNVG = 1;
};
class <API key> : rhssaf_helmet_base{
rgoc_canAcceptNVG = 1;
};
class <API key> : rhssaf_helmet_base{
rgoc_canAcceptNVG = 1;
};
class <API key> : rhssaf_helmet_base{
rgoc_canAcceptNVG = 1;
};
class <API key> : rhssaf_helmet_base{
rgoc_canAcceptNVG = 1;
};
class <API key>: <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key>: <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : rhssaf_helmet_base{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key>: <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class <API key> : <API key>{
rgoc_canAcceptNVG = 1;
};
class rhssaf_beret_green : rhssaf_helmet_base{
rgoc_canAcceptNVG = 0;
};
class rhssaf_beret_red : rhssaf_beret_green{
rgoc_canAcceptNVG = 0;
};
class rhssaf_beret_para : rhssaf_beret_green{
rgoc_canAcceptNVG = 0;
};
class rhssaf_beret_black : rhssaf_beret_green{
rgoc_canAcceptNVG = 0;
};
class <API key> : rhssaf_helmet_base{
rgoc_canAcceptNVG = 0;
};
class <API key>: <API key>{
rgoc_canAcceptNVG = 0;
};
class <API key>: <API key>{
rgoc_canAcceptNVG = 0;
};
class <API key>: <API key>{
rgoc_canAcceptNVG = 0;
};
class <API key>: H_Bandanna_khk{
rgoc_canAcceptNVG = 0;
};
class <API key>: <API key>{
rgoc_canAcceptNVG = 0;
};
class <API key>: <API key>{
rgoc_canAcceptNVG = 0;
};
class rhssaf_bandana_smb: <API key>{
rgoc_canAcceptNVG = 0;
};
class <API key>: <API key>{
rgoc_canAcceptNVG = 0;
};
};
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package services;
import FareCalculator.Calculate;
import java.util.ArrayList;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.lang.<API key>;
import java.net.URI;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import localstorage.FaresType;
/**
*
* @author peppa
*/
@Path("/")
public class calculatorService {
@Context
private UriInfo context;
public calculatorService(){
}
@GET
@Path("/calculate")
@Produces({"application/xml"})
public Response fareCalculator(@DefaultValue("TK") @QueryParam("carrier") String carrier,
@DefaultValue("2012-01-01") @QueryParam("date") String date,
@DefaultValue("ADB") @QueryParam("origCode") String origCode,
@DefaultValue("ESB") @QueryParam("destCode") String destCode,
@DefaultValue("Economy") @QueryParam("fareClass") String fareClass) {
Calculate cal = new Calculate();
FaresType fare = cal.fareCalculate(carrier, date, origCode, destCode, fareClass);
return Response.ok(new JAXBElement<FaresType>(new QName("faresType"), FaresType.class, fare)).build();
}
}
|
package xyw.ning.juicer.poco.model;
import xyw.ning.juicer.base.NoProguard;
public class Size implements NoProguard {
public String url;
public long width;
public long height;
}
|
#include <gtest/gtest.h>
#include "math/integr/WeightedIntegral.h"
#include "math/integr/<API key>.h"
#include <stdexcept>
#include <cmath>
class <API key>: public testing::Test
{
};
TEST_F(<API key>,Test)
{
rql::integr::WeightedIntegral wi(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::<API key>::Constant(1.0));
const double integral = wi.integrate<double(*)(double)>(cos);
const double sin1 = sin(1.0);
ASSERT_NEAR(sin1, integral, 1E-5);
rql::integr::WeightedIntegral ws(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::<API key>::Sine(2.0));
const double integral2 = ws.integrate<double(*)(double)>(cos);
const double cos1 = cos(1.0);
const double expected2 = (1-pow(cos1, 3))*2.0/3;
ASSERT_NEAR(expected2, integral2, 1E-8);
rql::integr::WeightedIntegral wc(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::<API key>::Cosine(2.0));
const double integral3 = wc.integrate<double(*)(double)>(sin);
const double expected3 = (3*cos1 - cos(3.0)-2)/6.0;
ASSERT_NEAR(expected3, integral3, 1E-8);
}
double constant_one(double x)
{
return 1;
}
double linear(double x)
{
return x;
}
TEST_F(<API key>,Sine)
{
rql::integr::WeightedIntegral wu(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::<API key>::Constant(1.0));
const double integral_u = wu.integrate<double(*)(double)>(sin);
ASSERT_NEAR(1 - cos(1.0), integral_u, 1E-5) << "unity";
rql::integr::WeightedIntegral ws(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::<API key>::Sine(1.0));
const double integral_s = ws.integrate(constant_one);
ASSERT_NEAR(1 - cos(1.0), integral_s, 1E-10) << "sine_weight";
const double integral_linear = ws.integrate(linear);
ASSERT_NEAR(sin(1.0) - cos(1.0), integral_linear, 1E-10);
}
|
#ifndef HSSEVENTSELECTOR_H
#define HSSEVENTSELECTOR_H
#include "HSSNameSelector.h"
namespace AXR
{
/**
* @brief The special object \@event in HSS.
*
* Used in selector chains, returns a special object that contains
* information about an event.
*/
class AXR_API HSSEventSelector : public HSSNameSelector
{
public:
/**
* Creates a new instance of a event selector.
*/
HSSEventSelector(AXRController * controller);
/**
* Clones an instance of HSSEventSelector and gives a shared pointer of the
* newly instanciated object.
* @return A shared pointer to the new HSSEventSelector
*/
QSharedPointer<HSSEventSelector> clone() const;
//see HSSNameSelector.h for the documentation of this method
AXRString getElementName();
//see HSSParserNode.h for the documentation of this method
virtual AXRString toString();
//see HSSParserNode.h for the documentation of this method
AXRString stringRep();
QSharedPointer<HSSSelection> filterSelection(QSharedPointer<HSSSelection> scope, QSharedPointer<HSSDisplayObject> thisObj, bool processing, bool <API key>);
private:
virtual QSharedPointer<HSSClonable> cloneImpl() const;
};
}
#endif
|
package ts3bot.helpers;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Helper for testing method signatures.
*/
public final class <API key> {
// Object methods.
private static final List<MethodSignature> <API key> = new ArrayList<<API key>.MethodSignature>();
static {
for (Method m : Object.class.getDeclaredMethods()) {
<API key>.add(new MethodSignature(m.getName(),
m.getParameterTypes()));
}
}
/**
* Checks whether specified interface declares all of public methods implementation class declares.
*
* @param impl
* implementation class
* @param interf
* interface class
* @throws RuntimeException
* When interface does not declare public method implementation class does
*/
public static final void <API key>(final Class<?> impl,
final Class<?> interf) {
List<MethodSignature> <API key> = new ArrayList<MethodSignature>(
100);
// Generate interface method signatures.
for (Method m : interf.getDeclaredMethods()) {
// Interface has only public abstract methods.
<API key>.add(new MethodSignature(m.getName(),
m.getParameterTypes()));
}
for (Method m : impl.getDeclaredMethods()) {
// Checking only public methods.
MethodSignature ms;
if (Modifier.isPublic(m.getModifiers())) {
// Build method signature.
ms = new MethodSignature(m.getName(), m.getParameterTypes());
// Don't check methods derived from Object.
if (!<API key>.contains(ms)) {
// Check if interface declares it.
if (!<API key>.contains(ms)) { throw new RuntimeException(
"Interface '" + interf.getName()
+ "' does not declare method " + ms.toString()
+ " implemented in class '" + impl.getName() + "'!"); }
}
}
}
}
/**
* Class that specified method signature in Java.
*/
private static class MethodSignature {
private final String name;
private final Class<?>[] params;
public MethodSignature(final String name, final Class<?>[] params) {
this.name = name;
this.params = params;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
result = prime * result
+ ((this.params == null) ? 0 : this.params.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (this.getClass() != obj.getClass())
return false;
MethodSignature other = (MethodSignature) obj;
if (this.name == null) {
if (other.name != null)
return false;
}
else if (!this.name.equals(other.name))
return false;
if (this.params == null) {
if (other.params != null)
return false;
}
else if (this.params.length != other.params.length)
return false;
for (int i = 0; i < this.params.length; i++) {
if (!this.params[i].equals(other.params[i])) { return false; }
}
return true;
}
@Override
public String toString() {
return "MethodSignature [name=" + this.name + ", params="
+ Arrays.toString(this.params) + "]";
}
}
}
|
// <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>
namespace Abide.HaloLibrary.Halo2.Retail.Tag.Generated
{
using System;
using Abide.HaloLibrary;
using Abide.HaloLibrary.Halo2.Retail.Tag;
<summary>
Represents the generated <API key> tag block.
</summary>
public sealed class <API key> : Block
{
<summary>
Initializes a new instance of the <see cref="<API key>"/> class.
</summary>
public <API key>()
{
this.Fields.Add(new PadField("", 16));
}
<summary>
Gets and returns the name of the <API key> tag block.
</summary>
public override string BlockName
{
get
{
return "<API key>";
}
}
<summary>
Gets and returns the display name of the <API key> tag block.
</summary>
public override string DisplayName
{
get
{
return "<API key>";
}
}
<summary>
Gets and returns the maximum number of elements allowed of the <API key> tag block.
</summary>
public override int MaximumElementCount
{
get
{
return 1;
}
}
<summary>
Gets and returns the alignment of the <API key> tag block.
</summary>
public override int Alignment
{
get
{
return 4;
}
}
}
}
|
<?php
require('../../php/bdd.php');
$bdd->query('DELETE FROM general WHERE 1');
$reqe = $bdd->prepare('INSERT INTO general (name, text, date) VALUES (:label, :text, 0)');
$reqe->execute(array(
"label" => 'titre_accueil',
"text" => $_POST['title']
));
$reqe->CloseCursor();
$reqe = $bdd->prepare('INSERT INTO general (name, text, date) VALUES (:label, :text, 0)');
$reqe->execute(array(
"label" => 'text_accueil',
"text" => $_POST['text']
));
$reqe->CloseCursor();
$reqe = $bdd->prepare('INSERT INTO general (name, text, date) VALUES (:label, :text, 0)');
$reqe->execute(array(
"label" => 'foot_accueil',
"text" => $_POST['foot']
));
$reqe->CloseCursor();
echo "Effectué !";
?>
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Newegg.Oversea.Silverlight.Controls;
using Newegg.Oversea.Silverlight.ControlPanel.Core.Base;
using ECCentral.Portal.UI.MKT.Models;
using ECCentral.Portal.UI.MKT.UserControls.Keywords;
using Newegg.Oversea.Silverlight.Controls.Components;
using ECCentral.Portal.UI.MKT.Facades;
using ECCentral.Portal.Basic.Utilities;
using ECCentral.QueryFilter.MKT;
using ECCentral.BizEntity.MKT;
using ECCentral.Portal.Basic;
using ECCentral.BizEntity.Common;
using ECCentral.BizEntity.Enum.Resources;
using Newegg.Oversea.Silverlight.ControlPanel.Core;
using ECCentral.Portal.UI.MKT.Resources;
using Newegg.Oversea.Silverlight.Utilities.Validation;
namespace ECCentral.Portal.UI.MKT.Views
{
[View(IsSingleton = true, SingletonType = SingletonTypes.Url)]
public partial class HotKeywords : PageBase
{
private <API key> facade;
private <API key> filter;
private List<HotKeywordsVM> gridVM;
private HotKeywordsQueryVM queryVM;
private <API key> filterVM;
public HotKeywords()
{
InitializeComponent();
}
<summary>
</summary>
<param name="sender"></param>
<param name="e"></param>
private void <API key>(object sender, EventArgs e)
{
if (filterVM == null || this.QueryResultGrid.TotalCount < 1)
{
Window.Alert(ResKeywords.<API key>);
return;
}
ColumnSet col = new ColumnSet(this.QueryResultGrid);
filter = queryVM.ConvertVM<HotKeywordsQueryVM, <API key>>();
filter.PageInfo = new ECCentral.QueryFilter.Common.PagingInfo()
{
PageSize = ConstValue.MaxRowCountLimit,
PageIndex = 0,
SortBy = string.Empty
};
facade.ExportExcelFile(filterVM, new ColumnSet[] { col });
}
public override void OnPageLoad(object sender, EventArgs e)
{
facade = new <API key>(this);
filter = new <API key>();
queryVM = new HotKeywordsQueryVM();
queryVM.CompanyCode = CPApplication.Current.CompanyCode;
queryVM.ChannelID = "1";
QuerySection.DataContext = queryVM;
facade.<API key>(CPApplication.Current.CompanyCode, (s, args) =>
{
if (args.FaultsHandle())
return;
BindEditUserList(args.Result);
});
base.OnPageLoad(sender, e);
}
private void BindEditUserList(List<UserInfo> userList)
{
if (userList == null)
{
userList = new List<UserInfo>();
}
userList.Insert(0, new UserInfo { SysNo = null, UserName = ResCommonEnum.Enum_All });
comEditUser.ItemsSource = userList;
}
private void <API key>(object sender, Newegg.Oversea.Silverlight.Controls.Data.<API key> e)
{
facade.QueryHotKeywords(QueryResultGrid.QueryCriteria as <API key>, e.PageSize, e.PageIndex, e.SortField, (s, args) =>
{
if (args.FaultsHandle())
return;
gridVM = DynamicConverter<HotKeywordsVM>.ConvertToVMList<List<HotKeywordsVM>>(args.Result.Rows);
QueryResultGrid.ItemsSource = gridVM;
QueryResultGrid.TotalCount = args.Result.TotalCount;
if (gridVM != null)
{
btnVoidItem.IsEnabled = true;
btnAvailableItem.IsEnabled = true;
}
else
{
btnVoidItem.IsEnabled = false;
btnAvailableItem.IsEnabled = false;
}
});
}
<summary>
</summary>
<param name="sender"></param>
<param name="e"></param>
private void hlViewItem_Click(object sender, RoutedEventArgs e)
{
HotKeywordsVM vm = QueryResultGrid.SelectedItem as HotKeywordsVM;
HotKeywordsVM vmItem = gridVM.SingleOrDefault(a => a.SysNo.Value == vm.SysNo.Value);
HotSearchKeyWords item = <API key>.ConvertVM<HotKeywordsVM, HotSearchKeyWords>(vmItem, (v, t) =>
{
t.Keywords = new BizEntity.LanguageContent(ConstValue.BizLanguageCode, v.Keywords);
});
<API key> usercontrol = new <API key>();
usercontrol.Model = item;
usercontrol.Dialog = Window.ShowDialog(ResKeywords.<API key>, usercontrol, <API key>);
}
private void btnNewItem_Click(object sender, RoutedEventArgs e)
{
UCAddHotKeywords usercontrol = new UCAddHotKeywords();
usercontrol.Dialog = Window.ShowDialog(ResKeywords.<API key>, usercontrol, <API key>);
}
private void <API key>(object sender, ResultEventArgs args)
{
if (args.DialogResult == DialogResultType.OK)
{
filter = queryVM.ConvertVM<HotKeywordsQueryVM, <API key>>();
filter.PageType = ucPageType.PageType;
filter.PageID = ucPageType.PageID;
filterVM = Newegg.Oversea.Silverlight.Utilities.UtilityHelper.DeepClone<<API key>>(filter);
QueryResultGrid.QueryCriteria = this.filter;
QueryResultGrid.Bind();
}
}
<summary>
</summary>
<param name="sender"></param>
<param name="e"></param>
private void btnVoidItem_Click(object sender, RoutedEventArgs e)
{
List<int> invalidSysNo = new List<int>();
gridVM.ForEach(item =>
{
if (item.IsChecked == true)
invalidSysNo.Add(item.SysNo.Value);
});
if (invalidSysNo.Count > 0)
facade.<API key>(invalidSysNo, (obj, args) =>
{
if (args.FaultsHandle())
return;
QueryResultGrid.Bind();
Window.Alert(ResKeywords.<API key>, MessageType.Information);
});
else
Window.Alert(ResKeywords.<API key>, MessageType.Error);
}
<summary>
</summary>
<param name="sender"></param>
<param name="e"></param>
private void hlEdit_Click(object sender, RoutedEventArgs e)
{
HotKeywordsVM item = this.QueryResultGrid.SelectedItem as HotKeywordsVM;
UCAddHotKeywords usercontrol = new UCAddHotKeywords();
//usercontrol.SysNo = item.SysNo.Value;
usercontrol.VM = gridVM.Single(a => a.SysNo.Value == item.SysNo.Value);//item;
usercontrol.Dialog = Window.ShowDialog(ResKeywords.<API key>, usercontrol, <API key>);
}
private void Button_Search_Click(object sender, RoutedEventArgs e)
{
if (ValidationManager.Validate(this.QuerySection))
{
filter = queryVM.ConvertVM<HotKeywordsQueryVM, <API key>>();
filter.PageType = ucPageType.PageType;
filter.PageID = ucPageType.PageID;
filterVM = Newegg.Oversea.Silverlight.Utilities.UtilityHelper.DeepClone<<API key>>(filter);
QueryResultGrid.QueryCriteria = this.filter;
QueryResultGrid.Bind();
}
}
private void ckbSelectRow_Click(object sender, RoutedEventArgs e)
{
var checkBoxAll = sender as CheckBox;
if (gridVM == null || checkBoxAll == null)
return;
gridVM.ForEach(item =>
{
item.IsChecked = checkBoxAll.IsChecked ?? false;
});
}
<summary>
</summary>
<param name="sender"></param>
<param name="e"></param>
private void <API key>(object sender, RoutedEventArgs e)
{
List<int> invalidSysNo = new List<int>();
gridVM.ForEach(item =>
{
if (item.IsChecked == true)
invalidSysNo.Add(item.SysNo.Value);
});
if (invalidSysNo.Count > 0)
facade.<API key>(invalidSysNo, (obj, args) =>
{
if (args.FaultsHandle())
return;
QueryResultGrid.Bind();
Window.Alert(ResKeywords.<API key>, MessageType.Information);
});
else
Window.Alert(ResKeywords.<API key>, MessageType.Error);
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class SelectOnInput : MonoBehaviour {
public EventSystem eventSystem;
public GameObject selectedObject;
private bool buttonSelected;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if(Input.GetAxisRaw("Vertical") != 0 && buttonSelected == false)
{
eventSystem.<API key>(selectedObject);
buttonSelected = true;
}
}
private void OnDisable()
{
buttonSelected = false;
}
}
|
package org.anddev.amatidev.pvb;
import java.util.LinkedList;
import org.amatidev.util.AdEnviroment;
import org.amatidev.util.AdPrefs;
import org.anddev.amatidev.pvb.bug.BugBeetle;
import org.anddev.amatidev.pvb.card.Card;
import org.anddev.amatidev.pvb.card.CardTomato;
import org.anddev.amatidev.pvb.obj.Dialog;
import org.anddev.amatidev.pvb.plant.Plant;
import org.anddev.amatidev.pvb.singleton.GameData;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.modifier.LoopEntityModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.modifier.<API key>;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.Text;
public class Tutorial extends MainGame {
private Sprite mArrow;
private int mTutorialStep = 1;
@Override
public void createScene() {
// sfondo e tabellone
Sprite back = new Sprite(0, 0, GameData.getInstance().mBackground);
Sprite table = new Sprite(0, 0, GameData.getInstance().mTable);
getChild(BACKGROUND_LAYER).attachChild(back);
getChild(BACKGROUND_LAYER).attachChild(table);
Sprite seed = new Sprite(25, 14, GameData.getInstance().mSeed);
table.attachChild(seed);
GameData.getInstance().mMySeed.setParent(null);
table.attachChild(GameData.getInstance().mMySeed);
// field position
for (int i = 0; i < FIELDS; i++) {
int x = i % 9;
int y = (int)(i / 9);
Rectangle field = new Rectangle(0, 0, 68, 74);
field.setColor(0f, 0f, 0f);
if (i % 2 == 0)
field.setAlpha(0.05f);
else
field.setAlpha(0.08f);
field.setPosition(42 + x * 71, 96 + y * 77);
getChild(GAME_LAYER).attachChild(field);
registerTouchArea(field);
}
}
protected void initLevel() {
// contatori per individuare se in una riga c'e' un nemico
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "enemy");
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "enemy_killed");
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count96.0");
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count173.0");
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count250.0");
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count327.0");
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count404.0");
GameData.getInstance().mMySeed.resetScore();
LinkedList<Card> cards = GameData.getInstance().mCards;
cards.clear();
cards.add(new CardTomato());
// TUTORIAL
this.mArrow = new Sprite(106, 95, GameData.getInstance().mArrow);
this.mArrow.setColor(1f, 0.4f, 0.4f);
this.mArrow.<API key>(
new LoopEntityModifier(
null,
-1,
null,
new <API key>(
new ScaleModifier(0.5f, 1f, 1.2f),
new ScaleModifier(0.5f, 1.2f, 1f)
)
)
);
getChild(GUI_LAYER).attachChild(this.mArrow);
AdEnviroment.getInstance().showMessage("Select a card to use");
AdEnviroment.getInstance().showMessage("Each card has a recharge time and price");
}
@Override
public void startScene() {
initLevel();
// add card
LinkedList<Card> cards = GameData.getInstance().mCards;
int start_x = 106;
for (int i = 0; i < cards.size(); i++) {
Card c = cards.get(i);
c.setPosition(start_x + i * 69, 7);
getChild(BACKGROUND_LAYER).attachChild(c);
}
Text skip = new Text(0, 0, GameData.getInstance().mFontTutorial, "Skip");
skip.setColor(1.0f, 0.3f, 0.3f);
skip.setPosition(37, 360);
getChild(GUI_LAYER).attachChild(skip);
registerTouchArea(skip);
}
public void checkLevelFinish() {
if (this.mGameOver == false && this.mLevelFinish == false) {
<API key>(new TimerHandler(2f, false, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
if (Tutorial.this.mTutorialStep == 4) {
final Sprite e = new Sprite(12, 25, GameData.getInstance().mSeed);
IEntity field = getChild(GAME_LAYER).getChild(12);
if (field.getChildCount() == 0)
field.attachChild(e);
Tutorial.this.mTutorialStep++;
Tutorial.this.mArrow.setPosition(310, 135);
Tutorial.this.mArrow.setRotation(-132f);
AdEnviroment.getInstance().showMessage("Pick the seeds producing the field to increase the stock");
}
}
}));
}
}
private void levelFinish() {
if (this.mGameOver == false && this.mLevelFinish == false) {
Dialog dialog = new Dialog("Tutorial\nComplete");
getChild(GUI2_LAYER).attachChild(dialog);
clearScene();
<API key>(new TimerHandler(6, false, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
AdEnviroment.getInstance().nextScene();
}
}));
this.mLevelFinish = true;
GameData.getInstance().mMyScore.resetScore();
}
}
@Override
public void manageAreaTouch(ITouchArea pTouchArea) {
if (pTouchArea instanceof Card) {
GameData.getInstance().mSoundCard.play();
this.mSelect = ((Card) pTouchArea).makeSelect();
// TUTORIAL
if (this.mTutorialStep == 1) {
this.mTutorialStep++;
this.mArrow.setPosition(595, 203);
this.mArrow.setRotation(132f);
AdEnviroment.getInstance().showMessage("If bugs incoming, try to kill them by planting");
BugBeetle e = new BugBeetle(250f);
getChild(GAME_LAYER).attachChild(e);
<API key>(new TimerHandler(6f, false, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
Tutorial.this.mTutorialStep++;
Tutorial.this.mArrow.setPosition(100, 203);
Tutorial.this.mArrow.setRotation(-132f);
AdEnviroment.getInstance().showMessage("If you have enough seeds you can plant");
}
}));
}
} else {
IEntity field = (IEntity) pTouchArea;
if (field.getChildCount() == 1 && !(field.getFirstChild() instanceof Plant)) {
GameData.getInstance().mSoundSeed.play();
GameData.getInstance().mMySeed.addScore(1);
AdEnviroment.getInstance().safeDetachEntity(field.getFirstChild());
if (this.mTutorialStep == 5) {
this.mTutorialStep++;
this.mArrow.setPosition(17, 95);
this.mArrow.setRotation(0f);
AdEnviroment.getInstance().showMessage("Seeds stock are increased to +1");
AdEnviroment.getInstance().showMessage("Kill bugs to complete levels and obtain score and new plants");
<API key>(new TimerHandler(9f, false, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
AdEnviroment.getInstance().getEngine().runOnUpdateThread(new Runnable() {
@Override
public void run() {
Tutorial.this.levelFinish();
}
});
}
}));
}
} else if (field instanceof Text) {
GameData.getInstance().mSoundMenu.play();
AdEnviroment.getInstance().nextScene();
} else {
if (this.mSelect != null && this.mSelect.isReady() && field.getChildCount() == 0 && this.mTutorialStep >= 3 && field.getY() == 250.0f) {
if (GameData.getInstance().mMySeed.getScore() >= this.mSelect.getPrice()) {
GameData.getInstance().mMySeed.addScore(-this.mSelect.getPrice());
this.mSelect.startRecharge();
field.attachChild(this.mSelect.getPlant());
// TUTORIAL
if (this.mTutorialStep == 3) {
this.mTutorialStep++;
this.mArrow.setPosition(17, 95);
this.mArrow.setRotation(0f);
AdEnviroment.getInstance().showMessage("Seeds stock are decreased because you bought a plant");
}
}
}
}
}
}
}
|
<html>
<body>
<table border="0" cellspacing="0" cellpadding="0" align="LEFT">
<tr>
<td><img src="file:
</tr>
</table>
</body>
</html>
|
## Introduction
<b>vedgTools/QtWidgetsUtilities</b> is a general-purpose C++ library, which
depends on QtCore and QtWidgets/QtGui libraries. Both Qt4 and Qt5 are supported.
It also depends on vedgTools/CMakeModules and vedgTools/QtCoreUtilities
libraries, which are present as submodules in this git repository.
Copyright (C) 2014 Igor Kushnir <igorkuo AT Google mail>
vedgTools/QtWidgetsUtilities is licensed under the <b>GNU GPLv3+</b> license,
a copy of which can be found in the `COPYING` file.
vedgTools/QtWidgetsUtilities 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.
vedgTools/QtWidgetsUtilities 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
vedgTools/QtWidgetsUtilities. If not, see <http:
|
package ai.grakn.engine.backgroundtasks.config;
/**
* <p>
* Class containing strings that describe the Kafka queues and groups
* </p>
*
* @author Denis Lobanov, alexandraorth
*/
public interface KafkaTerms {
String TASK_RUNNER_GROUP = "task-runners";
String SCHEDULERS_GROUP = "schedulers";
String WORK_QUEUE_TOPIC = "work-queue";
String NEW_TASKS_TOPIC = "new-tasks";
String LOG_TOPIC = "logs";
}
|
use sha1::{Sha1, Digest};
use std::fs;
let mut file = fs::File::open(&path)?;
let hash = Sha1::digest_reader(&mut file)?;
|
abstract class Adjunction[F[_], U[_]](
implicit val F: Functor[F],
val U: Representable[U]
){
def unit[A](a: A): U[F[A]]
def counit[A](a: F[U[A]]): A
}
|
function HistoryAssistant() {
}
HistoryAssistant.prototype.setup = function() {
this.appMenuModel = {
visible: true,
items: [
{ label: $L("About"), command: 'about' },
{ label: $L("Help"), command: 'tutorial' },
]
};
this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel);
var attributes = {};
this.model = {
//backgroundImage : 'images/glacier.png',
background: 'black',
onLeftFunction : this.wentLeft.bind(this),
onRightFunction : this.wentRight.bind(this)
}
this.controller.setupWidget('historydiv', attributes, this.model);
this.myPhotoDivElement = $('historydiv');
this.timestamp = new Date().getTime();
var env = Mojo.Environment.DeviceInfo;
if (env.screenHeight <= 400)
this.myPhotoDivElement.style.height = "372px";
}
HistoryAssistant.prototype.wentLeft = function(event){
this.timestamp = this.timestamp - (1000*60*60*24);
var timenow = new Date(this.timestamp);
var timenowstring = "";
var Ayear = timenow.getUTCFullYear();
var Amonth = timenow.getUTCMonth()+1;
if(Amonth.toString().length < 2)
Amonth = "0" + Amonth;
var Aday = timenow.getUTCDate();
if(Aday.toString().length < 2)
Aday = "0" + Aday;
/*var Ahours = timenow.getUTCHours();
if(Ahours.toString().length < 2)
Ahours = "0" + Ahours;*/
Ahours = "00";
if (this.timestamp > 1276146000000) {
if (this.timestamp > 1276146000000 + (1000 * 60 * 60 * 24)) {
this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday - 1) + Ahours + ".png");
}
this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png");
this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday + 1) + Ahours + ".png");
}
$('text').innerHTML = "<center>Histoy Of Pixels - " + Ayear + " / " + Amonth + " / " + Aday + "</center>";
}
HistoryAssistant.prototype.wentRight = function(event){
this.timestamp = this.timestamp + (1000*60*60*24);
var timenow = new Date(this.timestamp);
var timenowstring = "";
var Ayear = timenow.getUTCFullYear();
var Amonth = timenow.getUTCMonth()+1;
if(Amonth.toString().length < 2)
Amonth = "0" + Amonth;
var Aday = timenow.getUTCDate();
if(Aday.toString().length < 2)
Aday = "0" + Aday;
/*var Ahours = timenow.getUTCHours();
if(Ahours.toString().length < 2)
Ahours = "0" + Ahours;*/
Ahours = "00";
if (this.timestamp < new Date().getTime()) {
this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday - 1) + Ahours + ".png");
this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png");
if (this.timestamp + (1000*60*60*24) < new Date().getTime()) {
this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday + 1) + Ahours + ".png");
}
}
$('text').innerHTML = "<center>Histoy Of Pixels - " + Ayear + " / " + Amonth + " / " + Aday + "</center>";
}
HistoryAssistant.prototype.activate = function(event) {
var timenow = new Date(this.timestamp);
var timenowstring = "";
var Ayear = timenow.getUTCFullYear();
var Amonth = timenow.getUTCMonth()+1;
if(Amonth.toString().length < 2)
Amonth = "0" + Amonth;
var Aday = timenow.getUTCDate();
if(Aday.toString().length < 2)
Aday = "0" + Aday;
/*var Ahours = timenow.getUTCHours();
if(Ahours.toString().length < 2)
Ahours = "0" + Ahours;*/
Ahours = "00";
this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday-1) + Ahours + ".png");
this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png");
$('text').innerHTML = "<center>Histoy Of Pixels - " + Ayear + " / " + Amonth + " / " + Aday + "</center>";
}
HistoryAssistant.prototype.deactivate = function(event) {
}
HistoryAssistant.prototype.cleanup = function(event) {
}
HistoryAssistant.prototype.handleCommand = function(event){
if(event.type == Mojo.Event.command) {
switch (event.command) {
case 'about':
Mojo.Controller.stageController.pushScene("about");
break;
case 'tutorial':
this.controller.showAlertDialog({
onChoose: function(value) {},
title:"Help",
message:"This is the history of all pixels user have every created. Every night there is made a new snapshot.<br><br>Flip the image left or right to go through the history. Zoom into the image for more details.",
allowHTMLMessage: true,
choices:[ {label:'OK', value:'OK', type:'color'} ]
});
break;
}
}
}
|
# -*- coding: utf-8 -*-
import logging
from pprint import pformat
from time import clock, sleep
try:
import unittest2 as unittest
except ImportError:
import unittest
import config
from event_stack import TimeOutReached
from database_reception import Database_Reception
from static_agent_pools import Receptionists, Customers
logging.basicConfig (level = logging.INFO)
class Test_Case (unittest.TestCase):
Caller = None
Receptionist = None
Receptionist_2 = None
Callee = None
Reception_Database = None
Reception = None
Start_Time = None
Next_Step = 1
def Preconditions (self, Reception):
self.Start_Time = clock ()
self.Next_Step = 1
self.Log ("Incoming calls test case: Setting up preconditions...")
self.Log ("Requesting a customer (caller)...")
self.Caller = Customers.request ()
self.Log ("Requesting a receptionist...")
self.Receptionist = Receptionists.request ()
self.Log ("Requesting a second receptionist...")
self.Receptionist_2 = Receptionists.request ()
self.Log ("Requesting a customer (callee)...")
self.Callee = Customers.request ()
self.Log ("Select which reception to test...")
self.Reception = Reception
self.Log ("Select a reception database connection...")
self.Reception_Database = Database_Reception (uri = config.<API key>,
authtoken = self.Receptionist.call_control.authtoken)
def Postprocessing (self):
self.Log ("Incoming calls test case: Cleaning up after test...")
if not self.Caller is None:
self.Caller.release ()
if not self.Receptionist is None:
self.Receptionist.release ()
if not self.Receptionist_2 is None:
self.Receptionist_2.release ()
if not self.Callee is None:
self.Callee.release ()
def Step (self,
Message,
Delay_In_Seconds = 0.0):
if self.Next_Step is None:
self.Next_Step = 1
if self.Start_Time is None:
self.Start_Time = clock ()
logging.info ("Step " + str (self.Next_Step) + ": " + Message)
sleep (Delay_In_Seconds)
self.Next_Step += 1
def Log (self,
Message,
Delay_In_Seconds = 0.0):
if self.Next_Step is None:
self.Next_Step = 1
if self.Start_Time is None:
self.Start_Time = clock ()
logging.info (" " + str (self.Next_Step - 1) + ": " + Message)
sleep (Delay_In_Seconds)
def Caller_Places_Call (self, Number):
self.Step (Message = "Caller places call to " + str (Number) + "...")
self.Log (Message = "Dialling through caller agent...")
self.Caller.dial (Number)
def <API key> (self, Number):
self.Step (Message = "Receptionist places call to " + str (Number) + "...")
self.Log (Message = "Dialling through receptionist agent...")
self.Receptionist.dial (Number)
def <API key> (self):
self.Step (Message = "Caller hears dial-tone...")
self.Log (Message = "Caller agent waits for dial-tone...")
self.Caller.sip_phone.Wait_For_Dialtone ()
def <API key> (self):
self.Step (Message = "Receptionist hears dial-tone...")
self.Log (Message = "Receptionist agent waits for dial-tone...")
self.Receptionist.sip_phone.Wait_For_Dialtone ()
def Call_Announced (self):
self.Step (Message = "Receptionist's client waits for 'call_offer'...")
try:
self.Receptionist.event_stack.WaitFor ("call_offer")
except TimeOutReached:
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("Call offer didn't arrive from Call-Flow-Control.")
if not self.Receptionist.event_stack.stack_contains (event_type="call_offer",
destination=self.Reception):
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("The arrived call offer was not for the expected reception (destination).")
return self.Receptionist.event_stack.Get_Latest_Event (Event_Type="call_offer", Destination=self.Reception)['call']['id'],\
self.Receptionist.event_stack.Get_Latest_Event (Event_Type="call_offer", Destination=self.Reception)['call']['reception_id']
def <API key> (self, Call_ID):
self.Step (Message = "Call-Flow-Control sends out 'call_lock'...")
try:
self.Receptionist.event_stack.WaitFor (event_type = "call_lock",
call_id = Call_ID,
timeout = 20.0)
except TimeOutReached:
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("No 'call_lock' event arrived from Call-Flow-Control.")
if not self.Receptionist.event_stack.stack_contains (event_type = "call_lock",
destination = self.Reception,
call_id = Call_ID):
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("The arrived 'call_lock' event was not for the expected reception (destination).")
def <API key> (self, Call_ID):
self.Step (Message = "Call-Flow-Control sends out 'call_unlock'...")
try:
self.Receptionist.event_stack.WaitFor (event_type = "call_unlock",
call_id = Call_ID)
except TimeOutReached:
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("No 'call_unlock' event arrived from Call-Flow-Control.")
if not self.Receptionist.event_stack.stack_contains (event_type = "call_unlock",
destination = self.Reception,
call_id = Call_ID):
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("The arrived 'call_unlock' event was not for the expected reception (destination).")
def Request_Information (self, Reception_ID):
self.Step (Message = "Requesting (updated) information about reception " + str (Reception_ID))
Data_On_Reception = self.Reception_Database.Single (Reception_ID)
self.Step (Message = "Received information on reception " + str (Reception_ID))
return Data_On_Reception
def <API key> (self, Call_Flow_Control, Call_ID):
self.Step (Message = "Client offers to answer call...")
try:
Call_Flow_Control.PickupCall (call_id = Call_ID)
except:
self.Log (Message = "Pick-up call returned an error of some kind.")
def <API key> (self, Call_ID, Receptionist_ID):
self.Step (Message = "Receptionist's client waits for 'call_pickup'...")
try:
self.Receptionist.event_stack.WaitFor (event_type = "call_pickup",
call_id = Call_ID)
except TimeOutReached:
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("No 'call_pickup' event arrived from Call-Flow-Control.")
try:
Event = self.Receptionist.event_stack.Get_Latest_Event (Event_Type = "call_pickup",
Call_ID = Call_ID)
except:
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("Could not extract the received 'call_pickup' event from the Call-Flow-Control client.")
try:
if not Event['call']['assigned_to'] == Receptionist_ID:
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("The arrived 'call_pickup' event was for " + str (Event['call']['assigned_to']) + ", and not for " + str (Receptionist_ID) + " as expected.")
except:
logging.critical (self.Receptionist.event_stack.dump_stack ())
raise
self.Log (Message = "Call picked up: " + pformat (Event))
return Event
def <API key> (self, Call_Information, <API key>, <API key>):
self.Step (Message = "Receptionist answers...")
if Call_Information['call']['greeting_played']:
try:
self.Log (Message = "Receptionist says '" + <API key>['short_greeting'] + "'.")
except:
self.fail ("Reception information missing 'short_greeting'.")
else:
try:
self.Log (Message = "Receptionist says '" + <API key>['greeting'] + "'.")
except:
self.fail ("Reception information missing 'greeting'.")
if <API key>:
if not Call_Information['call']['greeting_played']:
self.fail ("It appears that the receptionist didn't wait long enough to allow the caller to hear the recorded message.")
else:
if Call_Information['call']['greeting_played']:
self.fail ("It appears that the receptionist waited too long, and allowed the caller to hear the recorded message.")
|
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//! Transaction data structure.
use std::ops::Deref;
use rlp::*;
use util::sha3::Hashable;
use util::{H256, Address, U256, Bytes, HeapSizeOf};
use ethkey::{Signature, Secret, Public, recover, public_to_address, Error as EthkeyError};
use error::*;
use evm::Schedule;
use header::BlockNumber;
use ethjson;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
Transaction action type.
pub enum Action {
Create creates new contract.
Create,
Calls contract at given address.
In the case of a transfer, this is the receiver's address.'
Call(Address),
}
impl Default for Action {
fn default() -> Action { Action::Create }
}
impl Decodable for Action {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let rlp = decoder.as_rlp();
if rlp.is_empty() {
Ok(Action::Create)
} else {
Ok(Action::Call(rlp.as_val()?))
}
}
}
Transaction activation condition.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
pub enum Condition {
Valid at this block number or later.
Number(BlockNumber),
Valid at this unix time or later.
Timestamp(u64),
}
A set of information describing an <API key> message call
or contract creation operation.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
pub struct Transaction {
Nonce.
pub nonce: U256,
Gas price.
pub gas_price: U256,
Gas paid up front for transaction execution.
pub gas: U256,
Action, can be either call or contract create.
pub action: Action,
Transfered value.
pub value: U256,
Transaction data.
pub data: Bytes,
}
impl Transaction {
Append object with a without signature into RLP stream
pub fn <API key>(&self, s: &mut RlpStream, network_id: Option<u64>) {
s.begin_list(if network_id.is_none() { 6 } else { 9 });
s.append(&self.nonce);
s.append(&self.gas_price);
s.append(&self.gas);
match self.action {
Action::Create => s.append_empty_data(),
Action::Call(ref to) => s.append(to)
};
s.append(&self.value);
s.append(&self.data);
if let Some(n) = network_id {
s.append(&n);
s.append(&0u8);
s.append(&0u8);
}
}
}
impl HeapSizeOf for Transaction {
fn <API key>(&self) -> usize {
self.data.<API key>()
}
}
impl From<ethjson::state::Transaction> for SignedTransaction {
fn from(t: ethjson::state::Transaction) -> Self {
let to: Option<ethjson::hash::Address> = t.to.into();
let secret = Secret::from_slice(&t.secret.0).expect("Valid secret expected.");
Transaction {
nonce: t.nonce.into(),
gas_price: t.gas_price.into(),
gas: t.gas_limit.into(),
action: match to {
Some(to) => Action::Call(to.into()),
None => Action::Create
},
value: t.value.into(),
data: t.data.into(),
}.sign(&secret, None)
}
}
impl From<ethjson::transaction::Transaction> for <API key> {
fn from(t: ethjson::transaction::Transaction) -> Self {
let to: Option<ethjson::hash::Address> = t.to.into();
<API key> {
unsigned: Transaction {
nonce: t.nonce.into(),
gas_price: t.gas_price.into(),
gas: t.gas_limit.into(),
action: match to {
Some(to) => Action::Call(to.into()),
None => Action::Create
},
value: t.value.into(),
data: t.data.into(),
},
r: t.r.into(),
s: t.s.into(),
v: t.v.into(),
hash: 0.into(),
}.compute_hash()
}
}
impl Transaction {
The message hash of the transaction.
pub fn hash(&self, network_id: Option<u64>) -> H256 {
let mut stream = RlpStream::new();
self.<API key>(&mut stream, network_id);
stream.as_raw().sha3()
}
Signs the transaction as coming from `sender`.
pub fn sign(self, secret: &Secret, network_id: Option<u64>) -> SignedTransaction {
let sig = ::ethkey::sign(secret, &self.hash(network_id))
.expect("data is valid and context has signing capabilities; qed");
SignedTransaction::new(self.with_signature(sig, network_id))
.expect("secret is valid so it's recoverable")
}
Signs the transaction with signature.
pub fn with_signature(self, sig: Signature, network_id: Option<u64>) -> <API key> {
<API key> {
unsigned: self,
r: sig.r().into(),
s: sig.s().into(),
v: sig.v() as u64 + if let Some(n) = network_id { 35 + n * 2 } else { 27 },
hash: 0.into(),
}.compute_hash()
}
Useful for test incorrectly signed transactions.
#[cfg(test)]
pub fn invalid_sign(self) -> <API key> {
<API key> {
unsigned: self,
r: U256::default(),
s: U256::default(),
v: 0,
hash: 0.into(),
}.compute_hash()
}
Specify the sender; this won't survive the serialize/deserialize process, but can be cloned.
pub fn fake_sign(self, from: Address) -> SignedTransaction {
SignedTransaction {
transaction: <API key> {
unsigned: self,
r: U256::default(),
s: U256::default(),
v: 0,
hash: 0.into(),
}.compute_hash(),
sender: from,
public: Public::default(),
}
}
Get the transaction cost in gas for the given params.
pub fn gas_required_for(is_create: bool, data: &[u8], schedule: &Schedule) -> u64 {
data.iter().fold(
(if is_create {schedule.tx_create_gas} else {schedule.tx_gas}) as u64,
|g, b| g + (match *b { 0 => schedule.tx_data_zero_gas, _ => schedule.<API key> }) as u64
)
}
Get the transaction cost in gas for this transaction.
pub fn gas_required(&self, schedule: &Schedule) -> u64 {
Self::gas_required_for(match self.action{Action::Create=>true, Action::Call(_)=>false}, &self.data, schedule)
}
}
Signed transaction information.
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "ipc", binary)]
pub struct <API key> {
Plain Transaction.
unsigned: Transaction,
The V field of the signature; the LS bit described which half of the curve our point falls
in. The MS bits describe which network this transaction is for. If 27/28, its for all networks.
v: u64,
The R field of the signature; helps describe the point on the curve.
r: U256,
The S field of the signature; helps describe the point on the curve.
s: U256,
Hash of the transaction
hash: H256,
}
impl Deref for <API key> {
type Target = Transaction;
fn deref(&self) -> &Self::Target {
&self.unsigned
}
}
impl Decodable for <API key> {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp();
if d.item_count() != 9 {
return Err(DecoderError::RlpIncorrectListLen);
}
let hash = decoder.as_raw().sha3();
Ok(<API key> {
unsigned: Transaction {
nonce: d.val_at(0)?,
gas_price: d.val_at(1)?,
gas: d.val_at(2)?,
action: d.val_at(3)?,
value: d.val_at(4)?,
data: d.val_at(5)?,
},
v: d.val_at(6)?,
r: d.val_at(7)?,
s: d.val_at(8)?,
hash: hash,
})
}
}
impl Encodable for <API key> {
fn rlp_append(&self, s: &mut RlpStream) { self.<API key>(s) }
}
impl <API key> {
Used to compute hash of created transactions
fn compute_hash(mut self) -> <API key> {
let hash = (&*self.rlp_bytes()).sha3();
self.hash = hash;
self
}
Append object with a signature into RLP stream
fn <API key>(&self, s: &mut RlpStream) {
s.begin_list(9);
s.append(&self.nonce);
s.append(&self.gas_price);
s.append(&self.gas);
match self.action {
Action::Create => s.append_empty_data(),
Action::Call(ref to) => s.append(to)
};
s.append(&self.value);
s.append(&self.data);
s.append(&self.v);
s.append(&self.r);
s.append(&self.s);
}
Reference to unsigned part of this transaction.
pub fn as_unsigned(&self) -> &Transaction {
&self.unsigned
}
0 if `v` would have been 27 under "Electrum" notation, 1 if 28 or 4 if invalid.
pub fn standard_v(&self) -> u8 { match self.v { v if v == 27 || v == 28 || v > 36 => ((v - 1) % 2) as u8, _ => 4 } }
The `v` value that appears in the RLP.
pub fn original_v(&self) -> u64 { self.v }
The network ID, or `None` if this is a global transaction.
pub fn network_id(&self) -> Option<u64> {
match self.v {
v if v > 36 => Some((v - 35) / 2),
_ => None,
}
}
Construct a signature object from the sig.
pub fn signature(&self) -> Signature {
Signature::from_rsv(&self.r.into(), &self.s.into(), self.standard_v())
}
Checks whether the signature has a low 's' value.
pub fn check_low_s(&self) -> Result<(), Error> {
if !self.signature().is_low_s() {
Err(EthkeyError::InvalidSignature.into())
} else {
Ok(())
}
}
Get the hash of this header (sha3 of the RLP).
pub fn hash(&self) -> H256 {
self.hash
}
Recovers the public key of the sender.
pub fn recover_public(&self) -> Result<Public, Error> {
Ok(recover(&self.signature(), &self.unsigned.hash(self.network_id()))?)
}
Do basic validation, checking for valid signature and minimum gas,
// TODO: consider use in block validation.
#[cfg(test)]
#[cfg(feature = "json-tests")]
pub fn validate(self, schedule: &Schedule, require_low: bool, <API key>: bool) -> Result<<API key>, Error> {
if require_low && !self.signature().is_low_s() {
return Err(EthkeyError::InvalidSignature.into())
}
match self.network_id() {
None => {},
Some(1) if <API key> => {},
_ => return Err(TransactionError::InvalidNetworkId.into()),
}
self.recover_public()?;
if self.gas < U256::from(self.gas_required(&schedule)) {
Err(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}).into())
} else {
Ok(self)
}
}
}
A `<API key>` with successfully recovered `sender`.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SignedTransaction {
transaction: <API key>,
sender: Address,
public: Public,
}
impl HeapSizeOf for SignedTransaction {
fn <API key>(&self) -> usize {
self.transaction.unsigned.<API key>()
}
}
impl Encodable for SignedTransaction {
fn rlp_append(&self, s: &mut RlpStream) { self.transaction.<API key>(s) }
}
impl Deref for SignedTransaction {
type Target = <API key>;
fn deref(&self) -> &Self::Target {
&self.transaction
}
}
impl From<SignedTransaction> for <API key> {
fn from(tx: SignedTransaction) -> Self {
tx.transaction
}
}
impl SignedTransaction {
Try to verify transaction and recover sender.
pub fn new(transaction: <API key>) -> Result<Self, Error> {
let public = transaction.recover_public()?;
let sender = public_to_address(&public);
Ok(SignedTransaction {
transaction: transaction,
sender: sender,
public: public,
})
}
Returns transaction sender.
pub fn sender(&self) -> Address {
self.sender
}
Returns a public key of the sender.
pub fn public_key(&self) -> Public {
self.public
}
}
Signed Transaction that is a part of canon blockchain.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
pub struct <API key> {
Signed part.
pub signed: <API key>,
Block number.
pub block_number: BlockNumber,
Block hash.
pub block_hash: H256,
Transaction index within block.
pub transaction_index: usize,
Cached sender
pub cached_sender: Option<Address>,
}
impl <API key> {
Returns transaction sender.
Panics if `<API key>` is constructed using invalid `<API key>`.
pub fn sender(&mut self) -> Address {
if let Some(sender) = self.cached_sender {
return sender;
}
let sender = public_to_address(&self.recover_public()
.expect("<API key> is always constructed from transaction from blockchain; Blockchain only stores verified transactions; qed"));
self.cached_sender = Some(sender);
sender
}
}
impl Deref for <API key> {
type Target = <API key>;
fn deref(&self) -> &Self::Target {
&self.signed
}
}
Queued transaction with additional information.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
pub struct PendingTransaction {
Signed transaction data.
pub transaction: SignedTransaction,
To be activated at this condition. `None` for immediately.
pub condition: Option<Condition>,
}
impl PendingTransaction {
Create a new pending transaction from signed transaction.
pub fn new(signed: SignedTransaction, condition: Option<Condition>) -> Self {
PendingTransaction {
transaction: signed,
condition: condition,
}
}
}
impl Deref for PendingTransaction {
type Target = SignedTransaction;
fn deref(&self) -> &SignedTransaction { &self.transaction }
}
impl From<SignedTransaction> for PendingTransaction {
fn from(t: SignedTransaction) -> Self {
PendingTransaction {
transaction: t,
condition: None,
}
}
}
#[test]
fn sender_test() {
let t: <API key> = decode(&::rustc_serialize::hex::FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap());
assert_eq!(t.data, b"");
assert_eq!(t.gas, U256::from(0x5208u64));
assert_eq!(t.gas_price, U256::from(0x01u64));
assert_eq!(t.nonce, U256::from(0x00u64));
if let Action::Call(ref to) = t.action {
assert_eq!(*to, "<SHA1-like>".into());
} else { panic!(); }
assert_eq!(t.value, U256::from(0x0au64));
assert_eq!(public_to_address(&t.recover_public().unwrap()), "<SHA1-like>".into());
assert_eq!(t.network_id(), None);
}
#[test]
fn signing() {
use ethkey::{Random, Generator};
let key = Random.generate().unwrap();
let t = Transaction {
action: Action::Create,
nonce: U256::from(42),
gas_price: U256::from(3000),
gas: U256::from(50_000),
value: U256::from(1),
data: b"Hello!".to_vec()
}.sign(&key.secret(), None);
assert_eq!(Address::from(key.public().sha3()), t.sender());
assert_eq!(t.network_id(), None);
}
#[test]
fn fake_signing() {
let t = Transaction {
action: Action::Create,
nonce: U256::from(42),
gas_price: U256::from(3000),
gas: U256::from(50_000),
value: U256::from(1),
data: b"Hello!".to_vec()
}.fake_sign(Address::from(0x69));
assert_eq!(Address::from(0x69), t.sender());
assert_eq!(t.network_id(), None);
let t = t.clone();
assert_eq!(Address::from(0x69), t.sender());
assert_eq!(t.network_id(), None);
}
#[test]
fn <API key>() {
use ethkey::{Random, Generator};
let key = Random.generate().unwrap();
let t = Transaction {
action: Action::Create,
nonce: U256::from(42),
gas_price: U256::from(3000),
gas: U256::from(50_000),
value: U256::from(1),
data: b"Hello!".to_vec()
}.sign(&key.secret(), Some(69));
assert_eq!(Address::from(key.public().sha3()), t.sender());
assert_eq!(t.network_id(), Some(69));
}
#[test]
fn <API key>() {
use rustc_serialize::hex::FromHex;
let test_vector = |tx_data: &str, address: &'static str| {
let signed = decode(&FromHex::from_hex(tx_data).unwrap());
let signed = SignedTransaction::new(signed).unwrap();
assert_eq!(signed.sender(), address.into());
flushln!("networkid: {:?}", signed.network_id());
};
test_vector("f864808504a817c800825208943535353535353535353535353535353535353535808025a0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116da0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d", "<API key>");
test_vector("f864018504a817c80182a410943535353535353535353535353535353535353535018025a0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bcaa0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", "<API key>");
test_vector("f864028504a817c80282f618943535353535353535353535353535353535353535088025a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5", "<API key>");
test_vector("f865038504a817c803830148209435353535353535353535353535353535353535351b8025a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4e0a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4de", "<API key>");
test_vector("f865048504a817c80483019a28943535353535353535353535353535353535353535408025a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c063a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c060", "<API key>");
test_vector("f865058504a817c8058301ec309435353535353535353535353535353535353535357d8025a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "<API key>");
test_vector("f866068504a817c80683023e3894353535353535353535353535353535353535353581d88025a06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2fa06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2d", "<API key>");
test_vector("f867078504a817c807830290409435353535353535353535353535353535353535358201578025a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021", "<API key>");
test_vector("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", "<API key>");
test_vector("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", "<API key>");
}
|
#pragma once
#include <ros/assert.h>
#include <iostream>
#include <eigen3/Eigen/Dense>
#include "../utility/utility.h"
#include "../parameters.h"
#include "integration_base.h"
#include <ceres/ceres.h>
class IMUFactor : public ceres::SizedCostFunction<15, 7, 9, 7, 9>
{
public:
IMUFactor() = delete;
IMUFactor(IntegrationBase* _pre_integration):pre_integration(_pre_integration)
{
}
virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const
{
Eigen::Vector3d Pi(parameters[0][0], parameters[0][1], parameters[0][2]);
Eigen::Quaterniond Qi(parameters[0][6], parameters[0][3], parameters[0][4], parameters[0][5]);
Eigen::Vector3d Vi(parameters[1][0], parameters[1][1], parameters[1][2]);
Eigen::Vector3d Bai(parameters[1][3], parameters[1][4], parameters[1][5]);
Eigen::Vector3d Bgi(parameters[1][6], parameters[1][7], parameters[1][8]);
Eigen::Vector3d Pj(parameters[2][0], parameters[2][1], parameters[2][2]);
Eigen::Quaterniond Qj(parameters[2][6], parameters[2][3], parameters[2][4], parameters[2][5]);
Eigen::Vector3d Vj(parameters[3][0], parameters[3][1], parameters[3][2]);
Eigen::Vector3d Baj(parameters[3][3], parameters[3][4], parameters[3][5]);
Eigen::Vector3d Bgj(parameters[3][6], parameters[3][7], parameters[3][8]);
//Eigen::Matrix<double, 15, 15> Fd;
//Eigen::Matrix<double, 15, 12> Gd;
//Eigen::Vector3d pPj = Pi + Vi * sum_t - 0.5 * g * sum_t * sum_t + corrected_delta_p;
//Eigen::Quaterniond pQj = Qi * delta_q;
//Eigen::Vector3d pVj = Vi - g * sum_t + corrected_delta_v;
//Eigen::Vector3d pBaj = Bai;
//Eigen::Vector3d pBgj = Bgi;
//Vi + Qi * delta_v - g * sum_dt = Vj;
//Qi * delta_q = Qj;
//delta_p = Qi.inverse() * (0.5 * g * sum_dt * sum_dt + Pj - Pi);
//delta_v = Qi.inverse() * (g * sum_dt + Vj - Vi);
//delta_q = Qi.inverse() * Qj;
#if 0
if ((Bai - pre_integration->linearized_ba).norm() > 0.10 ||
(Bgi - pre_integration->linearized_bg).norm() > 0.01)
{
pre_integration->repropagate(Bai, Bgi);
}
#endif
Eigen::Map<Eigen::Matrix<double, 15, 1>> residual(residuals);
residual = pre_integration->evaluate(Pi, Qi, Vi, Bai, Bgi,
Pj, Qj, Vj, Baj, Bgj);
Eigen::Matrix<double, 15, 15> sqrt_info = Eigen::LLT<Eigen::Matrix<double, 15, 15>>(pre_integration->covariance.inverse()).matrixL().transpose();
//sqrt_info.setIdentity();
residual = sqrt_info * residual;
if (jacobians)
{
double sum_dt = pre_integration->sum_dt;
Eigen::Matrix3d dp_dba = pre_integration->jacobian.template block<3, 3>(O_P, O_BA);
Eigen::Matrix3d dp_dbg = pre_integration->jacobian.template block<3, 3>(O_P, O_BG);
Eigen::Matrix3d dq_dbg = pre_integration->jacobian.template block<3, 3>(O_R, O_BG);
Eigen::Matrix3d dv_dba = pre_integration->jacobian.template block<3, 3>(O_V, O_BA);
Eigen::Matrix3d dv_dbg = pre_integration->jacobian.template block<3, 3>(O_V, O_BG);
if (pre_integration->jacobian.maxCoeff() > 1e8 || pre_integration->jacobian.minCoeff() < -1e8)
{
ROS_WARN("numerical unstable in preintegration");
//std::cout << pre_integration->jacobian << std::endl;
ROS_BREAK();
}
if (jacobians[0])
{
Eigen::Map<Eigen::Matrix<double, 15, 7, Eigen::RowMajor>> jacobian_pose_i(jacobians[0]);
jacobian_pose_i.setZero();
jacobian_pose_i.block<3, 3>(O_P, O_P) = -Qi.inverse().toRotationMatrix();
jacobian_pose_i.block<3, 3>(O_P, O_R) = Utility::skewSymmetric(Qi.inverse() * (0.5 * G * sum_dt * sum_dt + Pj - Pi - Vi * sum_dt));
#if 0
jacobian_pose_i.block<3, 3>(O_R, O_R) = -(Qj.inverse() * Qi).toRotationMatrix();
#else
Eigen::Quaterniond corrected_delta_q = pre_integration->delta_q * Utility::deltaQ(dq_dbg * (Bgi - pre_integration->linearized_bg));
jacobian_pose_i.block<3, 3>(O_R, O_R) = -(Utility::Qleft(Qj.inverse() * Qi) * Utility::Qright(corrected_delta_q)).bottomRightCorner<3, 3>();
#endif
jacobian_pose_i.block<3, 3>(O_V, O_R) = Utility::skewSymmetric(Qi.inverse() * (G * sum_dt + Vj - Vi));
jacobian_pose_i = sqrt_info * jacobian_pose_i;
if (jacobian_pose_i.maxCoeff() > 1e8 || jacobian_pose_i.minCoeff() < -1e8)
{
ROS_WARN("numerical unstable in preintegration");
//std::cout << sqrt_info << std::endl;
//ROS_BREAK();
}
}
if (jacobians[1])
{
Eigen::Map<Eigen::Matrix<double, 15, 9, Eigen::RowMajor>> <API key>(jacobians[1]);
<API key>.setZero();
<API key>.block<3, 3>(O_P, O_V - O_V) = -Qi.inverse().toRotationMatrix() * sum_dt;
<API key>.block<3, 3>(O_P, O_BA - O_V) = -dp_dba;
<API key>.block<3, 3>(O_P, O_BG - O_V) = -dp_dbg;
#if 0
<API key>.block<3, 3>(O_R, O_BG - O_V) = -dq_dbg;
#else
//Eigen::Quaterniond corrected_delta_q = pre_integration->delta_q * Utility::deltaQ(dq_dbg * (Bgi - pre_integration->linearized_bg));
//<API key>.block<3, 3>(O_R, O_BG - O_V) = -Utility::Qleft(Qj.inverse() * Qi * corrected_delta_q).bottomRightCorner<3, 3>() * dq_dbg;
<API key>.block<3, 3>(O_R, O_BG - O_V) = -Utility::Qleft(Qj.inverse() * Qi * pre_integration->delta_q).bottomRightCorner<3, 3>() * dq_dbg;
#endif
<API key>.block<3, 3>(O_V, O_V - O_V) = -Qi.inverse().toRotationMatrix();
<API key>.block<3, 3>(O_V, O_BA - O_V) = -dv_dba;
<API key>.block<3, 3>(O_V, O_BG - O_V) = -dv_dbg;
<API key>.block<3, 3>(O_BA, O_BA - O_V) = -Eigen::Matrix3d::Identity();
<API key>.block<3, 3>(O_BG, O_BG - O_V) = -Eigen::Matrix3d::Identity();
<API key> = sqrt_info * <API key>;
//ROS_ASSERT(fabs(<API key>.maxCoeff()) < 1e8);
//ROS_ASSERT(fabs(<API key>.minCoeff()) < 1e8);
}
if (jacobians[2])
{
Eigen::Map<Eigen::Matrix<double, 15, 7, Eigen::RowMajor>> jacobian_pose_j(jacobians[2]);
jacobian_pose_j.setZero();
jacobian_pose_j.block<3, 3>(O_P, O_P) = Qi.inverse().toRotationMatrix();
#if 0
jacobian_pose_j.block<3, 3>(O_R, O_R) = Eigen::Matrix3d::Identity();
#else
Eigen::Quaterniond corrected_delta_q = pre_integration->delta_q * Utility::deltaQ(dq_dbg * (Bgi - pre_integration->linearized_bg));
jacobian_pose_j.block<3, 3>(O_R, O_R) = Utility::Qleft(corrected_delta_q.inverse() * Qi.inverse() * Qj).bottomRightCorner<3, 3>();
#endif
jacobian_pose_j = sqrt_info * jacobian_pose_j;
//ROS_ASSERT(fabs(jacobian_pose_j.maxCoeff()) < 1e8);
//ROS_ASSERT(fabs(jacobian_pose_j.minCoeff()) < 1e8);
}
if (jacobians[3])
{
Eigen::Map<Eigen::Matrix<double, 15, 9, Eigen::RowMajor>> <API key>(jacobians[3]);
<API key>.setZero();
<API key>.block<3, 3>(O_V, O_V - O_V) = Qi.inverse().toRotationMatrix();
<API key>.block<3, 3>(O_BA, O_BA - O_V) = Eigen::Matrix3d::Identity();
<API key>.block<3, 3>(O_BG, O_BG - O_V) = Eigen::Matrix3d::Identity();
<API key> = sqrt_info * <API key>;
//ROS_ASSERT(fabs(<API key>.maxCoeff()) < 1e8);
//ROS_ASSERT(fabs(<API key>.minCoeff()) < 1e8);
}
}
return true;
}
//bool Evaluate_Direct(double const *const *parameters, Eigen::Matrix<double, 15, 1> &residuals, Eigen::Matrix<double, 15, 30> &jacobians);
//void checkCorrection();
//void checkTransition();
//void checkJacobian(double **parameters);
IntegrationBase* pre_integration;
};
|
#ifndef <API key>
#define <API key>
#include <vector>
#include <utility> // std::pair
#include "MATH_CONSTANTS.h"
#include "gnss_frequencies.h"
#define <API key> 20
#define <API key> 25
#define <API key> 50
#define <API key> 0.85
// Physical constants
const double GPS_C_m_s = SPEED_OF_LIGHT; //!< The speed of light, [m/s]
const double GPS_C_m_ms = 299792.4580; //!< The speed of light, [m/ms]
const double GPS_PI = 3.1415926535898; //!< Pi as defined in IS-GPS-200E
const double GPS_TWO_PI = 6.283185307179586;//!< 2Pi as defined in IS-GPS-200E
const double OMEGA_EARTH_DOT = <API key>; //!< Earth rotation rate, [rad/s]
const double GM = 3.986005e14; //!< Universal gravitational constant times the mass of the Earth, [m^3/s^2]
const double F = -4.442807633e-10; //!< Constant, [s/(m)^(1/2)]
// carrier and code frequencies
const double GPS_L1_FREQ_HZ = FREQ1; //!< L1 [Hz]
const double <API key> = 1.023e6; //!< GPS L1 C/A code rate [chips/s]
const double <API key> = 1023.0; //!< GPS L1 C/A code length [chips]
const double <API key> = 0.001; //!< GPS L1 C/A code period [seconds]
const double <API key> = 9.7752e-07; //!< GPS L1 C/A chip period [seconds]
/*!
* \brief Maximum Time-Of-Arrival (TOA) difference between satellites for a receiver operated on Earth surface is 20 ms
*
* According to the GPS orbit model described in [1] Pag. 32.
* It should be taken into account to set the buffer size for the PRN start timestamp in the pseudoranges block.
* [1] J. Bao-Yen Tsui, Fundamentals of Global Positioning System Receivers. A Software Approach, John Wiley & Sons,
* Inc., Hoboken, NJ, 2nd edition, 2005.
*/
const double MAX_TOA_DELAY_MS = 20;
//#define <API key> 1000 // this cannot go here
const double GPS_STARTOFFSET_ms = 68.802; //[ms] Initial sign. travel time (this cannot go here)
// OBSERVABLE HISTORY DEEP FOR INTERPOLATION
const int <API key> = 500;
// NAVIGATION MESSAGE DEMODULATION AND DECODING
#define GPS_PREAMBLE {1, 0, 0, 0, 1, 0, 1, 1}
const int <API key> = 8;
const int <API key> = 160;
const double <API key> = 0.160;
const int <API key> = 50; //!< NAV message bit rate [bits/s]
const int <API key> = 20;
const int <API key> = <API key>*<API key>; //!< NAV message bit rate [symbols/s]
const int GPS_WORD_LENGTH = 4; //!< CRC + GPS WORD (-2 -1 0 ... 29) Bits = 4 bytes
const int GPS_SUBFRAME_LENGTH = 40; //!< GPS_WORD_LENGTH x 10 = 40 bytes
const int GPS_SUBFRAME_BITS = 300; //!< Number of bits per subframe in the NAV message [bits]
const int <API key> = 6; //!< Subframe duration [seconds]
const int GPS_SUBFRAME_MS = 6000; //!< Subframe duration [seconds]
const int GPS_WORD_BITS = 30; //!< Number of bits per word in the NAV message [bits]
// GPS NAVIGATION MESSAGE STRUCTURE
// NAVIGATION MESSAGE FIELDS POSITIONS (from IS-GPS-200E Appendix II)
// SUBFRAME 1-5 (TLM and HOW)
const std::vector<std::pair<int,int> > TOW( { {31,17} } );
const std::vector<std::pair<int,int> > <API key>({{23,1}});
const std::vector<std::pair<int,int> > ALERT_FLAG({{48,1}});
const std::vector<std::pair<int,int> > ANTI_SPOOFING_FLAG({{49,1}});
const std::vector<std::pair<int,int> > SUBFRAME_ID({{50,3}});
// SUBFRAME 1
const std::vector<std::pair<int,int>> GPS_WEEK({{61,10}});
#endif /* <API key> */
|
app.controller('NavCtrl', [
'$scope',
'$state',
'auth',
function($scope, $state, auth){
$scope.isLoggedIn = auth.isLoggedIn;
$scope.currentUser = auth.currentUser;
$scope.logOut = auth.logOut;
$scope.loggedin = auth.isLoggedIn();
if($scope.loggedin){
auth.validate(auth.getToken()).success(function(data){
if(!data.valid){
auth.logOut();
$state.go("login");
}
});
}
}]);
|
# Topydo - A todo.txt client written in Python.
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
|
#ifndef SEGY_H
#define SEGY_H
#define SU_NFLTS 32768 /* Arbitrary limit on data array size */
/* TYPEDEFS */
#ifdef _CRAY
typedef struct { /* segy - trace identification header */
signed tracl :32; /* trace sequence number within line */
signed tracr :32; /* trace sequence number within reel */
signed fldr :32; /* field record number */
signed tracf :32; /* trace number within field record */
signed ep :32; /* energy source point number */
signed cdp :32; /* CDP ensemble number */
signed cdpt :32; /* trace number within CDP ensemble */
signed nvs :16; /* number of vertically summed traces (see vscode
in bhed structure) */
signed nhs :16; /* number of horizontally summed traces (see vscode
in bhed structure) */
signed duse :16; /* data use:
1 = production
2 = test */
signed offset :32; /* distance from source point to receiver
group (negative if opposite to direction
in which the line was shot) */
signed gelev :32; /* receiver group elevation from sea level
(above sea level is positive) */
signed selev :32; /* source elevation from sea level
(above sea level is positive) */
signed sdepth :32; /* source depth (positive) */
signed gdel :32; /* datum elevation at receiver group */
signed sdel :32; /* datum elevation at source */
signed swdep :32; /* water depth at source */
signed gwdep :32; /* water depth at receiver group */
signed scalel :16; /* scale factor for previous 7 entries
with value plus or minus 10 to the
power 0, 1, 2, 3, or 4 (if positive,
multiply, if negative divide) */
signed scalco :16; /* scale factor for next 4 entries
with value plus or minus 10 to the
power 0, 1, 2, 3, or 4 (if positive,
multiply, if negative divide) */
signed sx :32; /* X source coordinate */
signed sy :32; /* Y source coordinate */
signed gx :32; /* X group coordinate */
signed gy :32; /* Y group coordinate */
signed counit :16; /* coordinate units code:
for previous four entries
1 = length (meters or feet)
2 = seconds of arc (in this case, the
X values are longitude and the Y values
are latitude, a positive value designates
the number of seconds east of Greenwich
or north of the equator */
signed wevel :16; /* weathering velocity */
signed swevel :16; /* subweathering velocity */
signed sut :16; /* uphole time at source */
signed gut :16; /* uphole time at receiver group */
signed sstat :16; /* source static correction */
signed gstat :16; /* group static correction */
signed tstat :16; /* total static applied */
signed laga :16; /* lag time A, time in ms between end of 240-
byte trace identification header and time
break, positive if time break occurs after
end of header, time break is defined as
the initiation pulse which maybe recorded
on an auxiliary trace or as otherwise
specified by the recording system */
signed lagb :16; /* lag time B, time in ms between the time break
and the initiation time of the energy source,
may be positive or negative */
signed delrt :16; /* delay recording time, time in ms between
initiation time of energy source and time
when recording of data samples begins
(for deep water work if recording does not
start at zero time) */
signed muts :16; /* mute time--start */
signed mute :16; /* mute time--end */
unsigned ns :16; /* number of samples in this trace */
unsigned dt :16; /* sample interval; in micro-seconds */
signed igc :16; /* instrument gain constant */
signed igi :16; /* instrument early or initial gain */
signed corr :16; /* correlated:
1 = no
2 = yes */
signed sfs :16; /* sweep frequency at start */
signed sfe :16; /* sweep frequency at end */
signed slen :16; /* sweep length in ms */
signed styp :16; /* sweep type code:
1 = linear
2 = cos-squared
3 = other */
signed stas :16; /* sweep trace length at start in ms */
signed stae :16; /* sweep trace length at end in ms */
signed tatyp :16; /* taper type: 1=linear, 2=cos^2, 3=other */
signed afilf :16; /* alias filter frequency if used */
signed afils :16; /* alias filter slope */
signed nofilf :16; /* notch filter frequency if used */
signed nofils :16; /* notch filter slope */
signed lcf :16; /* low cut frequency if used */
signed hcf :16; /* high cut frequncy if used */
signed lcs :16; /* low cut slope */
signed hcs :16; /* high cut slope */
signed year :16; /* year data recorded */
signed day :16; /* day of year */
signed hour :16; /* hour of day (24 hour clock) */
signed minute :16; /* minute of hour */
signed sec :16; /* second of minute */
signed timbas :16; /* time basis code:
1 = local
2 = GMT
3 = other */
signed trwf :16; /* trace weighting factor, defined as 1/2^N
volts for the least sigificant bit */
signed grnors :16; /* geophone group number of roll switch
position one */
signed grnofr :16; /* geophone group number of trace one within
original field record */
signed grnlof :16; /* geophone group number of last trace within
original field record */
signed gaps :16; /* gap size (total number of groups dropped) */
signed otrav :16; /* overtravel taper code:
1 = down (or behind)
2 = up (or ahead) */
/* local assignments */
/* signed pad :32; */ /* double word alignment for Cray 64-bit floats */
float d1; /* sample spacing for non-seismic data */
float f1; /* first sample location for non-seismic data */
float d2; /* sample spacing between traces */
float f2; /* first trace location */
float ungpow; /* negative of power used for dynamic
range compression */
float unscale; /* reciprocal of scaling factor to normalize
range */
signed ntr :32; /* number of traces */
signed mark :16; /* mark selected traces */
signed unass :16; /* unassigned values */
float data[SU_NFLTS];
} segy;
typedef struct { /* bhed - binary header */
int jobid :32; /* job identification number */
int lino :32; /* line number (only one line per reel) */
int reno :32; /* reel number */
short ntrpr :16; /* number of data traces per record */
short nart :16; /* number of auxiliary traces per record */
short hdt :16; /* sample interval in micro secs for this reel */
short dto :16; /* same for original field recording */
short hns :16; /* number of samples per trace for this reel */
short nso :16; /* same for original field recording */
short format :16; /* data sample format code:
1 = floating point (4 bytes)
2 = fixed point (4 bytes)
3 = fixed point (2 bytes)
4 = fixed point w/gain code (4 bytes) */
short fold :16; /* CDP fold expected per CDP ensemble */
short tsort :16; /* trace sorting code:
1 = as recorded (no sorting)
2 = CDP ensemble
3 = single fold continuous profile
4 = horizontally stacked */
short vscode :16; /* vertical sum code:
1 = no sum
2 = two sum ...
N = N sum (N = 32,767) */
short hsfs :16; /* sweep frequency at start */
short hsfe :16; /* sweep frequency at end */
short hslen :16; /* sweep length (ms) */
short hstyp :16; /* sweep type code:
1 = linear
2 = parabolic
3 = exponential
4 = other */
short schn :16; /* trace number of sweep channel */
short hstas :16; /* sweep trace taper length at start if
tapered (the taper starts at zero time
and is effective for this length) */
short hstae :16; /* sweep trace taper length at end (the ending
taper starts at sweep length minus the taper
length at end) */
short htatyp :16; /* sweep trace taper type code:
1 = linear
2 = cos-squared
3 = other */
short hcorr :16; /* correlated data traces code:
1 = no
2 = yes */
short bgrcv :16; /* binary gain recovered code:
1 = yes
2 = no */
short rcvm :16; /* amplitude recovery method code:
1 = none
2 = spherical divergence
3 = AGC
4 = other */
short mfeet :16; /* measurement system code:
1 = meters
2 = feet */
short polyt :16; /* impulse signal polarity code:
1 = increase in pressure or upward
geophone case movement gives
negative number on tape
2 = increase in pressure or upward
geophone case movement gives
positive number on tape */
short vpol :16; /* vibratory polarity code:
code seismic signal lags pilot by
1 337.5 to 22.5 degrees
2 22.5 to 67.5 degrees
3 67.5 to 112.5 degrees
4 112.5 to 157.5 degrees
5 157.5 to 202.5 degrees
6 202.5 to 247.5 degrees
7 247.5 to 292.5 degrees
8 293.5 to 337.5 degrees */
signed pad :32; /* double word alignment pad */
double hunass[21]; /* unassigned, double is portable! */
} bhed;
#else /* bit fields may not be portable! */
typedef struct { /* segy - trace identification header */
int tracl ; /* trace sequence number within line */
int tracr ; /* trace sequence number within reel */
int fldr ; /* field record number */
int tracf ; /* trace number within field record */
int ep ; /* energy source point number */
int cdp ; /* CDP ensemble number */
int cdpt ; /* trace number within CDP ensemble */
short nvs ; /* number of vertically summed traces (see vscode
in bhed structure) */
short nhs ; /* number of horizontally summed traces (see vscode
in bhed structure) */
short duse ; /* data use:
1 = production
2 = test */
int offset ; /* distance from source point to receiver
group (negative if opposite to direction
in which the line was shot) */
int gelev ; /* receiver group elevation from sea level
(above sea level is positive) */
int selev ; /* source elevation from sea level
(above sea level is positive) */
int sdepth ; /* source depth (positive) */
int gdel ; /* datum elevation at receiver group */
int sdel ; /* datum elevation at source */
int swdep ; /* water depth at source */
int gwdep ; /* water depth at receiver group */
short scalel ; /* scale factor for previous 7 entries
with value plus or minus 10 to the
power 0, 1, 2, 3, or 4 (if positive,
multiply, if negative divide) */
short scalco ; /* scale factor for next 4 entries
with value plus or minus 10 to the
power 0, 1, 2, 3, or 4 (if positive,
multiply, if negative divide) */
int sx ; /* X source coordinate */
int sy ; /* Y source coordinate */
int gx ; /* X group coordinate */
int gy ; /* Y group coordinate */
short counit ; /* coordinate units code:
for previous four entries
1 = length (meters or feet)
2 = seconds of arc (in this case, the
X values are longitude and the Y values
are latitude, a positive value designates
the number of seconds east of Greenwich
or north of the equator */
short wevel ; /* weathering velocity */
short swevel ; /* subweathering velocity */
short sut ; /* uphole time at source */
short gut ; /* uphole time at receiver group */
short sstat ; /* source static correction */
short gstat ; /* group static correction */
short tstat ; /* total static applied */
short laga ; /* lag time A, time in ms between end of 240-
byte trace identification header and time
break, positive if time break occurs after
end of header, time break is defined as
the initiation pulse which maybe recorded
on an auxiliary trace or as otherwise
specified by the recording system */
short lagb ; /* lag time B, time in ms between the time break
and the initiation time of the energy source,
may be positive or negative */
short delrt ; /* delay recording time, time in ms between
initiation time of energy source and time
when recording of data samples begins
(for deep water work if recording does not
start at zero time) */
short muts ; /* mute time--start */
short mute ; /* mute time--end */
unsigned short ns ; /* number of samples in this trace */
unsigned short dt ; /* sample interval; in micro-seconds */
short igc ; /* instrument gain constant */
short igi ; /* instrument early or initial gain */
short corr ; /* correlated:
1 = no
2 = yes */
short sfs ; /* sweep frequency at start */
short sfe ; /* sweep frequency at end */
short slen ; /* sweep length in ms */
short styp ; /* sweep type code:
1 = linear
2 = cos-squared
3 = other */
short stas ; /* sweep trace length at start in ms */
short stae ; /* sweep trace length at end in ms */
short tatyp ; /* taper type: 1=linear, 2=cos^2, 3=other */
short afilf ; /* alias filter frequency if used */
short afils ; /* alias filter slope */
short nofilf ; /* notch filter frequency if used */
short nofils ; /* notch filter slope */
short lcf ; /* low cut frequency if used */
short hcf ; /* high cut frequncy if used */
short lcs ; /* low cut slope */
short hcs ; /* high cut slope */
short year ; /* year data recorded */
short day ; /* day of year */
short hour ; /* hour of day (24 hour clock) */
short minute ; /* minute of hour */
short sec ; /* second of minute */
short timbas ; /* time basis code:
1 = local
2 = GMT
3 = other */
short trwf ; /* trace weighting factor, defined as 1/2^N
volts for the least sigificant bit */
short grnors ; /* geophone group number of roll switch
position one */
short grnofr ; /* geophone group number of trace one within
original field record */
short grnlof ; /* geophone group number of last trace within
original field record */
short gaps ; /* gap size (total number of groups dropped) */
short otrav ; /* overtravel taper code:
1 = down (or behind)
2 = up (or ahead) */
/* local assignments */
float d1; /* sample spacing for non-seismic data */
float f1; /* first sample location for non-seismic data */
float d2; /* sample spacing between traces */
float f2; /* first trace location */
float ungpow; /* negative of power used for dynamic
range compression */
float unscale; /* reciprocal of scaling factor to normalize
range */
int ntr ; /* number of traces */
short mark ; /* mark selected traces */
short unass[15]; /* unassigned values */
float data[SU_NFLTS];
} segy;
typedef struct { /* bhed - binary header */
int jobid ; /* job identification number */
int lino ; /* line number (only one line per reel) */
int reno ; /* reel number */
short ntrpr ; /* number of data traces per record */
short nart ; /* number of auxiliary traces per record */
short hdt ; /* sample interval in micro secs for this reel */
short dto ; /* same for original field recording */
short hns ; /* number of samples per trace for this reel */
short nso ; /* same for original field recording */
short format ; /* data sample format code:
1 = floating point (4 bytes)
2 = fixed point (4 bytes)
3 = fixed point (2 bytes)
4 = fixed point w/gain code (4 bytes) */
short fold ; /* CDP fold expected per CDP ensemble */
short tsort ; /* trace sorting code:
1 = as recorded (no sorting)
2 = CDP ensemble
3 = single fold continuous profile
4 = horizontally stacked */
short vscode ; /* vertical sum code:
1 = no sum
2 = two sum ...
N = N sum (N = 32,767) */
short hsfs ; /* sweep frequency at start */
short hsfe ; /* sweep frequency at end */
short hslen ; /* sweep length (ms) */
short hstyp ; /* sweep type code:
1 = linear
2 = parabolic
3 = exponential
4 = other */
short schn ; /* trace number of sweep channel */
short hstas ; /* sweep trace taper length at start if
tapered (the taper starts at zero time
and is effective for this length) */
short hstae ; /* sweep trace taper length at end (the ending
taper starts at sweep length minus the taper
length at end) */
short htatyp ; /* sweep trace taper type code:
1 = linear
2 = cos-squared
3 = other */
short hcorr ; /* correlated data traces code:
1 = no
2 = yes */
short bgrcv ; /* binary gain recovered code:
1 = yes
2 = no */
short rcvm ; /* amplitude recovery method code:
1 = none
2 = spherical divergence
3 = AGC
4 = other */
short mfeet ; /* measurement system code:
1 = meters
2 = feet */
short polyt ; /* impulse signal polarity code:
1 = increase in pressure or upward
geophone case movement gives
negative number on tape
2 = increase in pressure or upward
geophone case movement gives
positive number on tape */
short vpol ; /* vibratory polarity code:
code seismic signal lags pilot by
1 337.5 to 22.5 degrees
2 22.5 to 67.5 degrees
3 67.5 to 112.5 degrees
4 112.5 to 157.5 degrees
5 157.5 to 202.5 degrees
6 202.5 to 247.5 degrees
7 247.5 to 292.5 degrees
8 293.5 to 337.5 degrees */
char pad[4] ; /* double word alignment pad */
int hunass[42]; /* unassigned */
} bhed;
#endif /* end of ifdef CRAY, the bit fields are not portable */
/* DEFINES */
#define gettr(x) fgettr(stdin, (x))
#define vgettr(x) fvgettr(stdin, (x))
#define puttr(x) fputtr(stdout, (x))
#define gettra(x, y) fgettra(stdin, (x), (y))
/* The following refer to the trid field in segy.h */
/* CHARPACK represents byte packed seismic data from supack1 */
#define CHARPACK 101
/* SHORTPACK represents 2 byte packed seismic data from supack2 */
#define SHORTPACK 102
/* TREAL represents real time traces */
#define TREAL 1
/* TDEAD represents dead time traces */
#define TDEAD 2
/* TDUMMY represents dummy time traces */
#define TDUMMY 3
/* TBREAK represents time break traces */
#define TBREAK 4
/* UPHOLE represents uphole traces */
#define UPHOLE 5
/* SWEEP represents sweep traces */
#define SWEEP 6
/* TIMING represents timing traces */
#define TIMING 7
/* WBREAK represents timing traces */
#define WBREAK 8
/* TCMPLX represents complex time traces */
#define TCMPLX 13
/* TAMPH represents time domain data in amplitude/phase form */
#define TAMPH 15
/* FPACK represents packed frequency domain data */
#define FPACK 12
/* FUNPACKNYQ represents complex frequency domain data */
#define FUNPACKNYQ 11
/* FCMPLX represents complex frequency domain data */
#define FCMPLX 10
/* FAMPH represents freq domain data in amplitude/phase form */
#define FAMPH 14
/* REALPART represents the real part of a trace to Nyquist */
#define REALPART 16
/* IMAGPART represents the imaginary part of a trace to Nyquist */
#define IMAGPART 17
/* AMPLITUDE represents the amplitude of a trace to Nyquist */
#define AMPLITUDE 18
/* PHASE represents the phase of a trace to Nyquist */
#define PHASE 19
/* KT represents wavenumber-time domain data */
#define KT 21
/* KOMEGA represents <API key> domain data */
#define KOMEGA 22
/* ENVELOPE represents the envelope of the complex time trace */
#define ENVELOPE 23
/* INSTPHASE represents the phase of the complex time trace */
#define INSTPHASE 24
/* INSTFREQ represents the frequency of the complex time trace */
#define INSTFREQ 25
/* DEPTH represents traces in depth-range (z-x) */
#define TRID_DEPTH 30
#define ISSEISMIC(id) ( (id)==0 || (id)==TREAL || (id)==TDEAD || (id)==TDUMMY )
/* FUNCTION PROTOTYPES */
#ifdef __cplusplus /* if C++, specify external linkage to C functions */
extern "C" {
#endif
int fgettr(FILE *fp, segy *tp);
int fvgettr(FILE *fp, segy *tp);
void fputtr(FILE *fp, segy *tp);
int fgettra(FILE *fp, segy *tp, int itr);
/* hdrpkge */
/* void gethval(const segy *tp, int index, Value *valp);
void puthval(segy *tp, int index, Value *valp);
void getbhval(const bhed *bhp, int index, Value *valp);
void putbhval(bhed *bhp, int index, Value *valp);
void gethdval(const segy *tp, char *key, Value *valp);
void puthdval(segy *tp, char *key, Value *valp);
char *hdtype(const char *key);
char *getkey(const int index);
int getindex(const char *key);
void swaphval(segy *tp, int index);
void swapbhval(bhed *bhp, int index);
void printheader(const segy *tp); */
void tabplot(segy *tp, int itmin, int itmax);
#ifdef __cplusplus /* if C++, end external linkage specification */
}
#endif
#endif
|
#include <QString>
#include "tstScore.h"
#include "Score.h"
using namespace QTournament;
void tstScore::<API key>()
{
printStartMsg("tstScore::<API key>");
int tstScore[][3] = {
{-1, 10, 0},
{21, -6, 0},
{29, 31, 0},
{32, 10, 0},
{21, 21, 0},
{12, 12, 0},
{30, 29, 1},
{29, 30, 1},
{20, 21, 0},
{21, 20, 0},
{13, 21, 1},
{21, 0, 1},
{23, 21, 1},
{28, 26, 1},
{28, 3, 0},
};
for (auto score : tstScore)
{
bool expectedResult = (score[2] == 1);
// test the static function isValidScore()
CPPUNIT_ASSERT(GameScore::isValidScore(score[0], score[1]) == expectedResult);
// test the factory function fromScore()
auto g = GameScore::fromScore(score[0], score[1]);
CPPUNIT_ASSERT((g == nullptr) == !expectedResult);
if (expectedResult)
{
auto sc = g->getScore();
CPPUNIT_ASSERT(get<0>(sc) == score[0]);
CPPUNIT_ASSERT(get<1>(sc) == score[1]);
}
// test the factory function fromString()
QString s = QString::number(score[0]) + ":" + QString::number(score[1]);
g = GameScore::fromString(s);
CPPUNIT_ASSERT((g == nullptr) == !expectedResult);
if (expectedResult)
{
auto sc = g->getScore();
CPPUNIT_ASSERT(get<0>(sc) == score[0]);
CPPUNIT_ASSERT(get<1>(sc) == score[1]);
}
}
printEndMsg();
}
void tstScore::<API key>()
{
printStartMsg("tstScore::<API key>");
auto gs = GameScore::fromScore(12, 21);
CPPUNIT_ASSERT(gs->toString() == "12:21");
gs = GameScore::fromScore(21, 0);
CPPUNIT_ASSERT(gs->toString() == "21:0");
printEndMsg();
}
void tstScore::<API key>()
{
printStartMsg("tstScore::<API key>");
int tstScore[][3] = {
{30, 29, 1},
{29, 30, 2},
{13, 21, 2},
{21, 0, 1},
{23, 21, 1},
{28, 26, 1},
};
for (auto score : tstScore)
{
auto gs = GameScore::fromScore(score[0], score[1]);
CPPUNIT_ASSERT(gs->getWinner() == score[2]);
int loser = (score[2] == 1) ? 2 : 1;
CPPUNIT_ASSERT(gs->getLoser() == loser);
}
printEndMsg();
}
void tstScore::<API key>()
{
constexpr int MAX_NUM_GAMES = 5;
printStartMsg("tstScore::<API key>");
int gameScore[][2] = {
{30, 29},
{29, 30},
{13, 21},
{21, 0},
{21, 18},
{23, 21},
{28, 26},
};
int gameCombinations[][MAX_NUM_GAMES + 5] = {
// game1, game2, game3, game4, game5, numWinGames, allowDraw, isValid, winner, loser
// +0 , +1 , +2 , +3 , +4
{0, 1, -1, -1, -1, 2, 0, 0, -1, -1}, // invalid draw
{0, 0, -1, -1, -1, 2, 0, 1, 1, 2}, // two games, player 1 wins
{2, 4, 2, 2, -1, 2, 0, 0, -1, -1}, // four games but only two win games ==> invalid
{2, 4, 2, 2, -1, 3, 0, 1, 2, 1}, // four games, three win games ==> valid
{2, 4, 4, 2, 2, 3, 0, 1, 2, 1}, // five games, three win games ==> valid
{2, 4, 4, -1, -1, 3, 0, 0, -1, -1}, // three games, three win games ==> invalid
{2, 4, 4, -1, -1, 2, 0, 1, 1, 2}, // three games, two win games ==> valid
{2, 4, 4, -1, -1, 3, 1, 0, -1, -1}, // three games, three win games, draw allowed ==> invalid
{2, 4, -1, -1, -1, 2, 1, 1, 0, 0}, // two games, two win games, draw allowed ==> valid
{2, 4, 2, 4, -1, 3, 1, 1, 0, 0}, // four games, three win games, draw allowed ==> valid
};
for (auto combi : gameCombinations)
{
GameScoreList gsl;
QString scoreString;
for (int gameCount = 0; gameCount < MAX_NUM_GAMES; ++gameCount)
{
if (combi[gameCount] != -1)
{
auto game = GameScore::fromScore(gameScore[combi[gameCount]][0], gameScore[combi[gameCount]][1]);
CPPUNIT_ASSERT(game != nullptr);
gsl.append(*game);
scoreString += game->toString() + ",";
}
}
scoreString = scoreString.left(scoreString.length() - 1);
int numWinGames = combi[MAX_NUM_GAMES];
bool allowDraw = (combi[MAX_NUM_GAMES+1] == 1);
bool isValidMatch = (combi[MAX_NUM_GAMES+2] == 1);
// test the factory function fromGameScoreList()
auto match = MatchScore::fromGameScoreList(gsl, numWinGames, allowDraw);
if (!isValidMatch)
{
CPPUNIT_ASSERT(match == nullptr);
continue;
}
CPPUNIT_ASSERT(match != nullptr);
// test the factory function fromString()
auto match1 = MatchScore::fromString(scoreString, numWinGames, allowDraw);
if (!isValidMatch)
{
CPPUNIT_ASSERT(match1 == nullptr);
continue;
}
CPPUNIT_ASSERT(match1 != nullptr);
// test the static isValidScore() function
CPPUNIT_ASSERT(MatchScore::isValidScore(gsl, numWinGames, allowDraw) == isValidMatch);
// test the toString() function
CPPUNIT_ASSERT(match->toString() == scoreString);
CPPUNIT_ASSERT(match1->toString() == scoreString);
}
printEndMsg();
}
void tstScore::<API key>()
{
constexpr int MAX_NUM_GAMES = 5;
printStartMsg("tstScore::<API key>");
int gameScore[][2] = {
{30, 29},
{29, 30},
{13, 21},
{21, 0},
{21, 18},
{23, 21},
{28, 26},
};
int gameCombinations[][MAX_NUM_GAMES + 5] = {
// game1, game2, game3, game4, game5, numWinGames, allowDraw, isValid, winner, loser
// +0 , +1 , +2 , +3 , +4
{0, 0, -1, -1, -1, 2, 0, 1, 1, 2}, // two games, player 1 wins
{2, 4, 2, 2, -1, 3, 0, 1, 2, 1}, // four games, three win games ==> valid
{2, 4, 4, 2, 2, 3, 0, 1, 2, 1}, // five games, three win games ==> valid
{2, 4, 4, -1, -1, 2, 0, 1, 1, 2}, // three games, two win games ==> valid
{2, 4, -1, -1, -1, 2, 1, 1, 0, 0}, // two games, two win games, draw allowed ==> valid
{2, 4, 2, 4, -1, 3, 1, 1, 0, 0}, // four games, three win games, draw allowed ==> valid
};
for (auto combi : gameCombinations)
{
GameScoreList gsl;
for (int gameCount = 0; gameCount < MAX_NUM_GAMES; ++gameCount)
{
if (combi[gameCount] != -1)
{
auto game = GameScore::fromScore(gameScore[combi[gameCount]][0], gameScore[combi[gameCount]][1]);
CPPUNIT_ASSERT(game != nullptr);
gsl.append(*game);
}
}
int numWinGames = combi[MAX_NUM_GAMES];
bool allowDraw = (combi[MAX_NUM_GAMES+1] == 1);
auto match = MatchScore::fromGameScoreList(gsl, numWinGames, allowDraw);
CPPUNIT_ASSERT(match != nullptr);
// test getWinner() and getLoser()
CPPUNIT_ASSERT(match->getWinner() == combi[MAX_NUM_GAMES+3]);
CPPUNIT_ASSERT(match->getLoser() == combi[MAX_NUM_GAMES+4]);
}
printEndMsg();
}
void tstScore::<API key>()
{
constexpr int MATCH_COUNT = 1000;
constexpr double PROBABILITY_MARGIN = 0.05;
printStartMsg("tstScore::<API key>");
// a lambda as a match generator
auto matchGenerator = [](int count, int numWinGames, bool drawAllowed) {
MatchScoreList result;
for (int i=0; i < count; ++i)
{
result.append(*(MatchScore::genRandomScore(numWinGames, drawAllowed)));
}
return result;
};
// a lambda to compare an actual count with an expected count
// including a margin
auto isCountInRange = [](int expected, int actual, double margin) {
int absMargin = static_cast<int>(expected * margin);
int minCount = expected - absMargin;
int maxCount = expected + absMargin;
return ((actual <= maxCount) && (actual >= minCount));
};
// Generate matches with 2 win games and no draw
MatchScoreList msl = matchGenerator(MATCH_COUNT, 2, false);
CPPUNIT_ASSERT(msl.count() == MATCH_COUNT);
// gather some statistics
int p1Wins = 0;
int p2Wins = 0;
int gamesCount = 0;
int gamesBeyond21 = 0;
for (MatchScore ms : msl)
{
if (ms.getWinner() == 1) ++p1Wins;
if (ms.getWinner() == 2) ++p2Wins;
int cnt = ms.getNumGames();
for (int i=0; i < cnt; ++i)
{
++gamesCount;
auto gs = ms.getGame(i);
if (gs->getWinnerScore() > 21) ++gamesBeyond21;
}
CPPUNIT_ASSERT(ms.isValidScore(2, false));
}
// make sure that wins are equally distributed among players
CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT / 2, p1Wins, PROBABILITY_MARGIN));
CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT / 2, p2Wins, PROBABILITY_MARGIN));
CPPUNIT_ASSERT(isCountInRange(gamesCount * 0.3, gamesBeyond21, PROBABILITY_MARGIN));
// Generate matches with 3 win games and draw
msl.clear();
msl = matchGenerator(MATCH_COUNT, 3, true);
CPPUNIT_ASSERT(msl.count() == MATCH_COUNT);
// gather some statistics
p1Wins = 0;
p2Wins = 0;
int draws = 0;
gamesCount = 0;
gamesBeyond21 = 0;
for (MatchScore ms : msl)
{
if (ms.getWinner() == 0) ++draws;
if (ms.getWinner() == 1) ++p1Wins;
if (ms.getWinner() == 2) ++p2Wins;
int cnt = ms.getNumGames();
for (int i=0; i < cnt; ++i)
{
++gamesCount;
auto gs = ms.getGame(i);
if (gs->getWinnerScore() > 21) ++gamesBeyond21;
}
if (ms.getWinner() == 0)
{
CPPUNIT_ASSERT(ms.getNumGames() == 4); // 4 = (numWinGames - 1) * 2
}
CPPUNIT_ASSERT(ms.isValidScore(3, true));
}
// make sure that wins are equally distributed among players
CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT * 0.3, draws, PROBABILITY_MARGIN));
CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT * 0.35, p1Wins, PROBABILITY_MARGIN));
CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT * 0.35, p2Wins, PROBABILITY_MARGIN));
CPPUNIT_ASSERT(isCountInRange(gamesCount * 0.3, gamesBeyond21, PROBABILITY_MARGIN));
printEndMsg();
}
|
CC = gcc
CFLAGS = -g -Wall -Werror -D_GNU_SOURCE -I../include
LDFLAGS = -ljson-c
HEADERS = ../include/json.h ../include/error.h ../include/account.h ../include/util.h
SRC = assignfee.c ../lib/json.c ../lib/account.c ../lib/error.c ../lib/util.c
assignfee: $(SRC) $(HEADERS)
$(CC) $(CFLAGS) $(LDFLAGS) $(SRC) -o$@
clean:
rm -f assignfee
.PHONY: clean
|
import java.util.Scanner;
public class FeetMeters {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Number of feet: ");
float feet = keyboard.nextInt();
float foottometers = (float) .305;
System.out.println("");
System.out.print("Number of meters: ");
float meters = (float) .305 * feet;
System.out.println(meters);
}
}
|
<?php
// Moodle is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Moodle is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
declare(strict_types = 1);
namespace core_grades\grades\grader\gradingpanel\point\external;
use coding_exception;
use context;
use core_user;
use core_grades\component_gradeitem as gradeitem;
use core_grades\<API key>;
use external_api;
use <API key>;
use <API key>;
use <API key>;
use external_value;
use external_warnings;
use moodle_exception;
use <API key>;
class store extends external_api {
/**
* Describes the parameters for fetching the grading panel for a simple grade.
*
* @return <API key>
* @since Moodle 3.8
*/
public static function execute_parameters(): <API key> {
return new <API key> ([
'component' => new external_value(
PARAM_ALPHANUMEXT,
'The name of the component',
VALUE_REQUIRED
),
'contextid' => new external_value(
PARAM_INT,
'The ID of the context being graded',
VALUE_REQUIRED
),
'itemname' => new external_value(
PARAM_ALPHANUM,
'The grade item itemname being graded',
VALUE_REQUIRED
),
'gradeduserid' => new external_value(
PARAM_INT,
'The ID of the user show',
VALUE_REQUIRED
),
'notifyuser' => new external_value(
PARAM_BOOL,
'Wheteher to notify the user or not',
VALUE_DEFAULT,
false
),
'formdata' => new external_value(
PARAM_RAW,
'The serialised form data representing the grade',
VALUE_REQUIRED
),
]);
}
/**
* Fetch the data required to build a grading panel for a simple grade.
*
* @param string $component
* @param int $contextid
* @param string $itemname
* @param int $gradeduserid
* @param bool $notifyuser
* @param string $formdata
* @return array
* @throws \dml_exception
* @throws \<API key>
* @throws \<API key>
* @throws coding_exception
* @throws moodle_exception
* @since Moodle 3.8
*/
public static function execute(string $component, int $contextid, string $itemname, int $gradeduserid,
bool $notifyuser, string $formdata): array {
global $USER;
[
'component' => $component,
'contextid' => $contextid,
'itemname' => $itemname,
'gradeduserid' => $gradeduserid,
'notifyuser' => $notifyuser,
'formdata' => $formdata,
] = self::validate_parameters(self::execute_parameters(), [
'component' => $component,
'contextid' => $contextid,
'itemname' => $itemname,
'gradeduserid' => $gradeduserid,
'notifyuser' => $notifyuser,
'formdata' => $formdata,
]);
// Validate the context.
$context = context::instance_by_id($contextid);
self::validate_context($context);
// Validate that the supplied itemname is a gradable item.
if (!<API key>::is_valid_itemname($component, $itemname)) {
throw new coding_exception("The '{$itemname}' item is not valid for the '{$component}' component");
}
// Fetch the gradeitem instance.
$gradeitem = gradeitem::instance($component, $context, $itemname);
// Validate that this gradeitem is actually enabled.
if (!$gradeitem->is_grading_enabled()) {
throw new moodle_exception("Grading is not enabled for {$itemname} in this context");
}
// Fetch the record for the graded user.
$gradeduser = \core_user::get_user($gradeduserid);
// Require that this user can save grades.
$gradeitem-><API key>($gradeduser, $USER);
if (!$gradeitem-><API key>()) {
throw new moodle_exception("The {$itemname} item in {$component}/{$contextid} is not configured for direct grading");
}
// Parse the serialised string into an object.
$data = [];
parse_str($formdata, $data);
// Grade.
$gradeitem-><API key>($gradeduser, $USER, (object) $data);
$hasgrade = $gradeitem->user_has_grade($gradeduser);
// Notify.
if ($notifyuser) {
// Send notification.
$gradeitem-><API key>($gradeduser, $USER);
}
// Fetch the updated grade back out.
$grade = $gradeitem->get_grade_for_user($gradeduser, $USER);
return fetch::get_fetch_data($grade, $hasgrade, 0);
}
/**
* Describes the data returned from the external function.
*
* @return <API key>
* @since Moodle 3.8
*/
public static function execute_returns(): <API key> {
return fetch::execute_returns();
}
}
|
from pupa.scrape import Jurisdiction, Organization
from .bills import MNBillScraper
from .committees import MNCommitteeScraper
from .people import MNPersonScraper
from .vote_events import MNVoteScraper
from .events import MNEventScraper
from .common import url_xpath
class Minnesota(Jurisdiction):
division_id = "ocd-division/country:us/state:mn"
classification = "government"
name = "Minnesota"
url = "http://state.mn.us/"
check_sessions = True
scrapers = {
"bills": MNBillScraper,
"committees": MNCommitteeScraper,
"people": MNPersonScraper,
"vote_events": MNVoteScraper,
"events": MNEventScraper,
}
parties = [{'name': 'Republican'},
{'name': '<API key>'}]
<API key> = [
{
'_scraped_name': '86th Legislature, 2009-2010',
'classification': 'primary',
'identifier': '2009-2010',
'name': '2009-2010 Regular Session'
},
{
'_scraped_name': '86th Legislature, 2010 1st Special Session',
'classification': 'special',
'identifier': '2010 1st Special Session',
'name': '2010, 1st Special Session'
},
{
'_scraped_name': '86th Legislature, 2010 2nd Special Session',
'classification': 'special',
'identifier': '2010 2nd Special Session',
'name': '2010, 2nd Special Session'
},
{
'_scraped_name': '87th Legislature, 2011-2012',
'classification': 'primary',
'identifier': '2011-2012',
'name': '2011-2012 Regular Session'
},
{
'_scraped_name': '87th Legislature, 2011 1st Special Session',
'classification': 'special',
'identifier': '2011s1',
'name': '2011, 1st Special Session'
},
{
'_scraped_name': '87th Legislature, 2012 1st Special Session',
'classification': 'special',
'identifier': '2012s1',
'name': '2012, 1st Special Session'
},
{
'_scraped_name': '88th Legislature, 2013-2014',
'classification': 'primary',
'identifier': '2013-2014',
'name': '2013-2014 Regular Session'
},
{
'_scraped_name': '88th Legislature, 2013 1st Special Session',
'classification': 'special',
'identifier': '2013s1',
'name': '2013, 1st Special Session'
},
{
'_scraped_name': '89th Legislature, 2015-2016',
'classification': 'primary',
'identifier': '2015-2016',
'name': '2015-2016 Regular Session'
},
{
'_scraped_name': '89th Legislature, 2015 1st Special Session',
'classification': 'special',
'identifier': '2015s1',
'name': '2015, 1st Special Session'
},
{
'_scraped_name': '90th Legislature, 2017-2018',
'classification': 'primary',
'identifier': '2017-2018',
'name': '2017-2018 Regular Session'
},
]
<API key> = [
'85th Legislature, 2007-2008',
'85th Legislature, 2007 1st Special Session',
'84th Legislature, 2005-2006',
'84th Legislature, 2005 1st Special Session',
'83rd Legislature, 2003-2004',
'83rd Legislature, 2003 1st Special Session',
'82nd Legislature, 2001-2002',
'82nd Legislature, 2002 1st Special Session',
'82nd Legislature, 2001 1st Special Session',
'81st Legislature, 1999-2000',
'80th Legislature, 1997-1998',
'80th Legislature, 1998 1st Special Session',
'80th Legislature, 1997 3rd Special Session',
'80th Legislature, 1997 2nd Special Session',
'80th Legislature, 1997 1st Special Session',
'79th Legislature, 1995-1996',
'79th Legislature, 1995 1st Special Session',
'89th Legislature, 2015-2016',
]
def get_organizations(self):
legis = Organization('Minnesota Legislature', classification='legislature')
upper = Organization('Minnesota Senate', classification='upper',
parent_id=legis._id)
lower = Organization('Minnesota House of Representatives',
classification='lower', parent_id=legis._id)
for n in range(1, 68):
upper.add_post(label=str(n), role='Senator',
division_id='ocd-division/country:us/state:mn/sldu:{}'.format(n))
lower.add_post(label=str(n) + 'A', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}a'.format(n))
lower.add_post(label=str(n) + 'B', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}b'.format(n))
yield legis
yield upper
yield lower
def get_session_list(self):
return url_xpath('https:
'search_status/status_search.php?body=House',
'//select[@name="session"]/option/text()')
|
<?php
namespace Test\FlexiPeeHP;
use FlexiPeeHP\Nastaveni;
/**
* Generated by <API key> on 2016-04-27 at 17:32:11.
*/
class NastaveniTest extends FlexiBeeROTest
{
/**
* @var Nastaveni
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp(): void
{
$this->object = new Nastaveni();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown(): void
{
}
/**
* @covers FlexiPeeHP\Nastaveni::getFlexiData
*/
public function testGetFlexiData()
{
if ($this->object->url == 'https://demo.flexibee.eu') {
$this->markTestSkipped('Public demo site does not allow read here');
} else {
$flexidata = $this->object->getFlexiData();
$this->assertArrayHasKey(0, $flexidata);
$this->assertArrayHasKey('id', $flexidata[0]);
$filtrered = $this->object->getFlexiData(null,
key($flexidata[0])." = ".current($flexidata[0]));
$this->assertArrayHasKey(0, $filtrered);
$this->assertArrayHasKey('id', $filtrered[0]);
}
}
}
|
#pragma once
#include <fstream>
#include <iomanip>
#include <map>
#include <sstream>
#include <string>
#include "jw.hpp"
namespace Zee {
class Report {
public:
Report(std::string title, std::string rowTitle)
: title_(title), rowTitle_(rowTitle) {
rowSize_ = rowTitle_.size();
}
void addColumn(std::string colName, std::string texName = "") {
columns_.push_back(colName);
if (!texName.empty())
columnsTex_.push_back(texName);
else
columnsTex_.push_back(colName);
columnWidth_[colName] = colName.size();
}
void addRow(std::string row) {
entries_[row] = std::map<std::string, std::string>();
if (row.size() > rowSize_) {
rowSize_ = row.size();
}
}
template <typename T>
void addResult(std::string row, std::string column, T result) {
if (entries_.find(row) == entries_.end()) {
JWLogError << "Trying to add result to non-existing row" << endLog;
return;
}
std::stringstream ss;
ss << std::fixed << std::setprecision(1) << result;
entries_[row][column] = ss.str();
entriesTex_[row][column] = ss.str();
if (ss.str().size() > columnWidth_[column]) {
columnWidth_[column] = ss.str().size();
}
}
void addResult(std::string row, std::string column, std::string result,
std::string texResult) {
addResult(row, column, result);
entriesTex_[row][column] = texResult;
}
void print() {
JWLogResult << title_ << endLog;
unsigned int lineSize = rowSize_ + 4;
for (auto col : columnWidth_) {
lineSize += col.second + 2;
}
std::string hline = "";
for (unsigned int i = 0; i < lineSize; ++i) hline.push_back('-');
auto addElement = [](int width, std::stringstream& result,
std::string entry) {
result << std::left << std::setprecision(1) << std::setw(width)
<< std::setfill(' ') << entry;
};
std::stringstream ss;
addElement(rowSize_ + 2, ss, rowTitle_);
ss << "| ";
for (auto& col : columns_) addElement(columnWidth_[col] + 2, ss, col);
JWLogInfo << hline << endLog;
JWLogInfo << ss.str() << endLog;
JWLogInfo << hline << endLog;
for (auto& rowCols : entries_) {
std::stringstream rowSs;
addElement(rowSize_ + 2, rowSs, rowCols.first);
rowSs << "| ";
for (auto& col : columns_) {
addElement(columnWidth_[col] + 2, rowSs, rowCols.second[col]);
}
JWLogInfo << rowSs.str() << endLog;
}
JWLogInfo << hline << endLog;
}
void saveToCSV();
void readFromCSV();
void saveToTex(std::string filename) {
auto replaceTex = [](std::string entry) {
std::string texEntry = entry;
auto pos = entry.find("+-");
if (pos != std::string::npos) {
texEntry =
texEntry.substr(0, pos) + "\\pm" + texEntry.substr(pos + 2);
}
pos = entry.find("%");
if (pos != std::string::npos) {
texEntry =
texEntry.substr(0, pos) + "\\%" + texEntry.substr(pos + 1);
}
return texEntry;
};
std::ofstream fout(filename);
fout << "\\begin{table}" << std::endl;
fout << "\\centering" << std::endl;
fout << "\\begin{tabular}{|l|";
for (unsigned int i = 0; i < columns_.size(); ++i) {
fout << "l";
fout << ((i < (columns_.size() - 1)) ? " " : "|}");
}
fout << std::endl << "\\hline" << std::endl;
fout << "\\textbf{" << rowTitle_ << "} & ";
for (unsigned int i = 0; i < columns_.size(); ++i) {
fout << "$" << columnsTex_[i] << "$";
fout << ((i < (columns_.size() - 1)) ? " & " : "\\\\");
}
fout << std::endl;
fout << "\\hline" << std::endl;
for (auto& rowCols : entriesTex_) {
fout << "\\verb|" << rowCols.first << "| & ";
for (unsigned int i = 0; i < columns_.size(); ++i) {
fout << "$" << replaceTex(rowCols.second[columns_[i]]) << "$";
fout << ((i < (columns_.size() - 1)) ? " & " : "\\\\");
}
fout << std::endl;
}
fout << "\\hline" << std::endl;
fout << "\\end{tabular}" << std::endl;
;
fout << "\\caption{\\ldots}" << std::endl;
fout << "\\end{table}" << std::endl;
}
private:
std::string title_;
std::string rowTitle_;
std::map<std::string, std::map<std::string, std::string>> entries_;
std::map<std::string, std::map<std::string, std::string>> entriesTex_;
std::vector<std::string> columns_;
std::vector<std::string> columnsTex_;
std::map<std::string, unsigned int> columnWidth_;
unsigned int rowSize_;
};
} // namespace Zee
|
package ProxyPattern;
public class <API key> {
public static void main(String[] args) {
int count = 0;
if (args .length < 2) {
System.out.println("GumballMachine <name> <inventory>");
System.exit(1);
}
count = Integer.parseInt(args[1]);
GumballMachine gumballMachine = new GumballMachine(args[0], count);
GumballMonitor monitor = new GumballMonitor(gumballMachine);
monitor.report();
}
}
|
<?php
class <API key> implements Countable, ArrayAccess, Iterator
{
protected $fieldnames = array();
protected $data = array();
protected $position = 0;
public function __set($fieldname, $value)
{
//this differs from self::offsetSet:
// - if a field has been set before, make this field multiValued
$offsetExists = $this->offsetExists($fieldname);
$value = !is_array($value) ? array($value) : $value;
if (!$offsetExists) {
$this->fieldnames[] = $fieldname;
$this->data[$fieldname] = $value;
} else {
if (is_array($this->data[$fieldname])) {
$this->data[$fieldname] = array_merge($this->data[$fieldname], $value);
} else {
$this->data[$fieldname] = array_merge(array($this->data[$fieldname]), $value);
}
}
}
public function offsetSet($fieldname, $value) {
$newField = false;
if (!$this->offsetExists($fieldname)) {
$this->fieldnames[] = $fieldname;
$newField = true;
}
if (!is_array($value)) {
if (false === $newField) {
$this->data[$fieldname][] = $value;
} else {
$this->data[$fieldname] = array($value);
}
} else {
if (false === $newField) {
$this->data[$fieldname] = $this->data[$fieldname] + $value;
} else {
$this->data[$fieldname] = $value;
}
}
}
public function offsetExists($fieldname) {
return in_array($fieldname, $this->fieldnames);
}
public function offsetUnset($fieldname) {
if (!$this->offsetExists($fieldname)) {
trigger_error('Undefined index: '.$fieldname, E_USER_NOTICE);
return;
}
unset ( $this->data[$fieldname]);
$ix = array_search($fieldname, $this->fieldnames);
unset($this->fieldnames[$ix]);
$fieldnames = array();
foreach ($this->fieldnames as $fieldname) $fieldnames[] = $fieldname;
$this->fieldnames = $fieldnames;
$this->rewind();
}
public function offsetGet($fieldname) {
return $this->offsetExists($fieldname) ? $this->data [$fieldname] : null;
}
public function count()
{
return count($this->fieldnames);
}
public function rewind() {
$this->position = 0;
}
public function current() {
return $this->data[$this->fieldnames[$this->position]];
}
public function key() {
return $this->fieldnames[$this->position];
}
public function next() {
++$this->position;
}
public function valid() {
return isset($this->data[$this->fieldnames[$this->position]]);
}
public function toArray()
{
return $this->data;
}
/**
* @return OpenSKOS_Solr
*/
protected function solr()
{
return Zend_Registry::get('OpenSKOS_Solr');
}
public function save($commit = null)
{
$this->solr()->add(new <API key>($this), $commit);
return $this;
}
/**
* Registers the notation of the document in the database, or generates one if the document does not have notation.
*
* @return OpenSKOS_Solr
*/
public function <API key>()
{
if ((isset($this->data['class']) && $this->data['class'] == 'Concept')
|| (isset($this->data['class'][0]) && $this->data['class'][0] == 'Concept')) {
$currentNotation = '';
if (isset($this->data['notation']) && isset($this->data['notation'][0])) {
$currentNotation = $this->data['notation'][0];
}
if (empty($currentNotation)) {
$this->fieldnames[] = 'notation';
$this->data['notation'] = array(<API key>::getNext());
// Adds the notation to the xml. At the end just before </rdf:Description>
$closingTag = '</rdf:Description>';
$notationTag = '<skos:notation>' . $this->data['notation'][0] . '</skos:notation>';
$xml = $this->data['xml'];
$xml = str_replace($closingTag, $notationTag . $closingTag, $xml);
$this->data['xml'] = $xml;
} else {
if ( ! <API key>::isRegistered($currentNotation)) {
// If we do not have the notation registered - register it.
<API key>::register($currentNotation);
}
}
}
return $this;
}
/**
* Generates uri if it can. Alters the document to put it in, also alters the xml to put rdf:about
* @param <API key> $collection From where to get the basic uri.
* @throws <API key>
*/
public function autoGenerateUri(<API key> $collection)
{
if (!((isset($this->data['class']) && $this->data['class'] == 'Concept')
|| (isset($this->data['class'][0]) && $this->data['class'][0] == 'Concept'))) {
throw new <API key>(
'Auto generate uri is for concepts only. Not working for concept schemas.'
);
}
if ($collection === null) {
throw new <API key>(
'Auto generate uri is set to true, but collection is not provided.'
);
}
$baseUri = $collection->getConceptsBaseUri();
if (empty($baseUri)) {
throw new <API key>(
'Auto generate uri is set to true, but collection is not provided.'
);
}
if (!preg_match('/\/$/', $baseUri) && !preg_match('/=$/', $baseUri)) {
$baseUri .= '/';
}
$this-><API key>();
$uri = $baseUri . $this->data['notation'][0];
// Write in the xml.
if (strpos($this->data['xml'][0], 'rdf:about') !== false) {
throw new <API key>(
'Can not auto generate uri if rdf about is set.'
);
}
$this->data['xml'] = str_replace(
'<rdf:Description',
'<rdf:Description rdf:about="' . $uri . '"',
$this->data['xml']
);
$this->uri = $uri;
}
/**
*
* @throws <API key>
*/
public function <API key>()
{
if (isset($this->data['status']) && isset($this->data['status'][0])) {
$statusTag = '<openskos:status>' . $this->data['status'][0] . '</openskos:status>';
if (strpos($this->data['xml'][0], 'openskos:status') === false) {
// Adds the status to the xml. At the end just before </rdf:Description>
$closingTag = '</rdf:Description>';
$xml = $this->data['xml'];
$xml = str_replace($closingTag, $statusTag . $closingTag, $xml);
$this->data['xml'] = $xml;
} else {
$xml = $this->data['xml'];
$xml = preg_replace('/<openskos:status>.*<\/openskos:status>/i', $statusTag, $xml);
$this->data['xml'] = $xml;
}
}
}
public function __toString()
{
$doc = new DOMDocument();
$doc->loadXML('<doc/>');
foreach ($this->fieldnames as $fieldname) {
foreach ($this->data[$fieldname] as $value) {
$node = $doc->documentElement->appendChild($doc->createElement('field'));
$htmlSafeValue = htmlspecialchars($value);
if ($htmlSafeValue == $value) {
$node->appendChild($doc->createTextNode($htmlSafeValue));
} else {
$node->appendChild($doc->createCDataSection($value));
}
$node->setAttribute('name', $fieldname);
}
}
return $doc->saveXml($doc->documentElement);
}
}
|
#ifndef SQLCONNECTDIALOG_H
#define SQLCONNECTDIALOG_H
#include <QDialog>
#include <QtSql>
namespace Ui {
class SQLConnectDialog;
}
class SQLConnectDialog : public QDialog
{
Q_OBJECT
public:
explicit SQLConnectDialog(QWidget *parent = 0);
~SQLConnectDialog();
QSqlDatabase connect(QSqlDatabase db);
private slots:
void <API key>();
private:
Ui::SQLConnectDialog *ui;
QSqlDatabase tmp;
};
#endif // SQLCONNECTDIALOG_H
|
// This code is part of the CPCC-NG project.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
package cpcc.demo.setup.builder;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.tuple.Pair;
import cpcc.core.entities.SensorDefinition;
import cpcc.core.entities.SensorType;
import cpcc.core.entities.SensorVisibility;
import cpcc.core.entities.TopicCategory;
/**
* Sensor Constants implementation.
*/
public final class SensorConstants
{
private static final String <API key> = "sensor_msgs/NavSatFix";
private static final String SENSOR_MSGS_IMAGE = "sensor_msgs/Image";
private static final String STD_MSGS_FLOAT32 = "std_msgs/Float32";
private static final Date now = new Date();
private static final SensorDefinition[] SENSOR_DEFINITIONS = {
new <API key>()
.setId(1)
.setDescription("Altimeter")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.ALTIMETER)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build(),
new <API key>()
.setId(2)
.setDescription("Area of Operations")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.AREA_OF_OPERATIONS)
.setVisibility(SensorVisibility.PRIVILEGED_VV)
.setDeleted(false).build(),
new <API key>()
.setId(3)
.setDescription("Barometer")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.BAROMETER)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build(),
new <API key>()
.setId(4)
.setDescription("Battery")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.BATTERY)
.setVisibility(SensorVisibility.PRIVILEGED_VV)
.setDeleted(false).build(),
new <API key>()
.setId(5)
.setDescription("Belly Mounted Camera 640x480")
.setLastUpdate(now)
.setMessageType(SENSOR_MSGS_IMAGE)
.setParameters("width=640 height=480 yaw=0 down=1.571 alignment=''north''")
.setType(SensorType.CAMERA)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build(),
// new <API key>()
// .setId(6)
// .setDescription("FPV Camera 640x480")
// .setLastUpdate(now)
// .setMessageType("sensor_msgs/Image")
// .setParameters("width=640 height=480 yaw=0 down=0 alignment=''heading''")
// .setType(SensorType.CAMERA)
// .setVisibility(SensorVisibility.ALL_VV)
// .setDeleted(false).build(),
new <API key>()
.setId(7)
.setDescription("CO2")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.CO2)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build(),
new <API key>()
.setId(9)
.setDescription("GPS")
.setLastUpdate(now)
.setMessageType(<API key>)
.setParameters(null)
.setType(SensorType.GPS)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build(),
new <API key>()
.setId(10)
.setDescription("Hardware")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.HARDWARE)
.setVisibility(SensorVisibility.PRIVILEGED_VV)
.setDeleted(false).build(),
new <API key>()
.setId(11)
.setDescription("NOx")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.NOX)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build(),
new <API key>()
.setId(12)
.setDescription("Thermometer")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.THERMOMETER)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build()
};
public static final Map<TopicCategory, SensorType> TOPIC_SENSOR_MAP = Collections.unmodifiableMap(Stream
.of(Pair.of(TopicCategory.<API key>, SensorType.ALTIMETER),
Pair.of(TopicCategory.CAMERA, SensorType.CAMERA),
Pair.of(TopicCategory.CAMERA_INFO, SensorType.CAMERA),
Pair.of(TopicCategory.<API key>, SensorType.GPS))
.collect(Collectors.toMap(Pair::getLeft, Pair::getRight)));
private SensorConstants()
{
// Intentionally empty.
}
/**
* @param type the required sensor types.
* @return all sensor definitions specified in type.
*/
public static List<SensorDefinition> byType(SensorType... type)
{
Set<SensorType> types = Stream.of(type).collect(Collectors.toSet());
return Stream.of(SENSOR_DEFINITIONS).filter(x -> types.contains(x.getType())).collect(Collectors.toList());
}
/**
* @return all sensor definitions.
*/
public static List<SensorDefinition> all()
{
return Arrays.asList(SENSOR_DEFINITIONS);
}
}
|
<?php
namespace App\Console\Commands;
use App\App;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Imperium\File\File;
class Venus extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:secure';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Configure app';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$db = database_path('venus');
if (!File::exist($db))
{
if (File::create($db))
{
File::copy('.env.example', '.env');
Artisan::call('key:generate');
}
}
return App::cryptEnv();
}
}
|
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* com.stimulsoft.base.drawing.StiBrush
* com.stimulsoft.base.drawing.StiColor
* com.stimulsoft.base.drawing.StiSolidBrush
* com.stimulsoft.base.drawing.enums.StiPenStyle
* com.stimulsoft.base.serializing.annotations.StiDefaulValue
* com.stimulsoft.base.serializing.annotations.StiSerializable
*/
package com.stimulsoft.report.chart.view.series.radar;
import com.stimulsoft.base.drawing.StiBrush;
import com.stimulsoft.base.drawing.StiColor;
import com.stimulsoft.base.drawing.StiSolidBrush;
import com.stimulsoft.base.drawing.enums.StiPenStyle;
import com.stimulsoft.base.serializing.annotations.StiDefaulValue;
import com.stimulsoft.base.serializing.annotations.StiSerializable;
import com.stimulsoft.report.chart.core.series.StiSeriesCoreXF;
import com.stimulsoft.report.chart.core.series.radar.<API key>;
import com.stimulsoft.report.chart.interfaces.series.IStiSeries;
import com.stimulsoft.report.chart.interfaces.series.radar.IStiRadarAreaSeries;
import com.stimulsoft.report.chart.view.areas.radar.StiRadarAreaArea;
import com.stimulsoft.report.chart.view.series.radar.StiRadarSeries;
public class StiRadarAreaSeries
extends StiRadarSeries
implements IStiRadarAreaSeries {
private StiColor lineColor = StiColor.Black;
private StiPenStyle lineStyle = StiPenStyle.Solid;
private boolean lighting = true;
private float lineWidth = 2.0f;
private StiBrush brush = new StiSolidBrush(StiColor.Gainsboro);
@StiSerializable
public StiColor getLineColor() {
return this.lineColor;
}
public void setLineColor(StiColor stiColor) {
this.lineColor = stiColor;
}
@StiDefaulValue(value="Solid")
@StiSerializable
public StiPenStyle getLineStyle() {
return this.lineStyle;
}
public void setLineStyle(StiPenStyle stiPenStyle) {
this.lineStyle = stiPenStyle;
}
@StiDefaulValue(value="true")
@StiSerializable
public boolean getLighting() {
return this.lighting;
}
public void setLighting(boolean bl) {
this.lighting = bl;
}
@StiDefaulValue(value="2.0")
@StiSerializable
public float getLineWidth() {
return this.lineWidth;
}
public void setLineWidth(float f) {
if (f > 0.0f) {
this.lineWidth = f;
}
}
@StiSerializable(shortName="bh")
public final StiBrush getBrush() {
return this.brush;
}
public final void setBrush(StiBrush stiBrush) {
this.brush = stiBrush;
}
public Class GetDefaultAreaType() {
return StiRadarAreaArea.class;
}
public StiRadarAreaSeries() {
this.setCore(new <API key>(this));
}
}
|
#if ! defined (<API key>)
#define <API key> 1
#include "ButtonControl.h"
class QPushButton;
namespace QtHandles
{
class PushButtonControl : public ButtonControl
{
public:
PushButtonControl (const graphics_object& go, QPushButton* btn);
~PushButtonControl (void);
static PushButtonControl* create (const graphics_object& go);
protected:
void update (int pId);
};
}
#endif
|
package com.base.engine.math;
public class Vector2f
{
private float x, y;
public Vector2f(float x, float y)
{
this.x = x;
this.y = y;
}
public Vector2f normalized()
{
float len = length();
float x_ = x / len;
float y_ = y / len;
return new Vector2f(x_, y_);
}
public float length()
{
return (float)Math.sqrt(x * x + y * y);
}
public Vector2f add(Vector2f r)
{
return new Vector2f(x + r.getX(), y + r.getY());
}
public Vector2f add(float r)
{
return new Vector2f(x + r, y + r);
}
public Vector2f sub(Vector2f r)
{
return new Vector2f(x - r.getX(), y - r.getY());
}
public Vector2f sub(float r)
{
return new Vector2f(x - r, y - r);
}
public Vector2f mul(Vector2f r)
{
return new Vector2f(x * r.getX(), y * r.getY());
}
public Vector2f mul(float r)
{
return new Vector2f(x * r, y * r);
}
public Vector2f div(Vector2f r)
{
return new Vector2f(x / r.getX(), y / r.getY());
}
public Vector2f div(float r)
{
return new Vector2f(x / r, y / r);
}
public Vector2f abs()
{
return new Vector2f(Math.abs(x), Math.abs(y));
}
@Override
public String toString()
{
return "(" + x + ", " + y + ")";
}
public float getX()
{
return this.x;
}
public void setX(float x)
{
this.x = x;
}
public float getY()
{
return this.y;
}
public void setY(float y)
{
this.y = y;
}
}
|
package org.mariotaku.twidere.util;
import java.io.File;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
public final class EnvironmentAccessor {
public static File getExternalCacheDir(final Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
return <API key>.getExternalCacheDir(context);
final File ext_storage_dir = Environment.<API key>();
if (ext_storage_dir != null && ext_storage_dir.isDirectory()) {
final String ext_cache_path = ext_storage_dir.getAbsolutePath() + "/Android/data/"
+ context.getPackageName() + "/cache/";
final File ext_cache_dir = new File(ext_cache_path);
if (ext_cache_dir.isDirectory() || ext_cache_dir.mkdirs()) return ext_cache_dir;
}
return null;
}
@TargetApi(Build.VERSION_CODES.FROYO)
private static class <API key> {
@TargetApi(Build.VERSION_CODES.FROYO)
private static File getExternalCacheDir(final Context context) {
return context.getExternalCacheDir();
}
}
}
|
#include "toString.h"
vector<string> splitString(string s, char c) {
stringstream ss(s);
string token;
vector<string> res;
while (std::getline(ss, token, c)) res.push_back(token);
return res;
}
string toString(string s) { return s; }
string toString(bool b) { stringstream ss; ss << b; return ss.str(); }
string toString(int i) { stringstream ss; ss << i; return ss.str(); }
string toString(size_t i) { stringstream ss; ss << i; return ss.str(); }
string toString(unsigned int i) { stringstream ss; ss << i; return ss.str(); }
string toString(float f) { stringstream ss; ss << f; return ss.str(); }
string toString(double f) { stringstream ss; ss << f; return ss.str(); }
string toString(OSG::Vec2f v) {
stringstream ss;
ss << v[0] << " " << v[1];
return ss.str();
}
string toString(OSG::Pnt3f v) { return toString(OSG::Vec3f(v)); }
string toString(OSG::Vec3f v) {
stringstream ss;
ss << v[0] << " " << v[1] << " " << v[2];
return ss.str();
}
string toString(OSG::Vec4f v) {
stringstream ss;
ss << v[0] << " " << v[1] << " " << v[2] << " " << v[3];
return ss.str();
}
string toString(OSG::Vec3i v) {
stringstream ss;
ss << v[0] << " " << v[1] << " " << v[2];
return ss.str();
}
bool toBool(string s) {
stringstream ss;
ss << s;
bool b;
ss >> b;
return b;
}
int toInt(string s) {
stringstream ss;
ss << s;
int i;
ss >> i;
return i;
}
float toFloat(string s) {
stringstream ss;
ss << s;
float i;
ss >> i;
return i;
}
OSG::Vec2f toVec2f(string s) {
OSG::Vec2f v;
stringstream ss(s);
ss >> v[0];
ss >> v[1];
return v;
}
OSG::Vec3f toVec3f(string s) {
OSG::Vec3f v;
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
return v;
}
OSG::Vec4f toVec4f(string s) {
OSG::Vec4f v;
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
ss >> v[3];
return v;
}
OSG::Pnt3f toPnt3f(string s) {
OSG::Pnt3f v;
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
return v;
}
OSG::Vec3i toVec3i(string s) {
OSG::Vec3i v;
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
return v;
}
void toValue(string s, string& s2) {
s2 = s;
}
void toValue(string s, bool& b) {
stringstream ss(s);
ss >> b;
}
void toValue(string s, int& i) {
stringstream ss(s);
ss >> i;
}
void toValue(string s, float& f) {
stringstream ss(s);
ss >> f;
}
void toValue(string s, OSG::Vec2f& v) {
stringstream ss(s);
ss >> v[0];
ss >> v[1];
}
void toValue(string s, OSG::Vec3f& v) {
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
}
void toValue(string s, OSG::Vec4f& v) {
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
ss >> v[3];
}
void toValue(string s, OSG::Vec3i& v) {
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
}
|
<!DOCTYPE html><html><head><link rel="canonical" href="http:
|
<?php
class NivelSni extends AppModel {
var $name = 'NivelSni';
var $displayField = 'nombre';
var $validate = array(
'nombre' => array(
'minlength' => array(
'rule' => array('minlength', 1),
'message' => 'Valor muy pequeño.',
'allowEmpty' => false
),
),
'descripcion' => array(
'minlength' => array(
'rule' => array('minlength',1),
'message' => 'Ingrese una descripción mas detallada.',
'allowEmpty' => false
),
),
);
var $hasMany = array(
'DatosProfesionales' => array(
'className' => 'DatosProfesionales',
'foreignKey' => 'nivel_sni_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
|
public class Silver extends Piece {
public Silver(int owner) {
super(owner);
setSymbol("S");
setType("Silver");
}
public boolean canMove(Square from, Square to, Board b) {
if(promoted) {
//Gold movement code
if((Math.abs(from.getR() - to.getR()) <= 1 &&
(Math.abs(from.getC() - to.getC()) <= 1))) {
if(owner == 1) {
//If Piece is moving backwards check for diagonal
if(from.getR() - to.getR() == 1) {
if(from.getC() != to.getC()) {
return false;
}
}
} else if(owner == 2) {
//If Piece is moving backwards check for diagonal
if(from.getR() - to.getR() == -1) {
if(from.getC() != to.getC()) {
return false;
}
}
}
if(to.getPiece() != null) {
if(from.getPiece().getOwner() == to.getPiece().getOwner()) {
return false;
}
}
return true;
}
return false;
}
if((Math.abs(from.getR() - to.getR()) <= 1 &&
(Math.abs(from.getC() - to.getC()) <= 1))) {
if(owner == 1) {
//If Piece is moving backwards p1
if(from.getR() - to.getR() == 1) {
if(from.getC() == to.getC()) {
return false;
}
}
} else if(owner == 2) {
//If Piece is moving backwards p2
if(from.getR() - to.getR() == -1) {
if(from.getC() == to.getC()) {
return false;
}
}
}
//moving sideways
if(from.getR() == to.getR()) {
return false;
}
if(to.getPiece() != null) {
if(from.getPiece().getOwner() == to.getPiece().getOwner()) {
return false;
}
}
return true;
}
return false;
}
}
|
package org.otherobjects.cms.tools;
import java.io.<API key>;
import java.net.URLEncoder;
import java.security.MessageDigest;
import javax.annotation.Resource;
import org.otherobjects.cms.model.User;
import org.otherobjects.cms.model.UserDao;
import org.otherobjects.cms.views.Tool;
import org.springframework.stereotype.Component;
@Component
@Tool
public class GravatarTool
{
private static final String GRAVATAR_SERVER = "http:
private static final String <API key> = "https://secure.gravatar.com/avatar/";
@Resource
protected UserDao userDao;
/**
* Generates url of Gravatar image for provided user. Username must be valid.
*
* @param username the username for the required user
* @param size width in pixels of required image
* @return the url to the image
*/
public String getUrl(String username, int size, boolean ssl)
{
return getUrl(username, size, null, ssl);
}
/**
* Generates url of Gravatar image for provided user. Username must be valid.
* If the user does not have a Gravatar image then the provided placeholder image url
* is returned.
*
* @param username the username for the required user
* @param size width in pixels of required image
* @param placeholder the url of image to use when no Gravatar is available
* @return the url to the image
*/
public String getUrl(String username, int size, String placeholder, boolean ssl)
{
User user = (User) userDao.loadUserByUsername(username);
return getUrlForEmail(user.getEmail(), size, null, ssl);
}
/**
* Generates url of Gravatar image for provided user. The email address does not
* need to be for a user in OTHERobjects.
*
* If the user does not have a Gravatar image then the provided placeholder image url
* is returned (provide a null placeholder to use the default Gravatar one).
*
* @param email the email address for the required user
* @param size width in pixels of required image
* @param placeholder the url of image to use when no Gravatar is available
* @param ssl whether or not to get an image from a secure Gravatar url
* @return the url to the image
*/
public String getUrlForEmail(String email, int size, String placeholder, boolean ssl)
{
StringBuffer url = new StringBuffer(ssl ? <API key> : GRAVATAR_SERVER);
// Add image name
url.append(md5Hex(email));
url.append(".jpg");
// Add options
StringBuffer options = new StringBuffer();
if (size > 0)
{
options.append("s=" + size);
}
try
{
if (placeholder != null)
{
if (options.length() > 0)
{
options.append("&");
}
options.append("d=" + URLEncoder.encode(placeholder, "UTF-8"));
}
}
catch (<API key> e)
{
// Ignore -- UTF-8 must be supported
}
if (options.length() > 0)
{
url.append("?" + options.toString());
}
return url.toString();
}
public String getUrlForEmail(String email, int size, String placeholder)
{
return getUrlForEmail(email, size, placeholder, false);
}
private static String hex(byte[] array)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i)
{
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
}
private static String md5Hex(String message)
{
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
return hex(md.digest(message.getBytes("CP1252")));
}
catch (Exception e)
{
// Ignore
}
return null;
}
}
|
import kivy
kivy.require('1.9.1')
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.metrics import dp
from kivy.app import Builder
from kivy.properties import StringProperty, ObjectProperty
from kivy.clock import Clock
from kivy.metrics import sp
from kivy.metrics import dp
from iconbutton import IconButton
__all__ = ('alertPopup, confirmPopup, okPopup, editor_popup')
Builder.load_string('''
<ConfirmPopup>:
cols:1
Label:
text: root.text
GridLayout:
cols: 2
size_hint_y: None
height: '44sp'
spacing: '5sp'
IconButton:
text: u'\uf00c'
on_press: root.dispatch('on_answer', True)
IconButton:
text: u'\uf00d'
color: ColorScheme.get_primary()
on_release: root.dispatch('on_answer', False)
<OkPopup>:
cols:1
Label:
text: root.text
GridLayout:
cols: 2
size_hint_y: None
height: '44sp'
spacing: '5sp'
IconButton:
text: u'\uf00c'
on_press: root.dispatch('on_answer', True)
<EditorPopup>:
id: editor_popup
cols:1
BoxLayout:
id: content
GridLayout:
id: buttons
cols: 2
size_hint_y: None
height: '44sp'
spacing: '5sp'
IconButton:
text: u'\uf00c'
on_press: root.dispatch('on_answer', True)
IconButton:
text: u'\uf00d'
color: ColorScheme.get_primary()
on_release: root.dispatch('on_answer', False)
''')
def alertPopup(title, msg):
popup = Popup(title = title,
content=Label(text = msg),
size_hint=(None, None), size=(dp(600), dp(200)))
popup.open()
def confirmPopup(title, msg, answerCallback):
content = ConfirmPopup(text=msg)
content.bind(on_answer=answerCallback)
popup = Popup(title=title,
content=content,
size_hint=(None, None),
size=(dp(600),dp(200)),
auto_dismiss= False)
popup.open()
return popup
class ConfirmPopup(GridLayout):
text = StringProperty()
def __init__(self,**kwargs):
self.register_event_type('on_answer')
super(ConfirmPopup,self).__init__(**kwargs)
def on_answer(self, *args):
pass
def editor_popup(title, content, answerCallback):
content = EditorPopup(content=content)
content.bind(on_answer=answerCallback)
popup = Popup(title=title,
content=content,
size_hint=(0.7, 0.8),
auto_dismiss= False,
title_size=sp(18))
popup.open()
return popup
class EditorPopup(GridLayout):
content = ObjectProperty(None)
def __init__(self,**kwargs):
self.register_event_type('on_answer')
super(EditorPopup,self).__init__(**kwargs)
def on_content(self, instance, value):
Clock.schedule_once(lambda dt: self.ids.content.add_widget(value))
def on_answer(self, *args):
pass
def okPopup(title, msg, answerCallback):
content = OkPopup(text=msg)
content.bind(on_ok=answerCallback)
popup = Popup(title=title,
content=content,
size_hint=(None, None),
size=(dp(600),dp(200)),
auto_dismiss= False)
popup.open()
return popup
class OkPopup(GridLayout):
text = StringProperty()
def __init__(self,**kwargs):
self.register_event_type('on_ok')
super(OkPopup,self).__init__(**kwargs)
def on_ok(self, *args):
pass
|
class CheckBase(object):
"""
Base class for checks.
"""
hooks = []
# pylint: disable=W0105
"""Git hooks to which this class applies. A list of strings."""
def execute(self, hook):
"""
Executes the check.
:param hook: The name of the hook being run.
:type hook: :class:`str`
:returns: ``True`` if the check passed, ``False`` if not.
:rtype: :class:`bool`
"""
pass
|
<?php
/**
* \file htdocs/product/stock/index.php
* \ingroup stock
* \brief Home page of stock area
*/
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
$langs->load("stocks");
// Security check
$result=restrictedArea($user,'stock');
/*
* View
*/
$help_url='EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks';
llxHeader("",$langs->trans("Stocks"),$help_url);
print_fiche_titre($langs->trans("StocksArea"));
//print '<table border="0" width="100%" class="notopnoleftnoright">';
//print '<tr><td valign="top" width="30%" class="notopnoleft">';
print '<div class="fichecenter"><div class="fichethirdleft">';
/*
* Zone recherche entrepot
*/
print '<form method="post" action="'.DOL_URL_ROOT.'/product/stock/liste.php">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<table class="noborder nohover" width="100%">';
print "<tr class=\"liste_titre\">";
print '<td colspan="3">'.$langs->trans("Search").'</td></tr>';
print "<tr ".$bc[false]."><td>";
print $langs->trans("Ref").':</td><td><input class="flat" type="text" size="18" name="sref"></td><td rowspan="2"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td></tr>';
print "<tr ".$bc[false]."><td>".$langs->trans("Other").':</td><td><input type="text" name="sall" class="flat" size="18"></td>';
print "</table></form><br>";
$sql = "SELECT e.label, e.rowid, e.statut";
$sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e";
$sql.= " WHERE e.statut in (0,1)";
$sql.= " AND e.entity = ".$conf->entity;
$sql.= $db->order('e.statut','DESC');
$sql.= $db->plimit(15, 0);
$result = $db->query($sql);
if ($result)
{
$num = $db->num_rows($result);
$i = 0;
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Warehouses").'</td></tr>';
if ($num)
{
$entrepot=new Entrepot($db);
$var=True;
while ($i < $num)
{
$objp = $db->fetch_object($result);
$var=!$var;
print "<tr $bc[$var]>";
print "<td><a href=\"fiche.php?id=$objp->rowid\">".img_object($langs->trans("ShowStock"),"stock")." ".$objp->label."</a></td>\n";
print '<td align="right">'.$entrepot->LibStatut($objp->statut,5).'</td>';
print "</tr>\n";
$i++;
}
$db->free($result);
}
print "</table>";
}
else
{
dol_print_error($db);
}
//print '</td><td valign="top" width="70%" class="notopnoleftnoright">';
print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
// Last movements
$max=10;
$sql = "SELECT p.rowid, p.label as produit,";
$sql.= " e.label as stock, e.rowid as entrepot_id,";
$sql.= " m.value, m.datem";
$sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e";
$sql.= ", ".MAIN_DB_PREFIX."stock_mouvement as m";
$sql.= ", ".MAIN_DB_PREFIX."product as p";
$sql.= " WHERE m.fk_product = p.rowid";
$sql.= " AND m.fk_entrepot = e.rowid";
$sql.= " AND e.entity = ".$conf->entity;
if (empty($conf->global-><API key>)) $sql.= " AND p.fk_product_type = 0";
$sql.= $db->order("datem","DESC");
$sql.= $db->plimit($max,0);
dol_syslog("Index:list stock movements sql=".$sql, LOG_DEBUG);
$resql = $db->query($sql);
if ($resql)
{
$num = $db->num_rows($resql);
print '<table class="noborder" width="100%">';
print "<tr class=\"liste_titre\">";
print '<td>'.$langs->trans("LastMovements",min($num,$max)).'</td>';
print '<td>'.$langs->trans("Product").'</td>';
print '<td>'.$langs->trans("Warehouse").'</td>';
print '<td align="right"><a href="'.DOL_URL_ROOT.'/product/stock/mouvement.php">'.$langs->trans("FullList").'</a></td>';
print "</tr>\n";
$var=True;
$i=0;
while ($i < min($num,$max))
{
$objp = $db->fetch_object($resql);
$var=!$var;
print "<tr $bc[$var]>";
print '<td>'.dol_print_date($db->jdate($objp->datem),'dayhour').'</td>';
print "<td><a href=\"../fiche.php?id=$objp->rowid\">";
print img_object($langs->trans("ShowProduct"),"product").' '.$objp->produit;
print "</a></td>\n";
print '<td><a href="fiche.php?id='.$objp->entrepot_id.'">';
print img_object($langs->trans("ShowWarehouse"),"stock").' '.$objp->stock;
print "</a></td>\n";
print '<td align="right">';
if ($objp->value > 0) print '+';
print $objp->value.'</td>';
print "</tr>\n";
$i++;
}
$db->free($resql);
print "</table>";
}
//print '</td></tr></table>';
print '</div></div></div>';
llxFooter();
$db->close();
?>
|
<?php
require_once ('getConnection.php');
$stmt = $connect -> stmt_init();
$query = "SELECT c_token FROM t_course WHERE c_id = ?";
if (!($stmt -> prepare($query))) {
echo "Prepare failed: " . $connect -> errno . $connect -> error;
}
if (!($stmt -> bind_param("d", $_POST["course"]))) {
echo "Bind failed: " . $connect -> errno . $connect -> error;
}
if (!$stmt -> execute()) {
echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error;
}
if (!($result = $stmt -> get_result())) {
echo "Result failed: (" . $connect -> errno . ") " . $connect -> error;
}
while ($row = $result -> fetch_array(MYSQLI_NUM)) {
$course_token = $row[0];
}
$stmt -> close();
$stmt = $connect -> stmt_init();
$query = "SELECT p_token FROM t_prof WHERE p_id = ?";
if (!($stmt -> prepare($query))) {
echo "Prepare failed: " . $connect -> errno . $connect -> error;
}
if (!($stmt -> bind_param("d", $_POST['prof']))) {
echo "Bind failed: " . $connect -> errno . $connect -> error;
}
if (!$stmt -> execute()) {
echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error;
}
if (!($result = $stmt -> get_result())) {
echo "Result failed: (" . $connect -> errno . ") " . $connect -> error;
}
while ($row = $result -> fetch_array(MYSQLI_NUM)) {
$prof_token = $row[0];
}
$stmt -> close();
for ($i = 1; $i <= $_POST['count_tan']; $i++) {
do {
$stmt = $connect -> stmt_init();
$query = "SELECT t_tan FROM t_tan";
if (!($stmt -> prepare($query))) {
echo "Prepare failed: " . $connect -> errno . $connect -> error;
}
if (!$stmt -> execute()) {
echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error;
}
if (!($result = $stmt -> get_result())) {
echo "Result failed: (" . $connect -> errno . ") " . $connect -> error;
}
while ($row = $result -> fetch_array(MYSQLI_NUM)) {
$generated_tans[] = $row[0];
}
$stmt -> close();
$tan_pruef = generate($prof_token, $course_token);
if (!empty($generated_tans)) {
$pruef = in_array($tan_pruef, $generated_tans);
} else {
$pruef = false;
}
} while ($pruef);
$tan[] = $tan_pruef;
}
echo "<h1>generated TANs</h1>";
echo "\n";
foreach ($tan as $t) {
$stmt = $connect -> stmt_init();
$query = "INSERT into t_tan(t_course, t_prof,t_tan) VALUES(?,?,?)";
if (!($stmt -> prepare($query))) {
echo "Prepare failed: " . $connect -> errno . $connect -> error;
}
if (!($stmt -> bind_param("dds", $_POST['course'], $_POST['prof'], $t))) {
echo "Bind failed: " . $connect -> errno . $connect -> error;
}
if (!$stmt -> execute()) {
echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error;
}
$stmt -> close();
echo '<p>' . $t . '</p>';
echo "\n";
}
unset($_POST);
echo '<a href="admin_tan.html"><img src="../images/buttons/button_back.jpg" alt="back" id="button" width = 300 height = 150/></a>';
echo "\n";
mysqli_close($connect);
function generate($token1, $token2) {
$token = rand(100000, 999999);
$TAN = $token1 . $token . $token2;
return $TAN;
};
?>
|
#define OVERRIDE_PLACEMENT
#include "common.h"
#include "pages.h"
#include "gui/gui.h"
#include "config/model.h"
#include "config/ini.h"
#include <stdlib.h>
enum {
LABELNUM_X = 0,
LABELNUM_WIDTH = 16,
LABEL_X = 17,
LABEL_WIDTH = 0,
};
#include "../128x64x1/model_loadsave.c"
|
package com.gowan.plugin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.<API key>;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.viewers.<API key>;
public class <API key> implements List<ICompilationUnit> {
private List<ICompilationUnit> list;
public <API key>(<API key> selection){
List<ICompilationUnit> localList = new ArrayList<ICompilationUnit>();
List<Object> selectionList = selection.toList();
for (Object object : selectionList) {
localList.addAll( delegate(object) );
}
this.list = localList;
}
protected List<ICompilationUnit> delegate(Object selected){
List<ICompilationUnit> compilationUnits = new ArrayList<ICompilationUnit>();
if( selected instanceof ICompilationUnit ){
compilationUnits.add((ICompilationUnit)selected);
}else if ( selected instanceof IPackageFragment){
compilationUnits.addAll(get((IPackageFragment)selected));
}else if( selected instanceof <API key>){
compilationUnits.addAll(get((<API key>)selected));
}else if( selected instanceof IJavaProject){
compilationUnits.addAll(get((IJavaProject)selected));
}
return compilationUnits;
}
protected List<ICompilationUnit> get(IJavaProject selected) {
List<ICompilationUnit> result = new ArrayList<ICompilationUnit>();
<API key>[] packageRoots;
try {
packageRoots = selected.<API key>();
for(int i=0; i<packageRoots.length; i++){
result.addAll(get(packageRoots[i]));
}
} catch (JavaModelException e) {
e.printStackTrace();
}
return result;
}
protected List<ICompilationUnit> get(IPackageFragment frag){
List<ICompilationUnit> result = new ArrayList<ICompilationUnit>();
try {
result = Arrays.asList(frag.getCompilationUnits());
} catch (JavaModelException e) {
e.printStackTrace();
}
return result;
}
protected List<ICompilationUnit> get(<API key> root){
List<ICompilationUnit> result = new ArrayList<ICompilationUnit>();
try {
for (IJavaElement frag : Arrays.asList(root.getChildren())) {
if( frag instanceof IPackageFragment ){
result.addAll(get((IPackageFragment) frag));
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
return result;
}
@Override
public int size() {
return list.size();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public boolean contains(Object o) {
return list.contains(o);
}
@Override
public Iterator<ICompilationUnit> iterator() {
return list.iterator();
}
@Override
public Object[] toArray() {
return list.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return list.toArray(a);
}
@Override
public boolean add(ICompilationUnit e) {
return list.add(e);
}
@Override
public boolean remove(Object o) {
return list.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return list.contains(c);
}
@Override
public boolean addAll(Collection<? extends ICompilationUnit> c) {
return list.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends ICompilationUnit> c) {
return list.addAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
return list.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return list.retainAll(c);
}
@Override
public void clear() {
list.clear();
}
@Override
public ICompilationUnit get(int index) {
return list.get(index);
}
@Override
public ICompilationUnit set(int index, ICompilationUnit element) {
return list.set(index, element);
}
@Override
public void add(int index, ICompilationUnit element) {
list.add(index, element);
}
@Override
public ICompilationUnit remove(int index) {
return list.remove(index);
}
@Override
public int indexOf(Object o) {
return list.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return list.lastIndexOf(o);
}
@Override
public ListIterator<ICompilationUnit> listIterator() {
return list.listIterator();
}
@Override
public ListIterator<ICompilationUnit> listIterator(int index) {
return list.listIterator(index);
}
@Override
public List<ICompilationUnit> subList(int fromIndex, int toIndex) {
return list.subList(fromIndex, toIndex);
}
}
|
<?php
namespace DB;
final class mPDO {
private $connection = null;
private $statement = null;
public function __construct($hostname, $username, $password, $database, $port = '3306') {
try {
$dsn = "mysql:host={$hostname};port={$port};dbname={$database};charset=UTF8";
$options = array(
\PDO::ATTR_PERSISTENT => true,
\PDO::ATTR_TIMEOUT => 15,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION );
$this->connection = new \PDO($dsn, $username, $password, $options);
} catch (\PDOException $e) {
throw new \Exception('Failed to connect to database. Reason: \'' . $e->getMessage() . '\'');
}
$this->connection->exec("SET NAMES 'utf8'");
$this->connection->exec("SET CHARACTER SET utf8");
$this->connection->exec("SET <API key>=utf8");
$this->connection->exec("SET SQL_MODE = ''");
$this->rowCount = 0;
}
public function prepare($sql) {
$this->statement = $this->connection->prepare($sql);
}
public function bindParam($parameter, $variable, $data_type = \PDO::PARAM_STR, $length = 0) {
if ($length) {
$this->statement->bindParam($parameter, $variable, $data_type, $length);
} else {
$this->statement->bindParam($parameter, $variable, $data_type);
}
}
public function execute() {
try {
if ($this->statement && $this->statement->execute()) {
$data = array();
while ($row = $this->statement->fetch(\PDO::FETCH_ASSOC)) {
$data[] = $row;
}
$result = new \stdClass();
$result->row = (isset($data[0])) ? $data[0] : array();
$result->rows = $data;
$result->num_rows = $this->statement->rowCount();
}
} catch (\PDOException $e) {
throw new \Exception('Error: ' . $e->getMessage() . ' Error Code : ' . $e->getCode());
}
}
public function query($sql, $params = array()) {
$this->statement = $this->connection->prepare($sql);
$result = false;
try {
if ($this->statement && $this->statement->execute($params)) {
$data = array();
$this->rowCount = $this->statement->rowCount();
if ($this->rowCount > 0) {
try {
$data = $this->statement->fetchAll(\PDO::FETCH_ASSOC);
} catch (\Exception $ex) {
}
}
// free up resources
$this->statement->closeCursor();
$this->statement = null;
$result = new \stdClass();
$result->row = (isset($data[0]) ? $data[0] : array());
$result->rows = $data;
$result->num_rows = $this->rowCount;
}
} catch (\PDOException $e) {
throw new \Exception('Error: ' . $e->getMessage() . ' Error Code : ' . $e->getCode() . ' <br />' . $sql);
}
if ($result) {
return $result;
} else {
$result = new \stdClass();
$result->row = array();
$result->rows = array();
$result->num_rows = 0;
return $result;
}
}
public function escape($value) {
return str_replace(array( "\\", "\0", "\n", "\r", "\x1a", "'", '"' ), array(
"\\\\",
"\\0", "\\n", "\\r", "\Z", "\'", '\"' ), $value);
}
public function countAffected() {
if ($this->statement) {
return $this->statement->rowCount();
} else {
return $this->rowCount;
}
}
public function getLastId() {
return $this->connection->lastInsertId();
}
public function isConnected() {
if ($this->connection) {
return true;
} else {
return false;
}
}
public function __destruct() {
$this->connection = null;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.