answer
stringlengths
15
1.25M
// Test get machiens var fs = require('fs'); try { fs.accessSync('testdb.json', fs.F_OK); fs.unlinkSync('testdb.json'); // Do something } catch (e) { // It isn't accessible console.log(e); } var server = require('../server.js').createServer(8000, 'testdb.json'); var addTestMachine = function(name) { var newMachine = {}; newMachine.name = name; newMachine.type = 'washer'; newMachine.queue = []; newMachine.operational = true; newMachine.problemMessage = ""; newMachine.activeJob = {}; server.db('machines').push(newMachine); } describe('ALL THE TESTS LOL', function() { it('should add a machine', function(done) { var options = { method: 'POST', url: '/machines', payload: { name: 'test1', type: 'washer' } } server.inject(options, function(response) { expect(response.statusCode).toBe(200); var p = JSON.parse(response.payload); expect(p.name).toBe(options.payload.name); expect(p.type).toBe(options.payload.type); done(); }) }); it('should get all machines', function(done) { var name = 'testMachine'; var name2 = 'anotherMachine'; addTestMachine(name); addTestMachine(name2); var options = { method: 'GET', url: '/machines', } server.inject(options, function(res) { expect(res.statusCode).toBe(200); var p = JSON.parse(res.payload); // check p has test and anotherMachine done(); }); }); it('should get one machine', function(done) { var name = 'sweetTestMachine'; addTestMachine(name); var options = { method: 'GET', url: '/machines/'+name }; server.inject(options, function(res) { expect(res.statusCode).toBe(200); var p = JSON.parse(res.payload); expect(p.name).toBe(name); done(); }); }); it('should add a job the queue then th queue should have the person', function(done) { addTestMachine('queueTest'); var addOptions = { method: 'POST', url: '/machines/queueTest/queue', payload: { user: 'test@mail.com', pin: 1234, minutes: 50 } }; server.inject(addOptions, function(res) { expect(res.statusCode).toBe(200); var p = JSON.parse(res.payload); expect(p.name).toBe('queueTest'); var getQueue = { method: 'GET', url: '/machines/queueTest/queue' }; server.inject(getQueue, function(newRes) { expect(newRes.statusCode).toBe(200); var q = JSON.parse(newRes.payload); console.log(q); expect(q.queue[0].user).toBe('test@mail.com'); expect(q.queue[0].pin).toBe(1234); done(); }) }) }); it('should delete a job from the queue', function(done) { addTestMachine('anotherQueue'); var addOptions = { method: 'POST', url: '/machines/anotherQueue/queue', payload: { user: 'test@mail.com', pin: 1235, minutes: 50 } }; server.inject(addOptions, function(res) { var deleteOptions = addOptions; deleteOptions.url = '/machines/anotherQueue/queue/delete'; deleteOptions.payload = { user: addOptions.payload.user, pin: addOptions.payload.pin } server.inject(deleteOptions, function(r) { expect(r.statusCode).toBe(200); console.log(JSON.parse(r.payload)); done(); }) }) }) it('should add a job to the active queue', function(done) { addTestMachine('activeQueue'); var addOptions = { method: 'POST', url: '/machines/activeQueue/queue', payload: { user: 'test@mail.com', pin: 1235, minutes: 50 } }; server.inject(addOptions, function(r) { var runJobOptions = { method: 'POST', url: '/machines/activeQueue/queue/start', payload: { command: 'next', pin: 1235, minutes: 0 } }; server.inject(runJobOptions, function(res) { expect(res.statusCode).toBe(200); done(); }) }) }); });
require('./loader.jsx');
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>sudoku: Not compatible </title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif] </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.1 / sudoku - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> sudoku <small> 8.8.0 <span class="label label-info">Not compatible </span> </small> </h1> <p> <em><script>document.write(moment("2022-02-09 07:07:27 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-09 07:07:27 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.11.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.11.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.11.2 Official release 4.11.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/sudoku&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Sudoku&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: sudoku&quot; &quot;keyword: puzzles&quot; &quot;keyword: Davis-Putnam&quot; &quot;category: Miscellaneous/Logical Puzzles and Entertainment&quot; &quot;date: 2006-02&quot; ] authors: [ &quot;Laurent Théry &lt;thery@sophia.inria.fr&gt; [http://www-sop.inria.fr/lemme/personnel/Laurent.Thery/me.html]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/sudoku/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/sudoku.git&quot; synopsis: &quot;A certified Sudoku solver&quot; description: &quot;&quot;&quot; ftp://ftp-sop.inria.fr/lemme/Laurent.Thery/Sudoku.zip A formalisation of Sudoku in Coq. It implements a naive Davis-Putnam procedure to solve sudokus.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/sudoku/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=<API key>&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install </h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-sudoku.8.8.0 coq.8.11.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.1). The following dependencies couldn&#39;t be met: - coq-sudoku -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-sudoku.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install </h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https: </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
from __future__ import absolute_import from .base import WhiteNoise __version__ = '2.0.3' __all__ = ['WhiteNoise']
game.PlayerEntity = me.Entity.extend ({ //builds the player class init: function(x, y, settings){ this.setSuper(x, y); this.setPlayerTimer(); this.setAttributes(); this.type="PlayerEntity"; this.setFlags(); me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); //locks camera on the character this.addAnimation(); this.renderable.setCurrentAnimation("idle"); //sets the idle animation }, setSuper: function(x, y){ this._super(me.Entity, 'init', [x, y, {//._super reaches to the object entity image: "player",//uses the image player width: 64, //preserves the height and width for player height: 64, spritewidth: "64", //uses height and width for player spriteheight: "64", getShape: function(){ return(new me.Rect(0, 0, 64, 64)) . toPolygon(); //creates a little rectangle for what the player can walk into. } }]); }, setPlayerTimer: function(){ this.now = new Date().getTime(); //keeps track of what time it is this.lastHit = this.now; //same as this.now this.lastSpear = this.now; this.lastAttack = new Date().getTime(); }, setAttributes: function(){ this.health = game.data.playerHealth; this.body.setVelocity(game.data.playerMoveSpeed, 20); //sets velocity to 5 this.attack = game.data.playerAttack; }, setFlags: function(){ this.facing = "right"; //makes the character face right this.dead = false; this.attacking = false; }, addAnimation: function(){ this.renderable.addAnimation("idle", [78]); //idle animation this.renderable.addAnimation("walk", [143, 144, 145, 146, 147, 148, 149, 150, 151], 80); //walking animation this.renderable.addAnimation("attack", [195, 196, 197, 198, 199, 200], 80); //setting the attack animation }, update: function(delta){ this.now = new Date().getTime(); //everytime we call update it updates the time this.dead = this.checkIfDead(); this.<API key>(); this.checkAbilityKeys(); this.setAnimation(); me.collision.check(this, true, this.collideHandler.bind(this), true); this.body.update(delta); //delta is the change in time this._super(me.Entity, "update", [delta]); return true; }, checkIfDead: function(){ if (this.health <= 0){ return true; } }, <API key>: function(){ if(me.input.isKeyPressed("right")){ //checks to see if the right key is pressed this.moveRight(); } else if(me.input.isKeyPressed("left")){ //allows the player to move left this.moveLeft(); } else{ this.body.vel.x = 0; //stops the movement } if(me.input.isKeyPressed("jump") && !this.jumping && !this.falling){ //allows the player to jump without double jumping or falling and jumping this.jump(); } this.attacking = me.input.isKeyPressed("attack"); //attack key }, moveRight: function(){ this.body.vel.x += this.body.accel.x * me.timer.tick; //adds the velocity to the set velocity and mutiplies by the me.timer.tick and makes the movement smooth this.facing = "right"; //sets the character to face right this.flipX(false); }, moveLeft: function(){ this.body.vel.x -= this.body.accel.x * me.timer.tick; this.facing = "left"; this.flipX(true); }, jump: function(){ this.body.jumping = true; this.body.vel.y -= this.body.accel.y * me.timer.tick; }, checkAbilityKeys: function(){ if(me.input.isKeyPressed("skill1")){ // this.speedBurst(); }else if(me.input.isKeyPressed("skill2")){ // this.eatCreep(); }else if(me.input.isKeyPressed("skill3")){ this.throwSpear(); } }, throwSpear: function(){ if(this.now-this.lastSpear >= game.data.spearTimer*100 && game.data.ability3 > 0){ this.lastSpear = this.now; var spear = me.pool.pull("spear", this.pos.x, this.pos.y, {}, this.facing); me.game.world.addChild(spear, 10); } }, setAnimation: function(){ if(this.attacking){ if(!this.renderable.isCurrentAnimation("attack")){ this.renderable.setCurrentAnimation("attack", "idle"); this.renderable.setAnimationFrame(); } } else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){ //changes the animation from attack to walking if (!this.renderable.isCurrentAnimation("walk")) { //sets the current animation for walk this.renderable.setCurrentAnimation("walk"); }; } else if(!this.renderable.isCurrentAnimation("attack")){ //changes the animation from attack to idle this.renderable.setCurrentAnimation("idle"); //if the player is not walking it uses idle animation } }, loseHealth: function(damage){ this.health = this.health - damage; }, collideHandler: function(response){ if(response.b.type==='EnemyBaseEntity'){ //sees if the enemy base entitiy is near a player entity and if so it is solid from left and right and top this.<API key>(response); } else if(response.b.type==='EnemyCreep'){ this.<API key>(response); } }, <API key>: function(response){ var ydif = this.pos.y - response.b.pos.y; var xdif = this.pos.x - response.b.pos.x; if(ydif<-40 && xdif<70 && xdif>-35){ this.body.falling=false; this.body.vel.y = -1; } if(xdif>-35 && this.facing==='right' && (xdif<0)){ this.body.vel.x = 0; //this.pos.x = this.pos.x -1; } else if(xdif<70 && this.facing==='left' && (xdif>0)){ this.body.vel.x=0; //this.pos.x = this.pos.x +1; } if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){ //if the animation is attack it will lose the base health and that it will check when the lasthit was this.lastHit = this.now; response.b.loseHealth(game.data.playerAttack); } }, <API key>: function(response){ var xdif = this.pos.x - response.b.pos.x; var ydif = this.pos.y - response.b.pos.y; this.stopMovement(xdif); if(this.checkAttack(xdif, ydif)){ this.hitCreep(response); }; }, stopMovement: function(xdif){ if(xdif > 0){ //this.pos.x = this.pos.x + 1; if (this.facing === "left"){ this.body.vel.x = 0; } } else{ //this.pos.x = this.pos.x - 1; if(this.facing === "right"){ this.body.vel.x = 0; } } }, checkAttack: function(xdif, ydif){ if(this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= game.data.playerAttackTimer && (Math.abs(ydif) <=40) && ((xdif>0) && this.facing==="left") || (((xdif<0) && this.facing === "right"))){ this.lastHit = this.now; return true; } return false; }, hitCreep: function(response){ if(response.b.health <= game.data.playerAttack){ game.data.gold += 1; } response.b.loseHealth(game.data.playerAttack); } }); //intermeidiae challenge creating an ally creep game.MyCreep = me.Entity.extend({ init: function(x, y, settings){ this._super(me.Entity, 'init', [x, y, { image: "creep2", width: 100, height:85, spritewidth: "100", spriteheight: "85", getShape: function(){ return (new me.Rect(0, 0, 52, 100)).toPolygon(); } }]); this.health = game.data.allyCreepHealth; this.alwaysUpdate = true; // //this.attacking lets us know if the enemy is currently attacking this.attacking = false; // //keeps track of when our creep last attacked anyting this.lastAttacking = new Date().getTime(); this.lastHit = new Date().getTime(); this.now = new Date().getTime(); this.body.setVelocity(game.data.allyCreepMoveSpeed, 20); this.type = "MyCreep"; this.renderable.addAnimation("walk", [0, 1, 2, 3, 4], 80); this.renderable.setCurrentAnimation("walk"); }, update: function(delta) { // this.now = new Date().getTime(); this.body.vel.x += this.body.accel.x * me.timer.tick; this.flipX(true); me.collision.check(this, true, this.collideHandler.bind(this), true); this.body.update(delta); this._super(me.Entity, "update", [delta]); return true; }, collideHandler: function(response) { if(response.b.type==='EnemyBaseEntity'){ this.attacking = true; //this.lastAttacking = this.now; this.body.vel.x = 0; this.pos.x = this.pos.x +1; //checks that it has been at least 1 second since this creep hit a base if((this.now-this.lastHit <= game.data.<API key>)){ //updates the last hit timer this.lastHit = this.now; //makes the player base call its loseHealth function and passes it a damage of 1 response.b.loseHealth(1); } } } });
<!DOCTYPE html> <html xmlns:msxsl="urn:<API key>:xslt"> <head> <meta content="en-us" http-equiv="Content-Language" /> <meta content="text/html; charset=utf-16" http-equiv="Content-Type" /> <title _locid="<API key>">.NET Portability Report</title> <style> /* Body style, for the entire document */ body { background: #F3F3F4; color: #1E1E1F; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 0; margin: 0; } /* Header1 style, used for the main title */ h1 { padding: 10px 0px 10px 10px; font-size: 21pt; background-color: #E2E2E2; border-bottom: 1px #C1C1C2 solid; color: #201F20; margin: 0; font-weight: normal; } /* Header2 style, used for "Overview" and other sections */ h2 { font-size: 18pt; font-weight: normal; padding: 15px 0 5px 0; margin: 0; } /* Header3 style, used for sub-sections, such as project name */ h3 { font-weight: normal; font-size: 15pt; margin: 0; padding: 15px 0 5px 0; background-color: transparent; } h4 { font-weight: normal; font-size: 12pt; margin: 0; padding: 0 0 0 0; background-color: transparent; } /* Color all hyperlinks one color */ a { color: #1382CE; } /* Paragraph text (for longer informational messages) */ p { font-size: 10pt; } /* Table styles */ table { border-spacing: 0 0; border-collapse: collapse; font-size: 10pt; } table th { background: #E7E7E8; text-align: left; text-decoration: none; font-weight: normal; padding: 3px 6px 3px 6px; } table td { vertical-align: top; padding: 3px 6px 5px 5px; margin: 0px; border: 1px solid #E7E7E8; background: #F7F7F8; } .NoBreakingChanges { color: darkgreen; font-weight:bold; } .FewBreakingChanges { color: orange; font-weight:bold; } .ManyBreakingChanges { color: red; font-weight:bold; } .BreakDetails { margin-left: 30px; } .CompatMessage { font-style: italic; font-size: 10pt; } .GoodMessage { color: darkgreen; } /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */ .localLink { color: #1E1E1F; background: #EEEEED; text-decoration: none; } .localLink:hover { color: #1382CE; background: #FFFF99; text-decoration: none; } /* Center text, used in the over views cells that contain message level counts */ .textCentered { text-align: center; } /* The message cells in message tables should take up all avaliable space */ .messageCell { width: 100%; } /* Padding around the content after the h1 */ #content { padding: 0px 12px 12px 12px; } /* The overview table expands to width, with a max width of 97% */ #overview table { width: auto; max-width: 75%; } /* The messages tables are always 97% width */ #messages table { width: 97%; } /* All Icons */ .IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded { min-width: 18px; min-height: 18px; background-repeat: no-repeat; background-position: center; } /* Success icon encoded */ .IconSuccessEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ background-image: url(data:image/png;base64,<API key>/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+<API key>/H5+sHpZwYfxyRjTs+<API key>/13u3Fjrs/EdhsdDFHGB/<API key>+m3tVe/t97D52CB/ziG0nIgD/<API key>/<API key>/<API key>+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==); } /* Information icon encoded */ .IconInfoEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ background-image: url(data:image/png;base64,<API key>/<API key>+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/<API key>/HF1RsMXq+<API key>/<API key>+<API key>/<API key>=); } /* Warning icon encoded */ .IconWarningEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ background-image: url(data:image/png;base64,<API key>/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/<API key>+wVDSyyzFoJjfz9NB+pAF+<API key>/<API key>/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/<API key>==); } /* Error icon encoded */ .IconErrorEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ background-image: url(data:image/png;base64,<API key>/<API key>/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+<API key>/<API key>/<API key>=); } </style> </head> <body> <h1 _locid="PortabilityReport">.NET Portability Report</h1> <div id="content"> <div id="submissionId" style="font-size:8pt;"> <p> <i> Submission Id&nbsp; <API key> </i> </p> </div> <h2 _locid="SummaryTitle"> <a name="Portability Summary"></a>Portability Summary </h2> <div id="summary"> <table> <tbody> <tr> <th>Assembly</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> </tr> <tr> <td><strong><a href="#IKVM.OpenJDK.Beans">IKVM.OpenJDK.Beans</a></strong></td> <td class="text-center">99.46 %</td> <td class="text-center">99.35 %</td> <td class="text-center">100.00 %</td> <td class="text-center">99.35 %</td> </tr> </tbody> </table> </div> <div id="details"> <a name="IKVM.OpenJDK.Beans"><h3>IKVM.OpenJDK.Beans</h3></a> <table> <tbody> <tr> <th>Target type</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> <th>Recommended changes</th> </tr> <tr> <td>System.Diagnostics.DebuggableAttribute</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">#ctor(System.Boolean,System.Boolean)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Runtime.Serialization.ISerializable</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Runtime.Serialization.SerializationInfo</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Remove serialization constructors on custom Exception types</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Threading.Thread</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Use System.Threading.Interlocked.MemoryBarrier instead</td> </tr> <tr> <td style="padding-left:2em">MemoryBarrier</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>Use System.Threading.Interlocked.MemoryBarrier instead</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> </table> <p> <a href="#Portability Summary">Back to Summary</a> </p> </div> </div> </body> </html>
/** ** @file errors.h ** @brief Header file for CHILD error-handling routines. ** ** Created Dec. 97 ** $Id: errors.h,v 1.11 2004-01-07 10:53:25 childcvs Exp $ */ #ifndef ERRORS_H #define ERRORS_H #include "../compiler.h" void ReportFatalError( const char *errStr ) ATTRIBUTE_NORETURN; void ReportWarning( const char *errstr ); #endif
package uk.gov.dvsa.ui.pages.vehicleinformation; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import uk.gov.dvsa.domain.model.vehicle.Make; import uk.gov.dvsa.domain.navigation.PageNavigator; import uk.gov.dvsa.framework.config.webdriver.MotAppDriver; import uk.gov.dvsa.helper.FormDataHelper; import uk.gov.dvsa.helper.<API key>; import uk.gov.dvsa.ui.pages.Page; public class VehicleMakePage extends Page { private static final String PAGE_TITLE = "What is the vehicle's make?"; public static final String PATH = "/create-vehicle/make"; @FindBy(id = "vehicleMake") private WebElement vehicleMakeDropdown; @FindBy(className = "button") private WebElement continueButton; public VehicleMakePage(MotAppDriver driver) { super(driver); selfVerify(); } @Override protected boolean selfVerify() { return <API key>.verifyTitle(this.getTitle(), PAGE_TITLE); } public VehicleMakePage selectMake(Make make){ FormDataHelper.<API key>(vehicleMakeDropdown, make.getId().toString()); vehicleMakeDropdown.sendKeys(Keys.TAB); return this; } public VehicleModelPage <API key>() { continueButton.click(); return new VehicleModelPage(driver); } public VehicleModelPage updateVehicleMake(Make make) { FormDataHelper.<API key>(vehicleMakeDropdown, make.getId().toString()); vehicleMakeDropdown.sendKeys(Keys.TAB); return <API key>(); } }
# New Format site for Reiker Seiffe A simple resume site build off of SCSS, running on a Node.JS server with express and twig.
<?php namespace Tecnokey\ShopBundle\Controller\Frontend\User; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\<API key>\Configuration\Method; use Sensio\Bundle\<API key>\Configuration\Route; use Sensio\Bundle\<API key>\Configuration\Template; use Tecnokey\ShopBundle\Entity\Shop\Order; use Tecnokey\ShopBundle\Form\Shop\OrderType; /** * Shop\Order controller. * * @Route("/tienda/usuario/pedidos") */ class OrderController extends Controller { /** * Lists all Shop\Order entities. * * @Route("/", name="<API key>") * @Template() */ public function indexAction() { $em = $this->getDoctrine()->getEntityManager(); $entities = $em->getRepository('TecnokeyShopBundle:Shop\Order')->findAll(); return array('entities' => $entities); } /** * * * @Route("/realizados", name="<API key>") * @Template() */ public function showDeliveredAction() { $orderBy = $this->get('view.sort'); $orderBy->add('pedido', 'publicId', 'pedido') ->add('fecha', 'created_at', 'Fecha') ->add('cantidad', 'quantity', 'Cantidad') ->add('importe', 'totalPrice', 'Importe') ->add('estado', 'status', 'Estado') ->initialize(); $em = $this->getDoctrine()->getEntityManager(); $user = $this->get('userManager')->getCurrentUser(); $entities = $em->getRepository('TecnokeyShopBundle:Shop\\User')->findDeliveredOrders($user, $orderBy->getValues()); return array( 'entities' => $entities, 'orderBy' => $orderBy->switchMode(), ); } /** * * * @Route("/en_proceso", name="<API key>") * @Template() */ public function showInProcessAction() { $orderBy = $this->get('view.sort'); $orderBy->add('pedido', 'publicId', 'pedido') ->add('fecha', 'createdAt', 'Fecha') ->add('cantidad', 'quantity', 'Cantidad') ->add('importe', 'totalPrice', 'Importe') ->add('estado', 'status', 'Estado') ->initialize(); $em = $this->getDoctrine()->getEntityManager(); $user = $this->get('userManager')->getCurrentUser(); $entities = $em->getRepository('TecnokeyShopBundle:Shop\\User')->findInProcessOrders($user, $orderBy->getValues()); return array( 'entities' => $entities, 'orderBy' => $orderBy->switchMode(), ); } /** * Finds and displays a Shop\Order entity. * * @Route("/{publicId}/show", name="<API key>") * @Template() */ public function showAction($publicId) { $em = $this->getDoctrine()->getEntityManager(); $entity = $em->getRepository('TecnokeyShopBundle:Shop\Order')->findByPublicId($publicId); if (!$entity) { throw $this-><API key>('Unable to find Shop\Order entity.'); } return array( 'order' => $entity, ); } /** * Finds and displays a Shop\Order entity. * * @Route("/confirmar", name="<API key>") * @Template() */ public function <API key>() { $confirmed = $this->confirmOrder(); if ($confirmed == true) { return $this->redirect($this->generateUrl('<API key>')); } else{ return $this->redirect($this->generateUrl('<API key>')); } } // HELPER FUNCTIONS // /** * Redirects to home page if there is a problem with Oder * * @param type $msg * @param type $redirect * @return type */ protected function orderErrorHandler($msg = NULL, $redirect=NULL){ //TODO: Redirect to index $this->get('session')->setFlash('order_error',"Atencion: El usuario no puede tener pedidos, cree un usuario de tipo cliente"); return $this->redirect($this->generateUrl("TKShopFrontendIndex")); } /** * Get the Order from the logged user * * @return Order */ protected function <API key>(){ $user = $this->get('userManager')->getCurrentUser(); $shoppingCart = NULL; if($this->get('userManager')->isDBUser($user)){ return $user->getOrders(); } else{ return NULL; } } /** * * @param ShoppingCart $shoppingCart * @return boolean */ public function confirmOrder() { $sc = $this->getUserShoppingCart(); $items = $sc->getItems(); if (count($items) < 1) { return false; } try { $checkoutManager = $this->get('checkoutManager'); $sc = $checkoutManager->checkout($sc); // generate an order $order = $checkoutManager->shoppingCartToOrder($sc); $user = $this->get('userManager')->getCurrentUser(); $order->setUser($user); $em = $this->getDoctrine()->getEntityManager(); $em->persist($order); $em->flush(); //End generating an order // remove all cart items $this->get('shoppingCartManager')->removeAllItems($sc); $em->flush(); //End removing all cart items return true; } catch (Exception $e) { return false; } } /** * Get the ShoppingCart from the logged user * If the user does NOT have a shoppingCart then one is created and attached to user but not persisted to database * * @return ShoppingCart */ protected function getUserShoppingCart() { $user = $this->get('userManager')->getCurrentUser(); $shoppingCart = NULL; if ($this->get('userManager')->isDBUser($user)) { $shoppingCart = $user->getShoppingCart(); if ($shoppingCart == NULL) { $shoppingCart = new ShoppingCart(); $user->setShoppingCart($shoppingCart); } } return $shoppingCart; } }
import {Component, ViewChild} from '@angular/core'; import { Platform, MenuController, NavController} from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { HomeComponent } from './pages/home-page/home.component'; import {CityListPage} from './pages/city-list/city-list'; import {ClausePage} from './pages/clause/clause'; @Component({ templateUrl: './app.component.html' }) export class AppComponent { @ViewChild('content') content: NavController; // make HelloIonicPage the root (or first) page rootPage: any = HomeComponent; pages: Array<{title: string, component: any}>; // stroage: Storage; constructor( private platform: Platform, private menu: MenuController, private splashScreen: SplashScreen ) { this.initializeApp(); // set our app's pages this.pages = [ { title: '', component: HomeComponent }, { title: '', component: CityListPage }, { title: '', component: ClausePage } ]; } initializeApp() { this.platform.ready().then(() => { this.splashScreen.hide(); }); } ionViewDidLoad(){ } openPage(page) { // close the menu when clicking a link from the menu this.menu.close(); // navigate to the new page if it is not the current page this.content.setRoot(page.component); } }
import { Log } from './log'; //import Url = require('./url'); import { Url } from './url'; import { HashString } from './lib'; export const Ajax = (opts: JQueryAjaxSettings) => { if (opts.dataType == 'json') { if (opts.data == null) { opts.data = { datatype: 'json' } } else if (typeof opts.data === "string") { let params: HashString = Url.SplitUrlParams(opts.data); params['datatype'] = 'json'; opts.data = Url.JoinUrlParams(params); } else { opts.data.datatype = 'json'; } } if (opts.xhrFields == null || opts.xhrFields == undefined) { opts.xhrFields = { withCredentials: true }; } if (opts.error == null || typeof opts.error !== 'function') { opts.error = function (jqXHR, textStatus, errorThrown) { Log('error:', textStatus, errorThrown); }; } else { let original = opts.error; opts.error = function (jqXHR, textStatus, errorThrown) { original(jqXHR, textStatus, errorThrown); Log('Ajax.error()', textStatus, errorThrown); }; } return $.ajax(opts); };
<div class="<API key> @if($from == "account") <API key> @endif"> @if(count($<API key>) > 0) <div class="hierarchy_parent"> <select name="title" id="<API key>" class="first_level hierarchy" size="5" data-number="1"> @foreach($<API key> as $area_of_interest_id=>$area_of_interest) <option value="{{$area_of_interest_id}}" data-type="{{$area_of_interest['type']}}">{{$area_of_interest['name']}}&nbsp;></option> @endforeach </select> @if($from == "site_admin") <div style="margin-left:10px;margin-top:5px;"> <a class="btn black-btn btn-xs add_category" data-pos="first" id="add_category_btn" style="padding:5px 10px 5px; text-decoration:none;"> <i class="fa fa-plus plus"></i> <span class="plus_text" style="left:-5px;">ADD</span> </a> </div> @endif </div> @endif </div> @if($from != "site_admin") <div class="row"> <div class="col-xs-12"> <div class="text-center"><h5>You have selected:<span class="selected_text_area">None</span></h5></div> </div> </div> @endif
# <API key>: true describe ContactController, type: :controller do include AuthHelper let!(:ada) { create(:published_profile, email: "ada@mail.org", main_topic_en: 'math') } describe 'create action' do it 'when profile active' do get :create, params: { id: ada.id, message: { name: "Maxi"} } expect(response).to be_successful expect(response.response_code).to eq(200) end it 'when profile inactive' do ada.update!(inactive: true) get :create, params: { id: ada.id, message: { name: "Maxi"} } expect(response).not_to be_successful expect(response.response_code).to eq(302) expect(response).to redirect_to("/#{I18n.locale}/profiles") end it 'when unpublished profiles' do ada.update!(published: false) get :create, params: { id: ada.id, message: { name: "Maxi"} } expect(response).not_to be_successful expect(response.response_code).to eq(302) expect(response).to redirect_to("/#{I18n.locale}/profiles") end end end
<?php namespace LCoder\Bundle\BlogBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\<API key>; class Configuration implements <API key> { /** * {@inheritDoc} */ public function <API key>() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('l_coder_blog'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
#ifndef <API key> #define <API key> #include <QObject> /** Macintosh-specific notification handler (supports <API key>). */ class <API key> : public QObject { Q_OBJECT public: /** shows a macOS 10.8+ UserNotification in the <API key> */ void showNotification(const QString &title, const QString &text); /** check if OS can handle UserNotifications */ bool <API key>(); static <API key> *instance(); }; #endif // <API key>
package tsmt import ( "encoding/xml" "github.com/fgrid/iso20022" ) type Document01800105 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsmt.018.001.05 Document"` Message *<API key> `xml:"FullPushThrghRpt"` } func (d *Document01800105) AddMessage() *<API key> { d.Message = new(<API key>) return d.Message } // Scope // The <API key> message is sent by the matching application to a party involved in a transaction. // This message is used to pass on information that the matching application has received from the submitter. The forwarded information can originate from an <API key> or <API key> or <API key> message. // Usage // The <API key> message can be sent by the matching application to a party to convey // - the details of an <API key> message that it has obtained,or // - the details of a <API key> message that it has obtained,or // - the details of a <API key> message that it has obtained. type <API key> struct { // Identifies the report. <API key> *iso20022.<API key> `xml:"RptId"` // Unique identification assigned by the matching application to the transaction. // This identification is to be used in any communication between the parties. <API key> *iso20022.<API key> `xml:"TxId"` // Unique identification assigned by the matching application to the baseline when it is established. <API key> *iso20022.<API key> `xml:"EstblishdBaselnId,omitempty"` // Identifies the status of the transaction by means of a code. TransactionStatus *iso20022.TransactionStatus4 `xml:"TxSts"` // Reference to the transaction for the financial institution which submitted the baseline. <API key> []*iso20022.<API key> `xml:"UsrTxRef,omitempty"` // Specifies the type of report. ReportPurpose *iso20022.ReportType1 `xml:"RptPurp"` // Specifies the commercial details of the underlying transaction. <API key> *iso20022.Baseline5 `xml:"PushdThrghBaseln"` // Person to be contacted in the organisation of the buyer. BuyerContactPerson []*iso20022.<API key> `xml:"BuyrCtctPrsn,omitempty"` // Person to be contacted in the organisation of the seller. SellerContactPerson []*iso20022.<API key> `xml:"SellrCtctPrsn,omitempty"` // Person to be contacted in the buyer's bank. <API key> []*iso20022.<API key> `xml:"BuyrBkCtctPrsn,omitempty"` // Person to be contacted in the seller's bank. <API key> []*iso20022.<API key> `xml:"SellrBkCtctPrsn,omitempty"` // Person to be contacted in another bank than the seller or buyer's bank. <API key> []*iso20022.<API key> `xml:"OthrBkCtctPrsn,omitempty"` // Information on the next processing step required. RequestForAction *iso20022.PendingActivity2 `xml:"ReqForActn,omitempty"` } func (f *<API key>) <API key>() *iso20022.<API key> { f.<API key> = new(iso20022.<API key>) return f.<API key> } func (f *<API key>) <API key>() *iso20022.<API key> { f.<API key> = new(iso20022.<API key>) return f.<API key> } func (f *<API key>) <API key>() *iso20022.<API key> { f.<API key> = new(iso20022.<API key>) return f.<API key> } func (f *<API key>) <API key>() *iso20022.TransactionStatus4 { f.TransactionStatus = new(iso20022.TransactionStatus4) return f.TransactionStatus } func (f *<API key>) <API key>() *iso20022.<API key> { newValue := new(iso20022.<API key>) f.<API key> = append(f.<API key>, newValue) return newValue } func (f *<API key>) AddReportPurpose() *iso20022.ReportType1 { f.ReportPurpose = new(iso20022.ReportType1) return f.ReportPurpose } func (f *<API key>) <API key>() *iso20022.Baseline5 { f.<API key> = new(iso20022.Baseline5) return f.<API key> } func (f *<API key>) <API key>() *iso20022.<API key> { newValue := new(iso20022.<API key>) f.BuyerContactPerson = append(f.BuyerContactPerson, newValue) return newValue } func (f *<API key>) <API key>() *iso20022.<API key> { newValue := new(iso20022.<API key>) f.SellerContactPerson = append(f.SellerContactPerson, newValue) return newValue } func (f *<API key>) <API key>() *iso20022.<API key> { newValue := new(iso20022.<API key>) f.<API key> = append(f.<API key>, newValue) return newValue } func (f *<API key>) <API key>() *iso20022.<API key> { newValue := new(iso20022.<API key>) f.<API key> = append(f.<API key>, newValue) return newValue } func (f *<API key>) <API key>() *iso20022.<API key> { newValue := new(iso20022.<API key>) f.<API key> = append(f.<API key>, newValue) return newValue } func (f *<API key>) AddRequestForAction() *iso20022.PendingActivity2 { f.RequestForAction = new(iso20022.PendingActivity2) return f.RequestForAction }
namespace Kondor.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class <API key> : DbMigration { public override void Up() { AddColumn("dbo.Cards", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.CardStates", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.StringResources", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.ExampleViews", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.Examples", "ExampleUniqueId", c => c.Guid(nullable: false)); AddColumn("dbo.Examples", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.Media", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.Notifications", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.Responses", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.Settings", "RowStatus", c => c.Int(nullable: false)); AddColumn("dbo.Updates", "RowStatus", c => c.Int(nullable: false)); } public override void Down() { DropColumn("dbo.Updates", "RowStatus"); DropColumn("dbo.Settings", "RowStatus"); DropColumn("dbo.Responses", "RowStatus"); DropColumn("dbo.Notifications", "RowStatus"); DropColumn("dbo.Media", "RowStatus"); DropColumn("dbo.Examples", "RowStatus"); DropColumn("dbo.Examples", "ExampleUniqueId"); DropColumn("dbo.ExampleViews", "RowStatus"); DropColumn("dbo.StringResources", "RowStatus"); DropColumn("dbo.CardStates", "RowStatus"); DropColumn("dbo.Cards", "RowStatus"); } } }
# <API key>: true class Dummy::Ui::CardListCell < ApplicationCell def show render if model.present? end end
# <API key>: true # :nocov: class <API key> include Sidekiq::Worker sidekiq_options backtrace: true, lock: :until_executed, queue: :customqueue, retry: true, lock_args_method: :unique_args def perform(optional = true) # rubocop:disable Style/<API key> optional # NO-OP end def self.unique_args; end end
import struct ''' Refer to docs for all the exact formats. There are many so check them out before converting things yourself ''' ''' If there's a specific offset you want to do things from, use pack_into and unack_into from the docs ''' #Integer to string i1= 1234 print "Int to string as 8 byte little endian", repr(struct.pack("<Q",i1)) print "Int to string as 8 byte big endian", repr(struct.pack(">Q",i1)) #String to integer. Make sure size of destination matches the length of the string s1= '1234' print "String to 4 byte integer little endian", struct.unpack("<i", s1) print "String to 4 byte integer big endian", struct.unpack(">i", s1) ''' Whenever you want to convert to and from binary, think of binascii ''' import binascii h1= binascii.b2a_hex(s1) print "String to hex", h1 uh1= binascii.a2b_hex(h1) print "Hex to string, even a binary string", uh1
\begin{figure}[H] \centering \includegraphics[width=6in]{figs/run_1/<API key>} \caption{Scatter plot of $ u_T$ reynolds stress term vs radius at $z/c$=5.37, $V_{free}$=15.22, station 1.} \label{fig:<API key>} \end{figure}
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module MobileCenterApi module Models # Model object. class Event # @return [String] attr_accessor :id # @return [String] attr_accessor :name # @return [Integer] attr_accessor :device_count # @return [Integer] the device count of previous time range of the event attr_accessor :<API key> # @return [Integer] attr_accessor :count # @return [Integer] the event count of previous time range of the event attr_accessor :previous_count # @return [Integer] attr_accessor :count_per_device # @return [Integer] attr_accessor :count_per_session # Mapper for Event class as Ruby Hash. # This will be used for serialization/deserialization. def self.mapper() { required: false, serialized_name: 'Event', type: { name: 'Composite', class_name: 'Event', model_properties: { id: { required: false, serialized_name: 'id', type: { name: 'String' } }, name: { required: false, serialized_name: 'name', type: { name: 'String' } }, device_count: { required: false, serialized_name: 'deviceCount', type: { name: 'Number' } }, <API key>: { required: false, serialized_name: '<API key>', type: { name: 'Number' } }, count: { required: false, serialized_name: 'count', type: { name: 'Number' } }, previous_count: { required: false, serialized_name: 'previous_count', type: { name: 'Number' } }, count_per_device: { required: false, serialized_name: 'count_per_device', type: { name: 'Number' } }, count_per_session: { required: false, serialized_name: 'count_per_session', type: { name: 'Number' } } } } } end end end end
import Helper from '@ember/component/helper'; import { inject as service } from '@ember/service'; import { get } from '@ember/object'; export default class MediaHelper extends Helper { @service() media; constructor() { super(...arguments); this.media.on('mediaChanged', () => { this.recompute(); }); } compute([prop]) { return get(this, `media.${prop}`); } }
Enum = { BarDrawDirect: { Horizontal: "Horizontal", Vertical: "Vertical" }, PowerType: { MP: 0, Angery: 1 }, EffectType: { StateChange: "StateChange", HpChange: "HpChange", Timing: "Timing", Control: "Control" }, EffectControlType: { Stun: "Stun", Silence: "Silence", Sleep: "Sleep" }, EffectCharacterType: { Passive: "Passive", Self: "Self", Column: "Column", Single: "Single", Row: "Row", All: "All" }, EffectRange: { Melee: "Melee", Range: "Range" }, StateChangeClass: { Plus: "Plus", Minus: "Minus" }, StateChangeType: { HitRate: "HitRate", DodgeRate: "DodgeRate" }, HpChangeClass: { Damage: "Damage", Heal: "Heal" }, HpChangeType: { Normal: "Normal", Critial: "Critial" }, BattleActionType: { Physical: "Physical", Magical: "Magical" }, EffectStyle: { Temp: "Temp", Static: "Static", UniqueTemp: "UniqueTemp" }, Align: { Left: "Left", Right: "Right", Center: "Center" } }
package io.prajesh.config; import io.prajesh.domain.HelloWorld; import io.prajesh.service.HelloWorldService; import io.prajesh.service.<API key>; import io.prajesh.service.factory.HelloWorldFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration public class HelloConfig { @Bean public HelloWorldFactory helloWorldFactory() { return new HelloWorldFactory(); } @Bean public HelloWorldService helloWorldService() { return new <API key>(); } @Bean @Profile("English") public HelloWorld helloWorldEn(HelloWorldFactory factory) { return factory.<API key>("en"); } @Bean @Profile("Malay") public HelloWorld helloWorldMy(HelloWorldFactory factory) { return factory.<API key>("my"); } }
#include "checkpoints.h" #include "db.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include "kernel.h" #include "main.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <cstdlib> #include "<API key>.h" #include "<API key>.h" #include "<API key>.h" using namespace std; using namespace boost; // Global state CCriticalSection <API key>; set<CWallet*> <API key>; CCriticalSection cs_main; CTxMemPool mempool; unsigned int <API key> = 0; map<uint256, CBlockIndex*> mapBlockIndex; set<pair<COutPoint, unsigned int> > setStakeSeen; CBlockIndex* pindexGenesisBlock = NULL; int nBestHeight = -1; CBigNum bnBestChainTrust = 0; CBigNum bnBestInvalidTrust = 0; uint256 hashBestChain = 0; CBlockIndex* pindexBest = NULL; int64 nTimeBestReceived = 0; CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have map<uint256, CBlock*> mapOrphanBlocks; multimap<uint256, CBlock*> <API key>; set<pair<COutPoint, unsigned int> > setStakeSeenOrphan; map<uint256, uint256> mapProofOfStake; map<uint256, CDataStream*> <API key>; map<uint256, map<uint256, CDataStream*> > <API key>; // Constant stuff for coinbase transactions we create: CScript COINBASE_FLAGS; const string strMessageMagic = COIN_NAME " Signed Message:\n"; double dHashesPerSec; int64 nHPSTimerStart; // Settings int64 nTransactionFee = MIN_TX_FEES; // dispatching functions // These functions dispatch to one or all registered wallets void RegisterWallet(CWallet* pwalletIn) { { LOCK(<API key>); <API key>.insert(pwalletIn); } } void UnregisterWallet(CWallet* pwalletIn) { { LOCK(<API key>); <API key>.erase(pwalletIn); } } // check whether the passed transaction is from us bool static IsFromMe(CTransaction& tx) { BOOST_FOREACH(CWallet* pwallet, <API key>) if (pwallet->IsFromMe(tx)) return true; return false; } // get the wallet transaction with the given hash (if it exists) bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) { BOOST_FOREACH(CWallet* pwallet, <API key>) if (pwallet->GetTransaction(hashTx,wtx)) return true; return false; } // erases transaction with the given hash from all wallets void static EraseFromWallets(uint256 hash) { BOOST_FOREACH(CWallet* pwallet, <API key>) pwallet->EraseFromWallet(hash); } // make sure all wallets know about the given transaction, in the given block void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect) { if (!fConnect) { // ppcoin: wallets need to refund inputs when disconnecting coinstake if (tx.IsCoinStake()) { BOOST_FOREACH(CWallet* pwallet, <API key>) if (pwallet->IsFromMe(tx)) pwallet->DisableTransaction(tx); } return; } BOOST_FOREACH(CWallet* pwallet, <API key>) pwallet-><API key>(tx, pblock, fUpdate); } // notify wallets about a new best chain void static SetBestChain(const CBlockLocator& loc) { BOOST_FOREACH(CWallet* pwallet, <API key>) pwallet->SetBestChain(loc); } // notify wallets about an updated transaction void static UpdatedTransaction(const uint256& hashTx) { BOOST_FOREACH(CWallet* pwallet, <API key>) pwallet->UpdatedTransaction(hashTx); } // dump all wallets void static PrintWallets(const CBlock& block) { BOOST_FOREACH(CWallet* pwallet, <API key>) pwallet->PrintWallet(block); } // notify wallets about an incoming inventory (for request counts) void static Inventory(const uint256& hash) { BOOST_FOREACH(CWallet* pwallet, <API key>) pwallet->Inventory(hash); } // ask wallets to resend their transactions void static <API key>() { BOOST_FOREACH(CWallet* pwallet, <API key>) pwallet-><API key>(); } // <API key> bool AddOrphanTx(const CDataStream& vMsg) { CTransaction tx; CDataStream(vMsg) >> tx; uint256 hash = tx.GetHash(); if (<API key>.count(hash)) return false; CDataStream* pvMsg = new CDataStream(vMsg); // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: if (pvMsg->size() > 5000) { printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str()); delete pvMsg; return false; } <API key>[hash] = pvMsg; BOOST_FOREACH(const CTxIn& txin, tx.vin) <API key>[txin.prevout.hash].insert(make_pair(hash, pvMsg)); printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(), <API key>.size()); return true; } void static EraseOrphanTx(uint256 hash) { if (!<API key>.count(hash)) return; const CDataStream* pvMsg = <API key>[hash]; CTransaction tx; CDataStream(*pvMsg) >> tx; BOOST_FOREACH(const CTxIn& txin, tx.vin) { <API key>[txin.prevout.hash].erase(hash); if (<API key>[txin.prevout.hash].empty()) <API key>.erase(txin.prevout.hash); } delete pvMsg; <API key>.erase(hash); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) { unsigned int nEvicted = 0; while (<API key>.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); map<uint256, CDataStream*>::iterator it = <API key>.lower_bound(randomhash); if (it == <API key>.end()) it = <API key>.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } // CTransaction and CTxIndex bool CTransaction::ReadFromDisk(CTxDB& txdb, const uint256& hash, CTxIndex& txindexRet) { SetNull(); if (!txdb.ReadTxIndex(hash, txindexRet)) return false; if (!ReadFromDisk(txindexRet.pos)) return false; return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet) { if (!ReadFromDisk(txdb, prevout.hash, txindexRet)) return false; if (prevout.n >= vout.size()) { SetNull(); return false; } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout) { CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::ReadFromDisk(COutPoint prevout) { CTxDB txdb("r"); CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::IsStandard() const { BOOST_FOREACH(const CTxIn& txin, vin) { // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG // pay-to-script-hash, which is 3 ~80-byte signatures, 3 // ~65-byte public keys, plus a few script ops. if (txin.scriptSig.size() > 500) return false; if (!txin.scriptSig.IsPushOnly()) return false; } unsigned int nDataOut = 0; txnouttype whichType; BOOST_FOREACH(const CTxOut& txout, vout) { if (!::IsStandard(txout.scriptPubKey, whichType)) { return false; } if (whichType == TX_NULL_DATA) nDataOut++; } // only one OP_RETURN txout is permitted if (nDataOut > 1) { return false; } return true; } // Check transaction inputs, and make sure any // pay-to-script-hash transactions are evaluating IsStandard scripts // Why bother? To avoid denial-of-service attacks; an attacker // can submit a standard HASH... OP_EQUAL transaction, // which will get accepted into blocks. The redemption // script can be anything; an attacker could use a very // <API key> script like: // DUP CHECKSIG DROP ... repeated 100 times... OP_1 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const { if (IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prev = GetOutputFor(vin[i], mapInputs); vector<vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = <API key>(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig the // IsStandard() call returns false vector<vector<unsigned char> > stack; if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0)) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); vector<vector<unsigned char> > vSolutions2; txnouttype whichType2; if (!Solver(subscript, whichType2, vSolutions2)) return false; if (whichType2 == TX_SCRIPTHASH) return false; int tmpExpected; tmpExpected = <API key>(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; } unsigned int CTransaction::GetLegacySigOpCount() const { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } int CMerkleTx::SetMerkleBranch(const CBlock* pblock) { if (fClient) { if (hashBlock == 0) return 0; } else { CBlock blockTmp; if (pblock == NULL) { // Load the block this tx is in CTxIndex txindex; if (!CTxDB("r").ReadTxIndex(GetHash(), txindex)) return 0; if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos)) return 0; pblock = &blockTmp; } // Update the tx's hashBlock hashBlock = pblock->GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++) if (pblock->vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)pblock->vtx.size()) { vMerkleBranch.clear(); nIndex = -1; printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = pblock->GetMerkleBranch(nIndex); } // Is the tx in a block that's in the main chain map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return pindexBest->nHeight - pindex->nHeight + 1; } bool CTransaction::<API key>() const { if (!IsCoinStake()) return false; int64 nValueIn = 0; CScript onlyAllowedScript; for (unsigned int i = 0; i < vin.size(); ++i) { const COutPoint& prevout = vin[i].prevout; CTxDB txdb("r"); CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, prevout, txindex)) return false; txdb.Close(); const CTxOut& prevtxo = txPrev.vout[prevout.n]; const CScript& prevScript = prevtxo.scriptPubKey; if (i == 0) { onlyAllowedScript = prevScript; if (onlyAllowedScript.empty()) { return false; } } else { if (prevScript != onlyAllowedScript) { return false; } } nValueIn += prevtxo.nValue; } int64 nValueOut = 0; for (unsigned int i = 1; i < vout.size(); ++i) { const CTxOut& txo = vout[i]; if (txo.nValue == 0) continue ; if (txo.scriptPubKey != onlyAllowedScript) return false; nValueOut += txo.nValue; } if (nValueOut < nValueIn) return false; return true; } bool CTransaction::CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); if (vout.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); // Time (prevent mempool memory exhaustion attack) if (nTime > GetAdjustedTime() + MAX_CLOCK_DRIFT) return DoS(10, error("CTransaction::CheckTransaction() : timestamp is too far into the future")); // Size limits if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64 nValueOut = 0; for (size_t i = 0; i < vout.size(); i++) { const CTxOut& txout = vout[i]; if (txout.IsEmpty() && (!IsCoinBase()) && (!IsCoinStake())) return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction")); // ppcoin: enforce minimum output amount if ((!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum (%d)", txout.nValue)); if (txout.nValue > MAX_MONEY_STACK) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high (%d)", txout.nValue)); nValueOut += txout.nValue; if (!IsValidAmount(nValueOut)) return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, vin) { if (vInOutPoints.count(txin.prevout)) return false; vInOutPoints.insert(txin.prevout); } if (IsCoinBase()) { if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size")); } else { BOOST_FOREACH(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); } return true; } bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs) { if (pfMissingInputs) *pfMissingInputs = false; if (!tx.CheckTransaction()) return error("CTxMemPool::accept() : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx")); // ppcoin: coinstake is also only valid in a block, not as a loose transaction if (tx.IsCoinStake()) return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx")); // To help v0.1.5 clients who would see it as a negative number if ((int64)tx.nLockTime > std::numeric_limits<int>::max()) return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet"); // Rather not work on nonstandard transactions if (!tx.IsStandard()) return error("CTxMemPool::accept() : nonstandard transaction type"); // Do we already have it? uint256 hash = tx.GetHash(); { LOCK(cs); if (mapTx.count(hash)) return false; } if (fCheckInputs) if (txdb.ContainsTx(hash)) return false; // Check for conflicts with in-memory transactions CTransaction* ptxOld = NULL; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; // Allow replacing with a newer version of the same transaction if (i != 0) return false; ptxOld = mapNextTx[outpoint].ptx; if (ptxOld->IsFinal()) return false; if (!tx.IsNewerThan(*ptxOld)) return false; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld) return false; } break; } } if (fCheckInputs) { MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { if (fInvalid) return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str()); if (pfMissingInputs) *pfMissingInputs = true; return error("CTxMemPool::accept() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str()); } // Check for non-standard pay-to-script-hash in inputs if (!tx.AreInputsStandard(mapInputs)) return error("CTxMemPool::accept() : nonstandard transaction input"); // Note: if you modify this code to accept non-standard transactions, then // you should add code here to check that the transaction does a // reasonable number of ECDSA signature verifications. int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Don't accept it if it can't get into a block if (nFees < tx.GetMinFee(1000, false, GMF_RELAY)) return error("CTxMemPool::accept() : not enough fees"); // Continuously rate-limit free transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make other's transactions take longer to confirm. if (nFees < MIN_RELAY_TX_FEES) { static CCriticalSection cs; static double dFreeCount; static int64 nLastTime; int64 nNow = GetTime(); { LOCK(cs); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is <API key> // At default rate it would take over a month to fill 1GB if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx)) return error("CTxMemPool::accept() : free transaction rejected by rate limiter"); if (fDebug) printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } } // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false)) { return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str()); } } // Store transaction in memory { LOCK(cs); if (ptxOld) { printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); remove(*ptxOld); } addUnchecked(tx); } // are we sure this is ok when loading transactions or restoring block txes // If updated, erase old tx from wallet if (ptxOld) EraseFromWallets(ptxOld->GetHash()); printf("CTxMemPool::accept() : accepted %s\n", hash.ToString().substr(0,10).c_str()); return true; } bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs) { return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs); } bool CTxMemPool::addUnchecked(CTransaction &tx) { printf("addUnchecked(): size %lu\n", mapTx.size()); // Add to memory pool without checking anything. Don't call this directly, // call CTxMemPool::accept to properly check the transaction first. { LOCK(cs); uint256 hash = tx.GetHash(); mapTx[hash] = tx; for (unsigned int i = 0; i < tx.vin.size(); i++) mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i); <API key>++; } return true; } bool CTxMemPool::remove(CTransaction &tx) { // Remove transaction from memory pool { LOCK(cs); uint256 hash = tx.GetHash(); if (mapTx.count(hash)) { BOOST_FOREACH(const CTxIn& txin, tx.vin) mapNextTx.erase(txin.prevout); mapTx.erase(hash); <API key>++; } } return true; } void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) { vtxid.clear(); LOCK(cs); vtxid.reserve(mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) vtxid.push_back((*mi).first); } int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; // Find the block it claims to be in map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return pindexBest->nHeight - pindex->nHeight + 1; } int CMerkleTx::GetBlocksToMaturity() const { if (!(IsCoinBase() || IsCoinStake())) return 0; int depth = GetDepthInMainChain(); if (depth == 0) // Not in the blockchain return COINBASE_MATURITY; return max(0, COINBASE_MATURITY - (depth - 1)); } bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs) { if (fClient) { if (!IsInMainChain() && !ClientConnectInputs()) return false; return CTransaction::AcceptToMemoryPool(txdb, false); } else { return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs); } } bool CMerkleTx::AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); } bool CWalletTx::<API key>(CTxDB& txdb, bool fCheckInputs) { { LOCK(mempool.cs); // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!(tx.IsCoinBase() || tx.IsCoinStake())) { uint256 hash = tx.GetHash(); if (!mempool.exists(hash) && !txdb.ContainsTx(hash)) tx.AcceptToMemoryPool(txdb, fCheckInputs); } } return AcceptToMemoryPool(txdb, fCheckInputs); } return false; } bool CWalletTx::<API key>() { CTxDB txdb("r"); return <API key>(txdb); } int CTxIndex::GetDepthInMainChain() const { // Read block header CBlock block; if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false)) return 0; // Find the block in the index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash()); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return 1 + nBestHeight - pindex->nHeight; } // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock) { { LOCK(cs_main); { LOCK(mempool.cs); if (mempool.exists(hash)) { tx = mempool.lookup(hash); return true; } } CTxDB txdb("r"); CTxIndex txindex; if (tx.ReadFromDisk(txdb, hash, txindex)) { CBlock block; if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) hashBlock = block.GetHash(); return true; } // look for transaction in disconnected blocks to find orphaned CoinBase and CoinStake transactions BOOST_FOREACH(PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) { CBlockIndex* pindex = item.second; if (pindex == pindexBest || pindex->pnext != 0) continue; CBlock block; if (!block.ReadFromDisk(pindex)) continue; BOOST_FOREACH(const CTransaction& txOrphan, block.vtx) { if (txOrphan.GetHash() == hash) { tx = txOrphan; return true; } } } } return false; } // CBlock and CBlockIndex bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions) { if (!fReadTransactions) { *this = pindex->GetBlockHeader(); return true; } if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions)) return false; if (GetHash() != pindex->GetBlockHash()) return error("CBlock::ReadFromDisk() : GetHash() doesn't match index"); return true; } uint256 static GetOrphanRoot(const CBlock* pblock) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblock->hashPrevBlock)) pblock = mapOrphanBlocks[pblock->hashPrevBlock]; return pblock->GetHash(); } // ppcoin: find block wanted by given orphan block uint256 WantedByOrphan(const CBlock* pblockOrphan) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock)) pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock]; return pblockOrphan->hashPrevBlock; } // minimum amount of work that could possibly be required nTime after // minimum work required was nBase unsigned int ComputeMinWork(unsigned int nBase, int64 nTime) { CBigNum bnResult; bnResult.SetCompact(nBase); bnResult *= 2; while (nTime > 0 && bnResult < POW_MAX_TARGET) { // Maximum 200% adjustment per day... bnResult *= 2; nTime -= 24 * 60 * 60; } if (bnResult > POW_MAX_TARGET) bnResult = POW_MAX_TARGET; return bnResult.GetCompact(); } // ppcoin: find last block index up to pindex const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake) { while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake)) pindex = pindex->pprev; return pindex; } bool CheckProofOfWork(uint256 hash, unsigned int nBits, bool triggerErrors) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > POW_MAX_TARGET) return triggerErrors ? error("CheckProofOfWork() : nBits below minimum work") : false; // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return triggerErrors ? error("CheckProofOfWork() : hash doesn't match nBits") : false; return true; } // Return maximum amount of blocks that other nodes claim to have int GetNumBlocksOfPeers() { return std::max(cPeerBlockCounts.median(), Checkpoints::<API key>()); } bool <API key>() { if (pindexBest == NULL || nBestHeight < Checkpoints::<API key>()) return true; static int64 nLastUpdate; static CBlockIndex* pindexLastBest; if (pindexBest != pindexLastBest) { pindexLastBest = pindexBest; nLastUpdate = GetTime(); } return (GetTime() - nLastUpdate < 10 && pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->bnChainTrust > bnBestInvalidTrust) { bnBestInvalidTrust = pindexNew->bnChainTrust; CTxDB().<API key>(bnBestInvalidTrust); MainFrameRepaint(); } printf("InvalidChainFound: invalid block=%s height=%d trust=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, CBigNum(pindexNew->bnChainTrust).ToString().c_str()); printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(bnBestChainTrust).ToString().c_str()); // ppcoin: should not enter safe mode for longer invalid chain } void CBlock::UpdateTime(const CBlockIndex* pindexPrev) { nTime = max(GetBlockTime(), GetAdjustedTime()); } bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers if (!IsCoinBase()) { BOOST_FOREACH(const CTxIn& txin, vin) { COutPoint prevout = txin.prevout; // Get prev txindex from disk CTxIndex txindex; if (!txdb.ReadTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : ReadTxIndex failed"); if (prevout.n >= txindex.vSpent.size()) return error("DisconnectInputs() : prevout.n out of range"); // Mark outpoint as not spent txindex.vSpent[prevout.n].SetNull(); // Write back if (!txdb.UpdateTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : UpdateTxIndex failed"); } } // Remove transaction from index // This can fail if a duplicate of this transaction was in a chain that got // reorganized away. This is only possible if this transaction was completely // spent, so erasing it would be a no-op anway. txdb.EraseTxIndex(*this); return true; } bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid) { // FetchInputs can return false either because we just haven't seen some inputs // (in which case the transaction should be stored as an orphan) // or because the transaction is malformed (in which case the transaction should // be dropped). If tx is definitely invalid, fInvalid will be set to true. fInvalid = false; if (IsCoinBase()) return true; // Coinbase transactions have no inputs to fetch. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; if (inputsRet.count(prevout.hash)) continue; // Got it already // Read txindex CTxIndex& txindex = inputsRet[prevout.hash].first; bool fFound = true; if ((fBlock || fMiner) && mapTestPool.count(prevout.hash)) { // Get txindex from current proposed changes txindex = mapTestPool.find(prevout.hash)->second; } else { // Read txindex from txdb fFound = txdb.ReadTxIndex(prevout.hash, txindex); } if (!fFound && (fBlock || fMiner)) return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); // Read txPrev CTransaction& txPrev = inputsRet[prevout.hash].second; if (!fFound || txindex.pos == CDiskTxPos(1,1,1)) { // Get prev tx from single transactions in memory { LOCK(mempool.cs); if (!mempool.exists(prevout.hash)) return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); txPrev = mempool.lookup(prevout.hash); } if (!fFound) txindex.vSpent.resize(txPrev.vout.size()); } else { // Get prev tx from disk if (!txPrev.ReadFromDisk(txindex.pos)) return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); } } // Make sure all prevout.n's are valid: for (unsigned int i = 0; i < vin.size(); i++) { const COutPoint prevout = vin[i].prevout; assert(inputsRet.count(prevout.hash) != 0); const CTxIndex& txindex = inputsRet[prevout.hash].first; const CTransaction& txPrev = inputsRet[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { // Revisit this if/when transaction replacement is implemented and allows // adding inputs: fInvalid = true; return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); } } return true; } const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const { MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash); if (mi == inputs.end()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found"); const CTransaction& txPrev = (mi->second).second; if (input.prevout.n >= txPrev.vout.size()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range"); return txPrev.vout[input.prevout.n]; } int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int64 nResult = 0; for (unsigned int i = 0; i < vin.size(); i++) { nResult += GetOutputFor(vin[i], inputs).nValue; } return nResult; } unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prevout = GetOutputFor(vin[i], inputs); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig); } return nSigOps; } bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool <API key>) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain // fMiner is true when called from the internal bitcoin miner // ... both are false when called from CTransaction::AcceptToMemoryPool if (!IsCoinBase()) { int64 nValueIn = 0; int64 nFees = 0; for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); // If prev is coinbase/coinstake, check that it's matured if (txPrev.IsCoinBase() || txPrev.IsCoinStake()) for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev) if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile) return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight); // ppcoin: check transaction timestamp if (txPrev.nTime > nTime) return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction")); // Check for negative or overflow input values nValueIn += txPrev.vout[prevout.n].nValue; if (!IsValidAmount(txPrev.vout[prevout.n].nValue) || !IsValidAmount(nValueIn)) return DoS(100, error("ConnectInputs() : txin values out of range")); } // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; // Check for conflicts (double-spend) // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!txindex.vSpent[prevout.n].IsNull()) return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str()); // Skip ECDSA signature verification when connecting blocks (fBlock=true) // before the last blockchain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (!(fBlock && (nBestHeight < Checkpoints::<API key>()))) { // Verify signature if (!VerifySignature(txPrev, *this, i, <API key>, 0)) { // only during transition phase for P2SH: do not invoke anti-DoS code for // potentially old clients relaying bad P2SH transactions if (<API key> && VerifySignature(txPrev, *this, i, false, 0)) return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str()); return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str())); } } // Mark outpoints as spent txindex.vSpent[prevout.n] = posThisTx; // Write back if (fBlock || fMiner) { mapTestPool[prevout.hash] = txindex; } } if (IsCoinStake()) { // ppcoin: coin stake tx earns reward instead of paying fee uint64 nCoinAge; if (!GetCoinAge(txdb, nCoinAge)) return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str()); int64 nStakeReward = GetValueOut() - nValueIn; if (nStakeReward > <API key>(nCoinAge, pindexBlock->pprev->nHeight) - GetMinFee() + MIN_TX_FEES) return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str())); } else { if (nValueIn < GetValueOut()) return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str())); // Tally transaction fees int64 nTxFee = nValueIn - GetValueOut(); if (nTxFee < 0) return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str())); // ppcoin: enforce transaction fees for every block if (nTxFee < GetMinFee()) return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false; nFees += nTxFee; if (!IsValidAmount(nFees)) return DoS(100, error("ConnectInputs() : nFees out of range")); } } return true; } bool CTransaction::ClientConnectInputs() { if (IsCoinBase()) return false; // Take over previous transactions' spent pointers { LOCK(mempool.cs); int64 nValueIn = 0; for (unsigned int i = 0; i < vin.size(); i++) { // Get prev tx from single transactions in memory COutPoint prevout = vin[i].prevout; if (!mempool.exists(prevout.hash)) return false; CTransaction& txPrev = mempool.lookup(prevout.hash); if (prevout.n >= txPrev.vout.size()) return false; // Verify signature if (!VerifySignature(txPrev, *this, i, true, 0)) return error("ConnectInputs() : VerifySignature failed"); // this is redundant with the mempool.mapNextTx stuff, // not sure which I want to get rid of // this has to go away now that posNext is gone // // Check for conflicts // if (!txPrev.vout[prevout.n].posNext.IsNull()) // return error("ConnectInputs() : prev tx already used"); // // Flag outpoints as used // txPrev.vout[prevout.n].posNext = posThisTx; nValueIn += txPrev.vout[prevout.n].nValue; if (!IsValidAmount(txPrev.vout[prevout.n].nValue) || !IsValidAmount(nValueIn)) { return error("ClientConnectInputs() : txin values out of range"); } } if (GetValueOut() > nValueIn) { return false; } } return true; } bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Disconnect in reverse order for (int i = vtx.size()-1; i >= 0; i if (!vtx[i].DisconnectInputs(txdb)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = 0; if (!txdb.WriteBlockIndex(blockindexPrev)) return error("DisconnectBlock() : WriteBlockIndex failed"); } // ppcoin: clean up wallet after disconnecting coinstake BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, false, false); return true; } bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Check it again in case a previous version let a bad block in if (!CheckBlock()) return false; // Check coinbase reward if (IsProofOfWork() && vtx[0].GetValueOut() > (IsProofOfWork() ? (<API key>(pindex->pprev ? pindex->pprev->nHeight : -1) - vtx[0].GetMinFee() + MIN_TX_FEES) : 0)) return DoS(50, error("CheckBlock() : coinbase reward exceeded %s > %s", FormatMoney(vtx[0].GetValueOut()).c_str(), FormatMoney(IsProofOfWork() ? <API key>(pindex->pprev ? pindex->pprev->nHeight : -1) : 0).c_str())); // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction id's entirely. BOOST_FOREACH(CTransaction& tx, vtx) { CTxIndex txindexOld; if (txdb.ReadTxIndex(tx.GetHash(), txindexOld)) { BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent) if (pos.IsNull()) return false; } } // BIP16 didn't become active until Apr 1 2012 int64 nBIP16SwitchTime = 1333238400; bool <API key> = (pindex->nTime >= nBIP16SwitchTime); / issue here: it doesn't know the version unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * <API key>(0)) + <API key>(vtx.size()); map<uint256, CTxIndex> mapQueuedChanges; int64 nFees = 0; int64 nValueIn = 0; int64 nValueOut = 0; unsigned int nSigOps = 0; BOOST_FOREACH(CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos); nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); MapPrevTx mapInputs; if (tx.IsCoinBase()) nValueOut += tx.GetValueOut(); else { bool fInvalid; if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid)) return false; if (<API key>) { // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an <API key> block. nSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); } int64 nTxValueIn = tx.GetValueIn(mapInputs); int64 nTxValueOut = tx.GetValueOut(); nValueIn += nTxValueIn; nValueOut += nTxValueOut; if (!tx.IsCoinStake()) nFees += nTxValueIn - nTxValueOut; if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, <API key>)) return false; } mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size()); } // ppcoin: track money supply and mint amount info pindex->nMint = nValueOut - nValueIn + nFees; pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn; if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex))) return error("Connect() : WriteBlockIndex for pindex failed"); // Write queued txindex changes for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi) { if (!txdb.UpdateTxIndex((*mi).first, (*mi).second)) return error("ConnectBlock() : UpdateTxIndex failed"); } // ppcoin: fees are not collected by miners as in bitcoin // ppcoin: fees are destroyed to compensate the entire network if (fDebug && GetBoolArg("-printcreation")) printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees); // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = pindex->GetBlockHash(); if (!txdb.WriteBlockIndex(blockindexPrev)) return error("ConnectBlock() : WriteBlockIndex for blockindexPrev failed"); } // Watch for transactions paying to me BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, true); return true; } bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew) { printf("REORGANIZE\n"); // Find the fork CBlockIndex* pfork = pindexBest; CBlockIndex* plonger = pindexNew; while (pfork != plonger) { while (plonger->nHeight > pfork->nHeight) if (!(plonger = plonger->pprev)) return error("Reorganize() : plonger->pprev is null"); if (pfork == plonger) break; if (!(pfork = pfork->pprev)) return error("Reorganize() : pfork->pprev is null"); } // List of what to disconnect vector<CBlockIndex*> vDisconnect; for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev) vDisconnect.push_back(pindex); // List of what to connect vector<CBlockIndex*> vConnect; for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) vConnect.push_back(pindex); reverse(vConnect.begin(), vConnect.end()); printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str()); printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str()); // Disconnect shorter branch vector<CTransaction> vResurrect; BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for disconnect failed"); if (!block.DisconnectBlock(txdb, pindex)) return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); // Queue memory transactions to resurrect BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!(tx.IsCoinBase() || tx.IsCoinStake())) vResurrect.push_back(tx); } // Connect longer branch vector<CTransaction> vDelete; for (unsigned int i = 0; i < vConnect.size(); i++) { CBlockIndex* pindex = vConnect[i]; CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for connect failed"); if (!block.ConnectBlock(txdb, pindex)) { // Invalid block txdb.TxnAbort(); return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); } // Queue memory transactions to delete BOOST_FOREACH(const CTransaction& tx, block.vtx) vDelete.push_back(tx); } if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash())) return error("Reorganize() : WriteHashBestChain failed"); // Make sure it's successfully written to disk before changing memory structure if (!txdb.TxnCommit()) return error("Reorganize() : TxnCommit failed"); // Disconnect shorter branch BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) if (pindex->pprev) pindex->pprev->pnext = NULL; // Connect longer branch BOOST_FOREACH(CBlockIndex* pindex, vConnect) if (pindex->pprev) pindex->pprev->pnext = pindex; // Resurrect memory transactions that were in the disconnected branch BOOST_FOREACH(CTransaction& tx, vResurrect) tx.AcceptToMemoryPool(txdb, false); // Delete redundant memory transactions that are in the connected branch BOOST_FOREACH(CTransaction& tx, vDelete) mempool.remove(tx); printf("REORGANIZE: done\n"); return true; } // Called from inside SetBestChain: attaches a block to the new best chain being built bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew) { uint256 hash = GetHash(); // Adding to current best branch if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return false; } if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); // Add to current best branch pindexNew->pprev->pnext = pindexNew; // Delete redundant memory transactions BOOST_FOREACH(CTransaction& tx, vtx) mempool.remove(tx); return true; } bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew) { uint256 hash = GetHash(); if (!txdb.TxnBegin()) return error("SetBestChain() : TxnBegin failed"); if (pindexGenesisBlock == NULL && hash == GENESIS_HASH) { txdb.WriteHashBestChain(hash); if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); pindexGenesisBlock = pindexNew; } else if (hashPrevBlock == hashBestChain) { if (!SetBestChainInner(txdb, pindexNew)) return error("SetBestChain() : SetBestChainInner failed"); } else { // the first block in the new chain that will cause it to become the new best chain CBlockIndex *pindexIntermediate = pindexNew; // list of blocks that need to be connected afterwards std::vector<CBlockIndex*> vpindexSecondary; // Reorganize is costly in terms of db load, as it works in a single db transaction. // Try to limit how much needs to be done inside while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust) { vpindexSecondary.push_back(pindexIntermediate); pindexIntermediate = pindexIntermediate->pprev; } if (!vpindexSecondary.empty()) printf("Postponing %i reconnects\n", vpindexSecondary.size()); // Switch to new best branch if (!Reorganize(txdb, pindexIntermediate)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return error("SetBestChain() : Reorganize failed"); } // Connect futher blocks <API key>(CBlockIndex *pindex, vpindexSecondary) { CBlock block; if (!block.ReadFromDisk(pindex)) { printf("SetBestChain() : ReadFromDisk failed\n"); break; } if (!txdb.TxnBegin()) { printf("SetBestChain() : TxnBegin 2 failed\n"); break; } // errors now are not fatal, we still did a reorganisation to a new chain in a valid way if (!block.SetBestChainInner(txdb, pindex)) break; } } // Update best block in wallet (so we can detect restored wallets) bool fIsInitialDownload = <API key>(); if (!fIsInitialDownload) { const CBlockLocator locator(pindexNew); ::SetBestChain(locator); } // New best block hashBestChain = hash; pindexBest = pindexNew; nBestHeight = pindexBest->nHeight; bnBestChainTrust = pindexNew->bnChainTrust; nTimeBestReceived = GetTime(); <API key>++; printf("SetBestChain: new best=%s height=%d trust=%s moneysupply=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(), FormatMoney(pindexBest->nMoneySupply).c_str()); std::string strCmd = GetArg("-blocknotify", ""); if (!fIsInitialDownload && !strCmd.empty()) { boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } return true; } // ppcoin: total coin age spent in transaction, in the unit of coin-days. // Only those coins meeting minimum age requirement counts. As those // transactions not in main chain are not currently indexed so we // might not find out about their coin age. Older transactions are // guaranteed to be in main chain by sync-checkpoint. This rule is // introduced to help nodes establish a consistent view of the coin // age (trust score) of competing branches. bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const { CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds nCoinAge = 0; if (IsCoinBase()) return true; BOOST_FOREACH(const CTxIn& txin, vin) { // First try finding the previous transaction in database CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) continue; // previous transaction not in main chain if (nTime < txPrev.nTime) return false; // Transaction timestamp violation // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return false; // unable to read block of previous transaction if (block.GetBlockTime() + STAKE_MIN_AGE > nTime) continue; // only count coins meeting min age requirement int64 nValueIn = txPrev.vout[txin.prevout.n].nValue; bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT; if (fDebug && GetBoolArg("-printcoinage")) { printf("coin age nValueIn=%-12"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str()); } } CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60); if (fDebug && GetBoolArg("-printcoinage")) printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str()); nCoinAge = bnCoinDay.getuint64(); return true; } // ppcoin: total coin age spent in block, in the unit of coin-days. bool CBlock::GetCoinAge(uint64& nCoinAge) const { nCoinAge = 0; CTxDB txdb("r"); BOOST_FOREACH(const CTransaction& tx, vtx) { uint64 nTxCoinAge; if (tx.GetCoinAge(txdb, nTxCoinAge)) nCoinAge += nTxCoinAge; else return false; } if (nCoinAge == 0) // block coin age minimum 1 coin-day nCoinAge = 1; if (fDebug && GetBoolArg("-printcoinage")) printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge); return true; } bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos) { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str()); // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this); if (!pindexNew) return error("AddToBlockIndex() : new CBlockIndex failed"); pindexNew->phashBlock = &hash; map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; } // ppcoin: compute chain trust score pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust(); // ppcoin: compute stake entropy bit for stake modifier if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit())) return error("AddToBlockIndex() : SetStakeEntropyBit() failed"); // ppcoin: record proof-of-stake hash value if (pindexNew->IsProofOfStake()) { if (!mapProofOfStake.count(hash)) return error("AddToBlockIndex() : hashProofOfStake not found in map"); pindexNew->hashProofOfStake = mapProofOfStake[hash]; } // ppcoin: compute stake modifier uint64 nStakeModifier = 0; bool <API key> = false; if (!<API key>(pindexNew, nStakeModifier, <API key>)) return error("AddToBlockIndex() : <API key>() failed"); pindexNew->SetStakeModifier(nStakeModifier, <API key>); pindexNew-><API key> = <API key>(pindexNew); if (!<API key>(pindexNew->nHeight, pindexNew-><API key>)) return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x", checksum=0x%08x", pindexNew->nHeight, nStakeModifier, pindexNew-><API key>); // Add to mapBlockIndex map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; if (pindexNew->IsProofOfStake()) setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime)); pindexNew->phashBlock = &((*mi).first); // Write to disk block index CTxDB txdb; if (!txdb.TxnBegin()) return false; txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew)); if (!txdb.TxnCommit()) return false; // New best if (pindexNew->bnChainTrust > bnBestChainTrust) if (!SetBestChain(txdb, pindexNew)) return false; txdb.Close(); if (pindexNew == pindexBest) { // Notify UI to display prev block's coinbase if it was ours static uint256 <API key>; UpdatedTransaction(<API key>); <API key> = vtx[0].GetHash(); } MainFrameRepaint(); return true; } bool CBlock::CheckBlock() const { // These are checks that are independent of context // that can be verified before saving an orphan block. // Size limits if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CheckBlock() : size limits failed")); // Check proof of work matches claimed amount if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits)) return DoS(50, error("CheckBlock() : proof of work failed")); // Check timestamp if (GetBlockTime() > GetAdjustedTime() + MAX_CLOCK_DRIFT) return error("CheckBlock() : block timestamp too far in the future"); // First transaction must be coinbase, the rest must not be if (vtx.empty() || !vtx[0].IsCoinBase()) return DoS(100, error("CheckBlock() : first tx is not coinbase")); for (unsigned int i = 1; i < vtx.size(); i++) if (vtx[i].IsCoinBase()) return DoS(100, error("CheckBlock() : more than one coinbase")); // ppcoin: only the second transaction can be the optional coinstake for (size_t i = 2; i < vtx.size(); i++) if (vtx[i].IsCoinStake()) return DoS(100, error("CheckBlock() : coinstake in wrong position")); // ppcoin: coinbase output should be empty if proof-of-stake block if (IsProofOfStake() && (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())) return error("CheckBlock() : coinbase output not empty for proof-of-stake block"); // Check coinbase timestamp if (GetBlockTime() > (int64)vtx[0].nTime + MAX_CLOCK_DRIFT) return DoS(50, error("CheckBlock() : coinbase timestamp is too early (block: %d, vtx[0]: %d)", GetBlockTime(), vtx[0].nTime)); // Check coinstake timestamp if (IsProofOfStake() && !<API key>(GetBlockTime(), (int64)vtx[1].nTime)) return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%u nTimeTx=%u", GetBlockTime(), vtx[1].nTime)); // Check coinbase reward // Note: We're not doing the reward check here, because we need to know the block height. // Check inside ConnectBlock instead. // Check transactions BOOST_FOREACH(const CTransaction& tx, vtx) { if (!tx.CheckTransaction()) return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed")); // ppcoin: check transaction timestamp if (GetBlockTime() < (int64)tx.nTime) return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp")); } // Check for duplicate txids. This is caught by ConnectInputs(), // but catching it earlier avoids a potential DoS attack: set<uint256> uniqueTx; BOOST_FOREACH(const CTransaction& tx, vtx) { uniqueTx.insert(tx.GetHash()); } if (uniqueTx.size() != vtx.size()) return DoS(100, error("CheckBlock() : duplicate transaction")); unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); } if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); // Check merkleroot if (hashMerkleRoot != BuildMerkleTree()) return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); // ppcoin: check block signature if (!CheckBlockSignature()) return DoS(100, error("CheckBlock() : bad block signature")); return true; } bool CBlock::AcceptBlock() { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AcceptBlock() : block already in mapBlockIndex"); // Get prev block index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); if (mi == mapBlockIndex.end()) return DoS(10, error("AcceptBlock() : prev block not found")); CBlockIndex* pindexPrev = (*mi).second; int nHeight = pindexPrev->nHeight+1; // Check proof-of-work or proof-of-stake if (nBits != <API key>(pindexPrev, IsProofOfStake())) return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake")); // Check timestamp against prev if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + MAX_CLOCK_DRIFT < pindexPrev->GetBlockTime()) return error("AcceptBlock() : block's timestamp is too early"); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.IsFinal(nHeight, GetBlockTime())) return DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a hardened checkpoint if (!Checkpoints::CheckHardened(nHeight, hash)) return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight)); // ppcoin: check that the block satisfies synchronized checkpoint if (!Checkpoints::CheckSync(hash, pindexPrev)) return error("AcceptBlock() : rejected by synchronized checkpoint"); // Write block to history file if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION))) return error("AcceptBlock() : out of disk space"); unsigned int nFile = -1; unsigned int nBlockPos = 0; if (!WriteToDisk(nFile, nBlockPos)) return error("AcceptBlock() : WriteToDisk failed"); if (!AddToBlockIndex(nFile, nBlockPos)) return error("AcceptBlock() : AddToBlockIndex failed"); // Relay inventory, but don't relay old inventory during initial block download int nBlockEstimate = Checkpoints::<API key>(); if (hashBestChain == hash) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); } // ppcoin: check pending sync-checkpoint Checkpoints::<API key>(); return true; } bool ProcessBlock(CNode* pfrom, CBlock* pblock) { // Check for duplicate uint256 hash = pblock->GetHash(); if (mapBlockIndex.count(hash)) return error("ProcessBlock() : already have block %d %s", mapBlockIndex.at(hash)->nHeight, hash.ToString().substr(0,20).c_str()); if (mapOrphanBlocks.count(hash)) return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str()); // ppcoin: check proof-of-stake if (pblock->IsProofOfStake()) { std::pair<COutPoint, unsigned int> proofOfStake = pblock->GetProofOfStake(); if (pindexBest->IsProofOfStake() && proofOfStake.first == pindexBest->prevoutStake) { if (!pblock->CheckBlockSignature()) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : invalid signature in a duplicate Proof-of-Stake kernel"); } RelayBlock(*pblock, hash); <API key>(proofOfStake, hash); CTxDB txdb; CBlock bestPrevBlock; bestPrevBlock.ReadFromDisk(pindexBest->pprev); if (!bestPrevBlock.SetBestChain(txdb, pindexBest->pprev)) return error("ProcessBlock() : Proof-of-stake rollback failed"); return error("ProcessBlock() : duplicate Proof-of-Stake kernel (%s, %d) in block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str()); } else if (setStakeSeen.count(proofOfStake) && !<API key>.count(hash) && !Checkpoints::<API key>(hash)) { return error("ProcessBlock() : duplicate Proof-of-Stake kernel (%s, %d) in block %s", proofOfStake.first.ToString().c_str(), proofOfStake.second, hash.ToString().c_str()); } } // Preliminary checks if (!pblock->CheckBlock()) return error("ProcessBlock() : CheckBlock FAILED"); CBlockIndex* pcheckpoint = Checkpoints::<API key>(); if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::<API key>(hash)) { // Extra checks to prevent "fill up memory by spamming with bogus blocks" int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; CBigNum bnNewBlock; bnNewBlock.SetCompact(pblock->nBits); CBigNum bnRequired; bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime)); if (bnNewBlock > bnRequired) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work"); } } // ppcoin: ask for pending sync-checkpoint if any if (!<API key>()) Checkpoints::<API key>(pfrom); // We remove the previous block from the blacklisted kernels, if needed <API key>(pblock->hashPrevBlock); // Find the previous block std::map<uint256, CBlockIndex*>::iterator parentBlockIt = mapBlockIndex.find(pblock->hashPrevBlock); // If we don't already have it, shunt off the block to the holding area until we get its parent if (parentBlockIt == mapBlockIndex.end()) { printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str()); CBlock* pblock2 = new CBlock(*pblock); // ppcoin: check proof-of-stake if (pblock2->IsProofOfStake()) setStakeSeenOrphan.insert(pblock2->GetProofOfStake()); mapOrphanBlocks.insert(make_pair(hash, pblock2)); <API key>.insert(make_pair(pblock2->hashPrevBlock, pblock2)); // Ask this guy to fill in what we're missing if (pfrom) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2)); // ppcoin: getblocks may not obtain the ancestor block rejected // earlier by duplicate-stake check so we ask for it again directly if (!<API key>()) { pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2))); } } return true; } // ppcoin: verify hash target and signature of coinstake tx if (pblock->IsProofOfStake()) { uint256 hashProofOfStake = 0; const CBlockIndex * pindexPrev = parentBlockIt->second; if (!CheckProofOfStake(pindexPrev, pblock->vtx[1], pblock->nBits, hashProofOfStake)) { printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str()); return false; // do not error here as we expect this during initial block download } if (!mapProofOfStake.count(hash)) // add to mapProofOfStake { mapProofOfStake.insert(make_pair(hash, hashProofOfStake)); } } // Store to disk if (!pblock->AcceptBlock()) return error("ProcessBlock() : AcceptBlock FAILED"); // Recursively process any orphan blocks that depended on this one vector<uint256> vWorkQueue; vWorkQueue.push_back(hash); for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; CBlockIndex* pindexPrev = mapBlockIndex.at(hashPrev); for (multimap<uint256, CBlock*>::iterator mi = <API key>.lower_bound(hashPrev); mi != <API key>.upper_bound(hashPrev); ++mi) { bool validated = true; CBlock* pblockOrphan = (*mi).second; uint256 orphanHash = pblockOrphan->GetHash(); if (pblockOrphan->IsProofOfStake()) { uint256 hashProofOfStake = 0; if (CheckProofOfStake(pindexPrev, pblockOrphan->vtx[1], pblockOrphan->nBits, hashProofOfStake)) { if (!mapProofOfStake.count(orphanHash)) mapProofOfStake.insert(make_pair(orphanHash, hashProofOfStake)); validated = true; } else { validated = false; } } if (validated && pblockOrphan->AcceptBlock()) vWorkQueue.push_back(orphanHash); mapOrphanBlocks.erase(orphanHash); setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake()); delete pblockOrphan; } <API key>.erase(hashPrev); } printf("ProcessBlock: ACCEPTED\n"); // ppcoin: if responsible for sync-checkpoint send it if (pfrom && !<API key>.empty()) Checkpoints::SendSyncCheckpoint(Checkpoints::<API key>()); return true; } // ppcoin: sign block bool CBlock::SignBlock(const CKeyStore& keystore) { vector<valtype> vSolutions; txnouttype whichType; const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { // Sign const valtype& vchPubKey = vSolutions[0]; CKey key; if (!keystore.GetKey(Hash160(vchPubKey), key)) return false; if (key.GetPubKey() != vchPubKey) return false; return key.Sign(GetHash(), vchBlockSig); } else if (whichType == TX_SCRIPTHASH) { CScript subscript; if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript)) return false; if (!Solver(subscript, whichType, vSolutions)) return false; if (whichType != TX_COLDMINTING) return false; CKey key; if (!keystore.GetKey(uint160(vSolutions[0]), key)) return false; return key.Sign(GetHash(), vchBlockSig); } return false; } // ppcoin: check block signature bool CBlock::CheckBlockSignature() const { if (GetHash() == GENESIS_HASH) return vchBlockSig.empty(); vector<valtype> vSolutions; txnouttype whichType; const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { const valtype& vchPubKey = vSolutions[0]; CKey key; if (!key.SetPubKey(vchPubKey)) return false; if (vchBlockSig.empty()) return false; return key.Verify(GetHash(), vchBlockSig); } else if (whichType == TX_SCRIPTHASH) { // Output is a pay-to-script-hash // Only allowed with cold minting if (!IsProofOfStake()) return false; // CoinStake scriptSig should contain 3 pushes: the signature, the pubkey and the cold minting script CScript scriptSig = vtx[1].vin[0].scriptSig; if (!scriptSig.IsPushOnly()) return false; vector<vector<unsigned char> > stack; if (!EvalScript(stack, scriptSig, CTransaction(), 0, 0)) return false; if (stack.size() != 3) return false; // Verify the script is a cold minting script const valtype& scriptSerialized = stack.back(); CScript script(scriptSerialized.begin(), scriptSerialized.end()); if (!Solver(script, whichType, vSolutions)) return false; if (whichType != TX_COLDMINTING) return false; // Verify the scriptSig pubkey matches the minting key valtype& vchPubKey = stack[1]; if (Hash160(vchPubKey) != uint160(vSolutions[0])) return false; // Verify the block signature with the minting key CKey key; if (!key.SetPubKey(vchPubKey)) return false; if (vchBlockSig.empty()) return false; return key.Verify(GetHash(), vchBlockSig); } return false; } // ppcoin: entropy bit for stake modifier if chosen by modifier unsigned int CBlock::GetStakeEntropyBit() const { unsigned int nEntropyBit = 0; nEntropyBit = ((GetHash().Get64()) & 1llu); // last bit of block hash if (fDebug && GetBoolArg("-printstakemodifier")) printf("GetStakeEntropyBit(v0.4+): nTime=%u hashBlock=%s entropybit=%d\n", nTime, GetHash().ToString().c_str(), nEntropyBit); return nEntropyBit; } bool CheckDiskSpace(uint64 nAdditionalBytes) { uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available; // Check for 15MB because database could create another 10MB log file at any time if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes) { fShutdown = true; string strMessage = _("Warning: Disk space is low"); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); <API key>(strMessage, COIN_NAME, wxOK | wxICON_EXCLAMATION | wxMODAL); StartShutdown(); return false; } return true; } FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode) { if (nFile == static_cast<unsigned int>(-1)) return NULL; FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode); if (!file) return NULL; if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w')) { if (fseek(file, nBlockPos, SEEK_SET) != 0) { fclose(file); return NULL; } } return file; } static unsigned int nCurrentBlockFile = 1; FILE* AppendBlockFile(unsigned int& nFileRet) { nFileRet = 0; INFINITE_LOOP { FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab"); if (!file) return NULL; if (fseek(file, 0, SEEK_END) != 0) return NULL; // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB if (ftell(file) < 0x7F000000 - MAX_SIZE) { nFileRet = nCurrentBlockFile; return file; } fclose(file); nCurrentBlockFile++; } } bool LoadBlockIndex(bool fAllowNew) { // Load block index CTxDB txdb("cr"); if (!txdb.LoadBlockIndex()) return false; txdb.Close(); // Init with genesis block if (mapBlockIndex.empty()) { if (!fAllowNew) return false; // Genesis Block: // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) // CTxOut(nValue=50.00000000, scriptPubKey=<API key>) // vMerkleTree: 4a5e1e const char* pszTimestamp = GENESIS_IDENT; CTransaction txNew; txNew.nTime = GENESIS_TX_TIME; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].SetEmpty(); CBlock block; block.vtx.push_back(txNew); block.hashPrevBlock = 0; block.hashMerkleRoot = block.BuildMerkleTree(); block.nVersion = <API key>; block.nTime = GENESIS_BLOCK_TIME; block.nBits = POW_INITIAL_TARGET.GetCompact(); block.nNonce = GENESIS_BLOCK_NONCE; printf("target : %s\n", POW_INITIAL_TARGET.getuint256().ToString().c_str()); printf("nBits : %08X\n", block.nBits); printf("expected genesis hash : %s\n", GENESIS_HASH.ToString().c_str()); printf("true genesis hash : %s\n", block.GetHash().ToString().c_str()); // If genesis block hash does not match, then generate new genesis hash. if (block.GetHash() != GENESIS_HASH || !CheckProofOfWork(block.GetHash(), block.nBits, false)) { printf("\n"); printf("FATAL ERROR: The genesis block is invalid.\n"); printf("Please notify the coins maintainers at " COIN_BUGTRACKER ".\n"); printf("If you're working on an Altcoin, we suggest you to use the following parameters as new genesis (wait a bit):\n"); // This will figure out a valid hash and Nonce if you're // creating a different genesis block: while (!CheckProofOfWork(block.GetHash(), block.nBits, false)) { if ((block.nNonce & 0xFFF) == 0) printf("Trying nonce %08X and above...\n", block.nNonce); ++block.nNonce; if (block.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++block.nTime; } } printf("A matching block has been found, with the following parameters:\n"); printf(" - GENESIS_MERKLE_HASH : %s\n", block.hashMerkleRoot.ToString().c_str()); printf(" - GENESIS_HASH : %s\n", block.GetHash().ToString().c_str()); printf(" - GENESIS_TIME : %u\n", block.nTime); printf(" - GENESIS_NONCE : %u\n", block.nNonce); std::exit( 1 ); } / debug print assert(block.hashMerkleRoot == GENESIS_MERKLE_HASH); assert(block.GetHash() == GENESIS_HASH); assert(block.CheckBlock()); // Start new block file unsigned int nFile; unsigned int nBlockPos; if (!block.WriteToDisk(nFile, nBlockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); if (!block.AddToBlockIndex(nFile, nBlockPos)) return error("LoadBlockIndex() : genesis block not accepted"); // ppcoin: initialize synchronized checkpoint if (!Checkpoints::WriteSyncCheckpoint(GENESIS_HASH)) { return error("LoadBlockIndex() : failed to init sync checkpoint"); } } // ppcoin: if checkpoint master key changed must reset sync-checkpoint { CTxDB txdb; string strPubKey = ""; if (!txdb.<API key>(strPubKey) || strPubKey != <API key>) { // write checkpoint master key to db txdb.TxnBegin(); if (!txdb.<API key>(<API key>)) return error("LoadBlockIndex() : failed to write new checkpoint master key to db"); if (!txdb.TxnCommit()) return error("LoadBlockIndex() : failed to commit new checkpoint master key to db"); if (!Checkpoints::ResetSyncCheckpoint()) return error("LoadBlockIndex() : failed to reset sync-checkpoint"); } txdb.Close(); } return true; } void PrintBlockTree() { // precompute tree structure map<CBlockIndex*, vector<CBlockIndex*> > mapNext; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { CBlockIndex* pindex = (*mi).second; mapNext[pindex->pprev].push_back(pindex); // test //while (rand() % 3 == 0) // mapNext[pindex->pprev].push_back(pindex); } vector<pair<int, CBlockIndex*> > vStack; vStack.push_back(make_pair(0, pindexGenesisBlock)); int nPrevCol = 0; while (!vStack.empty()) { int nCol = vStack.back().first; CBlockIndex* pindex = vStack.back().second; vStack.pop_back(); // print split or gap if (nCol > nPrevCol) { for (int i = 0; i < nCol-1; i++) printf("| "); printf("|\\\n"); } else if (nCol < nPrevCol) { for (int i = 0; i < nCol; i++) printf("| "); printf("|\n"); } nPrevCol = nCol; // print columns for (int i = 0; i < nCol; i++) printf("| "); // print item CBlock block; block.ReadFromDisk(pindex); printf("%d (%u,%u) %s %08lx %s mint %7s tx %d", pindex->nHeight, pindex->nFile, pindex->nBlockPos, block.GetHash().ToString().c_str(), block.nBits, DateTimeStrFormat(block.GetBlockTime()).c_str(), FormatMoney(pindex->nMint).c_str(), block.vtx.size()); PrintWallets(block); // put the main timechain first vector<CBlockIndex*>& vNext = mapNext[pindex]; for (unsigned int i = 0; i < vNext.size(); i++) { if (vNext[i]->pnext) { swap(vNext[0], vNext[i]); break; } } // iterate children for (unsigned int i = 0; i < vNext.size(); i++) vStack.push_back(make_pair(nCol+i, vNext[i])); } } // CAlert map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static string strMintMessage = _("Warning: Minting suspended due to locked wallet."); static string strMintWarning; string GetWarnings(string strFor) { int nPriority = 0; string strStatusBar; string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // ppcoin: wallet lock warning for minting if (strMintWarning != "") { nPriority = 0; strStatusBar = strMintWarning; } // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // ppcoin: if detected invalid checkpoint enter safe mode if (Checkpoints::<API key> != 0) { nPriority = 3000; strStatusBar = strRPC = "Warning: An invalid checkpoint has been found! Displayed transactions may not be correct! You may need to upgrade, and/or notify developers of the issue."; } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; if (nPriority > 1000) { strRPC = strStatusBar; // ppcoin: safe mode for high alert } } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } bool CAlert::ProcessAlert() { if (!CheckSignature()) return false; if (!IsInEffect()) return false; { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); MainFrameRepaint(); return true; } // Messages bool static AlreadyHave(CTxDB& txdb, const CInv& inv) { switch (inv.type) { case MSG_TX: { bool txInMap = false; { LOCK(mempool.cs); txInMap = (mempool.exists(inv.hash)); } return txInMap || <API key>.count(inv.hash) || txdb.ContainsTx(inv.hash); } case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); } // Don't know what it is, just say we already got one return true; } bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) { static map<CService, CPubKey> mapReuseKey; RandAddSeedPerfmon(); if (fDebug) { printf("%s ", DateTimeStrFormat(GetTime()).c_str()); printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size()); } if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { printf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->Misbehaving(1); return false; } int64 nTime; CAddress addrMe; CAddress addrFrom; uint64 nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < MIN_PROTO_VERSION) { // Since February 20, 2012, the protocol is initiated at version 209, // and earlier versions are no longer supported printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) vRecv >> pfrom->strSubVer; if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; return true; } // ppcoin: record my external IP reported by peer if (addrFrom.IsRoutable() && addrMe.IsRoutable()) addrSeenByPeer = addrMe; // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); AddTimeData(pfrom->addr, nTime); // Change version pfrom->PushMessage("verack"); pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() && !<API key>()) { CAddress addr(addrLocalHost); addr.nTime = GetAdjustedTime(); pfrom->PushAddress(addr); } // Get recent addresses if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Ask the first connected node for block updates static int nAskedForBlocks = 0; if (!pfrom->fClient && (pfrom->nVersion < <API key> || pfrom->nVersion >= NOBLKS_VERSION_END)) { nAskedForBlocks++; pfrom->PushGetBlocks(pindexBest, uint256(0)); } // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); } // ppcoin: relay sync-checkpoint { LOCK(Checkpoints::<API key>); if (!Checkpoints::checkpointMessage.IsNull()) Checkpoints::checkpointMessage.RelayTo(pfrom); } pfrom-><API key> = true; printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight); cPeerBlockCounts.input(pfrom->nStartingHeight); // ppcoin: ask for pending sync-checkpoint if any if (!<API key>()) Checkpoints::<API key>(pfrom); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else pfrom->Misbehaving(1); return false; } else if (strCommand == "verack") { pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); } else if (strCommand == "addr") { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { pfrom->Misbehaving(20); return error("message addr size() = %d", vAddr.size()); } // Store the new addresses int64 nNow = GetAdjustedTime(); int64 nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { if (fShutdown) return true; // ignore IPv6 for now, since it isn't implemented anyway if (!addr.IsIPv4()) continue; if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); int64 hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = 2; for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } } addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; } else if (strCommand == "inv") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message inv size() = %d", vInv.size()); } // find last block in inv vector unsigned int nLastBlock = (unsigned int)(-1); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) { nLastBlock = vInv.size() - 1 - nInv; break; } } CTxDB txdb("r"); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; if (fShutdown) return true; pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(txdb, inv); if (fDebug) printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); if (!fAlreadyHave) { pfrom->AskFor(inv); } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); } else if (nInv == nLastBlock) { // In case we are on a very long side-chain, it is possible that we already have // the last block in an inv bundle sent in response to getblocks. Try to detect // this situation and push another getblocks to continue. std::vector<CInv> vGetData(1,inv); pfrom->PushGetBlocks(mapBlockIndex.at(inv.hash), uint256(0)); if (fDebug) { printf("force request: %s\n", inv.ToString().c_str()); } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getdata") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message getdata size() = %d", vInv.size()); } BOOST_FOREACH(const CInv& inv, vInv) { if (fShutdown) return true; printf("received getdata for: %s\n", inv.ToString().c_str()); if (inv.type == MSG_BLOCK) { // Send block from disk map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { CBlock block; block.ReadFromDisk((*mi).second); pfrom->PushMessage("block", block); // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. // ppcoin: send latest proof-of-work block to allow the // download node to accept as orphan (proof-of-stake // block might be rejected by stake connection check) vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash())); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory { LOCK(cs_mapRelay); map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) pfrom->PushMessage(inv.GetCommand(), (*mi).second); } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; // Find the last block the caller has in the main chain CBlockIndex* pindex = locator.GetBlockIndex(); // Send the rest of the chain if (pindex) pindex = pindex->pnext; int nLimit = 500 + locator.GetDistanceBack(); unsigned int nBytes = 0; printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit); for (; pindex; pindex = pindex->pnext) { if (pindex->GetBlockHash() == hashStop) { printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes); // ppcoin: tell downloading node about the latest block if it's // without risk being rejected due to stake connection check if (hashStop != hashBestChain && pindex->GetBlockTime() + STAKE_MIN_AGE > pindexBest->GetBlockTime()) pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain)); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); CBlock block; block.ReadFromDisk(pindex, true); nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION); if (--nLimit <= 0 || nBytes >= SendBufferSize()/2) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = locator.GetBlockIndex(); if (pindex) pindex = pindex->pnext; } vector<CBlock> vHeaders; int nLimit = 2000; printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str()); for (; pindex; pindex = pindex->pnext) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx") { vector<uint256> vWorkQueue; vector<uint256> vEraseQueue; CDataStream vMsg(vRecv); CTxDB txdb("r"); CTransaction tx; vRecv >> tx; CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); bool fMissingInputs = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs)) { SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); // Recursively process any orphan transactions that depended on this one for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (map<uint256, CDataStream*>::iterator mi = <API key>[hashPrev].begin(); mi != <API key>[hashPrev].end(); ++mi) { const CDataStream& vMsg = *((*mi).second); CTransaction tx; CDataStream(vMsg) >> tx; CInv inv(MSG_TX, tx.GetHash()); bool fMissingInputs2 = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2)) { printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); } else if (!fMissingInputs2) { // invalid orphan vEraseQueue.push_back(inv.hash); printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); } } } BOOST_FOREACH(uint256 hash, vEraseQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { AddOrphanTx(vMsg); // DoS prevention: do not allow <API key> to grow unbounded unsigned int nEvicted = LimitOrphanTxSize(MAX_BLOCK_ORPHAN_TX); if (nEvicted > 0) printf("mapOrphan overflow, removed %u tx\n", nEvicted); } if (tx.nDoS) pfrom->Misbehaving(tx.nDoS); } else if (strCommand == "block") { CBlock block; vRecv >> block; printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str()); // block.print(); CInv inv(MSG_BLOCK, block.GetHash()); pfrom->AddInventoryKnown(inv); if (ProcessBlock(pfrom, &block)) mapAlreadyAskedFor.erase(inv); if (block.nDoS) pfrom->Misbehaving(block.nDoS); } else if (strCommand == "getaddr") { pfrom->vAddrToSend.clear(); vector<CAddress> vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) pfrom->PushAddress(addr); } else if (strCommand == "checkorder") { uint256 hashReply; vRecv >> hashReply; if (!GetBoolArg("-allowreceivebyip")) { pfrom->PushMessage("reply", hashReply, (int)2, string("")); return true; } CWalletTx order; vRecv >> order; we have a chance to check the order here // Keep giving the same key to the same ip until they use it if (!mapReuseKey.count(pfrom->addr)) pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true); // Send back approval of order and pubkey to use CScript scriptPubKey; scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG; pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey); } else if (strCommand == "reply") { uint256 hashReply; vRecv >> hashReply; CRequestTracker tracker; { LOCK(pfrom->cs_mapRequests); map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply); if (mi != pfrom->mapRequests.end()) { tracker = (*mi).second; pfrom->mapRequests.erase(mi); } } if (!tracker.IsNull()) tracker.fn(tracker.param1, vRecv); } else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) { uint64 nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); } } else if (strCommand == "alert") { CAlert alert; vRecv >> alert; if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alert.GetHash()); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } } else if (strCommand == "checkpoint") { CSyncCheckpoint checkpoint; vRecv >> checkpoint; if (checkpoint.<API key>(pfrom)) { // Relay pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint; LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) checkpoint.RelayTo(pnode); } } else { // Ignore unknown commands for extensibility } // Update the last seen time for this node's address if (pfrom->fNetworkNode) if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") <API key>(pfrom->addr); return true; } bool ProcessMessages(CNode* pfrom) { CDataStream& vRecv = pfrom->vRecv; if (vRecv.empty()) return true; //if (fDebug) // printf("ProcessMessages(%u bytes)\n", vRecv.size()); // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data unsigned char pchMessageStart[4]; GetMessageStart(pchMessageStart); static int64 <API key> = 0; if (fDebug && GetBoolArg("-printmessagestart") && <API key> + 30 < GetAdjustedTime()) { string strMessageStart((const char *)pchMessageStart, sizeof(pchMessageStart)); vector<unsigned char> vchMessageStart(strMessageStart.begin(), strMessageStart.end()); printf("ProcessMessages : AdjustedTime=%"PRI64d" MessageStart=%s\n", GetAdjustedTime(), HexStr(vchMessageStart).c_str()); <API key> = GetAdjustedTime(); } INFINITE_LOOP { // Safe guards to prevent the node to ignore a requested shutdown // in case of long processing if (fRequestShutdown) { StartShutdown(); return true; } // Scan for message start CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart)); int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader()); if (vRecv.end() - pstart < nHeaderSize) { if ((int)vRecv.size() > nHeaderSize) { printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n"); vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize); } break; } if (pstart - vRecv.begin() > 0) printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin()); vRecv.erase(vRecv.begin(), pstart); // Read header vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize); CMessageHeader hdr; vRecv >> hdr; if (!hdr.IsValid()) { printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; if (nMessageSize > MAX_SIZE) { printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize); continue; } if (nMessageSize > vRecv.size()) { // Rewind and wait for rest of message vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end()); break; } // Checksum uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Copy message to its own buffer CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion); vRecv.ignore(nMessageSize); // Process message bool fRet = false; try { { LOCK(cs_main); fRet = ProcessMessage(pfrom, strCommand, vMsg); } if (fShutdown) return true; } catch (std::ios_base::failure& e) { if (strstr(e.what(), "end of data")) { // Allow exceptions from underlength message on vRecv printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from overlong size printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); } else { <API key>(&e, "ProcessMessages()"); } } catch (std::exception& e) { <API key>(&e, "ProcessMessages()"); } catch (...) { <API key>(NULL, "ProcessMessages()"); } if (!fRet) printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); } vRecv.Compact(); return true; } bool SendMessages(CNode* pto, bool fSendTrickle) { TRY_LOCK(cs_main, lockMain); if (lockMain) { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // Keep-alive ping. We send a nonce of zero because we don't use it anywhere // right now. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) { uint64 nonce = 0; if (pto->nVersion > BIP0031_VERSION) pto->PushMessage("ping", nonce); else pto->PushMessage("ping"); } // Resend wallet transactions that haven't gotten in a block yet <API key>(); // Address refresh broadcast static int64 nLastRebroadcast; if (!<API key>() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable()) { CAddress addr(addrLocalHost); addr.nTime = GetAdjustedTime(); pnode->PushAddress(addr); } } } nLastRebroadcast = GetTime(); } // Message: addr if (fSendTrickle) { vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } // Message: inventory vector<CInv> vInv; vector<CInv> vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); // always trickle our own transactions if (!fTrickleWait) { CWalletTx wtx; if (GetTransaction(inv.hash, wtx)) if (wtx.fFromMe) fTrickleWait = true; } if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // Message: getdata vector<CInv> vGetData; int64 nNow = GetTime() * 1000000; CTxDB txdb("r"); while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(txdb, inv)) { printf("sending getdata: %s\n", inv.ToString().c_str()); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } } mapAlreadyAskedFor[inv] = nNow; pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; } // BitcoinMiner int static FormatHashBlocks(void* pbuffer, unsigned int len) { unsigned char* pdata = (unsigned char*)pbuffer; unsigned int blocks = 1 + ((len + 8) / 64); unsigned char* pend = pdata + 64 * blocks; memset(pdata + len, 0, 64 * blocks - len); pdata[len] = 0x80; unsigned int bits = len * 8; pend[-1] = (bits >> 0) & 0xff; pend[-2] = (bits >> 8) & 0xff; pend[-3] = (bits >> 16) & 0xff; pend[-4] = (bits >> 24) & 0xff; return blocks; } static const unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; void SHA256Transform(void* pstate, void* pinput, const void* pinit) { SHA256_CTX ctx; unsigned char data[64]; SHA256_Init(&ctx); for (int i = 0; i < 16; i++) ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); for (int i = 0; i < 8; i++) ctx.h[i] = ((uint32_t*)pinit)[i]; SHA256_Update(&ctx, data, sizeof(data)); for (int i = 0; i < 8; i++) ((uint32_t*)pstate)[i] = ctx.h[i]; } // Some explaining would be appreciated class COrphan { public: CTransaction* ptx; set<uint256> setDependsOn; double dPriority; COrphan(CTransaction* ptxIn) { ptx = ptxIn; dPriority = 0; } void print() const { printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority); BOOST_FOREACH(uint256 hash, setDependsOn) printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); } }; uint64 nLastBlockTx = 0; uint64 nLastBlockSize = 0; int64 <API key> = 0; // CreateNewBlock: // fProofOfStake: try (best effort) to make a proof-of-stake block CBlock* CreateNewBlock(CReserveKey& reservekey, CWallet* pwallet, bool fProofOfStake) { // Create new block auto_ptr<CBlock> pblock(new CBlock()); if (!pblock.get()) return NULL; // Create coinbase tx CTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG; // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); // ppcoin: if coinstake available add coinstake tx static int64 <API key> = GetAdjustedTime(); // only initialized at startup CBlockIndex* pindexPrev = pindexBest; if (fProofOfStake) // attemp to find a coinstake { pblock->nBits = <API key>(pindexPrev, true); CTransaction txCoinStake; int64 nSearchTime = txCoinStake.nTime; // search to current time if (nSearchTime > <API key>) { if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, <API key>, txCoinStake)) { if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - MAX_CLOCK_DRIFT)) { // make sure coinstake would meet timestamp protocol // as it would be the same as the block timestamp pblock->vtx[0].vout[0].SetEmpty(); pblock->vtx[0].nTime = txCoinStake.nTime; pblock->vtx.push_back(txCoinStake); } } <API key> = nSearchTime - <API key>; <API key> = nSearchTime; } } pblock->nBits = <API key>(pindexPrev, pblock->IsProofOfStake()); // Collect memory pool transactions into the block int64 nFees = 0; { LOCK2(cs_main, mempool.cs); CTxDB txdb("r"); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; multimap<double, CTransaction*> mapPriority; for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { CTransaction& tx = (*mi).second; if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal()) continue; COrphan* porphan = NULL; double dPriority = 0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Read prev transaction CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) { // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); } mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); continue; } int64 nValueIn = txPrev.vout[txin.prevout.n].nValue; // Read block header int nConf = txindex.GetDepthInMainChain(); dPriority += (double)nValueIn * nConf; if (fDebug && GetBoolArg("-printpriority")) printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority); } // Priority is sum(valuein * age) / txsize dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (porphan) porphan->dPriority = dPriority; else mapPriority.insert(make_pair(-dPriority, &(*mi).second)); if (fDebug && GetBoolArg("-printpriority")) { printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str()); if (porphan) porphan->print(); printf("\n"); } } // Collect transactions into block map<uint256, CTxIndex> mapTestPool; uint64 nBlockSize = 1000; uint64 nBlockTx = 0; int nBlockSigOps = 100; while (!mapPriority.empty()) { // Take highest priority transaction off priority queue CTransaction& tx = *(*mapPriority.begin()).second; mapPriority.erase(mapPriority.begin()); // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) continue; // Legacy limits on sigOps: unsigned int nTxSigOps = tx.GetLegacySigOpCount(); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Timestamp limit if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime)) continue; // ppcoin: simplify transaction fee - allow free = false int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK); // Connecting shouldn't fail due to dependency on other memory pool transactions // because we're already processing them in order of dependency map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); MapPrevTx mapInputs; bool fInvalid; if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid)) continue; int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (nTxFees < nMinFee) continue; nTxSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true)) continue; mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size()); swap(mapTestPool, mapTestPoolTmp); // Added pblock->vtx.push_back(tx); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; // Add transactions that depend on this one to the priority queue uint256 hash = tx.GetHash(); if (mapDependers.count(hash)) { BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx)); } } } } nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; if (fDebug && GetBoolArg("-printpriority")) { printf("CreateNewBlock(): total size %lu\n", nBlockSize); } } if (pblock->IsProofOfWork()) pblock->vtx[0].vout[0].nValue = <API key>(pindexPrev->nHeight); // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); if (pblock->IsProofOfStake()) pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock-><API key>()); pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - MAX_CLOCK_DRIFT); if (pblock->IsProofOfWork()) pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; return pblock.release(); } void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS; assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) { // Prebuild hash buffers struct { struct unnamed2 { int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; } block; unsigned char pchPadding0[64]; uint256 hash1; unsigned char pchPadding1[64]; } tmp; memset(&tmp, 0, sizeof(tmp)); tmp.block.nVersion = pblock->nVersion; tmp.block.hashPrevBlock = pblock->hashPrevBlock; tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; tmp.block.nTime = pblock->nTime; tmp.block.nBits = pblock->nBits; tmp.block.nNonce = pblock->nNonce; FormatHashBlocks(&tmp.block, sizeof(tmp.block)); FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); // Byte swap all the input buffer for (unsigned int i = 0; i < sizeof(tmp)/4; i++) ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); // Precalc the first half of the first hash, which stays constant SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); memcpy(pdata, &tmp.block, 128); memcpy(phash1, &tmp.hash1, 64); } bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) { uint256 hash = pblock->GetHash(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); printf("Hash: %s\nTarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); if (hash > hashTarget && pblock->IsProofOfWork()) return error("BitcoinMiner : proof-of-work not meeting target"); / debug print printf("BitcoinMiner:\n"); printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); printf("%s ", DateTimeStrFormat(GetTime()).c_str()); printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("BitcoinMiner : generated block is stale"); // Remove key from key pool reservekey.KeepKey(); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[pblock->GetHash()] = 0; } // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock)) return error("BitcoinMiner : ProcessBlock, block not accepted"); } return true; } void static ThreadBitcoinMiner(void* parg); bool fStaking = true; static bool fGenerateBitcoins = false; static bool fLimitProcessors = false; static int nLimitProcessors = -1; bool BitcoinMiner(CWallet *pwallet, bool fProofOfStake, uint256 * minedBlock, uint64 nTimeout) { printf("CPUMiner started for proof-of-%s (%d)\n", fProofOfStake? "stake" : "work", vnThreadsRunning[fProofOfStake? THREAD_MINTER : THREAD_MINER]); SetThreadPriority(<API key>); uint64 nStartTime = GetTime(); // Each thread has its own key and counter CReserveKey reservekey(pwallet); unsigned int nExtraNonce = 0; while (minedBlock || fGenerateBitcoins || fProofOfStake) { if (fShutdown || (fProofOfStake && !fStaking)) return false; if (nTimeout && (GetTime() - nStartTime > nTimeout)) return false; while (vNodes.empty() || <API key>()) { Sleep(1000); if (fShutdown || (fProofOfStake && !fStaking)) return false; if (!minedBlock && (!fGenerateBitcoins && !fProofOfStake)) return false; } while (pwallet->IsLocked()) { strMintWarning = strMintMessage; Sleep(1000); } strMintWarning.clear(); // Create new block unsigned int <API key> = <API key>; CBlockIndex* pindexPrev = pindexBest; auto_ptr<CBlock> pblock(CreateNewBlock(reservekey, pwallet, fProofOfStake)); if (!pblock.get()) return false; IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce); if (fProofOfStake) { // ppcoin: if proof-of-stake block found then process block if (pblock->IsProofOfStake()) { if (!pblock->SignBlock(*pwalletMain)) { strMintWarning = strMintMessage; continue; } strMintWarning.clear(); printf("CPUMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str()); SetThreadPriority(<API key>); bool fSucceeded = CheckWork(pblock.get(), *pwalletMain, reservekey); SetThreadPriority(<API key>); if (fSucceeded && minedBlock) { *minedBlock = pblock->GetHash(); return true; } } Sleep(500); continue; } printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size()); // Search int64 nStart = GetTime(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); INFINITE_LOOP { unsigned int nHashesDone = 0; pblock->nNonce = 0; INFINITE_LOOP { if (pblock->GetHash() <= hashTarget) break; pblock->nNonce += 1; nHashesDone += 1; if ((pblock->nNonce & 0xFFFF) == 0) break; } // Check if something found if (pblock->GetHash() <= hashTarget) { if (!pblock->SignBlock(*pwalletMain)) { strMintWarning = strMintMessage; break; } else { strMintWarning = ""; } SetThreadPriority(<API key>); bool fSucceeded = CheckWork(pblock.get(), *pwalletMain, reservekey); SetThreadPriority(<API key>); if (fSucceeded && minedBlock) { *minedBlock = pblock->GetHash(); return true; } break; } // Meter hashes/sec static int64 nHashCounter; if (nHPSTimerStart == 0) { nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; } else { nHashCounter += nHashesDone; } if (GetTimeMillis() - nHPSTimerStart > 4000) { static CCriticalSection cs; { LOCK(cs); if (GetTimeMillis() - nHPSTimerStart > 4000) { dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart); nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; static int64 nLogTime; if (GetTime() - nLogTime > 30 * 60) { nLogTime = GetTime(); printf("%s ", DateTimeStrFormat(GetTime()).c_str()); printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0); } } } } // Check for stop or if block needs to be rebuilt if (fShutdown || (fProofOfStake && !fStaking)) return false; if (!minedBlock && !fGenerateBitcoins) return false; if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors) return false; if (vNodes.empty()) break; if (<API key> != <API key> && GetTime() - nStart > 60) break; if (pindexPrev != pindexBest) break; // Update nTime every few seconds pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock-><API key>()); pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - MAX_CLOCK_DRIFT); pblock->UpdateTime(pindexPrev); if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + MAX_CLOCK_DRIFT) { break; // need to update coinbase timestamp } } } return false; } void static ThreadBitcoinMiner(void* parg) { CWallet* pwallet = (CWallet*)parg; try { vnThreadsRunning[THREAD_MINER]++; BitcoinMiner(pwallet, false); vnThreadsRunning[THREAD_MINER] } catch (std::exception& e) { vnThreadsRunning[THREAD_MINER] PrintException(&e, "ThreadBitcoinMiner()"); } catch (...) { vnThreadsRunning[THREAD_MINER] PrintException(NULL, "ThreadBitcoinMiner()"); } nHPSTimerStart = 0; if (vnThreadsRunning[THREAD_MINER] == 0) dHashesPerSec = 0; printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]); } void GenerateBitcoins(bool fGenerate, CWallet* pwallet) { fGenerateBitcoins = fGenerate; nLimitProcessors = GetArg("-genproclimit", -1); if (nLimitProcessors == 0) fGenerateBitcoins = false; fLimitProcessors = (nLimitProcessors != -1); if (fGenerate) { int nProcessors = boost::thread::<API key>(); printf("%d processors\n", nProcessors); if (nProcessors < 1) nProcessors = 1; if (fLimitProcessors && nProcessors > nLimitProcessors) nProcessors = nLimitProcessors; int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER]; printf("Starting %d BitcoinMiner threads\n", nAddThreads); for (int i = 0; i < nAddThreads; i++) { if (!CreateThread(ThreadBitcoinMiner, pwallet)) printf("Error: CreateThread(ThreadBitcoinMiner) failed\n"); Sleep(10); } } }
'use strict'; console.log('TESTTTT'); var mean = require('meanio'); exports.render = function (req, res) { function isAdmin() { return req.user && req.user.roles.indexOf('admin') !== -1; } // Send some basic starting info to the view res.render('index', { user: req.user ? { name: req.user.name, _id: req.user._id, username: req.user.username, roles: req.user.roles } : {}, modules: 'ho', motti: 'motti is cool', isAdmin: 'motti', adminEnabled: isAdmin() && mean.moduleEnabled('mean-admin') }); };
/* concatenated from client/src/app/js/globals.js */ (function () { if (!window.console) { window.console = {}; } var m = [ "log", "info", "warn", "error", "debug", "trace", "dir", "group", "groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd", "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear" ]; for (var i = 0; i < m.length; i++) { if (!window.console[m[i]]) { window.console[m[i]] = function() {}; } } _.mixin({ compactObject: function(o) { _.each(o, function(v, k) { if(!v) { delete o[k]; } }); return o; } }); })(); /* concatenated from client/src/app/js/app.js */ const mainPages = { HOME: "/", WALKS: "/walks", SOCIAL: "/social", JOIN_US: "/join-us", CONTACT_US: "/contact-us", COMMITTEE: "/committee", ADMIN: "/admin", HOW_TO: "/how-to" }; angular.module("ekwgApp", [ "btford.markdown", "ngRoute", "ngSanitize", "ui.bootstrap", "angularModalService", "btford.markdown", "<API key>", "ngAnimate", "ngCookies", "ngFileUpload", "ngSanitize", "ui.bootstrap", "ui.select", "angular-logger", "ezfb", "ngCsv"]) .constant("MONGOLAB_CONFIG", { trimErrorMessage: false, baseUrl: "/databases/", database: "ekwg" }) .constant("AUDIT_CONFIG", { auditSave: true, }) .constant("PAGE_CONFIG", { mainPages: mainPages }) .config(["$compileProvider", function ($compileProvider) { $compileProvider.<API key>(/^\s*(https?|ftp|mailto|chrome-extension|tel):/); }]) .constant("<API key>", { allowSendCampaign: true, apiServer: "https://us3.admin.mailchimp.com" }) .config(["$locationProvider", function ($locationProvider) { $locationProvider.hashPrefix(""); }]) .config(["$routeProvider", "uiSelectConfig", "uibDatepickerConfig", "<API key>", "logEnhancerProvider", function ($routeProvider, uiSelectConfig, uibDatepickerConfig, <API key>, logEnhancerProvider) { uiSelectConfig.theme = "bootstrap"; uiSelectConfig.closeOnSelect = false; $routeProvider .when(mainPages.ADMIN + "/expenseId/:expenseId", { controller: "AdminController", templateUrl: "partials/admin/admin.html", title: "expenses" }) .when(mainPages.ADMIN + "/:area?", { controller: "AdminController", templateUrl: "partials/admin/admin.html", title: "admin" }) .when(mainPages.COMMITTEE + "/committeeFileId/:committeeFileId", { controller: "CommitteeController", templateUrl: "partials/committee/committee.html", title: "AGM and committee" }) .when(mainPages.COMMITTEE, { controller: "CommitteeController", templateUrl: "partials/committee/committee.html", title: "AGM and committee" }) .when(mainPages.HOW_TO, { controller: "HowToController", templateUrl: "partials/howTo/how-to.html", title: "How-to" }) .when("/image-editor/:imageSource", { controller: "ImageEditController", templateUrl: "partials/imageEditor/image-editor.html", title: "image editor" }) .when(mainPages.JOIN_US, { controller: "HomeController", templateUrl: "partials/joinUs/join-us.html", title: "join us" }) .when("/letterhead/:firstPart?/:secondPart", { controller: "<API key>", templateUrl: "partials/letterhead/letterhead.html", title: "letterhead" }) .when(mainPages.CONTACT_US, { controller: "ContactUsController", templateUrl: "partials/contactUs/contact-us.html", title: "contact us" }) .when("/links", {redirectTo: mainPages.CONTACT_US}) .when(mainPages.SOCIAL + "/socialEventId/:socialEventId", { controller: "<API key>", templateUrl: "partials/socialEvents/social.html", title: "social" }) .when(mainPages.SOCIAL + "/:area?", { controller: "<API key>", templateUrl: "partials/socialEvents/social.html", title: "social" }) .when(mainPages.WALKS + "/walkId/:walkId", { controller: "WalksController", templateUrl: "partials/walks/walks.html", title: "walks" }) .when(mainPages.WALKS + "/:area?", { controller: "WalksController", templateUrl: "partials/walks/walks.html", title: "walks" }) .when(mainPages.HOME, { controller: "HomeController", templateUrl: "partials/home/home.html", title: "home" }) .when("/set-password/:passwordResetId", { controller: "<API key>, templateUrl: "partials/home/home.html" }) .otherwise({ controller: "<API key>, templateUrl: "partials/home/home.html" }); uibDatepickerConfig.startingDay = 1; uibDatepickerConfig.showWeeks = false; <API key>.datepickerPopup = "dd-MMM-yyyy"; <API key>.formatDay = "dd"; logEnhancerProvider.datetimePattern = "hh:mm:ss"; logEnhancerProvider.prefixPattern = "%s - %s -"; }]) .run(["$log", "$rootScope", "$route", "URLService", "CommitteeConfig", "<API key>", function ($log, $rootScope, $route, URLService, CommitteeConfig, <API key>) { var logger = $log.getInstance("App.run"); $log.logLevels["App.run"] = $log.LEVEL.OFF; $rootScope.$on('$locationChangeStart', function (evt, absNewUrl, absOldUrl) { }); $rootScope.$on("$<API key>", function (event, newUrl, absOldUrl) { if (!$rootScope.pageHistory) $rootScope.pageHistory = []; $rootScope.pageHistory.push(URLService.relativeUrl(newUrl)); logger.info("newUrl", newUrl, "$rootScope.pageHistory", $rootScope.pageHistory); }); $rootScope.$on("$routeChangeSuccess", function (currentRoute, previousRoute) { $rootScope.title = $route.current.title; }); CommitteeConfig.getConfig() .then(function (config) { angular.extend(<API key>, config.committee); $rootScope.$broadcast("<API key>", <API key>); }); }]); /* concatenated from client/src/app/js/admin.js */ angular.module('ekwgApp') .controller('AdminController', ["$rootScope", "$scope", "<API key>", function($rootScope, $scope, <API key>) { function setViewPriveleges() { $scope.loggedIn = <API key>.memberLoggedIn(); $scope.memberAdmin = <API key>.<API key>(); <API key>.<API key>('expenseId'); } setViewPriveleges(); $scope.$on('memberLoginComplete', function() { setViewPriveleges(); }); $scope.$on('<API key>', function() { setViewPriveleges(); }); }] ); /* concatenated from client/src/app/js/<API key>.js */ angular.module('ekwgApp') .controller("<API key>, ["$log", "$scope", "URLService", "$location", "$routeParams", "<API key>, "<API key>", function ($log, $scope, URLService, $location, $routeParams, <API key>, <API key>) { var logger = $log.getInstance("<API key>); $log.logLevels["<API key>] = $log.LEVEL.OFF; var urlFirstSegment = URLService.<API key>(); logger.info("URLService.relativeUrl:", urlFirstSegment, "$routeParams:", $routeParams); switch (urlFirstSegment) { case "/login": return <API key>.showLoginDialog(); case "/logout": return <API key>.logout(); case "/mailing-preferences": if (<API key>.memberLoggedIn()) { return <API key>.<API key>(<API key>.loggedInMember().memberId); } else { return URLService.setRoot(); } case "/forgot-password": return <API key>.<API key>(); case "/set-password": return <API key>.<API key>($routeParams.passwordResetId) .then(function (member) { logger.info("for $routeParams.passwordResetId", $routeParams.passwordResetId, "member", member); if (_.isEmpty(member)) { return <API key>.<API key>(); } else { return <API key>.<API key>(member.userName) } }); default: logger.warn(URLService.relativeUrl(), "doesnt match any of the supported urls"); return URLService.setRoot(); } }] ); /* concatenated from client/src/app/js/<API key>.js */ angular.module('ekwgApp') .factory("<API key>, ["$log", "ModalService", "URLService", function ($log, ModalService, URLService) { var logger = $log.getInstance("<API key>); $log.logLevels["<API key>] = $log.LEVEL.OFF; function <API key>() { logger.info('called <API key>'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/<API key>.html", controller: "<API key>", preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('close event with result', result); if (!result) URLService.<API key>(); }); }).catch(function (error) { logger.warn("error happened:", error); }) } function <API key>(userName, message) { logger.info('called <API key> for userName', userName); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/<API key>.html", controller: "<API key>", inputs: {userName: userName, message: message}, preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('<API key> close event with result', result); if (!result) URLService.<API key>(); }); }) } function showLoginDialog() { logger.info('called showLoginDialog'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/login-dialog.html", controller: "LoginController", preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('showLoginDialog close event with result', result); if (!result) URLService.<API key>(); }); }) } function <API key>() { logger.info('called <API key>'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/<API key>.html", controller: "Reset<API key>, preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('<API key> modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('<API key> close event with result', result); if (!result) URLService.<API key>(); }); }) } function <API key>(memberId) { logger.info('called <API key>'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/<API key>.html", controller: "<API key>", inputs: {memberId: memberId}, preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('<API key> modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('close event with result', result); if (!result) URLService.<API key>(); }); }) } return { <API key>: <API key>, <API key>: <API key>, <API key>: <API key>, showLoginDialog: showLoginDialog, <API key>: <API key> } }]); /* concatenated from client/src/app/js/awsServices.js */ angular.module('ekwgApp') .factory('AWSConfig', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) { function getConfig() { return $http.get('/aws/config').then(HTTPResponseService.returnResponse); } function awsPolicy(fileType, objectKey) { return $http.get('/aws/s3Policy?mimeType=' + fileType + '&objectKey=' + objectKey).then(HTTPResponseService.returnResponse); } return { getConfig: getConfig, awsPolicy: awsPolicy } }]) .factory('EKWGFileUpload', ["$log", "AWSConfig", "NumberUtils", "Upload", function ($log, AWSConfig, NumberUtils, Upload) { $log.logLevels['EKWGFileUpload'] = $log.LEVEL.OFF; var logger = $log.getInstance('EKWGFileUpload'); var awsConfig; AWSConfig.getConfig().then(function (config) { awsConfig = config; }); function onFileSelect(file, notify, objectKey) { logger.debug(file, objectKey); function <API key>() { return { originalFileName: file.name, awsFileName: NumberUtils.generateUid() + '.' + _.last(file.name.split('.')) }; } var fileNameData = <API key>(), fileUpload = file; fileUpload.progress = parseInt(0); logger.debug('uploading fileNameData', fileNameData); return AWSConfig.awsPolicy(file.type, objectKey) .then(function (response) { var s3Params = response; var url = 'https://' + awsConfig.bucket + '.s3.amazonaws.com/'; return Upload.upload({ url: url, method: 'POST', data: { 'key': objectKey + '/' + fileNameData.awsFileName, 'acl': 'public-read', 'Content-Type': file.type, 'AWSAccessKeyId': s3Params.AWSAccessKeyId, '<API key>': '201', 'Policy': s3Params.s3Policy, 'Signature': s3Params.s3Signature }, file: file }).then(function (response) { fileUpload.progress = parseInt(100); if (response.status === 201) { var data = xml2json.parser(response.data), parsedData; parsedData = { location: data.postresponse.location, bucket: data.postresponse.bucket, key: data.postresponse.key, etag: data.postresponse.etag }; logger.debug('parsedData', parsedData); return fileNameData; } else { notify.error('Upload Failed for file ' + fileNameData); } }, notify.error, function (evt) { fileUpload.progress = parseInt(100.0 * evt.loaded / evt.total); }); }); } return {onFileSelect: onFileSelect}; }]); /* concatenated from client/src/app/js/batchGeoServices.js */ angular.module('ekwgApp') .factory('<API key>', ["StringUtils", "DateUtils", "$filter", function(StringUtils, DateUtils, $filter) { function exportWalksFileName() { return '<API key>-' + DateUtils.asMoment().format('DD-MMMM-YYYY-HH-mm') + '.csv' } function exportableWalks(walks) { return _(walks).sortBy('walkDate'); } function exportWalks(walks) { return _.chain(walks) .filter(filterWalk) .sortBy('walkDate') .last(250) .map(walkToCsvRecord) .value(); } function filterWalk(walk) { return _.has(walk, '<API key>') && (_.has(walk, 'gridReference') || _.has(walk, 'postcode')); } function <API key>() { return [ "Walk Date", "Start Time", "Postcode", "Contact Name/Email", "Distance", "Description", "Longer Description", "Grid Ref" ]; } function walkToCsvRecord(walk) { return { "walkDate": walkDate(walk), "startTime": walkStartTime(walk), "postcode": walkPostcode(walk), "displayName": contactDisplayName(walk), "distance": walkDistanceMiles(walk), "description": walkTitle(walk), "longerDescription": walkDescription(walk), "gridRef": walkGridReference(walk) }; } function walkTitle(walk) { var walkDescription = []; if (walk.<API key>) walkDescription.push(walk.<API key>); if (walk.<API key>) walkDescription.push(walk.<API key>); return _.chain(walkDescription).map(<API key>).value().join('. '); } function walkDescription(walk) { return <API key>(walk.longerDescription); } function asString(value) { return value ? value : ''; } function contactDisplayName(walk) { return walk.displayName ? <API key>(_.first(walk.displayName.split(' '))) : ''; } function <API key>(value) { return value ? StringUtils.stripLineBreaks(value .replace("’", "'") .replace("é", "e") .replace("’", "'") .replace('…', '…') .replace('–', '–') .replace('’', '’') .replace('“', '“')) : ''; } function walkDistanceMiles(walk) { return walk.distance ? String(parseFloat(walk.distance).toFixed(1)) : ''; } function walkStartTime(walk) { return walk.startTime ? DateUtils.asString(walk.startTime, 'HH mm', 'HH:mm') : ''; } function walkGridReference(walk) { return walk.gridReference ? walk.gridReference : ''; } function walkPostcode(walk) { return walk.postcode ? walk.postcode : ''; } function walkDate(walk) { return $filter('displayDate')(walk.walkDate); } return { exportWalksFileName: exportWalksFileName, exportWalks: exportWalks, exportableWalks: exportableWalks, <API key>: <API key> } }]); /* concatenated from client/src/app/js/bulkUploadServices.js */ angular.module('ekwgApp') .factory('<API key>', ["$log", "$q", "$filter", "MemberService", "<API key>", "<API key>", "ErrorMessageService", "<API key>", "DateUtils", "DbUtils", "MemberNamingService", function ($log, $q, $filter, MemberService, <API key>, <API key>, ErrorMessageService, <API key>, DateUtils, DbUtils, MemberNamingService) { var logger = $log.getInstance('<API key>'); var noLogger = $log.getInstance('NoLogger'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; $log.logLevels['NoLogger'] = $log.LEVEL.OFF; var RESET_PASSWORD = 'changeme'; function <API key>(file, <API key>, members, notify) { notify.setBusy(); var today = DateUtils.momentNowNoTime().valueOf(); var promises = []; var <API key> = <API key>.data; logger.debug('received', <API key>); return DbUtils.auditedSaveOrUpdate(new <API key>(<API key>)) .then(function (auditResponse) { var uploadSessionId = auditResponse.$id(); return <API key>(promises, uploadSessionId); }); function <API key>(promises) { if (<API key>.members && <API key>.members.length > 1) { notify.progress('Processing ' + members.length + ' members ready for bulk load'); _.each(members, function (member) { if (member.<API key>) { member.<API key> = false; promises.push(DbUtils.auditedSaveOrUpdate(member, auditUpdateCallback(member), auditErrorCallback(member))); } }); return $q.all(promises).then(function () { notify.progress('Marked ' + promises.length + ' out of ' + members.length + ' in preparation for update'); return promises; }); } else { return $q.when(promises); } } function <API key>(promises, uploadSessionId) { return <API key>(promises).then(function (updatedPromises) { _.each(<API key>.members, function (ramblersMember, recordIndex) { <API key>(uploadSessionId, recordIndex, ramblersMember, updatedPromises); }); return $q.all(updatedPromises).then(function () { logger.debug('performed total of', updatedPromises.length, 'audit or member updates'); return updatedPromises; }); }); } function auditUpdateCallback(member) { return function (response) { logger.debug('auditUpdateCallback for member:', member, 'response', response); } } function auditErrorCallback(member, audit) { return function (response) { logger.warn('member save error for member:', member, 'response:', response); if (audit) { audit.auditErrorMessage = response; } } } function <API key>(promises, uploadSessionId, rowNumber, memberAction, changes, auditMessage, member) { var audit = new <API key>({ uploadSessionId: uploadSessionId, updateTime: DateUtils.nowAsValue(), memberAction: memberAction, rowNumber: rowNumber, changes: changes, auditMessage: auditMessage }); var qualifier = 'for membership ' + member.membershipNumber; member.<API key> = true; member.lastBulkLoadDate = DateUtils.momentNow().valueOf(); return DbUtils.auditedSaveOrUpdate(member, auditUpdateCallback(member), auditErrorCallback(member, audit)) .then(function (savedMember) { if (savedMember) { audit.memberId = savedMember.$id(); notify.success({title: 'Bulk member load ' + qualifier + ' was successful', message: auditMessage}) } else { audit.member = member; audit.memberAction = 'error'; logger.warn('member was not saved, so saving it to audit:', audit); notify.warning({title: 'Bulk member load ' + qualifier + ' failed', message: auditMessage}) } logger.debug('<API key>:', audit); promises.push(audit.$save()); return promises; }); } function <API key>(ramblersMember) { var dataValue = ramblersMember.<API key> ? DateUtils.asValueNoTime(ramblersMember.<API key>, 'DD/MM/YYYY') : ramblersMember.<API key>; logger.debug('ramblersMember', ramblersMember, '<API key>', ramblersMember.<API key>, '->', DateUtils.displayDate(dataValue)); return dataValue; } function <API key>(uploadSessionId, recordIndex, ramblersMember, promises) { var memberAction; ramblersMember.<API key> = <API key>(ramblersMember); ramblersMember.groupMember = !ramblersMember.<API key> || ramblersMember.<API key> >= today; var member = _.find(members, function (member) { var existingUserName = MemberNamingService.createUserName(ramblersMember); var match = member.membershipNumber && member.membershipNumber.toString() === ramblersMember.membershipNumber; if (!match && member.userName) { match = member.userName === existingUserName; } noLogger.debug('match', !!(match), 'ramblersMember.membershipNumber', ramblersMember.membershipNumber, 'ramblersMember.userName', existingUserName, 'member.membershipNumber', member.membershipNumber, 'member.userName', member.userName); return match; }); if (member) { <API key>.<API key>(member); } else { memberAction = 'created'; member = new MemberService(); member.userName = MemberNamingService.<API key>(ramblersMember, members); member.displayName = MemberNamingService.<API key>(ramblersMember, members); member.password = RESET_PASSWORD; member.expiredPassword = true; <API key>.<API key>(member, true); logger.debug('new member created:', member); } var updateAudit = {auditMessages: [], fieldsChanged: 0, fieldsSkipped: 0}; _.each([ {fieldName: '<API key>', writeDataIf: 'changed', type: 'date'}, {fieldName: 'membershipNumber', writeDataIf: 'changed', type: 'string'}, {fieldName: 'mobileNumber', writeDataIf: 'empty', type: 'string'}, {fieldName: 'email', writeDataIf: 'empty', type: 'string'}, {fieldName: 'firstName', writeDataIf: 'empty', type: 'string'}, {fieldName: 'lastName', writeDataIf: 'empty', type: 'string'}, {fieldName: 'postcode', writeDataIf: 'empty', type: 'string'}, {fieldName: 'groupMember', writeDataIf: 'not-revoked', type: 'boolean'}], function (field) { <API key>(updateAudit, member, ramblersMember, field) }); DbUtils.removeEmptyFieldsIn(member); logger.debug('<API key> -> member:', member, 'updateAudit:', updateAudit); return <API key>(promises, uploadSessionId, recordIndex + 1, memberAction || (updateAudit.fieldsChanged > 0 ? 'updated' : 'skipped'), updateAudit.fieldsChanged, updateAudit.auditMessages.join(', '), member); } function <API key>(updateAudit, member, ramblersMember, field) { function auditValueForType(field, source) { var dataValue = source[field.fieldName]; switch (field.type) { case 'date': return ($filter('displayDate')(dataValue) || '(none)'); case 'boolean': return dataValue || false; default: return dataValue || '(none)'; } } var fieldName = field.fieldName; var performMemberUpdate = false; var auditQualifier = ' not overwritten with '; var auditMessage; var oldValue = auditValueForType(field, member); var newValue = auditValueForType(field, ramblersMember); if (field.writeDataIf === 'changed') { performMemberUpdate = (oldValue !== newValue) && ramblersMember[fieldName]; } else if (field.writeDataIf === 'empty') { performMemberUpdate = !member[fieldName]; } else if (field.writeDataIf === 'not-revoked') { performMemberUpdate = newValue && (oldValue !== newValue) && !member.revoked; } else if (field.writeDataIf) { performMemberUpdate = newValue; } if (performMemberUpdate) { auditQualifier = ' updated to '; member[fieldName] = ramblersMember[fieldName]; updateAudit.fieldsChanged++; } if (oldValue !== newValue) { if (!performMemberUpdate) updateAudit.fieldsSkipped++; auditMessage = fieldName + ': ' + oldValue + auditQualifier + newValue; } if ((performMemberUpdate || (oldValue !== newValue)) && auditMessage) { updateAudit.auditMessages.push(auditMessage); } } } return { <API key>: <API key>, } }]); /* concatenated from client/src/app/js/clipboardService.js */ angular.module('ekwgApp') .factory('ClipboardService', ["$compile", "$rootScope", "$document", "$log", function ($compile, $rootScope, $document, $log) { return { copyToClipboard: function (element) { var logger = $log.getInstance("ClipboardService"); $log.logLevels['ClipboardService'] = $log.LEVEL.OFF; var copyElement = angular.element('<span id="<API key>">' + element + '</span>'); var body = $document.find('body').eq(0); body.append($compile(copyElement)($rootScope)); var <API key> = angular.element(document.getElementById('<API key>')); logger.debug(<API key>); var range = document.createRange(); range.selectNode(<API key>[0]); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; logger.debug('Copying text command was ' + msg); window.getSelection().removeAllRanges(); copyElement.remove(); } } }]); /* concatenated from client/src/app/js/<API key>.js */ angular.module('ekwgApp') .controller('<API key>', ["$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "<API key>", "MemberService", "<API key>", "<API key>", "<API key>", "<API key>", "<API key>", "MailchimpConfig", "Notifier", "<API key>", "<API key>", "committeeFile", "close", function ($window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, <API key>, MemberService, <API key>, <API key>, <API key>, <API key>, <API key>, MailchimpConfig, Notifier, <API key>, <API key>, committeeFile, close) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); $scope.members = []; $scope.committeeFile = committeeFile; $scope.roles = {signoff: <API key>.<API key>(), replyTo: []}; $scope.<API key> = <API key>.baseUrl('committeeFiles'); function loggedOnRole() { var memberId = <API key>.loggedInMember().memberId; var loggedOnRoleData = _(<API key>.<API key>()).find(function (role) { return role.memberId === memberId }); logger.debug('loggedOnRole for', memberId, '->', loggedOnRoleData); return loggedOnRoleData || {}; } $scope.fromDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.fromDateCalendar.opened = true; } }; $scope.toDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.toDateCalendar.opened = true; } }; $scope.populateGroupEvents = function () { notify.setBusy(); populateGroupEvents().then(function () { notify.clearBusy(); return true; }) }; function populateGroupEvents() { return <API key>.groupEvents($scope.userEdits.groupEvents) .then(function (events) { $scope.userEdits.groupEvents.events = events; logger.debug('groupEvents', events); return events; }); } $scope.<API key> = function (groupEvent) { groupEvent.selected = !groupEvent.selected; }; $scope.notification = { editable: { text: '', signoffText: 'If you have any questions about the above, please don\'t hesitate to contact me.\n\nBest regards,', }, destinationType: 'committee', includeSignoffText: true, addresseeType: 'Hi *|FNAME|*,', addingNewFile: false, recipients: [], groupEvents: function () { return _.filter($scope.userEdits.groupEvents.events, function (groupEvent) { logger.debug('notification.groupEvents ->', groupEvent); return groupEvent.selected; }); }, signoffAs: { include: true, value: loggedOnRole().type || 'secretary' }, <API key>: $scope.committeeFile, title: 'Committee Notification', text: function () { return $filter('lineFeedsToBreaks')($scope.notification.editable.text); }, signoffText: function () { return $filter('lineFeedsToBreaks')($scope.notification.editable.signoffText); } }; if ($scope.committeeFile) { $scope.notification.title = $scope.committeeFile.fileType; $scope.notification.editable.text = 'This is just a quick note to let you know in case you are interested, that I\'ve uploaded a new file to the EKWG website. The file information is as follows:'; } logger.debug('initialised on open: committeeFile', $scope.committeeFile, ', roles', $scope.roles); logger.debug('initialised on open: notification ->', $scope.notification); $scope.userEdits = { sendInProgress: false, cancelled: false, groupEvents: { events: [], fromDate: DateUtils.momentNowNoTime().valueOf(), toDate: DateUtils.momentNowNoTime().add(2, 'weeks').valueOf(), includeContact: true, includeDescription: true, includeLocation: true, includeWalks: true, includeSocialEvents: true, <API key>: true }, <API key>: function () { return _.chain($scope.members) .filter(MemberService.filterFor.<API key>) .map(<API key>).value(); }, <API key>: function () { return _.chain($scope.members) .filter(MemberService.filterFor.<API key>) .map(toSelectWalksMember).value(); }, <API key>: function () { return _.chain($scope.members) .filter(MemberService.filterFor.<API key>) .map(<API key>).value(); }, allCommitteeList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.COMMITTEE_MEMBERS) .map(<API key>).value(); }, replyToRole: function () { return _($scope.roles.replyTo).find(function (role) { return role.type === $scope.socialEvent.notification.items.replyTo.value; }); }, notReady: function () { return $scope.members.length === 0 || $scope.userEdits.sendInProgress || ($scope.notification.recipients.length === 0 && $scope.notification.destinationType === 'custom'); } }; function <API key>(member) { var memberGrouping; var order; if (member.groupMember && member.mailchimpLists.general.subscribed) { memberGrouping = 'Subscribed to general emails'; order = 0; } else if (member.groupMember && !member.mailchimpLists.general.subscribed) { memberGrouping = 'Not subscribed to general emails'; order = 1; } else if (!member.groupMember) { memberGrouping = 'Not a group member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } function toSelectWalksMember(member) { var memberGrouping; var order; if (member.groupMember && member.mailchimpLists.walks.subscribed) { memberGrouping = 'Subscribed to walks emails'; order = 0; } else if (member.groupMember && !member.mailchimpLists.walks.subscribed) { memberGrouping = 'Not subscribed to walks emails'; order = 1; } else if (!member.groupMember) { memberGrouping = 'Not a group member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } function <API key>(member) { var memberGrouping; var order; if (member.groupMember && member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Subscribed to social emails'; order = 0; } else if (member.groupMember && !member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Not subscribed to social emails'; order = 1; } else if (!member.groupMember) { memberGrouping = 'Not a group member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } $scope.<API key> = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('general'); $scope.notification.list = 'general'; $scope.notification.recipients = $scope.userEdits.<API key>(); $scope.campaignIdChanged(); }; $scope.<API key> = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('walks'); $scope.notification.list = 'walks'; $scope.notification.recipients = $scope.userEdits.<API key>(); $scope.campaignIdChanged(); }; $scope.<API key> = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('socialEvents'); $scope.notification.list = 'socialEvents'; $scope.notification.recipients = $scope.userEdits.<API key>(); $scope.campaignIdChanged(); }; $scope.<API key> = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('committee'); $scope.notification.list = 'general'; $scope.notification.recipients = $scope.userEdits.allCommitteeList(); $scope.campaignIdChanged(); }; $scope.<API key> = function (campaignType) { $scope.notification.customCampaignType = campaignType; $scope.notification.campaignId = campaignIdFor(campaignType); $scope.notification.list = 'general'; $scope.notification.recipients = []; $scope.campaignIdChanged(); }; $scope.fileUrl = function () { return $scope.committeeFile && $scope.committeeFile.fileNameData ? URLService.baseUrl() + $scope.<API key> + '/' + $scope.committeeFile.fileNameData.awsFileName : ''; }; $scope.fileTitle = function () { return $scope.committeeFile ? DateUtils.asString($scope.committeeFile.eventDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + $scope.committeeFile.fileNameData.title : ''; }; function campaignIdFor(campaignType) { switch (campaignType) { case 'committee': return $scope.config.mailchimp.campaigns.committee.campaignId; case 'general': return $scope.config.mailchimp.campaigns.newsletter.campaignId; case 'socialEvents': return $scope.config.mailchimp.campaigns.socialEvents.campaignId; case 'walks': return $scope.config.mailchimp.campaigns.walkNotification.campaignId; default: return $scope.config.mailchimp.campaigns.committee.campaignId; } } function <API key>(campaignId) { return _.chain($scope.config.mailchimp.campaigns) .map(function (data, campaignType) { var campaignData = _.extend({campaignType: campaignType}, data); logger.debug('campaignData for', campaignType, '->', campaignData); return campaignData; }).find({campaignId: campaignId}) .value(); } $scope.campaignIdChanged = function () { var infoForCampaign = <API key>($scope.notification.campaignId); logger.debug('for campaignId', $scope.notification.campaignId, 'infoForCampaign', infoForCampaign); if (infoForCampaign) { $scope.notification.title = infoForCampaign.name; } }; $scope.<API key> = function (dontSend) { $scope.userEdits.sendInProgress = true; var campaignName = $scope.notification.title; notify.setBusy(); return $q.when(templateFor('partials/committee/<API key>.html')) .then(<API key>) .then(<API key>) .then(sendEmailCampaign) .then(<API key>) .catch(<API key>); function templateFor(template) { return $templateRequest($sce.<API key>(template)) } function <API key>(errorResponse) { $scope.userEdits.sendInProgress = false; notify.clearBusy(); notify.error({ title: 'Your notification could not be sent', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '') }); } function <API key>(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction($scope); $timeout(function () { $scope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function <API key>(notificationText) { logger.debug('<API key> -> notificationText', notificationText); return { sections: { notification_text: notificationText } }; } function sendEmailCampaign(contentSections) { notify.progress(dontSend ? ('Preparing to complete ' + campaignName + ' in Mailchimp') : ('Sending ' + campaignName)); return MailchimpConfig.getConfig() .then(function (config) { var replyToRole = $scope.notification.signoffAs.value || 'secretary'; logger.debug('replyToRole', replyToRole); var members; var list = $scope.notification.list; var otherOptions = { from_name: <API key>.contactUsField(replyToRole, 'fullName'), from_email: <API key>.contactUsField(replyToRole, 'email'), list_id: config.mailchimp.lists[list] }; logger.debug('Sending ' + campaignName, 'with otherOptions', otherOptions); var segmentId = config.mailchimp.segments[list].committeeSegmentId; var campaignId = $scope.notification.campaignId; switch ($scope.notification.destinationType) { case 'custom': members = $scope.notification.recipients; break; case 'committee': members = $scope.userEdits.allCommitteeList(); break; default: members = []; break; } logger.debug('<API key>:notification->', $scope.notification); if (members.length === 0) { logger.debug('about to <API key> to', list, 'list with campaignName', campaignName, 'campaign Id', campaignId, 'dontSend', dontSend); return <API key>.<API key>({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); } else { var segmentName = <API key>.formatSegmentName('Committee Notification Recipients'); return <API key>.saveSegment(list, {segmentId: segmentId}, members, segmentName, $scope.members) .then(function (segmentResponse) { logger.debug('segmentResponse following save segment of segmentName:', segmentName, '->', segmentResponse); logger.debug('about to <API key> to committee with campaignName', campaignName, 'campaign Id', campaignId, 'segmentId', segmentResponse.segment.id); return <API key>.<API key>({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, segmentId: segmentResponse.segment.id, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); }); } }) } function openInMailchimpIf(dontSend) { return function (<API key>) { logger.debug('openInMailchimpIf:<API key>', <API key>, 'dontSend', dontSend); if (dontSend) { return $window.open(<API key>.apiServer + "/campaigns/wizard/neapolitan?id=" + <API key>.web_id, '_blank'); } else { return true; } } } function <API key>() { if (!$scope.userEdits.cancelled) { notify.success('Sending of ' + campaignName + ' was successful.', false); $scope.userEdits.sendInProgress = false; $scope.<API key>(); } notify.clearBusy(); } }; $scope.completeInMailchimp = function () { notify.warning({ title: 'Complete in Mailchimp', message: 'You can close this dialog now as the message was presumably completed and sent in Mailchimp' }); $scope.<API key>(true); }; $scope.<API key> = function () { if ($scope.userEdits.sendInProgress) { $scope.userEdits.sendInProgress = false; $scope.userEdits.cancelled = true; notify.error({ title: 'Cancelling during send', message: "Because notification sending was already in progress when you cancelled, campaign may have already been sent - check in Mailchimp if in doubt." }); } else { logger.debug('calling <API key>'); close(); } }; var promises = [ MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) { $scope.members = members; logger.debug('refreshMembers -> populated ->', $scope.members.length, 'members'); $scope.<API key> = _.chain(members) .map(<API key>) .sortBy(function (member) { return member.order + member.text }) .value(); logger.debug('refreshMembers -> populated ->', $scope.<API key>.length, '<API key>'); }), MailchimpConfig.getConfig() .then(function (config) { $scope.config = config; logger.debug('retrieved config', $scope.config); $scope.<API key>('committee'); }), <API key>.list({ limit: 1000, concise: true, status: 'save', title: 'Master' }).then(function (response) { $scope.campaigns = response.data; logger.debug('response.data', response.data); })]; if (!$scope.committeeFile) promises.push(populateGroupEvents()); $q.all(promises).then(function () { logger.debug('performed total of', promises.length); notify.clearBusy(); }); }] ); /* concatenated from client/src/app/js/committee.js */ angular.module('ekwgApp') .controller('CommitteeController', ["$rootScope", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "<API key>", "MemberService", "<API key>", "<API key>", "<API key>", "<API key>", "<API key>", "MailchimpConfig", "Notifier", "EKWGFileUpload", "<API key>", "<API key>", "ModalService", function ($rootScope, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, <API key>, MemberService, <API key>, <API key>, <API key>, <API key>, <API key>, MailchimpConfig, Notifier, EKWGFileUpload, <API key>, <API key>, ModalService) { var logger = $log.getInstance('CommitteeController'); $log.logLevels['CommitteeController'] = $log.LEVEL.OFF; var notify = Notifier($scope); notify.setBusy(); $scope.emailingInProgress = false; $scope.<API key> = <API key>.baseUrl('committeeFiles'); $scope.destinationType = ''; $scope.members = []; $scope.committeeFiles = []; $scope.alertMessages = []; $scope.allowConfirmDelete = false; $scope.latestYearOpen = true; $scope.<API key> = <API key>; $scope.selected = { addingNewFile: false, committeeFiles: [] }; $rootScope.$on('<API key>', function () { assignFileTypes(); }); function assignFileTypes() { $scope.fileTypes = <API key>.fileTypes; logger.debug('<API key> -> fileTypes ->', $scope.fileTypes); } $scope.userEdits = { saveInProgress: false }; $scope.showAlertMessage = function () { return ($scope.alert.class === 'alert-danger') || $scope.emailingInProgress; }; $scope.latestYear = function () { return <API key>.latestYear($scope.committeeFiles) }; $scope.<API key> = function (year) { return <API key>.<API key>(year, $scope.committeeFiles) }; $scope.isActive = function (committeeFile) { return committeeFile === $scope.selected.committeeFile; }; $scope.eventDateCalendar = { open: function ($event) { $scope.eventDateCalendar.opened = true; } }; $scope.allowSend = function () { return <API key>.allowFileAdmin(); }; $scope.<API key> = function () { return $scope.fileTypes && <API key>.allowFileAdmin(); }; $scope.<API key> = function (committeeFile) { return $scope.<API key>() && committeeFile && committeeFile.$id(); }; $scope.<API key> = function (committeeFile) { return $scope.<API key>(committeeFile); }; $scope.cancelFileChange = function () { $q.when($scope.<API key>()).then(<API key>).then(notify.clearBusy); }; $scope.saveCommitteeFile = function () { $scope.userEdits.saveInProgress = true; $scope.selected.committeeFile.eventDate = DateUtils.asValueNoTime($scope.selected.committeeFile.eventDate); logger.debug('saveCommitteeFile ->', $scope.selected.committeeFile); return $scope.selected.committeeFile.$saveOrUpdate(notify.success, notify.success, notify.error, notify.error) .then($scope.<API key>) .then(<API key>) .then(notify.clearBusy) .catch(handleError); function handleError(errorResponse) { $scope.userEdits.saveInProgress = false; notify.error({ title: 'Your changes could not be saved', message: (errorResponse && errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } }; var <API key> = function () { return _.clone({ "createdDate": DateUtils.nowAsValue(), "fileType": $scope.fileTypes && $scope.fileTypes[0].description, "fileNameData": {} }) }; function <API key>() { $scope.allowConfirmDelete = false; $scope.selected.addingNewFile = false; $scope.userEdits.saveInProgress = false; } $scope.deleteCommitteeFile = function () { $scope.allowConfirmDelete = true; }; $scope.<API key> = function () { <API key>(); }; $scope.<API key> = function () { $scope.userEdits.saveInProgress = true; function <API key>() { return notify.success('File was deleted successfully'); } $scope.selected.committeeFile.$remove(<API key>, <API key>, notify.error, notify.error) .then($scope.<API key>) .then(<API key>) .then(<API key>) .then(notify.clearBusy); }; $scope.selectCommitteeFile = function (committeeFile, committeeFiles) { if (!$scope.selected.addingNewFile) { $scope.selected.committeeFile = committeeFile; $scope.selected.committeeFiles = committeeFiles; } }; $scope.editCommitteeFile = function () { <API key>(); delete $scope.uploadedFile; $('#file-detail-dialog').modal('show'); }; $scope.openMailchimp = function () { $window.open(<API key>.apiServer + "/campaigns", '_blank'); }; $scope.openSettings = function () { ModalService.showModal({ templateUrl: "partials/committee/<API key>.html", controller: "<API key>", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; $scope.sendNotification = function (committeeFile) { ModalService.showModal({ templateUrl: "partials/committee/<API key>.html", controller: "<API key>", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, inputs: { committeeFile: committeeFile } }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; $scope.<API key> = function () { $('#<API key>').modal('hide'); $scope.resubmit = false; }; $scope.addCommitteeFile = function ($event) { $event.stopPropagation(); $scope.selected.addingNewFile = true; var committeeFile = new <API key>(<API key>()); $scope.selected.committeeFiles.push(committeeFile); $scope.selected.committeeFile = committeeFile; logger.debug('addCommitteeFile:', committeeFile, 'of', $scope.selected.committeeFiles.length, 'files'); $scope.editCommitteeFile(); }; $scope.<API key> = function () { <API key>(); $('#file-detail-dialog').modal('hide'); }; $scope.attachFile = function (file) { $scope.oldTitle = $scope.selected.committeeFile.fileNameData ? $scope.selected.committeeFile.fileNameData.title : file.name; logger.debug('then:attachFile:oldTitle', $scope.oldTitle); $('#hidden-input').click(); }; $scope.onFileSelect = function (file) { if (file) { $scope.userEdits.saveInProgress = true; logger.debug('onFileSelect:file:about to upload ->', file); $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, 'committeeFiles') .then(function (fileNameData) { logger.debug('onFileSelect:file:upload complete -> fileNameData', fileNameData); $scope.selected.committeeFile.fileNameData = fileNameData; $scope.selected.committeeFile.fileNameData.title = $scope.oldTitle || file.name; $scope.userEdits.saveInProgress = false; }); } }; $scope.attachmentTitle = function () { return ($scope.selected.committeeFile && _.isEmpty($scope.selected.committeeFile.fileNameData) ? 'Attach' : 'Replace') + ' File'; }; $scope.fileUrl = function (committeeFile) { return committeeFile && committeeFile.fileNameData ? URLService.baseUrl() + $scope.<API key> + '/' + committeeFile.fileNameData.awsFileName : ''; }; $scope.fileTitle = function (committeeFile) { return committeeFile ? DateUtils.asString(committeeFile.eventDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + committeeFile.fileNameData.title : ''; }; $scope.iconFile = function (committeeFile) { if (!committeeFile.fileNameData) return undefined; function fileExtensionIs(fileName, extensions) { return _.contains(extensions, fileExtension(fileName)); } function fileExtension(fileName) { return fileName ? _.last(fileName.split('.')).toLowerCase() : ''; } if (fileExtensionIs(committeeFile.fileNameData.awsFileName, ['doc', 'docx', 'jpg', 'pdf', 'ppt', 'png', 'txt', 'xls', 'xlsx'])) { return 'icon-' + fileExtension(committeeFile.fileNameData.awsFileName).substring(0, 3) + '.jpg'; } else { return 'icon-default.jpg'; } }; $scope.$on('memberLoginComplete', function () { refreshAll(); }); $scope.$on('<API key>', function () { refreshAll(); }); function refreshMembers() { function <API key>(members) { $scope.members = members; return $scope.members; } if (<API key>.allowFileAdmin()) { return MemberService.all() .then(<API key>); } } function <API key>() { <API key>.committeeFiles(notify).then(function (files) { logger.debug('committeeFiles', files); if (URLService.hasRouteParameter('committeeFileId')) { $scope.committeeFiles = _.filter(files, function (file) { return file.$id() === $routeParams.committeeFileId; }); } else { $scope.committeeFiles = files; } $scope.committeeFileYears = <API key>.committeeFileYears($scope.committeeFiles); }); } function refreshAll() { <API key>(); refreshMembers(); } assignFileTypes(); refreshAll(); }]); /* concatenated from client/src/app/js/committeeData.js */ angular.module('ekwgApp') .factory('CommitteeConfig', ["Config", function (Config) { function getConfig() { return Config.getConfig('committee', { committee: { contactUs: { chairman: {description: 'Chairman', fullName: 'Claire Mansfield', email: 'chairman@ekwg.co.uk'}, secretary: {description: 'Secretary', fullName: 'Kerry O\'Grady', email: 'secretary@ekwg.co.uk'}, treasurer: {description: 'Treasurer', fullName: 'Marianne Christensen', email: 'treasurer@ekwg.co.uk'}, membership: {description: 'Membership', fullName: 'Desiree Nel', email: 'membership@ekwg.co.uk'}, social: {description: 'Social Co-ordinator', fullName: 'Suzanne Graham Beer', email: 'social@ekwg.co.uk'}, walks: {description: 'Walks Co-ordinator', fullName: 'Stuart Maisner', email: 'walks@ekwg.co.uk'}, support: {description: 'Technical Support', fullName: 'Nick Barrett', email: 'nick.barrett@ekwg.co.uk'} }, fileTypes: [ {description: "AGM Agenda", public: true}, {description: "AGM Minutes", public: true}, {description: "Committee Meeting Agenda"}, {description: "Committee Meeting Minutes"}, {description: "Financial Statements", public: true} ] } }) } function saveConfig(config, saveCallback, errorSaveCallback) { return Config.saveConfig('committee', config, saveCallback, errorSaveCallback); } return { getConfig: getConfig, saveConfig: saveConfig } }]) .factory('<API key>', ["$<API key>", function ($<API key>) { return $<API key>('committeeFiles'); }]) .factory('<API key>', ["$rootScope", function ($rootScope) { var refData = { contactUsRoles: function () { var keys = _.keys(refData.contactUs); if (keys.length > 0) { return keys; } }, contactUsField: function (role, field) { return refData.contactUs && refData.contactUs[role][field] }, fileTypesField: function (type, field) { return refData.fileTypes && refData.fileTypes[type][field] }, toFileType: function (fileTypeDescription, fileTypes) { return _.find(fileTypes, {description: fileTypeDescription}); }, <API key>: function () { return _.map(refData.contactUs, function (data, type) { return { type: type, fullName: data.fullName, memberId: data.memberId, description: data.description + ' (' + data.fullName + ')', email: data.email }; }); } }; $rootScope.$on('<API key>', function () { refData.ready = true; }); return refData; }]) .factory('<API key>', ["$q", "$log", "$filter", "$routeParams", "URLService", "<API key>", "<API key>", "DateUtils", "<API key>", "WalksService", "SocialEventsService", function ($q, $log, $filter, $routeParams, URLService, <API key>, <API key>, DateUtils, <API key>, WalksService, SocialEventsService) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; function groupEvents(groupEvents) { logger.debug('groupEvents', groupEvents); var fromDate = DateUtils.convertDateField(groupEvents.fromDate); var toDate = DateUtils.convertDateField(groupEvents.toDate); logger.debug('groupEvents:fromDate', $filter('displayDate')(fromDate), 'toDate', $filter('displayDate')(toDate)); var events = []; var promises = []; if (groupEvents.includeWalks) promises.push( WalksService.query({walkDate: {$gte: fromDate, $lte: toDate}}) .then(function (walks) { return _.map(walks, function (walk) { return events.push({ id: walk.$id(), selected: true, eventType: 'Walk', area: 'walks', type: 'walk', eventDate: walk.walkDate, eventTime: walk.startTime, distance: walk.distance, postcode: walk.postcode, title: walk.<API key> || 'Awaiting walk details', description: walk.longerDescription, contactName: walk.displayName || 'Awaiting walk leader', contactPhone: walk.contactPhone, contactEmail: walk.contactEmail }); }) })); if (groupEvents.<API key>) promises.push( <API key>.query({eventDate: {$gte: fromDate, $lte: toDate}}) .then(function (committeeFiles) { return _.map(committeeFiles, function (committeeFile) { return events.push({ id: committeeFile.$id(), selected: true, eventType: 'AGM & Committee', area: 'committee', type: 'committeeFile', eventDate: committeeFile.eventDate, postcode: committeeFile.postcode, description: committeeFile.fileType, title: committeeFile.fileNameData.title }); }) })); if (groupEvents.includeSocialEvents) promises.push( SocialEventsService.query({eventDate: {$gte: fromDate, $lte: toDate}}) .then(function (socialEvents) { return _.map(socialEvents, function (socialEvent) { return events.push({ id: socialEvent.$id(), selected: true, eventType: 'Social Event', area: 'social', type: 'socialEvent', eventDate: socialEvent.eventDate, eventTime: socialEvent.eventTimeStart, postcode: socialEvent.postcode, title: socialEvent.briefDescription, description: socialEvent.longerDescription, contactName: socialEvent.displayName, contactPhone: socialEvent.contactPhone, contactEmail: socialEvent.contactEmail }); }) })); return $q.all(promises).then(function () { logger.debug('performed total of', promises.length, 'events of length', events.length); return _.chain(events) .sortBy('eventDate') .value(); }); } function <API key>(committeeFiles) { return _.chain(committeeFiles) .sortBy('eventDate') .reverse() .value(); } function latestYear(committeeFiles) { return _.first( _.chain(<API key>(committeeFiles)) .pluck('eventDate') .map(function (eventDate) { return parseInt(DateUtils.asString(eventDate, undefined, 'YYYY')); }) .value()); } function <API key>(year, committeeFiles) { var latestYearValue = latestYear(committeeFiles); return _.filter(<API key>(committeeFiles), function (committeeFile) { var fileYear = extractYear(committeeFile); return (fileYear === year) || (!fileYear && (latestYearValue === year)); }); } function extractYear(committeeFile) { return parseInt(DateUtils.asString(committeeFile.eventDate, undefined, 'YYYY')); } function committeeFileYears(committeeFiles) { var latestYearValue = latestYear(committeeFiles); function addLatestYearFlag(committeeFileYear) { return {year: committeeFileYear, latestYear: latestYearValue === committeeFileYear}; } var years = _.chain(committeeFiles) .map(extractYear) .unique() .sort() .map(addLatestYearFlag) .reverse() .value(); logger.debug('committeeFileYears', years); return years.length === 0 ? [{year: latestYear(committeeFiles), latestYear: true}] : years; } function committeeFiles(notify) { notify.progress('Refreshing Committee files...'); function queryCommitteeFiles() { if (URLService.hasRouteParameter('committeeFileId')) { return <API key>.getById($routeParams.committeeFileId) .then(function (committeeFile) { if (!committeeFile) notify.error('Committee file could not be found. Try opening again from the link in the notification email'); return [committeeFile]; }); } else { return <API key>.all().then(function (files) { return <API key>(files); }); } } return queryCommitteeFiles() .then(function (committeeFiles) { notify.progress('Found ' + committeeFiles.length + ' committee file(s)'); notify.setReady(); return _.chain(committeeFiles) .sortBy('fileDate') .reverse() .sortBy('createdDate') .value(); }, notify.error); } function <API key>(files) { logger.debug('<API key> files ->', files); var filteredFiles = _.filter(files, function (file) { return <API key>.fileTypes && <API key>.toFileType(file.fileType, <API key>.fileTypes).public || <API key>.allowCommittee() || <API key>.allowFileAdmin(); }); logger.debug('<API key> in ->', files && files.length, 'out ->', filteredFiles.length, '<API key>.fileTypes', <API key>.fileTypes); return filteredFiles } return { groupEvents: groupEvents, committeeFiles: committeeFiles, latestYear: latestYear, committeeFileYears: committeeFileYears, <API key>: <API key> } }] ); /* concatenated from client/src/app/js/<API key>.js */ angular.module('ekwgApp') .controller('<API key>', ["$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "<API key>", "MemberService", "<API key>", "<API key>", "<API key>", "<API key>", "<API key>", "MailchimpConfig", "Notifier", "close", function ($window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, <API key>, MemberService, <API key>, <API key>, <API key>, <API key>, <API key>, MailchimpConfig, Notifier, close) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; $scope.notify = {}; $scope.campaigns = []; var notify = Notifier($scope.notify); var campaignSearchTerm = 'Master'; notify.setBusy(); notify.progress({ title: 'Mailchimp Campaigns', message: 'Getting campaign information matching "' + campaignSearchTerm + '"' }); $scope.notReady = function () { return $scope.campaigns.length === 0; }; MailchimpConfig.getConfig() .then(function (config) { $scope.config = config; logger.debug('retrieved config', $scope.config); }); <API key>.list({ limit: 1000, concise: true, status: 'save', title: campaignSearchTerm }).then(function (response) { $scope.campaigns = response.data; logger.debug('response.data', response.data); notify.success({ title: 'Mailchimp Campaigns', message: 'Found ' + $scope.campaigns.length + ' draft campaigns matching "' + campaignSearchTerm + '"' }); notify.clearBusy(); }); $scope.editCampaign = function (campaignId) { if (!campaignId) { notify.error({ title: 'Edit Mailchimp Campaign', message: 'Please select a campaign from the drop-down before choosing edit' }); } else { notify.hide(); var webId = _.find($scope.campaigns, function (campaign) { return campaign.id === campaignId; }).web_id; logger.debug('editCampaign:campaignId', campaignId, 'web_id', webId); $window.open(<API key>.apiServer + "/campaigns/edit?id=" + webId, '_blank'); } }; $scope.save = function () { logger.debug('saving config', $scope.config); MailchimpConfig.saveConfig($scope.config).then(close).catch(notify.error); }; $scope.cancel = function () { close(); }; }] ); /* concatenated from client/src/app/js/contentMetaServices.js */ angular.module('ekwgApp') .factory('<API key>', ["ContentMetaData", "$q", function (ContentMetaData, $q) { var baseUrl = function (metaDataPathSegment) { return '/aws/s3/' + metaDataPathSegment; }; var createNewMetaData = function (withDefaults) { if (withDefaults) { return {image: '/(select file)', text: '(Enter title here)'}; } else { return {}; } }; var getMetaData = function (contentMetaDataType) { var task = $q.defer(); ContentMetaData.query({contentMetaDataType: contentMetaDataType}, {limit: 1}) .then(function (results) { if (results && results.length > 0) { task.resolve(results[0]); } else { task.resolve(new ContentMetaData({ contentMetaDataType: contentMetaDataType, baseUrl: baseUrl(contentMetaDataType), files: [createNewMetaData(true)] })); } }, function (response) { task.reject('Query of contentMetaDataType for ' + contentMetaDataType + ' failed: ' + response); }); return task.promise; }; var saveMetaData = function (metaData, saveCallback, errorSaveCallback) { return metaData.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback, errorSaveCallback); }; return { baseUrl: baseUrl, getMetaData: getMetaData, createNewMetaData: createNewMetaData, saveMetaData: saveMetaData } }]) .factory('ContentMetaData', ["$<API key>", function ($<API key>) { return $<API key>('contentMetaData'); }]) .factory('ContentTextService', ["$<API key>", function ($<API key>) { return $<API key>('contentText'); }]) .factory('ContentText', ["ContentTextService", function (ContentTextService) { function forName(name) { return ContentTextService.all().then(function (contentDocuments) { return _.findWhere(contentDocuments, {name: name}) || new ContentTextService({name: name}); }); } return {forName: forName} }]); /* concatenated from client/src/app/js/directives.js */ angular.module('ekwgApp') .directive('contactUs', ["$log", "$compile", "URLService", "<API key>", function ($log, $compile, URLService, <API key>) { var logger = $log.getInstance('contactUs'); $log.logLevels['contactUs'] = $log.LEVEL.OFF; function email(role) { return <API key>.contactUsField(role, 'email'); } function description(role) { return <API key>.contactUsField(role, 'description'); } function fullName(role) { return <API key>.contactUsField(role, 'fullName'); } function createHref(scope, role) { return '<a href="mailto:' + email(role) + '">' + (scope.text || email(role)) + '</a>'; } function createListItem(scope, role) { return '<li ' + 'style="' + 'font-weight: normal;' + 'padding: 4px 0px 4px 21px;' + 'list-style: none;' + 'background-image: url(' + URLService.baseUrl() + '/assets/images/ramblers/bull-green.png);' + 'background-position: 0px 9px;' + 'background-repeat: no-repeat no-repeat">' + fullName(role) + ' - ' + description(role) + ' - ' + '<a href="mailto:' + email(role) + '"' + 'style="' + 'background-color: transparent;' + 'color: rgb(120, 35, 39);' + 'text-decoration: none; ' + 'font-weight: bold; ' + 'background-position: initial; ' + 'background-repeat: initial;">' + (scope.text || email(role)) + '</a>' + '</li>'; } function expandRoles(scope) { var roles = scope.role ? scope.role.split(',') : <API key>.contactUsRoles(); logger.debug('role ->', scope.role, ' roles ->', roles); return _(roles).map(function (role) { if (scope.format === 'list') { return createListItem(scope, role); } else { return createHref(scope, role); } }).join('\n'); } function wrapInUL(scope) { if (scope.format === 'list') { return '<ul style="' + 'margin: 10px 0 0;' + 'padding: 0 0 10px 10px;' + 'font-weight: bold;' + 'background-image: url(' + URLService.baseUrl() + '/assets/images/ramblers/dot-darkgrey-hor.png);' + 'background-position: 0% 100%;' + 'background-repeat: repeat no-repeat;' + 'margin-bottom: 20px;"> ' + (scope.heading || '') + expandRoles(scope) + '</ul>'; } else { return expandRoles(scope); } } return { restrict: 'EA', replace: true, link: function (scope, element) { scope.$watch('name', function () { if (<API key>.ready) { var html = wrapInUL(scope); logger.debug('html before compile ->', html); element.html($compile(html)(scope)); } }); }, scope: { format: '@', text: '@', role: '@', heading: '@' } }; }]); /* concatenated from client/src/app/js/emailerService.js */ angular.module('ekwgApp') .factory('<API key>', ["$rootScope", "$log", "$http", "$q", "MemberService", "DateUtils", "<API key>", function ($rootScope, $log, $http, $q, MemberService, DateUtils, <API key>) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; var <API key> = function (members, subscribedState) { var deferredTask = $q.defer(); var savePromises = []; deferredTask.notify('Resetting Mailchimp subscriptions for ' + members.length + ' members'); _.each(members, function (member) { <API key>(member, subscribedState); savePromises.push(member.$saveOrUpdate()); }); $q.all(savePromises).then(function () { deferredTask.notify('Reset of Mailchimp subscriptions completed. Next member save will resend all lists to Mailchimp'); MemberService.all().then(function (refreshedMembers) { deferredTask.resolve(refreshedMembers); }) }); }; function <API key>(member, subscribedState) { member.mailchimpLists = { "walks": {"subscribed": subscribedState}, "socialEvents": {"subscribed": subscribedState}, "general": {"subscribed": subscribedState} } } function booleanToString(value) { return String(value || false); } function <API key>(member, listType, request) { var <API key> = {email: {}}; <API key>.email.email = member.email; if (member.mailchimpLists[listType].leid) { <API key>.email.leid = member.mailchimpLists[listType].leid; } if (request) { return angular.extend(request, <API key>); } else { return <API key>.email; } } var <API key> = function (listType, members) { var deferredTask = $q.defer(); var progress = 'Sending ' + listType + ' member data to Mailchimp'; deferredTask.notify(progress); var batchedMembers = []; var subscriptionEntries = _.chain(members) .filter(function (member) { return <API key>(listType, member); }) .map(function (member) { batchedMembers.push(member); var request = { "merge_vars": { "FNAME": member.firstName, "LNAME": member.lastName, "MEMBER_NUM": member.membershipNumber, "MEMBER_EXP": DateUtils.displayDate(member.<API key>), "USERNAME": member.userName, "PW_RESET": member.passwordResetId || '' } }; return <API key>(member, listType, request); }).value(); if (subscriptionEntries.length > 0) { var url = '/mailchimp/lists/' + listType + '/batchSubscribe'; logger.debug('sending', subscriptionEntries.length, listType, 'subscriptions to mailchimp', subscriptionEntries); $http({method: 'POST', url: url, data: subscriptionEntries}) .then(function (response) { var responseData = response.data; logger.debug('received response', responseData); var errorObject = <API key>.extractError(responseData); if (errorObject.error) { var errorResponse = { message: 'Sending of ' + listType + ' list subscription to Mailchimp was not successful', error: errorObject.error }; deferredTask.reject(errorResponse); } else { var totalResponseCount = responseData.updates.concat(responseData.adds).concat(responseData.errors).length; deferredTask.notify('Send of ' + subscriptionEntries.length + ' ' + listType + ' members completed - processing ' + totalResponseCount + ' Mailchimp response(s)'); var savePromises = []; <API key>(listType, responseData.updates.concat(responseData.adds), batchedMembers, savePromises, deferredTask); <API key>(listType, responseData.errors, batchedMembers, savePromises, deferredTask); $q.all(savePromises).then(function () { MemberService.all().then(function (refreshedMembers) { deferredTask.notify('Send of ' + subscriptionEntries.length + ' members to ' + listType + ' list completed with ' + responseData.add_count + ' member(s) added, ' + responseData.update_count + ' updated and ' + responseData.error_count + ' error(s)'); deferredTask.resolve(refreshedMembers); }) }); } }).catch(function (response) { var data = response.data; var errorMessage = 'Sending of ' + listType + ' member data to Mailchimp was not successful due to response: ' + data.trim(); logger.error(errorMessage); deferredTask.reject(errorMessage); }) } else { deferredTask.notify('No ' + listType + ' updates to send Mailchimp'); MemberService.all().then(function (refreshedMembers) { deferredTask.resolve(refreshedMembers); }); } return deferredTask.promise; }; function <API key>(listType, member) { if (member.email && member.mailchimpLists[listType].subscribed) { if (listType === 'socialEvents') { return member.groupMember && member.socialMember; } else { return member.groupMember; } } else { return false; } } function <API key>(listType, member) { return <API key>(listType, member) && !member.mailchimpLists[listType].updated; } function <API key>(listType, member) { if (!member || !member.groupMember) { return true; } else if (member.mailchimpLists) { if (listType === 'socialEvents') { return (!member.socialMember && member.mailchimpLists[listType].subscribed); } else { return (!member.mailchimpLists[listType].subscribed); } } else { return false; } } function <API key>(listType, allMembers, subscriber) { return <API key>(listType, responseToMember(listType, allMembers, subscriber)); } function <API key>(member) { // updated == false means not up to date with mail e.g. next list update will send this data to mailchimo member.mailchimpLists.walks.updated = false; member.mailchimpLists.socialEvents.updated = false; member.mailchimpLists.general.updated = false; } function responseToMember(listType, allMembers, mailchimpResponse) { return _(allMembers).find(function (member) { var <API key> = mailchimpResponse.leid && member.mailchimpLists[listType].leid && (mailchimpResponse.leid.toString() === member.mailchimpLists[listType].leid.toString()); var <API key> = member.mailchimpLists[listType].email && (mailchimpResponse.email.toLowerCase() === member.mailchimpLists[listType].email.toLowerCase()); var <API key> = member.email && mailchimpResponse.email.toLowerCase() === member.email.toLowerCase(); return (<API key> || <API key> || <API key>); }); } function <API key>(listType, batchedMembers, response, deferredTask) { var member = responseToMember(listType, batchedMembers, response); if (member) { member.mailchimpLists[listType].leid = response.leid; member.mailchimpLists[listType].updated = true; // updated == true means up to date e.g. nothing to send to mailchimo member.mailchimpLists[listType].lastUpdated = DateUtils.nowAsValue(); member.mailchimpLists[listType].email = member.email; } else { deferredTask.notify('From ' + batchedMembers.length + ' members, could not find any member related to response ' + JSON.stringify(response)); } return member; } function <API key>(listType, validResponses, batchedMembers, savePromises, deferredTask) { _.each(validResponses, function (response) { var member = <API key>(listType, batchedMembers, response, deferredTask); if (member) { delete member.mailchimpLists[listType].code; delete member.mailchimpLists[listType].error; deferredTask.notify('processing valid response for member ' + member.email); savePromises.push(member.$saveOrUpdate()); } }); } function <API key>(listType, errorResponses, batchedMembers, savePromises, deferredTask) { _.each(errorResponses, function (response) { var member = <API key>(listType, batchedMembers, response.email, deferredTask); if (member) { deferredTask.notify('processing error response for member ' + member.email); member.mailchimpLists[listType].code = response.code; member.mailchimpLists[listType].error = response.error; if (_.contains([210, 211, 212, 213, 214, 215, 220, 250], response.code)) member.mailchimpLists[listType].subscribed = false; savePromises.push(member.$saveOrUpdate()); } }); } return { responseToMember: responseToMember, <API key>: <API key>, <API key>: <API key>, <API key>: <API key>, <API key>: <API key>, <API key>: <API key>, <API key>: <API key>, <API key>: <API key>, <API key>: <API key> } }]); /* concatenated from client/src/app/js/expenses.js */ angular.module('ekwgApp') .controller('ExpensesController', ["$compile", "$log", "$timeout", "$sce", "$templateRequest", "$q", "$rootScope", "$location", "$routeParams", "$scope", "$filter", "DateUtils", "NumberUtils", "URLService", "<API key>", "MemberService", "<API key>", "<API key>", "<API key>", "<API key>", "MailchimpConfig", "Notifier", "EKWGFileUpload", function ($compile, $log, $timeout, $sce, $templateRequest, $q, $rootScope, $location, $routeParams, $scope, $filter, DateUtils, NumberUtils, URLService, <API key>, MemberService, <API key>, <API key>, <API key>, <API key>, MailchimpConfig, Notifier, EKWGFileUpload) { var logger = $log.getInstance('ExpensesController'); var noLogger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; $log.logLevels['ExpensesController'] = $log.LEVEL.OFF; const SELECTED_EXPENSE = 'Expense from last email link'; $scope.receiptBaseUrl = <API key>.baseUrl('expenseClaims'); $scope.dataError = false; $scope.members = []; $scope.expenseClaims = []; $scope.<API key> = []; $scope.expensesOpen = URLService.hasRouteParameter('expenseId') || URLService.isArea('expenses'); $scope.alertMessages = []; $scope.filterTypes = [{ disabled: !$routeParams.expenseId, description: SELECTED_EXPENSE, filter: function (expenseClaim) { if ($routeParams.expenseId) { return expenseClaim && expenseClaim.$id() === $routeParams.expenseId; } else { return false; } } }, { description: 'Unpaid expenses', filter: function (expenseClaim) { return !$scope.expenseClaimStatus(expenseClaim).atEndpoint; } }, { description: 'Paid expenses', filter: function (expenseClaim) { return $scope.expenseClaimStatus(expenseClaim).atEndpoint; } }, { description: 'Expenses awaiting action from me', filter: function (expenseClaim) { return <API key>.allowFinanceAdmin() ? editable(expenseClaim) : editableAndOwned(expenseClaim); } }, { description: 'All expenses', filter: function () { return true; } }]; $scope.selected = { showOnlyMine: !allowAdminFunctions(), saveInProgress: false, expenseClaimIndex: 0, expenseItemIndex: 0, expenseFilter: $scope.filterTypes[$routeParams.expenseId ? 0 : 1] }; $scope.itemAlert = {}; var notify = Notifier($scope); var notifyItem = Notifier($scope.itemAlert); notify.setBusy(); var <API key> = 'partials/expenses/notifications'; <API key>.<API key>('expenseId'); $scope.showArea = function (area) { URLService.navigateTo('admin', area) }; $scope.selected.expenseClaim = function () { try { return $scope.expenseClaims[$scope.selected.expenseClaimIndex]; } catch (e) { console.error(e); } }; $scope.isInactive = function (expenseClaim) { return expenseClaim !== $scope.selected.expenseClaim(); }; $scope.selected.expenseItem = function () { try { var expenseClaim = $scope.expenseClaims[$scope.selected.expenseClaimIndex]; return expenseClaim ? expenseClaim.expenseItems[$scope.selected.expenseItemIndex] : undefined; } catch (e) { console.error(e); } }; $scope.expenseTypes = [ {value: "travel-reccie", name: "Travel (walk reccie)", travel: true}, {value: "travel-committee", name: "Travel (attend committee meeting)", travel: true}, {value: "other", name: "Other"}]; var eventTypes = { created: {description: "Created", editable: true}, submitted: {description: "Submitted", actionable: true, notifyCreator: true, notifyApprover: true}, 'first-approval': {description: "First Approval", actionable: true, notifyApprover: true}, 'second-approval': { description: "Second Approval", actionable: true, notifyCreator: true, notifyApprover: true, notifyTreasurer: true }, returned: {description: "Returned", atEndpoint: false, editable: true, notifyCreator: true, notifyApprover: true}, paid: {description: "Paid", atEndpoint: true, notifyCreator: true, notifyApprover: true, notifyTreasurer: true} }; var defaultExpenseClaim = function () { return _.clone({ "cost": 0, "expenseItems": [], "expenseEvents": [] }) }; var defaultExpenseItem = function () { return _.clone({ expenseType: $scope.expenseTypes[0], "travel": { "costPerMile": 0.28, "miles": 0, "from": '', "to": '', "returnJourney": true } }); }; function editable(expenseClaim) { return memberCanEditClaim(expenseClaim) && $scope.expenseClaimStatus(expenseClaim).editable; } function editableAndOwned(expenseClaim) { return memberOwnsClaim(expenseClaim) && $scope.expenseClaimStatus(expenseClaim).editable; } $scope.editable = function () { return editable($scope.selected.expenseClaim()); }; $scope.allowClearError = function () { return URLService.hasRouteParameter('expenseId') && $scope.dataError; }; $scope.<API key> = function () { return !$scope.dataError && !_.find($scope.<API key>, editableAndOwned); }; $scope.allowFinanceAdmin = function () { return <API key>.allowFinanceAdmin(); }; $scope.<API key> = function () { return $scope.allowAddExpenseItem() && $scope.selected.expenseItem() && $scope.selected.expenseClaim().$id(); }; $scope.allowAddExpenseItem = function () { return $scope.editable(); }; $scope.<API key> = function () { return $scope.<API key>(); }; $scope.<API key> = function () { return !$scope.<API key>() && $scope.allowAddExpenseItem(); }; $scope.<API key> = function () { return $scope.<API key>() && !$scope.<API key>(); }; function allowAdminFunctions() { return <API key>.allowTreasuryAdmin() || <API key>.allowFinanceAdmin(); } $scope.allowAdminFunctions = function () { return allowAdminFunctions(); }; $scope.<API key> = function () { return $scope.allowAdminFunctions() && $scope.selected.expenseClaim() && <API key>($scope.selected.expenseClaim(), eventTypes.submitted) && !<API key>($scope.selected.expenseClaim(), eventTypes.returned) && $scope.expenseClaimStatus($scope.selected.expenseClaim()).actionable; }; $scope.<API key> = function () { return $scope.editable() && <API key>($scope.selected.expenseClaim(), eventTypes.returned); }; $scope.<API key> = function () { return <API key>.allowTreasuryAdmin() && _.contains( [eventTypes.submitted.description, eventTypes['second-approval'].description, eventTypes['first-approval'].description], $scope.<API key>().eventType.description); }; function activeEvents(optionalEvents) { var events = optionalEvents || $scope.selected.expenseClaim().expenseEvents; var latestReturnedEvent = _.find(events.reverse(), function (event) { return _.isEqual(event.eventType, $scope.expenseClaimStatus.returned); }); return latestReturnedEvent ? events.slice(events.indexOf(latestReturnedEvent + 1)) : events; } function <API key>(expenseClaim, eventType) { if (!expenseClaim) return false; return eventForEventType(expenseClaim, eventType); } function eventForEventType(expenseClaim, eventType) { if (expenseClaim) return _.find(expenseClaim.expenseEvents, function (event) { return _.isEqual(event.eventType, eventType); }); } $scope.<API key> = function () { return false; }; $scope.lastApprovedByMe = function () { var approvalEvents = $scope.approvalEvents(); return approvalEvents.length > 0 && _.last(approvalEvents).memberId === <API key>.loggedInMember().memberId; }; $scope.approvalEvents = function () { if (!$scope.selected.expenseClaim()) return []; return _.filter($scope.selected.expenseClaim().expenseEvents, function (event) { return _.isEqual(event.eventType, eventTypes['first-approval']) || _.isEqual(event.eventType, eventTypes['second-approval']); }); }; $scope.expenseClaimStatus = function (<API key>) { var expenseClaim = <API key> || $scope.selected.expenseClaim(); return $scope.<API key>(expenseClaim).eventType; }; $scope.<API key> = function (<API key>) { var expenseClaim = <API key> || $scope.selected.expenseClaim(); return expenseClaim ? _.last(expenseClaim.expenseEvents) : {}; }; $scope.nextApprovalStage = function () { var approvals = $scope.approvalEvents(); if (approvals.length === 0) { return 'First Approval'; } else if (approvals.length === 1) { return 'Second Approval' } else { return 'Already has ' + approvals.length + ' approvals!'; } }; $scope.<API key> = function () { var approvals = $scope.approvalEvents(); notifyItem.hide(); if (approvals.length === 0) { <API key>(eventTypes['first-approval']); } else if (approvals.length === 1) { <API key>(eventTypes['second-approval']); } else { notify.error('This expense claim already has ' + approvals.length + ' approvals!'); } }; $scope.<API key> = function () { $scope.dataError = false; $location.path('/admin/expenses') }; $scope.addExpenseClaim = function () { $scope.expenseClaims.unshift(new <API key>(defaultExpenseClaim())); $scope.selectExpenseClaim(0); createEvent(eventTypes.created); $scope.addExpenseItem(); }; $scope.selectExpenseItem = function (index) { if ($scope.selected.saveInProgress) { noLogger.info('selectExpenseItem - selected.saveInProgress - not changing to index', index); } else { noLogger.info('selectExpenseItem:', index); $scope.selected.expenseItemIndex = index; } }; $scope.selectExpenseClaim = function (index) { if ($scope.selected.saveInProgress) { noLogger.info('selectExpenseClaim - selected.saveInProgress - not changing to index', index); } else { $scope.selected.expenseClaimIndex = index; var expenseClaim = $scope.selected.expenseClaim(); noLogger.info('selectExpenseClaim:', index, expenseClaim); } }; $scope.editExpenseItem = function () { $scope.removeConfirm(); delete $scope.uploadedFile; $('#<API key>').modal('show'); }; $scope.hideExpenseClaim = function () { $scope.removeConfirm(); $('#<API key>').modal('hide'); }; $scope.addReceipt = function () { $('#hidden-input').click(); }; $scope.removeReceipt = function () { delete $scope.selected.expenseItem().receipt; delete $scope.uploadedFile; }; $scope.receiptTitle = function (expenseItem) { return expenseItem && expenseItem.receipt ? (expenseItem.receipt.title || expenseItem.receipt.originalFileName) : ''; }; function baseUrl() { return _.first($location.absUrl().split('/ } $scope.receiptUrl = function (expenseItem) { return expenseItem && expenseItem.receipt ? baseUrl() + $scope.receiptBaseUrl + '/' + expenseItem.receipt.awsFileName : ''; }; $scope.onFileSelect = function (file) { if (file) { $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, 'expenseClaims') .then(function (fileNameData) { var expenseItem = $scope.selected.expenseItem(); var oldTitle = (expenseItem.receipt && expenseItem.receipt.title) ? receipt.title : undefined; expenseItem.receipt = fileNameData; expenseItem.receipt.title = oldTitle; }); } }; function createEvent(eventType, reason) { var expenseClaim = $scope.selected.expenseClaim(); if (!expenseClaim.expenseEvents) expenseClaim.expenseEvents = []; var event = { "date": DateUtils.nowAsValue(), "memberId": <API key>.loggedInMember().memberId, "eventType": eventType }; if (reason) event.reason = reason; expenseClaim.expenseEvents.push(event); } $scope.addExpenseItem = function () { $scope.removeConfirm(); var newExpenseItem = defaultExpenseItem(); $scope.selected.expenseClaim().expenseItems.push(newExpenseItem); var index = $scope.selected.expenseClaim().expenseItems.indexOf(newExpenseItem); if (index > -1) { $scope.selectExpenseItem(index); $scope.editExpenseItem(); } else { <API key>('Could not display new expense item') } }; $scope.expenseTypeChange = function () { logger.debug('$scope.selected.expenseItem().expenseType', $scope.selected.expenseItem().expenseType); if ($scope.selected.expenseItem().expenseType.travel) { if (!$scope.selected.expenseItem().travel) $scope.selected.expenseItem().travel = defaultExpenseItem().travel; } else { delete $scope.selected.expenseItem().travel; } $scope.<API key>(); }; $scope.expenseDateCalendar = { open: function ($event) { $scope.expenseDateCalendar.opened = true; } }; function <API key>() { $scope.selected.expenseClaim().cost = $filter('sumValues')($scope.selected.expenseClaim().expenseItems, 'cost'); } $scope.cancelExpenseChange = function () { $scope.refreshExpenses().then($scope.hideExpenseClaim).then(notify.clearBusy); }; function <API key>(message) { var messageDefaulted = message || 'Please try this again.'; notify.error('Your expense claim could not be saved. ' + messageDefaulted); $scope.selected.saveInProgress = false; } function <API key>(message) { $scope.selected.saveInProgress = false; notify.error('Your expense claim email processing failed. ' + message); } function <API key>(message, busy) { notify.progress(message, busy); } function <API key>(message, busy) { notify.success(message, busy); } $scope.saveExpenseClaim = function (<API key>) { $scope.selected.saveInProgress = true; function showExpenseSaved(data) { $scope.expenseClaims[$scope.selected.expenseClaimIndex] = data; $scope.selected.saveInProgress = false; return notify.success('Expense was saved successfully'); } <API key>('Saving expense claim', true); $scope.<API key>(); return (<API key> || $scope.selected.expenseClaim()).$saveOrUpdate(showExpenseSaved, showExpenseSaved, <API key>, <API key>) .then($scope.hideExpenseClaim) .then(notify.clearBusy); }; $scope.approveExpenseClaim = function () { $scope.confirmAction = {approve: true}; if ($scope.lastApprovedByMe()) notifyItem.warning({ title: 'Duplicate approval warning', message: 'You were the previous approver, therefore ' + $scope.nextApprovalStage() + ' ought to be carried out by someone else. Are you sure you want to do this?' }); }; $scope.deleteExpenseClaim = function () { $scope.confirmAction = {delete: true}; }; $scope.deleteExpenseItem = function () { $scope.confirmAction = {delete: true}; }; $scope.<API key> = function () { $scope.selected.saveInProgress = true; <API key>('Deleting expense item', true); var expenseItem = $scope.selected.expenseItem(); logger.debug('removing', expenseItem); var index = $scope.selected.expenseClaim().expenseItems.indexOf(expenseItem); if (index > -1) { $scope.selected.expenseClaim().expenseItems.splice(index, 1); } else { <API key>('Could not delete expense item') } $scope.selectExpenseItem(0); <API key>(); $scope.saveExpenseClaim() .then($scope.removeConfirm) .then(notify.clearBusy); }; $scope.removeConfirm = function () { delete $scope.confirmAction; <API key>(); }; $scope.<API key> = function () { <API key>('Deleting expense claim', true); function showExpenseDeleted() { return <API key>('Expense was deleted successfully'); } $scope.selected.expenseClaim().$remove(showExpenseDeleted, showExpenseDeleted, <API key>, <API key>) .then($scope.hideExpenseClaim) .then(showExpenseDeleted) .then($scope.refreshExpenses) .then($scope.removeConfirm) .then(notify.clearBusy); }; $scope.submitExpenseClaim = function (state) { $scope.resubmit = state; $('#submit-dialog').modal('show'); }; function hideSubmitDialog() { $('#submit-dialog').modal('hide'); $scope.resubmit = false; } $scope.<API key> = function () { hideSubmitDialog(); }; $scope.returnExpenseClaim = function () { $('#return-dialog').modal('show'); }; $scope.<API key> = function (reason) { hideReturnDialog(); return <API key>(eventTypes.returned, reason); }; function hideReturnDialog() { $('#return-dialog').modal('hide'); } $scope.<API key> = function () { hideReturnDialog(); }; $scope.paidExpenseClaim = function () { $('#paid-dialog').modal('show'); }; $scope.<API key> = function () { <API key>(eventTypes.paid) .then(hidePaidDialog); }; function hidePaidDialog() { $('#paid-dialog').modal('hide'); } $scope.<API key> = function () { hidePaidDialog(); }; $scope.<API key> = function () { if ($scope.resubmit) $scope.selected.expenseClaim().expenseEvents = [eventForEventType($scope.selected.expenseClaim(), eventTypes.created)]; <API key>(eventTypes.submitted); }; $scope.<API key> = function () { $scope.submitExpenseClaim(true); }; $scope.<API key> = function (<API key>) { return eventForEventType(<API key> || $scope.selected.expenseClaim(), eventTypes.created); }; function <API key>(eventType, reason) { notify.setBusy(); $scope.selected.saveInProgress = true; var expenseClaim = $scope.selected.expenseClaim(); var <API key> = $scope.<API key>(expenseClaim); return $q.when(createEvent(eventType, reason)) .then(<API key>, <API key>) .then($scope.saveExpenseClaim, <API key>, <API key>); function <API key>(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction($scope); $timeout(function () { $scope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function <API key>() { return <API key>.<API key>(<API key>.memberId) .then(function (member) { logger.debug('sendNotification:', 'memberId', <API key>.memberId, 'member', member); var memberFullName = $filter('fullNameWithAlias')(member); return $q.when(<API key>('Preparing to email ' + memberFullName)) .then(hideSubmitDialog, <API key>, <API key>) .then(<API key>, <API key>, <API key>) .then(<API key>, <API key>, <API key>) .then(<API key>, <API key>, <API key>); function <API key>() { if (eventType.notifyCreator) return sendNotificationsTo({ templateUrl: templateForEvent('creator', eventType), memberIds: [<API key>.memberId], segmentType: 'directMail', segmentNameSuffix: '', destination: 'creator' }); return false; } function <API key>() { if (eventType.notifyApprover) return sendNotificationsTo({ templateUrl: templateForEvent('approver', eventType), memberIds: MemberService.<API key>('financeAdmin', $scope.members), segmentType: 'expenseApprover', segmentNameSuffix: 'approval ', destination: 'approvers' }); return false; } function <API key>() { if (eventType.notifyTreasurer) return sendNotificationsTo({ templateUrl: templateForEvent('treasurer', eventType), memberIds: MemberService.<API key>('treasuryAdmin', $scope.members), segmentType: 'expenseTreasurer', segmentNameSuffix: 'payment ', destination: 'treasurer' }); return false; } function templateForEvent(role, eventType) { return <API key> + '/' + role + '/' + eventType.description.toLowerCase().replace(' ', '-') + '-notification.html'; } function sendNotificationsTo(<API key>) { logger.debug('sendNotificationsTo:', <API key>); var campaignName = 'Expense ' + eventType.description + ' notification (to ' + <API key>.destination + ')'; var <API key> = campaignName + ' (' + memberFullName + ')'; var segmentName = 'Expense notification ' + <API key>.segmentNameSuffix + '(' + memberFullName + ')'; if (<API key>.memberIds.length === 0) throw new Error('No members have been configured as ' + <API key>.destination + ' therefore notifications for this step will fail!!'); return $templateRequest($sce.<API key>(<API key>.templateUrl)) .then(<API key>) .then(<API key>) .then(sendNotification(<API key>)) .catch(<API key>); function <API key>(<API key>) { return { sections: { expense_id_url: 'Please click <a href="' + baseUrl() + '/#/admin/expenseId/' + expenseClaim.$id() + '" target="_blank">this link</a> to see the details of the above expense claim, or to make changes to it.', <API key>: <API key> } }; } function sendNotification(<API key>) { return function (contentSections) { return <API key>() .then(<API key>, <API key>, <API key>) .then(sendEmailCampaign, <API key>, <API key>) .then(<API key>, <API key>, <API key>); function <API key>() { return <API key>.saveSegment('general', {segmentId: <API key>.getMemberSegmentId(member, <API key>.segmentType)}, <API key>.memberIds, segmentName, $scope.members); } function <API key>(segmentResponse) { <API key>.setMemberSegmentId(member, <API key>.segmentType, segmentResponse.segment.id); return <API key>.saveMember(member); } function sendEmailCampaign() { <API key>('Sending ' + <API key>); return MailchimpConfig.getConfig() .then(function (config) { var campaignId = config.mailchimp.campaigns.expenseNotification.campaignId; var segmentId = <API key>.getMemberSegmentId(member, <API key>.segmentType); logger.debug('about to <API key> with campaignName', <API key>, 'campaign Id', campaignId, 'segmentId', segmentId); return <API key>.<API key>({ campaignId: campaignId, campaignName: <API key>, contentSections: contentSections, segmentId: segmentId }); }) .then(function () { <API key>('Sending of ' + <API key> + ' was successful', true); }); } function <API key>() { <API key>('Sending of ' + campaignName + ' was successful. Check your inbox for progress.'); } } } } }); } } $scope.<API key> = function () { var expenseItem = $scope.selected.expenseItem(); if (expenseItem) { expenseItem.expenseDate = DateUtils.asValueNoTime(expenseItem.expenseDate); if (expenseItem.travel) expenseItem.travel.miles = NumberUtils.asNumber(expenseItem.travel.miles); expenseItem.description = <API key>(expenseItem); expenseItem.cost = expenseItemCost(expenseItem); } <API key>(); }; $scope.<API key> = function (expenseItem) { if (!expenseItem) return ''; var prefix = expenseItem.expenseType && expenseItem.expenseType.travel ? expenseItem.expenseType.name + ' - ' : ''; return prefix + expenseItem.description; }; function <API key>(expenseItem) { var description; if (!expenseItem) return ''; if (expenseItem.travel && expenseItem.expenseType.travel) { description = [ expenseItem.travel.from, 'to', expenseItem.travel.to, expenseItem.travel.returnJourney ? 'return trip' : 'single trip', '(' + expenseItem.travel.miles, 'miles', expenseItem.travel.returnJourney ? 'x 2' : '', 'x', parseInt(expenseItem.travel.costPerMile * 100) + 'p per mile)' ].join(' '); } else { description = expenseItem.description; } return description; } function expenseItemCost(expenseItem) { var cost; if (!expenseItem) return 0; if (expenseItem.travel && expenseItem.expenseType.travel) { cost = (NumberUtils.asNumber(expenseItem.travel.miles) * (expenseItem.travel.returnJourney ? 2 : 1) * NumberUtils.asNumber(expenseItem.travel.costPerMile)); } else { cost = expenseItem.cost; } noLogger.info(cost, 'from expenseItem=', expenseItem); return NumberUtils.asNumber(cost, 2); } function refreshMembers() { if (<API key>.memberLoggedIn()) { notify.progress('Refreshing member data...'); return MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) { logger.debug('refreshMembers: found', members.length, 'members'); return $scope.members = members; }); } } function memberCanEditClaim(expenseClaim) { if (!expenseClaim) return false; return memberOwnsClaim(expenseClaim) || <API key>.allowFinanceAdmin(); } function memberOwnsClaim(expenseClaim) { if (!expenseClaim) return false; return (<API key>.loggedInMember().memberId === $scope.<API key>(expenseClaim).memberId); } $scope.refreshExpenses = function () { $scope.dataError = false; logger.debug('refreshExpenses started'); notify.setBusy(); notify.progress('Filtering for ' + $scope.selected.expenseFilter.description + '...'); logger.debug('refreshing expenseFilter', $scope.selected.expenseFilter); let noExpenseFound = function () { $scope.dataError = true; return notify.warning({ title: 'Expense claim could not be found', message: 'Try opening again from the link in the notification email, or click Show All Expense Claims' }) }; function query() { if ($scope.selected.expenseFilter.description === SELECTED_EXPENSE && $routeParams.expenseId) { return <API key>.getById($routeParams.expenseId) .then(function (expense) { if (!expense) { return noExpenseFound(); } else { return [expense]; } }) .catch(noExpenseFound); } else { return <API key>.all(); } } return query() .then(function (expenseClaims) { $scope.<API key> = []; $scope.expenseClaims = _.chain(expenseClaims).filter(function (expenseClaim) { return $scope.allowAdminFunctions() ? ($scope.selected.showOnlyMine ? memberOwnsClaim(expenseClaim) : true) : memberCanEditClaim(expenseClaim); }).filter(function (expenseClaim) { $scope.<API key>.push(expenseClaim); return $scope.selected.expenseFilter.filter(expenseClaim); }).sortBy(function (expenseClaim) { var <API key> = $scope.<API key>(expenseClaim); return <API key> ? <API key>.date : true; }).reverse().value(); let outcome = 'Found ' + $scope.expenseClaims.length + ' expense claim(s)'; notify.progress(outcome); logger.debug('refreshExpenses finished', outcome); notify.clearBusy(); return $scope.expenseClaims; }, notify.error) .catch(notify.error); }; $q.when(refreshMembers()) .then($scope.refreshExpenses) .then(notify.setReady) .catch(notify.error); }] ); /* concatenated from client/src/app/js/filters.js */ angular.module('ekwgApp') .factory('FilterUtils', function () { return { nameFilter: function (alias) { return alias ? 'fullNameWithAlias' : 'fullName'; } }; }) .filter('keepLineFeeds', function () { return function (input) { if (!input) return input; return input .replace(/(\r\n|\r|\n)/g, '<br/>') .replace(/\t/g, '&nbsp;&nbsp;&nbsp;') .replace(/ /g, '&nbsp;'); } }) .filter('lineFeedsToBreaks', function () { return function (input) { if (!input) return input; return input .replace(/(\r\n|\r|\n)/g, '<br/>') } }) .filter('displayName', function () { return function (member) { return member === undefined ? null : (member.firstName + ' ' + (member.hideSurname ? '' : member.lastName)).trim(); } }) .filter('fullName', function () { return function (member, defaultValue) { return member === undefined ? defaultValue || '(deleted member)' : (member.firstName + ' ' + member.lastName).trim(); } }) .filter('fullNameWithAlias', ["$filter", function ($filter) { return function (member, defaultValue) { return member ? ($filter('fullName')(member, defaultValue)) + (member.nameAlias ? ' (' + member.nameAlias + ')' : '') : defaultValue; } }]) .filter('<API key>', ["$filter", "<API key>", function ($filter, <API key>) { return function (member, defaultValue, memberId) { return member ? (<API key>.loggedInMember().memberId === member.$id() && member.$id() === memberId ? "Me" : ($filter('fullName')(member, defaultValue)) + (member.nameAlias ? ' (' + member.nameAlias + ')' : '')) : defaultValue; } }]) .filter('firstName', ["$filter", function ($filter) { return function (member, defaultValue) { return s.words($filter('fullName')(member, defaultValue))[0]; } }]) .filter('<API key>', ["$filter", function ($filter) { return function (memberIds, members, defaultValue) { return _(memberIds).map(function (memberId) { return $filter('memberIdToFullName')(memberId, members, defaultValue); }).join(', '); } }]) .filter('memberIdToFullName', ["$filter", "MemberService", "FilterUtils", function ($filter, MemberService, FilterUtils) { return function (memberId, members, defaultValue, alias) { return $filter(FilterUtils.nameFilter(alias))(MemberService.toMember(memberId, members), defaultValue); } }]) .filter('memberIdToFirstName', ["$filter", "MemberService", function ($filter, MemberService) { return function (memberId, members, defaultValue) { return $filter('firstName')(MemberService.toMember(memberId, members), defaultValue); } }]) .filter('asMoney', ["NumberUtils", function (NumberUtils) { return function (number) { return isNaN(number) ? '' : '£' + NumberUtils.asNumber(number).toFixed(2); } }]) .filter('humanize', function () { return function (string) { return s.humanize(string); } }) .filter('sumValues', ["NumberUtils", function (NumberUtils) { return function (items, propertyName) { return NumberUtils.sumValues(items, propertyName); } }]) .filter('walkSummary', ["$filter", function ($filter) { return function (walk) { return walk === undefined ? null : $filter('displayDate')(walk.walkDate) + " led by " + (walk.displayName || walk.contactName || "unknown") + " (" + (walk.<API key> || 'no description') + ')'; } }]) .filter('meetupEventSummary', ["$filter", function ($filter) { return function (meetupEvent) { return meetupEvent ? $filter('displayDate')(meetupEvent.startTime) + " (" + meetupEvent.title + ')' : null; } }]) .filter('asWalkEventType', ["<API key>", function (<API key>) { return function (eventTypeString, field) { var eventType = <API key>.toEventType(eventTypeString); return eventType && field ? eventType[field] : eventType; } }]) .filter('asEventNote', function () { return function (event) { return _.compact([event.description, event.reason]).join(', '); } }) .filter('<API key>', ["$filter", function ($filter) { return function (event, members) { return _(event.data).map(function (value, key) { return s.humanize(key) + ': ' + $filter('toAuditDeltaValue')(value, key, members); }).join(', '); } }]) .filter('valueOrDefault', function () { return function (value, defaultValue) { return value || defaultValue || '(none)'; } }) .filter('toAuditDeltaValue', ["$filter", function ($filter) { return function (value, fieldName, members, defaultValue) { switch (fieldName) { case 'walkDate': return $filter('displayDate')(value); case 'walkLeaderMemberId': return $filter('memberIdToFullName')(value, members, defaultValue); default: return $filter('valueOrDefault')(value, defaultValue); } } }]) .filter('<API key>', function () { return function (<API key>) { return _(<API key>).pluck('fieldName').map(s.humanize).join(', '); } }) .filter('<API key>', function () { return function (walkValidations) { var lastItem = _.last(walkValidations); var firstItems = _.without(walkValidations, lastItem); var joiner = firstItems.length > 0 ? ' and ' : ''; return firstItems.join(', ') + joiner + lastItem; } }) .filter('idFromRecord', function () { return function (mongoRecord) { return mongoRecord.$id; } }) .filter('eventTimes', function () { return function (socialEvent) { var eventTimes = socialEvent.eventTimeStart; if (socialEvent.eventTimeEnd) eventTimes += ' - ' + socialEvent.eventTimeEnd; return eventTimes; } }) .filter('displayDate', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDate(dateValue); } }]) .filter('displayDay', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDay(dateValue); } }]) .filter('displayDates', ["$filter", function ($filter) { return function (dateValues) { return _(dateValues).map(function (dateValue) { return $filter('displayDate')(dateValue); }).join(', '); } }]) .filter('displayDateAndTime', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDateAndTime(dateValue); } }]) .filter('fromExcelDate', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDate(dateValue); } }]) .filter('<API key>', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDateAndTime(dateValue); } }]) .filter('<API key>', ["DateUtils", function (DateUtils) { return function (member) { return member && member.<API key> ? 'by ' + (member.<API key> || 'member') + ' at ' + DateUtils.displayDateAndTime(member.<API key>) : 'not confirmed yet'; } }]) .filter('createdAudit', ["StringUtils", function (StringUtils) { return function (resource, members) { return StringUtils.formatAudit(resource.createdBy, resource.createdDate, members) } }]) .filter('updatedAudit', ["StringUtils", function (StringUtils) { return function (resource, members) { return StringUtils.formatAudit(resource.updatedBy, resource.updatedDate, members) } }]); /* concatenated from client/src/app/js/<API key>.js */ angular.module("ekwgApp") .controller("<API key>", ["$q", "$log", "$scope", "$rootScope", "$location", "$routeParams", "<API key>", "MemberService", "<API key>", "URLService", "MailchimpConfig", "<API key>", "<API key>", "Notifier", "ValidationUtils", "close", function ($q, $log, $scope, $rootScope, $location, $routeParams, <API key>, MemberService, <API key>, URLService, MailchimpConfig, <API key>, <API key>, Notifier, ValidationUtils, close) { var logger = $log.getInstance("<API key>"); $log.logLevels["<API key>"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); $scope.showSubmit = true; $scope.<API key> = "Forgotten Password"; $scope.<API key> = {}; $scope.actions = { close: function () { close(); }, submittable: function () { var onePopulated = ValidationUtils.fieldPopulated($scope.<API key>, "credentialOne"); var twoPopulated = ValidationUtils.fieldPopulated($scope.<API key>, "credentialTwo"); logger.info("notSubmittable: onePopulated", onePopulated, "twoPopulated", twoPopulated); return twoPopulated && onePopulated; }, submit: function () { var userDetails = "User Name " + $scope.<API key>.credentialOne + " and Membership Number " + $scope.<API key>.credentialTwo; notify.setBusy(); $scope.showSubmit = false; notify.success("Checking our records for " + userDetails, true); if ($scope.<API key>.credentialOne.length === 0 || $scope.<API key>.credentialTwo.length === 0) { $scope.showSubmit = true; notify.error({ title: "Incorrect information entered", message: "Please enter both a User Name and a Membership Number" }); } else { var forgotPasswordData = {loginResponse: {memberLoggedIn: false}}; var message; <API key>.<API key>($scope.<API key>.credentialOne, $scope.<API key>.credentialTwo) .then(function (member) { if (_.isEmpty(member)) { message = "No member was found with " + userDetails; forgotPasswordData.loginResponse.alertMessage = message; $scope.showSubmit = true; return { forgotPasswordData: forgotPasswordData, notifyObject: { title: "Incorrect information entered", message: message } }; } else if (!member.mailchimpLists.general.subscribed) { message = "Sorry, " + userDetails + " is not setup in our system to receive emails"; forgotPasswordData.member = member; forgotPasswordData.loginResponse.alertMessage = message; $scope.showSubmit = true; return { forgotPasswordData: forgotPasswordData, notifyObject: { title: "Message cannot be sent", message: message } }; } else { <API key>.setPasswordResetId(member); <API key>.<API key>(member); logger.debug("saving member", member); $scope.<API key> = member; member.$saveOrUpdate(<API key>, <API key>, saveFailed, saveFailed); forgotPasswordData.member = member; forgotPasswordData.loginResponse.alertMessage = "New password requested from login screen"; return {forgotPasswordData: forgotPasswordData}; } }).then(function (response) { return <API key>.auditMemberLogin($scope.<API key>.credentialOne, "", response.forgotPasswordData.member, response.forgotPasswordData.loginResponse) .then(function () { if (response.notifyObject) { notify.error(response.notifyObject) } }); }); } } }; function saveFailed(error) { notify.error({title: "The password reset failed", message: error}); } function getMailchimpConfig() { return MailchimpConfig.getConfig() .then(function (config) { $scope.mailchimpConfig = config.mailchimp; }); } function <API key>() { return <API key>.saveSegment("general", {segmentId: $scope.mailchimpConfig.segments.general.<API key>}, [{id: $scope.<API key>.$id()}], $scope.<API key>, [$scope.<API key>]); } function <API key>(segmentResponse) { return MailchimpConfig.getConfig() .then(function (config) { config.mailchimp.segments.general.<API key> = segmentResponse.segment.id; MailchimpConfig.saveConfig(config); }); } function <API key>() { var member = $scope.<API key>.firstName + " " + $scope.<API key>.lastName; return MailchimpConfig.getConfig() .then(function (config) { logger.debug("config.mailchimp.campaigns.forgottenPassword.campaignId", config.mailchimp.campaigns.forgottenPassword.campaignId); logger.debug("config.mailchimp.segments.general.<API key>", config.mailchimp.segments.general.<API key>); return <API key>.<API key>({ campaignId: config.mailchimp.campaigns.forgottenPassword.campaignId, campaignName: "EKWG website password reset instructions (" + member + ")", segmentId: config.mailchimp.segments.general.<API key> }); }); } function updateGeneralList() { return <API key>.<API key>("general", [$scope.<API key>]); } function <API key>() { $q.when(notify.success("Sending forgotten password email")) .then(updateGeneralList) .then(getMailchimpConfig) .then(<API key>) .then(<API key>) .then(<API key>) .then(finalMessage) .then(notify.clearBusy) .catch(handleSendError); } function handleSendError(errorResponse) { notify.error({ title: "Your email could not be sent", message: (errorResponse.message || errorResponse) + (errorResponse.error ? (". Error was: " + ErrorMessageService.stringify(errorResponse.error)) : "") }); } function finalMessage() { return notify.success({ title: "Message sent", message: "We've sent a message to the email address we have for you. Please check your inbox and follow the instructions in the message." }) } }] ); /* concatenated from client/src/app/js/googleMapsServices.js */ angular.module('ekwgApp') .factory('GoogleMapsConfig', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) { function getConfig() { return $http.get('/googleMaps/config').then(function (response) { return HTTPResponseService.returnResponse(response); }); } return { getConfig: getConfig, } }]); /* concatenated from client/src/app/js/homeController.js */ angular.module('ekwgApp') .controller('HomeController', ["$log", "$scope", "$routeParams", "<API key>", "<API key>", "<API key>", "InstagramService", "SiteEditService", function ($log, $scope, $routeParams, <API key>, <API key>, <API key>, InstagramService, SiteEditService) { var logger = $log.getInstance('HomeController'); $log.logLevels['HomeController'] = $log.LEVEL.OFF; $scope.feeds = {instagram: {recentMedia: []}, facebook: {}}; <API key>.getMetaData('imagesHome') .then(function (contentMetaData) { $scope.interval = 5000; $scope.slides = contentMetaData.files; }); InstagramService.recentMedia() .then(function (recentMediaResponse) { $scope.feeds.instagram.recentMedia = _.take(recentMediaResponse.instagram, 14); logger.debug("Refreshed social media", $scope.feeds.instagram.recentMedia, 'count =', $scope.feeds.instagram.recentMedia.length); }); $scope.mediaUrlFor = function (media) { logger.debug('mediaUrlFor:media', media); return (media && media.images) ? media.images.standard_resolution.url : ""; }; $scope.mediaCaptionFor = function (media) { logger.debug('mediaCaptionFor:media', media); return media ? media.caption.text : ""; }; $scope.allowEdits = function () { return SiteEditService.active() && <API key>.allowContentEdits(); }; }]); /* concatenated from client/src/app/js/howTo.js */ angular.module('ekwgApp') .controller("<API key>", ["$rootScope", "$log", "$q", "$scope", "$filter", "FileUtils", "DateUtils", "EKWGFileUpload", "DbUtils", "<API key>", "ErrorMessageService", "<API key>", "<API key>", "Notifier", "<API key>", "memberResource", "close", function ($rootScope, $log, $q, $scope, $filter, FileUtils, DateUtils, EKWGFileUpload, DbUtils, <API key>, ErrorMessageService, <API key>, <API key>, Notifier, <API key>, memberResource, close) { var logger = $log.getInstance("<API key>"); $log.logLevels["<API key>"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); $scope.fileUtils = FileUtils; $scope.<API key> = <API key>; $scope.<API key> = <API key>; $scope.memberResource = memberResource; logger.debug("<API key>:", $scope.<API key>, "memberResource:", memberResource); $scope.<API key> = { open: function () { $scope.<API key>.opened = true; } }; $scope.cancel = function () { close(); }; $scope.onSelect = function (file) { if (file) { logger.debug("onSelect:file:about to upload ->", file); $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, "memberResources") .then(function (fileNameData) { logger.debug("onSelect:file:upload complete -> fileNameData", fileNameData); $scope.memberResource.data.fileNameData = fileNameData; $scope.memberResource.data.fileNameData.title = $scope.oldTitle || file.name; }); } }; $scope.attach = function (file) { $("#hidden-input").click(); }; $scope.save = function () { notify.setBusy(); logger.debug("save ->", $scope.memberResource); return $scope.memberResource.$saveOrUpdate(notify.success, notify.success, notify.error, notify.error) .then($scope.hideDialog) .then(notify.clearBusy) .catch(handleError); function handleError(errorResponse) { notify.error({ title: "Your changes could not be saved", message: (errorResponse && errorResponse.error ? (". Error was: " + JSON.stringify(errorResponse.error)) : "") }); notify.clearBusy(); } }; $scope.cancelChange = function () { $q.when($scope.hideDialog()).then(notify.clearBusy); }; $scope.campaignDate = function (campaign) { return DateUtils.asValueNoTime(campaign.send_time || campaign.create_time); }; $scope.campaignTitle = function (campaign) { return campaign.title + " (" + $filter("displayDate")($scope.campaignDate(campaign)) + ")"; }; $scope.campaignChange = function () { logger.debug("campaignChange:memberResource.data.campaign", $scope.memberResource.data.campaign); if ($scope.memberResource.data.campaign) { $scope.memberResource.title = $scope.memberResource.data.campaign.title; $scope.memberResource.resourceDate = $scope.campaignDate($scope.memberResource.data.campaign); } }; $scope.<API key> = function (selectFirst) { var campaignSearchTerm = $scope.memberResource.data.campaignSearchTerm; if (campaignSearchTerm) { notify.setBusy(); notify.progress({ title: "Email search", message: "searching for campaigns matching '" + campaignSearchTerm + "'" }); var options = { limit: $scope.memberResource.data.campaignSearchLimit, concise: true, status: "sent", campaignSearchTerm: campaignSearchTerm }; options[$scope.memberResource.data.campaignSearchField] = campaignSearchTerm; return <API key>.list(options).then(function (response) { $scope.campaigns = response.data; if (selectFirst) { $scope.memberResource.data.campaign = _.first($scope.campaigns); $scope.campaignChange(); } else { logger.debug("$scope.memberResource.data.campaign", $scope.memberResource.data.campaign, "first campaign=", _.first($scope.campaigns)) } logger.debug("response.data", response.data); notify.success({ title: "Email search", message: "Found " + $scope.campaigns.length + " campaigns matching '" + campaignSearchTerm + "'" }); notify.clearBusy(); return true; }); } else { return $q.when(true); } }; $scope.hideDialog = function () { $rootScope.$broadcast("<API key>"); close(); }; $scope.editMode = $scope.memberResource.$id() ? "Edit" : "Add"; logger.debug("editMode:", $scope.editMode); if ($scope.memberResource.resourceType === "email" && $scope.memberResource.$id()) { $scope.<API key>(false).then(notify.clearBusy) } else { notify.clearBusy(); } }]) .controller("HowToController", ["$rootScope", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "<API key>", "FileUtils", "NumberUtils", "<API key>", "MemberService", "<API key>", "<API key>", "<API key>", "<API key>", "MailchimpConfig", "Notifier", "<API key>", "<API key>", "ModalService", "SiteEditService", function ($rootScope, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $scope, $filter, $routeParams, $location, URLService, DateUtils, <API key>, FileUtils, NumberUtils, <API key>, MemberService, <API key>, <API key>, <API key>, <API key>, MailchimpConfig, Notifier, <API key>, <API key>, ModalService, SiteEditService) { var logger = $log.getInstance("HowToController"); $log.logLevels["HowToController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); $scope.fileUtils = FileUtils; $scope.<API key> = <API key>; $scope.<API key> = <API key>; $scope.destinationType = ""; $scope.members = []; $scope.memberResources = []; $scope.alertMessages = []; $scope.allowConfirmDelete = false; $scope.selected = { addingNew: false, }; $scope.isActive = function (memberResource) { var active = SiteEditService.active() && <API key>.memberLoggedIn() && memberResource === $scope.selected.memberResource; logger.debug("isActive =", active, "with memberResource", memberResource); return active; }; $scope.allowAdd = function () { return SiteEditService.active() && <API key>.allowFileAdmin(); }; $scope.allowEdit = function (memberResource) { return $scope.allowAdd() && memberResource && memberResource.$id(); }; $scope.allowDelete = function (memberResource) { return $scope.allowEdit(memberResource); }; var <API key> = function () { return new <API key>({ data: {campaignSearchLimit: "1000", campaignSearchField: "title"}, resourceType: "email", accessLevel: "hidden", createdDate: DateUtils.nowAsValue(), createdBy: <API key>.loggedInMember().memberId }) }; function <API key>() { $scope.allowConfirmDelete = false; $scope.selected.addingNew = false; } $scope.delete = function () { $scope.allowConfirmDelete = true; }; $scope.cancelDelete = function () { <API key>(); }; $scope.confirmDelete = function () { notify.setBusy(); function showDeleted() { return notify.success("member resource was deleted successfully"); } $scope.selected.memberResource.$remove(showDeleted, showDeleted, notify.error, notify.error) .then($scope.hideDialog) .then(<API key>) .then(<API key>) .then(notify.clearBusy); }; $scope.<API key> = function (memberResource) { logger.debug("<API key> with memberResource", memberResource, "$scope.selected.addingNew", $scope.selected.addingNew); if (!$scope.selected.addingNew) { $scope.selected.memberResource = memberResource; } }; $scope.edit = function () { ModalService.showModal({ templateUrl: "partials/howTo/how-to-dialog.html", controller: "<API key>", preClose: function (modal) { logger.debug("preClose event with modal", modal); modal.element.modal("hide"); }, inputs: { memberResource: $scope.selected.memberResource } }).then(function (modal) { logger.debug("modal event with modal", modal); modal.element.modal(); modal.close.then(function (result) { logger.debug("close event with result", result); }); }) }; $scope.add = function () { $scope.selected.addingNew = true; var memberResource = <API key>(); $scope.selected.memberResource = memberResource; logger.debug("add:", memberResource); $scope.edit(); }; $scope.hideDialog = function () { <API key>(); }; $scope.$on("<API key>", function () { refreshAll(); }); $scope.$on("<API key>", function () { refreshAll(); }); $scope.$on("memberLoginComplete", function () { refreshAll(); }); $scope.$on("<API key>", function () { refreshAll(); }); $scope.$on("editSite", function (event, data) { logger.debug("editSite:", data); refreshAll(); }); function <API key>() { <API key>.all() .then(function (memberResources) { if (URLService.hasRouteParameter("memberResourceId")) { $scope.memberResources = _.filter(memberResources, function (memberResource) { return memberResource.$id() === $routeParams.memberResourceId; }); } else { $scope.memberResources = _.chain(memberResources) .filter(function (memberResource) { return $scope.<API key>.accessLevelFor(memberResource.accessLevel).filter(); }).sortBy("resourceDate") .value() .reverse(); logger.debug(memberResources.length, "memberResources", $scope.memberResources.length, "filtered memberResources"); } }); } function refreshAll() { <API key>(); } refreshAll(); }]); /* concatenated from client/src/app/js/httpServices.js */ angular.module('ekwgApp') .factory('HTTPResponseService', ["$log", function ($log) { var logger = $log.getInstance('HTTPResponseService'); $log.logLevels['HTTPResponseService'] = $log.LEVEL.OFF; function returnResponse(response) { logger.debug('response.data=', response.data); var returnObject = (typeof response.data === 'object') || !response.data ? response.data : JSON.parse(response.data); logger.debug('returned ', typeof response.data, 'response status =', response.status, returnObject.length, 'response items:', returnObject); return returnObject; } return { returnResponse: returnResponse } }]); /* concatenated from client/src/app/js/imageEditor.js */ angular.module('ekwgApp') .controller('ImageEditController', ["$scope", "$location", "Upload", "$http", "$q", "$routeParams", "$window", "<API key>", "<API key>", "Notifier", "EKWGFileUpload", function($scope, $location, Upload, $http, $q, $routeParams, $window, <API key>, <API key>, Notifier, EKWGFileUpload) { var notify = Notifier($scope); $scope.imageSource = $routeParams.imageSource; applyAllowEdits(); $scope.onFileSelect = function(file) { if (file) { $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, $scope.imageSource).then(function(fileNameData) { $scope.<API key>.image = $scope.imageMetaData.baseUrl + '/' + fileNameData.awsFileName; console.log(' $scope.<API key>.image', $scope.<API key>.image); }); } }; $scope.<API key> = function(imageSource) { notify.setBusy(); $scope.imageSource = imageSource; <API key>.getMetaData(imageSource).then(function(contentMetaData) { $scope.imageMetaData = contentMetaData; notify.clearBusy(); }, function(response) { notify.error(response); }); }; $scope.<API key>($scope.imageSource); $scope.$on('memberLoginComplete', function() { applyAllowEdits(); }); $scope.$on('<API key>', function() { applyAllowEdits(); }); $scope.<API key> = function() { $window.history.back(); }; $scope.reverseSortOrder = function() { $scope.imageMetaData.files = $scope.imageMetaData.files.reverse(); }; $scope.imageTitleLength = function() { if ($scope.imageSource === 'imagesHome') { return 50; } else { return 20 } }; $scope.replace = function(imageMetaDataItem) { $scope.files = []; $scope.<API key> = imageMetaDataItem; $('#hidden-input').click(); }; $scope.moveUp = function(imageMetaDataItem) { var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem); if (currentIndex > 0) { $scope.delete(imageMetaDataItem); $scope.imageMetaData.files.splice(currentIndex - 1, 0, imageMetaDataItem); } }; $scope.moveDown = function(imageMetaDataItem) { var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem); if (currentIndex < $scope.imageMetaData.files.length) { $scope.delete(imageMetaDataItem); $scope.imageMetaData.files.splice(currentIndex + 1, 0, imageMetaDataItem); } }; $scope.delete = function(imageMetaDataItem) { $scope.imageMetaData.files = _.without($scope.imageMetaData.files, imageMetaDataItem); }; $scope.insertHere = function(imageMetaDataItem) { var <API key> = new <API key>.createNewMetaData(true); var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem); $scope.imageMetaData.files.splice(currentIndex, 0, <API key>); $scope.replace(<API key>); }; $scope.<API key> = function(imageMetaDataItem) { return ($scope.<API key> && $scope.<API key>.$$hashKey === imageMetaDataItem.$$hashKey); }; $scope.saveAll = function() { <API key>.saveMetaData($scope.imageMetaData, <API key>, notify.error) .then(function(contentMetaData) { $scope.<API key>(); }, function(response) { notify.error(response); }); }; function applyAllowEdits() { $scope.allowEdits = <API key>.allowContentEdits(); } function <API key>() { notify.success('data for ' + $scope.imageMetaData.files.length + ' images was saved successfully.'); } }]); /* concatenated from client/src/app/js/indexController.js */ angular.module('ekwgApp') .controller("IndexController", ["$q", "$cookieStore", "$log", "$scope", "$rootScope", "URLService", "<API key>", "<API key>", "<API key>, "Notifier", "DateUtils", function ($q, $cookieStore, $log, $scope, $rootScope, URLService, <API key>, <API key>, <API key>, Notifier, DateUtils) { var logger = $log.getInstance("IndexController"); $log.logLevels["IndexController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); logger.info('called IndexController'); $scope.ready = false; $scope.year = DateUtils.asString(DateUtils.momentNow().valueOf(), undefined, "YYYY"); $scope.actions = { forgotPassword: function () { URLService.navigateTo("forgot-password"); }, loginOrLogout: function () { if (<API key>.memberLoggedIn()) { <API key>.logout(); } else { URLService.navigateTo("login"); } } }; $scope.memberLoggedIn = function () { return <API key>.memberLoggedIn() }; $scope.memberLoginStatus = function () { if (<API key>.memberLoggedIn()) { var loggedInMember = <API key>.loggedInMember(); return "Logout " + loggedInMember.firstName + " " + loggedInMember.lastName; } else { return "Login to EWKG Site"; } }; $scope.allowEdits = function () { return <API key>.allowContentEdits(); }; $scope.isHome = function () { return URLService.<API key>() === "/"; }; $scope.isOnPage = function (data) { var matchedUrl = s.endsWith(URLService.<API key>(), data); logger.debug("isOnPage", matchedUrl, "data=", data); return matchedUrl; }; $scope.isProfileOrAdmin = function () { return $scope.isOnPage("profile") || $scope.isOnPage("admin"); }; }]); /* concatenated from client/src/app/js/instagramServices.js */ angular.module('ekwgApp') .factory('InstagramService', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) { function recentMedia() { return $http.get('/instagram/recentMedia').then(HTTPResponseService.returnResponse); } return { recentMedia: recentMedia, } }]); /* concatenated from client/src/app/js/<API key>.js */ angular.module('ekwgApp') .controller('<API key>', ["$scope", "$location", function ($scope, $location) { var pathParts = $location.path().replace('/letterhead/', '').split('/'); $scope.firstPart = _.first(pathParts); $scope.lastPart = _.last(pathParts); }]); /* concatenated from client/src/app/js/links.js */ angular.module('ekwgApp') .factory('<API key>', ["$filter", "<API key>", "DateUtils", function ($filter, <API key>, DateUtils) { }]) .controller('ContactUsController', ["$log", "$rootScope", "$routeParams", "$scope", "<API key>", "<API key>", function ($log, $rootScope, $routeParams, $scope, <API key>, <API key>) { var logger = $log.getInstance('ContactUsController'); $log.logLevels['ContactUsController'] = $log.LEVEL.OFF; $scope.contactUs = { ready: function () { return <API key>.ready; } }; $scope.allowEdits = function () { return <API key>.<API key>(); } }]); /* concatenated from client/src/app/js/<API key>.js */ angular.module('ekwgApp') .factory('<API key>', ["$rootScope", "$q", "$routeParams", "$cookieStore", "URLService", "MemberService", "MemberAuditService", "DateUtils", "NumberUtils", "$log", function ($rootScope, $q, $routeParams, $cookieStore, URLService, MemberService, MemberAuditService, DateUtils, NumberUtils, $log) { var logger = $log.getInstance('<API key>'); var noLogger = $log.getInstance('NoLogger'); $log.logLevels['NoLogger'] = $log.LEVEL.OFF; $log.logLevels['<API key>'] = $log.LEVEL.OFF; function loggedInMember() { if (!getCookie('loggedInMember')) setCookie('loggedInMember', {}); return getCookie('loggedInMember'); } function loginResponse() { if (!getCookie('loginResponse')) setCookie('loginResponse', {memberLoggedIn: false}); return getCookie('loginResponse'); } function showResetPassword() { return getCookie('showResetPassword'); } function allowContentEdits() { return memberLoggedIn() ? loggedInMember().contentAdmin : false; } function <API key>() { return loginResponse().memberLoggedIn ? loggedInMember().memberAdmin : false; } function allowFinanceAdmin() { return loginResponse().memberLoggedIn ? loggedInMember().financeAdmin : false; } function allowCommittee() { return loginResponse().memberLoggedIn ? loggedInMember().committee : false; } function allowTreasuryAdmin() { return loginResponse().memberLoggedIn ? loggedInMember().treasuryAdmin : false; } function allowFileAdmin() { return loginResponse().memberLoggedIn ? loggedInMember().fileAdmin : false; } function memberLoggedIn() { return !_.isEmpty(loggedInMember()) && loginResponse().memberLoggedIn; } function <API key>(routeParameter) { if (URLService.hasRouteParameter(routeParameter) && !memberLoggedIn()) $('#login-dialog').modal(); } function allowWalkAdminEdits() { return memberLoggedIn() ? loggedInMember().walkAdmin : false; } function <API key>() { return memberLoggedIn() ? loggedInMember().socialAdmin : false; } function <API key>() { return memberLoggedIn() ? loggedInMember().socialMember : false; } function logout() { var member = loggedInMember(); var loginResponseValue = loginResponse(); if (!_.isEmpty(member)) { loginResponseValue.alertMessage = 'The member ' + member.userName + ' logged out successfully'; auditMemberLogin(member.userName, undefined, member, loginResponseValue) } removeCookie('loginResponse'); removeCookie('loggedInMember'); removeCookie('showResetPassword'); removeCookie('editSite'); $rootScope.$broadcast('<API key>'); } function auditMemberLogin(userName, password, member, loginResponse) { var audit = new MemberAuditService({ userName: userName, password: password, loginTime: DateUtils.nowAsValue(), loginResponse: loginResponse }); if (!_.isEmpty(member)) audit.member = member; return audit.$save(); } function setCookie(key, value) { noLogger.debug('setting cookie ' + key + ' with value ', value); $cookieStore.put(key, value); } function removeCookie(key) { logger.info('removing cookie ' + key); $cookieStore.remove(key); } function getCookie(key) { var object = $cookieStore.get(key); noLogger.debug('getting cookie ' + key + ' with value', object); return object; } function login(userName, password) { return <API key>(userName) .then(function (member) { removeCookie('showResetPassword'); var loginResponse = {}; if (!_.isEmpty(member)) { loginResponse.memberLoggedIn = false; if (!member.groupMember) { loginResponse.alertMessage = 'Logins for member ' + userName + ' have been disabled. Please'; } else if (member.password !== password) { loginResponse.alertMessage = 'The password was incorrectly entered for ' + userName + '. Please try again or'; } else if (member.expiredPassword) { setCookie('showResetPassword', true); loginResponse.alertMessage = 'The password for ' + userName + ' has expired. You must enter a new password before continuing. Alternatively'; } else { loginResponse.memberLoggedIn = true; loginResponse.alertMessage = 'The member ' + userName + ' logged in successfully'; <API key>(member); } } else { removeCookie('loggedInMember'); loginResponse.alertMessage = 'The member ' + userName + ' was not recognised. Please try again or'; } return {loginResponse: loginResponse, member: member}; }) .then(function (loginData) { setCookie('loginResponse', loginData.loginResponse); return auditMemberLogin(userName, password, loginData.member, loginData.loginResponse) .then(function () { logger.debug('loginResponse =', loginData.loginResponse); return $rootScope.$broadcast('memberLoginComplete'); } ); }, function (response) { throw new Error('Something went wrong...' + response); }) } function <API key>(member) { var memberId = member.$id(); var cookie = getCookie('loggedInMember'); if (_.isEmpty(cookie) || (cookie.memberId === memberId)) { var newCookie = angular.extend(member, {memberId: memberId}); logger.debug('saving loggedInMember ->', newCookie); setCookie('loggedInMember', newCookie); } else { logger.debug('not saving member (' + memberId + ') to cookie as not currently logged in member (' + cookie.memberId + ')', member); } } function saveMember(memberToSave, saveCallback, errorSaveCallback) { memberToSave.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback, errorSaveCallback) .then(function () { <API key>(memberToSave); }) .then(function () { $rootScope.$broadcast('memberSaveComplete'); }); } function resetPassword(userName, newPassword, newPasswordConfirm) { return <API key>(userName) .then(validateNewPassword) .then(<API key>) .then(<API key>) .then(auditPasswordChange); function validateNewPassword(member) { var loginResponse = {memberLoggedIn: false}; var showResetPassword = true; if (member.password === newPassword) { loginResponse.alertMessage = 'The new password was the same as the old one for ' + member.userName + '. Please try again or'; } else if (!newPassword || newPassword.length < 6) { loginResponse.alertMessage = 'The new password needs to be at least 6 characters long. Please try again or'; } else if (newPassword !== newPasswordConfirm) { loginResponse.alertMessage = 'The new password was not confirmed correctly for ' + member.userName + '. Please try again or'; } else { showResetPassword = false; logger.debug('Saving new password for ' + member.userName + ' and removing expired status'); delete member.expiredPassword; delete member.passwordResetId; member.password = newPassword; loginResponse.memberLoggedIn = true; loginResponse.alertMessage = 'The password for ' + member.userName + ' was changed successfully'; } return {loginResponse: loginResponse, member: member, showReset<API key>}; } function <API key>(resetPasswordData) { logger.debug('saveNewPassword.resetPasswordData:', resetPasswordData); setCookie('loginResponse', resetPasswordData.loginResponse); setCookie('showResetPassword', resetPasswordData.showResetPassword); if (!resetPasswordData.showResetPassword) { return resetPasswordData.member.$update().then(function () { <API key>(resetPasswordData.member); return resetPasswordData; }) } else { return resetPasswordData; } } function auditPasswordChange(resetPasswordData) { return auditMemberLogin(userName, resetPasswordData.member.password, resetPasswordData.member, resetPasswordData.loginResponse) } function <API key>(resetPasswordData) { $rootScope.$broadcast('memberLoginComplete'); return resetPasswordData } } function <API key>(userName) { return MemberService.query({userName: userName.toLowerCase()}, {limit: 1}) .then(function (queryResults) { return (queryResults && queryResults.length > 0) ? queryResults[0] : {}; }); } function <API key>(credentialOne, credentialTwo) { var <API key> = credentialOne.toLowerCase().trim(); var <API key> = credentialTwo.toUpperCase().trim(); var orOne = {$or: [{userName: {$eq: <API key>}}, {email: {$eq: <API key>}}]}; var orTwo = {$or: [{membershipNumber: {$eq: <API key>}}, {postcode: {$eq: <API key>}}]}; var criteria = {$and: [orOne, orTwo]}; logger.info("querying member using", criteria); return MemberService.query(criteria, {limit: 1}) .then(function (queryResults) { logger.info("queryResults:", queryResults); return (queryResults && queryResults.length > 0) ? queryResults[0] : {}; }); } function <API key>(memberId) { return MemberService.getById(memberId) } function <API key>(passwordResetId) { return MemberService.query({passwordResetId: passwordResetId}, {limit: 1}) .then(function (queryResults) { return (queryResults && queryResults.length > 0) ? queryResults[0] : {}; }); } function setPasswordResetId(member) { member.passwordResetId = NumberUtils.generateUid(); logger.debug('member.userName', member.userName, 'member.passwordResetId', member.passwordResetId); return member; } return { auditMemberLogin: auditMemberLogin, setPasswordResetId: setPasswordResetId, <API key>: <API key>, getMemberForReset<API key>, <API key>: <API key>, <API key>: <API key>, loggedInMember: loggedInMember, loginResponse: loginResponse, logout: logout, login: login, saveMember: saveMember, resetPassword: resetPassword, memberLoggedIn: memberLoggedIn, allowContentEdits: allowContentEdits, <API key>: <API key>, allowWalkAdminEdits: allowWalkAdminEdits, <API key>: <API key>, <API key>: <API key>, allowCommittee: allowCommittee, allowFinanceAdmin: allowFinanceAdmin, allowTreasuryAdmin: allowTreasuryAdmin, allowFileAdmin: allowFileAdmin, showReset<API key>, <API key>: <API key> }; }] ); /* concatenated from client/src/app/js/loginController.js */ angular.module('ekwgApp') .controller('LoginController', ["$log", "$scope", "$routeParams", "<API key>", "<API key>, "Notifier", "URLService", "ValidationUtils", "close", function ($log, $scope, $routeParams, <API key>, <API key>, Notifier, URLService, ValidationUtils, close) { $scope.notify = {}; var logger = $log.getInstance('LoginController'); $log.logLevels['LoginController'] = $log.LEVEL.OFF; var notify = Notifier($scope.notify); <API key>.logout(); $scope.actions = { submittable: function () { var userNamePopulated = ValidationUtils.fieldPopulated($scope.<API key>, "userName"); var passwordPopulated = ValidationUtils.fieldPopulated($scope.<API key>, "password"); logger.info("submittable: userNamePopulated", userNamePopulated, "passwordPopulated", passwordPopulated); return passwordPopulated && userNamePopulated; }, forgotPassword: function () { URLService.navigateTo("forgot-password"); }, close: function () { close() }, login: function () { notify.showContactUs(false); notify.setBusy(); notify.progress({ busy: true, title: "Logging in", message: "using credentials for " + $scope.<API key>.userName + " - please wait" }); <API key>.login($scope.<API key>.userName, $scope.<API key>.password).then(function () { var loginResponse = <API key>.loginResponse(); if (<API key>.memberLoggedIn()) { close(); if (!<API key>.loggedInMember().<API key>) { return URLService.navigateTo("mailing-preferences"); } return true; } else if (<API key>.showResetPassword()) { return <API key>.<API key>($scope.<API key>.userName, "Your password has expired, therefore you need to reset it to a new one before continuing."); } else { notify.showContactUs(true); notify.error({ title: "Login failed", message: loginResponse.alertMessage }); } }); }, } }] ); /* concatenated from client/src/app/js/mailChimpServices.js */ angular.module('ekwgApp') .factory('MailchimpConfig', ["Config", function (Config) { function getConfig() { return Config.getConfig('mailchimp', { mailchimp: { interestGroups: { walks: {interestGroupingId: undefined}, socialEvents: {interestGroupingId: undefined}, general: {interestGroupingId: undefined} }, segments: { walks: {segmentId: undefined}, socialEvents: {segmentId: undefined}, general: { <API key>: undefined, <API key>: undefined, committeeSegmentId: undefined } } } }) } function saveConfig(config, key, saveCallback, errorSaveCallback) { return Config.saveConfig('mailchimp', config, key, saveCallback, errorSaveCallback); } return { getConfig: getConfig, saveConfig: saveConfig } }]) .factory('<API key>', ["$log", "$q", "$http", "<API key>", function ($log, $q, $http, <API key>) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; function call(serviceCallType, method, url, data, params) { var deferredTask = $q.defer(); deferredTask.notify(serviceCallType); logger.debug(serviceCallType); $http({ method: method, data: data, params: params, url: url }).then(function (response) { var responseData = response.data; var errorObject = <API key>.extractError(responseData); if (errorObject.error) { var errorResponse = {message: serviceCallType + ' was not successful', error: errorObject.error}; logger.debug(errorResponse); deferredTask.reject(errorResponse); } else { logger.debug('success', responseData); deferredTask.resolve(responseData); return responseData; } }).catch(function (response) { var responseData = response.data; var errorObject = <API key>.extractError(responseData); var errorResponse = {message: serviceCallType + ' was not successful', error: errorObject.error}; logger.debug(errorResponse); deferredTask.reject(errorResponse); }); return deferredTask.promise; } return { call: call } }]) .factory('<API key>', ["$log", function ($log) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; function extractError(responseData) { var error; if (responseData && (responseData.error || responseData.errno)) { error = {error: responseData} } else if (responseData && responseData.errors && responseData.errors.length > 0) { error = { error: _.map(responseData.errors, function (error) { var response = error.error; if (error.email && error.email.email) { response += (': ' + error.email.email); } return response; }).join(', ') } } else { error = {error: undefined} } logger.debug('responseData:', responseData, 'error:', error) return error; } return { extractError: extractError } }]) .factory('<API key>', ["$log", "<API key>", function ($log, <API key>) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; function campaignPreview(webId) { return <API key>.apiServer + "/campaigns/<API key>?id=" + webId; } function campaignEdit(webId) { return <API key>.apiServer + "/campaigns/<API key>?id=" + webId; } return { campaignPreview: campaignPreview } }]) .factory('<API key>', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "<API key>", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, <API key>) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; var addInterestGroup = function (listType, interestGroupName, interestGroupingId) { return <API key>.call('Adding Mailchimp Interest Group for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/interestGroupAdd', { interestGroupingId: interestGroupingId, interestGroupName: interestGroupName }); }; var deleteInterestGroup = function (listType, interestGroupName, interestGroupingId) { return <API key>.call('Deleting Mailchimp Interest Group for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/interestGroupDel', { interestGroupingId: interestGroupingId, interestGroupName: interestGroupName }); }; var addInterestGrouping = function (listType, <API key>, groups) { return <API key>.call('Adding Mailchimp Interest Grouping for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/interestGroupingAdd', { groups: groups, <API key>: <API key> }); }; var <API key> = function (listType, interestGroupingId) { return <API key>.call('Deleting Mailchimp Interest Grouping for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/interestGroupingDel', {interestGroupingId: interestGroupingId}); }; var <API key> = function (listType) { return <API key>.call('Listing Mailchimp Interest Groupings for ' + listType, 'GET', 'mailchimp/lists/' + listType + '/interestGroupings'); }; var <API key> = function (listType, interestGroupingId, <API key>, <API key>) { return <API key>.call('Updating Mailchimp Interest Groupings for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/<API key>', { interestGroupingId: interestGroupingId, <API key>: <API key>, <API key>: <API key> }); }; var updateInterestGroup = function (listType, oldName, newName) { return function (config) { var interestGroupingId = config.mailchimp.interestGroups[listType].interestGroupingId; return <API key>.call('Updating Mailchimp Interest Group for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/interestGroupUpdate', { interestGroupingId: interestGroupingId, oldName: oldName, newName: newName }) .then(<API key>(interestGroupingId)); } }; var saveInterestGroup = function (listType, oldName, newName) { oldName = oldName.substring(0, 60); newName = newName.substring(0, 60); return MailchimpConfig.getConfig() .then(updateInterestGroup(listType, oldName, newName)) .then(findInterestGroup(listType, newName)); }; var createInterestGroup = function (listType, interestGroupName) { return MailchimpConfig.getConfig() .then(<API key>(listType, interestGroupName)) .then(findInterestGroup(listType, interestGroupName)); }; var <API key> = function (listType, interestGroupName) { return function (config) { logger.debug('<API key> using config', config); var <API key> = s.titleize(s.humanize(listType)); var interestGroupingId = config.mailchimp.interestGroups[listType].interestGroupingId; if (interestGroupingId) { return addInterestGroup(listType, interestGroupName, interestGroupingId) .then(<API key>(interestGroupingId)); } else { return addInterestGrouping(listType, <API key> + ' Interest Groups', [interestGroupName]) .then(<API key>(listType, config)); } } }; var <API key> = function (interestGroupingId) { return function (response) { logger.debug('received', response, 'returning', interestGroupingId); return interestGroupingId; } }; var <API key> = function (listType, config) { return function (response) { config.mailchimp.interestGroups[listType].interestGroupingId = response.id; logger.debug('saving config', config); return MailchimpConfig.saveConfig(config, function () { logger.debug('config save was successful'); return response.id; }, function (error) { throw Error('config save was not successful. ' + error) }); } }; var findInterestGroup = function (listType, interestGroupName) { return function (interestGroupingId) { logger.debug('finding findInterestGroup ', interestGroupingId); return <API key>(listType) .then(<API key>(interestGroupingId, interestGroupName)); } }; var <API key> = function (interestGroupingId, interestGroupName) { return function (interestGroupings) { logger.debug('<API key>: interestGroupings passed in ', interestGroupings, 'for interestGroupingId', interestGroupingId); var interestGrouping = _.find(interestGroupings, function (interestGrouping) { return interestGrouping.id === interestGroupingId; }); logger.debug('<API key>: interestGrouping returned ', interestGrouping); var interestGroup = _.find(interestGrouping.groups, function (group) { return group.name === interestGroupName; }); logger.debug('<API key>: interestGroup returned', interestGroup); return interestGroup; } }; return { createInterestGroup: createInterestGroup, saveInterestGroup: saveInterestGroup } }]) .factory('<API key>', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "<API key>", "<API key>", "MemberService", "StringUtils", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, <API key>, <API key>, MemberService, StringUtils) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; function addSegment(listType, segmentName) { return <API key>.call('Adding Mailchimp segment for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentAdd', {segmentName: segmentName}); } function resetSegment(listType, segmentId) { return <API key>.call('Resetting Mailchimp segment for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/segmentReset', {segmentId: segmentId}); } function deleteSegment(listType, segmentId) { return <API key>.call('Deleting Mailchimp segment for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/segmentDel/' + segmentId); } function callRenameSegment(listType, segmentId, segmentName) { return function () { return renameSegment(listType, segmentId, segmentName); } } function renameSegment(listType, segmentId, segmentNameInput) { var segmentName = StringUtils.stripLineBreaks(StringUtils.left(segmentNameInput, 99), true); logger.debug('renaming segment with name=\'' + segmentName + '\' length=' + segmentName.length); return <API key>.call('Renaming Mailchimp segment for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentRename', { segmentId: segmentId, segmentName: segmentName }); } function <API key>(listType, segmentId, segmentMembers) { return function () { return addSegmentMembers(listType, segmentId, segmentMembers); } } function addSegmentMembers(listType, segmentId, segmentMembers) { return <API key>.call('Adding Mailchimp segment members ' + JSON.stringify(segmentMembers) + ' for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentMembersAdd', { segmentId: segmentId, segmentMembers: segmentMembers }); } function <API key>(listType, segmentId, segmentMembers) { return function () { return <API key>(listType, segmentId, segmentMembers); } } function <API key>(listType, segmentId, segmentMembers) { return <API key>.call('Deleting Mailchimp segment members ' + segmentMembers + ' for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/segmentMembersDel', { segmentId: segmentId, segmentMembers: segmentMembers }); } function listSegments(listType) { return <API key>.call('Listing Mailchimp segments for ' + listType, 'GET', 'mailchimp/lists/' + listType + '/segments'); } function <API key>(listType, memberIds, members) { var segmentMembers = _.chain(memberIds) .map(function (memberId) { return MemberService.toMember(memberId, members) }) .filter(function (member) { return member && member.email; }) .map(function (member) { return <API key>.<API key>(member, listType); }) .value(); if (!segmentMembers || segmentMembers.length === 0) throw new Error('No members were added to the ' + listType + ' email segment from the ' + memberIds.length + ' supplied members. Please check that they have a valid email address and are subscribed to ' + listType); return segmentMembers; } function saveSegment(listType, mailchimpConfig, memberIds, segmentName, members) { var segmentMembers = <API key>(listType, memberIds, members); logger.debug('saveSegment:<API key>:', listType, memberIds, segmentMembers); if (mailchimpConfig && mailchimpConfig.segmentId) { var segmentId = mailchimpConfig.segmentId; logger.debug('saveSegment:segmentId', mailchimpConfig); return resetSegment(listType, segmentId) .then(callRenameSegment(listType, segmentId, segmentName)) .then(<API key>(listType, segmentId, segmentMembers)) .then(<API key>({id: segmentId})); } else { return addSegment(listType, segmentName) .then(<API key>(listType, segmentMembers)) } } function <API key>(addSegmentResponse) { return function (<API key>) { return {members: <API key>.members, segment: addSegmentResponse}; }; } function <API key>(addSegmentResponse) { return function (addMemberResponse) { return ({segment: addSegmentResponse, members: addMemberResponse}); }; } function <API key>(listType, segmentId, segmentMembers) { return function (<API key>) { if (segmentMembers.length > 0) { return addSegmentMembers(listType, segmentId, segmentMembers) .then(<API key>(<API key>)); } else { return {segment: <API key>.id, members: {}}; } } } function <API key>(listType, segmentMembers) { return function (addSegmentResponse) { if (segmentMembers.length > 0) { return addSegmentMembers(listType, addSegmentResponse.id, segmentMembers) .then(<API key>(addSegmentResponse)); } else { return {segment: addSegmentResponse, members: {}}; } } } function getMemberSegmentId(member, segmentType) { if (member.mailchimpSegmentIds) return member.mailchimpSegmentIds[segmentType]; } function setMemberSegmentId(member, segmentType, segmentId) { if (!member.mailchimpSegmentIds) member.mailchimpSegmentIds = {}; member.mailchimpSegmentIds[segmentType] = segmentId; } function formatSegmentName(prefix) { var date = ' (' + DateUtils.nowAsValue() + ')'; var segmentName = prefix.substring(0, 99 - date.length) + date; logger.debug('segmentName', segmentName, 'length', segmentName.length); return segmentName; } return { formatSegmentName: formatSegmentName, saveSegment: saveSegment, deleteSegment: deleteSegment, getMemberSegmentId: getMemberSegmentId, setMemberSegmentId: setMemberSegmentId } }]) .factory('<API key>', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "<API key>", "<API key>", "MemberService", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, <API key>, <API key>, MemberService) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; var listSubscribers = function (listType) { return <API key>.call('Listing Mailchimp subscribers for ' + listType, 'GET', 'mailchimp/lists/' + listType); }; var batchUnsubscribe = function (listType, subscribers) { return <API key>.call('Batch unsubscribing members from Mailchimp List for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/batchUnsubscribe', subscribers); }; var <API key> = function (listType, allMembers, <API key>) { return listSubscribers(listType) .then(<API key>(listType, allMembers)) .then(<API key>(listType, allMembers, <API key>)) .then(<API key>); }; function <API key>() { return MemberService.all(); } function <API key>(listType, allMembers, <API key>) { return function (subscribers) { if (subscribers.length > 0) { return batchUnsubscribe(listType, subscribers) .then(<API key>(listType, allMembers, subscribers, <API key>)); } else { <API key>('No members needed to be unsubscribed from ' + listType + ' list'); } } } function <API key>(listType, allMembers, subscribers, <API key>) { return function () { var updatedMembers = _.chain(subscribers) .map(function (subscriber) { var member = <API key>.responseToMember(listType, allMembers, subscriber); if (member) { member.mailchimpLists[listType] = {subscribed: false, updated: true}; member.$saveOrUpdate(); } else { <API key>('Could not find member from ' + listType + ' response containing data ' + JSON.stringify(subscriber)); } return member; }) .filter(function (member) { return member; }) .value(); $q.all(updatedMembers).then(function () { <API key>('Successfully unsubscribed ' + updatedMembers.length + ' member(s) from ' + listType + ' list'); return updatedMembers; }) } } function <API key>(listType, allMembers) { return function (listResponse) { return _.chain(listResponse.data) .filter(function (subscriber) { return <API key>.<API key>(listType, allMembers, subscriber); }) .map(function (subscriber) { return { email: subscriber.email, euid: subscriber.euid, leid: subscriber.leid }; }) .value(); } } return { <API key>: <API key> } }]) .factory('<API key>', ["<API key>", "$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "<API key>", function (<API key>, $log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, <API key>) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; function addCampaign(campaignId, campaignName) { return <API key>.call('Adding Mailchimp campaign ' + campaignId + ' with name ' + campaignName, 'POST', 'mailchimp/campaigns/' + campaignId + '/campaignAdd', {campaignName: campaignName}); } function deleteCampaign(campaignId) { return <API key>.call('Deleting Mailchimp campaign ' + campaignId, 'DELETE', 'mailchimp/campaigns/' + campaignId + '/delete'); } function getContent(campaignId) { return <API key>.call('Getting Mailchimp content for campaign ' + campaignId, 'GET', 'mailchimp/campaigns/' + campaignId + '/content'); } function list(options) { return <API key>.call('Listing Mailchimp campaigns', 'GET', 'mailchimp/campaigns/list', {}, options); } function setContent(campaignId, contentSections) { return contentSections ? <API key>.call('Setting Mailchimp content for campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/update', { updates: { name: "content", value: contentSections } }) : $q.when({ result: "success", campaignId: campaignId, message: "setContent skipped as no content provided" }) } function setOrClearSegment(<API key>, optionalSegmentId) { if (optionalSegmentId) { return setSegmentId(<API key>, optionalSegmentId); } else { return clearSegment(<API key>) } } function setSegmentId(campaignId, segmentId) { return setSegmentOpts(campaignId, {saved_segment_id: segmentId}); } function clearSegment(campaignId) { return setSegmentOpts(campaignId, []); } function setSegmentOpts(campaignId, value) { return <API key>.call('Setting Mailchimp segment opts for campaign ' + campaignId + ' with value ' + JSON.stringify(value), 'POST', 'mailchimp/campaigns/' + campaignId + '/update', { updates: { name: "segment_opts", value: value } }); } function setCampaignOptions(campaignId, campaignName, otherOptions) { var value = angular.extend({}, { title: campaignName.substring(0, 99), subject: campaignName }, otherOptions); return <API key>.call('Setting Mailchimp campaign options for id ' + campaignId + ' with ' + JSON.stringify(value), 'POST', 'mailchimp/campaigns/' + campaignId + '/update', { updates: { name: "options", value: value } }); } function replicateCampaign(campaignId) { return <API key>.call('Replicating Mailchimp campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/replicate'); } function sendCampaign(campaignId) { if (!<API key>.allowSendCampaign) throw new Error('You cannot send campaign ' + campaignId + ' as sending has been disabled'); return <API key>.call('Sending Mailchimp campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/send'); } function listCampaigns() { return <API key>.call('Listing Mailchimp campaigns', 'GET', 'mailchimp/campaigns/list'); } function <API key>(options) { logger.debug('<API key>:options', options); return replicateCampaign(options.campaignId) .then(function (<API key>) { logger.debug('<API key>', <API key>); var <API key> = <API key>.id; return setCampaignOptions(<API key>, options.campaignName, options.otherSegmentOptions) .then(function (renameResponse) { logger.debug('renameResponse', renameResponse); return setContent(<API key>, options.contentSections) .then(function (setContentResponse) { logger.debug('setContentResponse', setContentResponse); return setOrClearSegment(<API key>, options.segmentId) .then(function (setSegmentResponse) { logger.debug('setSegmentResponse', setSegmentResponse); return options.dontSend ? <API key> : sendCampaign(<API key>) }) }) }) }); } return { <API key>: <API key>, list: list } }]); /* concatenated from client/src/app/js/<API key>.js */ angular.module('ekwgApp') .controller('<API key>', ["$log", "$scope", "<API key>", "Notifier", "URLService", "<API key>", "memberId", "close", function ($log, $scope, <API key>, Notifier, URLService, <API key>, memberId, close) { var logger = $log.getInstance("<API key>"); $log.logLevels["<API key>"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); <API key>.<API key>(memberId) .then(function (member) { logger.info('memberId ->', memberId, 'member ->', member); $scope.member = member; }); function <API key>(message) { notify.showContactUs(true); notify.error({ continue: true, title: "Error in saving mailing preferences", message: "Changes to your mailing preferences could not be saved. " + (message || "Please try again later.") }); } $scope.actions = { save: function () { <API key>.confirmProfile($scope.member); <API key>.saveMember($scope.member, $scope.actions.close, <API key>); }, close: function () { close(); } }; }]); /* concatenated from client/src/app/js/markdownEditor.js */ angular.module('ekwgApp') .component('markdownEditor', { templateUrl: 'partials/components/markdown-editor.html', controller: ["$cookieStore", "$log", "$rootScope", "$scope", "$element", "$attrs", "ContentText", function ($cookieStore, $log, $rootScope, $scope, $element, $attrs, ContentText) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; var ctrl = this; ctrl.userEdits = {preview: true, saveInProgress: false, revertInProgress: false}; function assignData(data) { ctrl.data = data; ctrl.originalData = _.clone(data); logger.debug(ctrl.name, 'content retrieved:', data); return data; } function populateContent(type) { if (type) ctrl.userEdits[type + 'InProgress'] = true; return ContentText.forName(ctrl.name).then(function (data) { data = assignData(data); if (type) ctrl.userEdits[type + 'InProgress'] = false; return data; }); } ctrl.edit = function () { ctrl.userEdits.preview = false; }; ctrl.revert = function () { logger.debug('reverting ' + ctrl.name, 'content'); ctrl.data = _.clone(ctrl.originalData); }; ctrl.dirty = function () { var dirty = ctrl.data && ctrl.originalData && (ctrl.data.text !== ctrl.originalData.text); logger.debug(ctrl.name, 'dirty ->', dirty); return dirty; }; ctrl.revertGlyph = function () { return ctrl.userEdits.revertInProgress ? "fa fa-spinner fa-spin" : "glyphicon glyphicon-remove <API key>" }; ctrl.saveGlyph = function () { return ctrl.userEdits.saveInProgress ? "fa fa-spinner fa-spin" : "glyphicon glyphicon-ok <API key>" }; ctrl.save = function () { ctrl.userEdits.saveInProgress = true; logger.info('saving', ctrl.name, 'content', ctrl.data, $element, $attrs); ctrl.data.$saveOrUpdate().then(function (data) { ctrl.userEdits.saveInProgress = false; assignData(data); }) }; ctrl.editSite = function () { return $cookieStore.get('editSite'); }; ctrl.rows = function () { var text = _.property(["data", "text"])(ctrl); var rows = text ? text.split(/\r*\n/).length + 1 : 1; logger.info('number of rows in text ', text, '->', rows); return rows; }; ctrl.preview = function () { logger.info('previewing ' + ctrl.name, 'content', $element, $attrs); ctrl.userEdits.preview = true; }; ctrl.$onInit = function () { logger.debug('initialising:', ctrl.name, 'content, editSite:', ctrl.editSite()); if (!ctrl.description) { ctrl.description = ctrl.name; } populateContent(); }; }], bindings: { name: '@', description: '@', } }); /* concatenated from client/src/app/js/meetupServices.js */ angular.module('ekwgApp') .factory('MeetupService', ["$log", "$http", "HTTPResponseService", function ($log, $http, HTTPResponseService) { var logger = $log.getInstance('MeetupService'); $log.logLevels['MeetupService'] = $log.LEVEL.OFF; return { config: function () { return $http.get('/meetup/config').then(HTTPResponseService.returnResponse); }, eventUrlFor: function (meetupEventUrl) { return $http.get('/meetup/config').then(HTTPResponseService.returnResponse).then(function (meetupConfig) { return meetupConfig.url + '/' + meetupConfig.group + '/events/' + meetupEventUrl; }); }, eventsForStatus: function (status) { var queriedStatus = status || 'upcoming'; return $http({ method: 'get', params: { status: queriedStatus, }, url: '/meetup/events' }).then(function (response) { var returnValue = HTTPResponseService.returnResponse(response); logger.debug('eventsForStatus', queriedStatus, returnValue); return returnValue; }) } } }]); /* concatenated from client/src/app/js/memberAdmin.js */ angular.module('ekwgApp') .controller('<API key>', ["$timeout", "$location", "$window", "$log", "$q", "$rootScope", "$routeParams", "$scope", "ModalService", "Upload", "StringUtils", "DbUtils", "URLService", "<API key>", "MemberService", "MemberAuditService", "<API key>", "<API key>", "<API key>", "<API key>", "DateUtils", "MailchimpConfig", "<API key>", "MemberNamingService", "<API key>", "<API key>", "Notifier", "ErrorMessageService", "<API key>", "<API key>", "MONGOLAB_CONFIG", "<API key>", function ($timeout, $location, $window, $log, $q, $rootScope, $routeParams, $scope, ModalService, Upload, StringUtils, DbUtils, URLService, <API key>, MemberService, MemberAuditService, <API key>, <API key>, <API key>, <API key>, DateUtils, MailchimpConfig, <API key>, MemberNamingService, <API key>, <API key>, Notifier, ErrorMessageService, <API key>, <API key>, MONGOLAB_CONFIG, <API key>) { var logger = $log.getInstance('<API key>'); var noLogger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; $log.logLevels['<API key>'] = $log.LEVEL.OFF; $scope.memberAdminBaseUrl = <API key>.baseUrl('memberAdmin'); $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); var DESCENDING = ''; var ASCENDING = ''; $scope.today = DateUtils.momentNowNoTime().valueOf(); $scope.currentMember = {}; $scope.display = { saveInProgress: false }; $scope.<API key> = function () { $scope.display.memberFilterDate = DateUtils.momentNowNoTime().subtract($scope.display && $scope.display.emailType.monthsInPast, 'months').valueOf(); }; $scope.showArea = function (area) { URLService.navigateTo('admin', area) }; $scope.display.emailTypes = [$scope.display.emailType]; $scope.dropSupported = true; $scope.memberAdminOpen = !URLService.hasRouteParameter('expenseId') && (URLService.isArea('member-admin') || URLService.noArea()); $scope.memberBulkLoadOpen = URLService.isArea('member-bulk-load'); $scope.memberAuditOpen = URLService.isArea('member-audit'); <API key>.<API key>('expenseId'); if (<API key>.memberLoggedIn()) { refreshMembers() .then(refreshMemberAudit) .then(<API key>) .then(<API key>) .then(notify.clearBusy); } else { notify.clearBusy(); } $scope.<API key> = function () { return DateUtils.<API key>(); }; $scope.<API key> = function (item) { $window.open(<API key>.apiServer + "/lists/members/view?id=" + item, '_blank'); }; $scope.<API key> = function () { $scope.<API key> = false; $scope.display.emailMembers = []; ModalService.showModal({ templateUrl: "partials/admin/send-emails-dialog.html", controller: "<API key>", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, inputs: { members: $scope.members } }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; function handleSaveError(errorResponse) { $scope.display.saveInProgress = false; applyAllowEdits(); var message = ErrorMessageService.stringify(errorResponse); var duplicate = s.include(message, 'duplicate'); logger.debug('errorResponse', errorResponse, 'duplicate', duplicate); if (duplicate) { message = 'Duplicate data was detected. A member record must have a unique Email Address, Display Name, Ramblers Membership Number and combination of First Name, Last Name and Alias. Please amend the current member and try again.'; $scope.display.duplicate = true; } notify.clearBusy(); notify.error({ title: 'Member could not be saved', message: message }); } function resetSendFlags() { logger.debug('resetSendFlags'); $scope.display.saveInProgress = false; return applyAllowEdits(); } $scope.<API key> = function () { return $scope.notify.showAlert && $scope.<API key>; }; $scope.<API key> = [ {title: "All"}, {status: "created", title: "Created"}, {status: "summary", title: "Summary"}, {status: "skipped", title: "Skipped"}, {status: "updated", title: "Updated"}, {status: "error", title: "Error"}]; $scope.filters = { uploadSession: {selected: undefined}, memberUpdateAudit: { query: $scope.<API key>[0], orderByField: 'updateTime', reverseSort: true, sortDirection: DESCENDING }, membersUploaded: { query: '', orderByField: 'email', reverseSort: true, sortDirection: DESCENDING } }; function applySortTo(field, filterSource) { logger.debug('sorting by field', field, 'current value of filterSource', filterSource); if (field === 'member') { filterSource.orderByField = 'memberId | memberIdToFullName : members : "" : true'; } else { filterSource.orderByField = field; } filterSource.reverseSort = !filterSource.reverseSort; filterSource.sortDirection = filterSource.reverseSort ? DESCENDING : ASCENDING; logger.debug('sorting by field', field, 'new value of filterSource', filterSource); } $scope.<API key> = function () { notify.setBusy(); notify.hide(); <API key>().then(notify.clearBusy); }; $scope.<API key> = function (field) { applySortTo(field, $scope.filters.membersUploaded); }; $scope.<API key> = function (field) { applySortTo(field, $scope.filters.memberUpdateAudit); }; $scope.<API key> = function (field) { return s.startsWith($scope.filters.memberUpdateAudit.orderByField, field); }; $scope.<API key> = function (field) { return $scope.filters.membersUploaded.orderByField === field; }; $scope.sortMembersBy = function (field) { applySortTo(field, $scope.filters.members); }; $scope.showMembersColumn = function (field) { return s.startsWith($scope.filters.members.orderByField, field); }; $scope.toGlyphicon = function (status) { if (status === 'created') return "glyphicon glyphicon-plus green-icon"; if (status === 'complete' || status === 'summary') return "glyphicon-ok green-icon"; if (status === 'success') return "glyphicon-ok-circle green-icon"; if (status === 'info') return "glyphicon-info-sign blue-icon"; if (status === 'updated') return "glyphicon glyphicon-pencil green-icon"; if (status === 'error') return "<API key> red-icon"; if (status === 'skipped') return "glyphicon glyphicon-thumbs-up green-icon"; }; $scope.filters.members = { query: '', orderByField: 'firstName', reverseSort: false, sortDirection: ASCENDING, filterBy: [ { title: "Active Group Member", group: 'Group Settings', filter: function (member) { return member.groupMember; } }, { title: "All Members", filter: function () { return true; } }, { title: "Active Social Member", group: 'Group Settings', filter: MemberService.filterFor.SOCIAL_MEMBERS }, { title: "Membership Date Active/Not set", group: 'From Ramblers Supplied Datas', filter: function (member) { return !member.<API key> || (member.<API key> >= $scope.today); } }, { title: "Membership Date Expired", group: 'From Ramblers Supplied Data', filter: function (member) { return member.<API key> < $scope.today; } }, { title: "Not received in last Ramblers Bulk Load", group: 'From Ramblers Supplied Data', filter: function (member) { return !member.<API key>; } }, { title: "Was received in last Ramblers Bulk Load", group: 'From Ramblers Supplied Data', filter: function (member) { return member.<API key>; } }, { title: "Password Expired", group: 'Other Settings', filter: function (member) { return member.expiredPassword; } }, { title: "Walk Admin", group: 'Administrators', filter: function (member) { return member.walkAdmin; } }, { title: "Walk Change Notifications", group: 'Administrators', filter: function (member) { return member.<API key>; } }, { title: "Social Admin", group: 'Administrators', filter: function (member) { return member.socialAdmin; } }, { title: "Member Admin", group: 'Administrators', filter: function (member) { return member.memberAdmin; } }, { title: "Finance Admin", group: 'Administrators', filter: function (member) { return member.financeAdmin; } }, { title: "File Admin", group: 'Administrators', filter: function (member) { return member.fileAdmin; } }, { title: "Treasury Admin", group: 'Administrators', filter: function (member) { return member.treasuryAdmin; } }, { title: "Content Admin", group: 'Administrators', filter: function (member) { return member.contentAdmin; } }, { title: "Committee Member", group: 'Administrators', filter: function (member) { return member.committee; } }, { title: "Subscribed to the General emails list", group: 'Email Subscriptions', filter: MemberService.filterFor.<API key> }, { title: "Subscribed to the Walks email list", group: 'Email Subscriptions', filter: MemberService.filterFor.<API key> }, { title: "Subscribed to the Social email list", group: 'Email Subscriptions', filter: MemberService.filterFor.<API key> } ] }; $scope.filters.members.filterSelection = $scope.filters.members.filterBy[0].filter; $scope.memberAuditTabs = [ {title: "All Member Logins", active: true} ]; applyAllowEdits(); $scope.allowConfirmDelete = false; $scope.open = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.members = []; $scope.memberAudit = []; $scope.memberUpdateAudit = []; $scope.membersUploaded = []; $scope.<API key> = function () { // careful with calling this - it resets all batch subscriptions to default values return <API key>.<API key>($scope.members, false); }; function updateWalksList(members) { return <API key>.<API key>('walks', members); } function <API key>(members) { return <API key>.<API key>('socialEvents', members); } function updateGeneralList(members) { return <API key>.<API key>('general', members); } function <API key>(members) { notify.success({title: 'Mailchimp updates', message: 'Mailchimp lists were updated successfully'}); $scope.members = members; notify.clearBusy(); } $scope.deleteMemberAudit = function (filteredMemberAudit) { <API key>(filteredMemberAudit, refreshMemberAudit, 'member audit'); }; $scope.<API key> = function (<API key>) { <API key>(<API key>, <API key>, 'member update audit'); }; function <API key>(records, refreshFunction, type) { notify.success('Deleting ' + records.length + ' ' + type + ' record(s)'); var removePromises = []; angular.forEach(records, function (record) { removePromises.push(record.$remove()) }); $q.all(removePromises).then(function () { notify.success('Deleted ' + records.length + ' ' + type + ' record(s)'); refreshFunction.apply(); }); } $scope.$on('memberLoginComplete', function () { applyAllowEdits('memberLoginComplete'); refreshMembers(); refreshMemberAudit(); <API key>() .then(<API key>); }); $scope.$on('memberSaveComplete', function () { refreshMembers(); }); $scope.$on('<API key>', function () { applyAllowEdits('<API key>'); }); $scope.<API key> = function (memberFromAudit) { var member = new MemberService(memberFromAudit); <API key>.<API key>(member, true); member.groupMember = true; showMemberDialog(member, 'Add New'); notify.warning({ title: 'Recreating Member', message: "Note that clicking Save immediately on this member is likely to cause the same error to occur as was originally logged in the audit. Therefore make the necessary changes here to allow the member record to be saved successfully" }) }; $scope.addMember = function () { var member = new MemberService(); <API key>.<API key>(member, true); member.groupMember = true; showMemberDialog(member, 'Add New'); }; $scope.viewMember = function (member) { showMemberDialog(member, 'View'); }; $scope.editMember = function (member) { showMemberDialog(member, 'Edit Existing'); }; $scope.deleteMemberDetails = function () { $scope.allowDelete = false; $scope.allowConfirmDelete = true; }; function <API key>() { return <API key>.<API key>('walks', $scope.members, notify.success); } function <API key>(members) { return <API key>.<API key>('socialEvents', members, notify.success); } function <API key>(members) { return <API key>.<API key>('general', members, notify.success); } $scope.<API key> = function () { $scope.display.saveInProgress = true; return $q.when(notify.success('Sending updates to Mailchimp lists', true)) .then(refreshMembers, notify.error, notify.success) .then(updateWalksList, notify.error, notify.success) .then(<API key>, notify.error, notify.success) .then(updateGeneralList, notify.error, notify.success) .then(<API key>, notify.error, notify.success) .then(<API key>, notify.error, notify.success) .then(<API key>, notify.error, notify.success) .then(<API key>, notify.error, notify.success) .then(resetSendFlags) .catch(mailchimpError); }; function mailchimpError(errorResponse) { resetSendFlags(); notify.error({ title: 'Mailchimp updates failed', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + ErrorMessageService.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } $scope.<API key> = function () { $scope.currentMember.$remove(<API key>); }; $scope.cancelMemberDetails = function () { <API key>(); }; $scope.<API key> = function () { <API key>.processMember($scope.currentMember); }; $scope.refreshMemberAudit = refreshMemberAudit; $scope.memberUrl = function () { return $scope.currentMember && $scope.currentMember.$id && (MONGOLAB_CONFIG.baseUrl + MONGOLAB_CONFIG.database + '/collections/members/' + $scope.currentMember.$id()); }; $scope.saveMemberDetails = function () { var member = DateUtils.<API key>($scope.currentMember, '<API key>'); $scope.display.saveInProgress = true; if (!member.userName) { member.userName = MemberNamingService.<API key>(member, $scope.members); logger.debug('creating username', member.userName); } if (!member.displayName) { member.displayName = MemberNamingService.<API key>(member, $scope.members); logger.debug('creating displayName', member.displayName); } function <API key>() { DbUtils.removeEmptyFieldsIn(member); return <API key>.<API key>(member); } function removeEmptyFieldsIn(obj) { _.each(obj, function (value, field) { logger.debug('processing', typeof(field), 'field', field, 'value', value); if (_.contains([null, undefined, ""], value)) { logger.debug('removing non-populated', typeof(field), 'field', field); delete obj[field]; } }); } function saveAndHide() { return DbUtils.auditedSaveOrUpdate(member, <API key>, notify.error) } $q.when(notify.success('Saving member', true)) .then(<API key>, notify.error, notify.success) .then(saveAndHide, notify.error, notify.success) .then(resetSendFlags) .then(function () { return notify.success('Member saved successfully'); }) .catch(handleSaveError) }; $scope.<API key> = function () { var copiedMember = new MemberService($scope.currentMember); delete copiedMember._id; <API key>.<API key>(copiedMember, true); <API key>.unconfirmProfile(copiedMember); showMemberDialog(copiedMember, 'Copy Existing'); notify.success('Existing Member copied! Make changes here and save to create new member.') }; function applyAllowEdits() { $scope.allowEdits = <API key>.<API key>(); $scope.allowCopy = <API key>.<API key>(); return true; } function <API key>(member) { var memberAudit = _.chain($scope.memberAudit) .filter(function (memberAudit) { return memberAudit.userName === member.userName; }) .sortBy(function (memberAudit) { return memberAudit.lastLoggedIn; }) .last() .value(); return memberAudit === undefined ? undefined : memberAudit.loginTime; } $scope.<API key> = function () { $('#<API key>').click(); }; $scope.<API key> = function (error) { logger.error('<API key>', error); resetSendFlags(); return notify.error(error); }; $scope.<API key> = function (file) { if (file) { var fileUpload = file; $scope.display.saveInProgress = true; function <API key>(<API key>) { return <API key>.<API key>(file, <API key>, $scope.members, notify) } function <API key>(evt) { fileUpload.progress = parseInt(100.0 * evt.loaded / evt.total); logger.debug("<API key>:progress event", evt); } $scope.uploadedFile = Upload.upload({ url: 'uploadRamblersData', method: 'POST', file: file }).then(<API key>, $scope.<API key>, <API key>) .then(<API key>) .then(<API key>) .then(<API key>) .catch($scope.<API key>); } }; function showMemberDialog(member, memberEditMode) { logger.debug('showMemberDialog:', memberEditMode, member); $scope.<API key> = false; var <API key> = $scope.allowEdits && s.startsWith(memberEditMode, 'Edit'); $scope.allowConfirmDelete = false; $scope.allowCopy = <API key>; $scope.allowDelete = <API key>; $scope.memberEditMode = memberEditMode; $scope.currentMember = member; $scope.<API key> = []; if ($scope.currentMember.$id()) { logger.debug('querying <API key> for memberId', $scope.currentMember.$id()); <API key>.query({memberId: $scope.currentMember.$id()}, {sort: {updateTime: -1}}) .then(function (data) { logger.debug('<API key>:', data.length, 'events', data); $scope.<API key> = data; }); $scope.lastLoggedIn = <API key>(member); } else { logger.debug('new member with default values', $scope.currentMember); } $('#member-admin-dialog').modal(); } function <API key>() { $q.when($('#member-admin-dialog').modal('hide')) .then(refreshMembers) .then(notify.clearBusy) .then(notify.hide) } function refreshMembers() { if (<API key>.<API key>()) { return MemberService.all() .then(function (refreshedMembers) { $scope.members = refreshedMembers; return $scope.members; }); } } function refreshMemberAudit() { if (<API key>.<API key>()) { MemberAuditService.all({limit: 100, sort: {loginTime: -1}}).then(function (memberAudit) { logger.debug('refreshed', memberAudit && memberAudit.length, 'member audit records'); $scope.memberAudit = memberAudit; }); } return true; } function <API key>() { if (<API key>.<API key>()) { return <API key>.all({limit: 100, sort: {createdDate: -1}}).then(function (uploadSessions) { logger.debug('refreshed', uploadSessions && uploadSessions.length, 'upload sessions'); $scope.uploadSessions = uploadSessions; $scope.filters.uploadSession.selected = _.first(uploadSessions); return $scope.filters.uploadSession.selected; }); } else { return true; } } function migrateAudits() { // temp - remove this! <API key>.all({ limit: 10000, sort: {updateTime: -1} }).then(function (<API key>) { logger.debug('temp queried all', <API key> && <API key>.length, 'member audit records'); var keys = []; var <API key> = []; var <API key> = []; var bulkAudits = _.chain(<API key>) // .filter(function (audit) { // return !audit.uploadSessionId; .map(function (audit) { var auditLog = { fileName: audit.fileName, createdDate: DateUtils.asValueNoTime(audit.updateTime), auditLog: [ { "status": "complete", "message": "Migrated audit log for upload of file " + audit.fileName } ] }; return auditLog; }) .uniq(JSON.stringify) .map(function (auditLog) { return new <API key>(auditLog).$save() .then(function (auditResponse) { <API key>.push(auditResponse); logger.debug('saved bulk load session id', auditResponse.$id(), 'number', <API key>.length); return auditResponse; }); }) .value(); function saveAudit(audit) { <API key>.push(audit.$saveOrUpdate()); logger.debug('saved', audit.uploadSessionId, 'to audit number', <API key>.length); } $q.all(bulkAudits).then(function (<API key>) { logger.debug('saved bulk load sessions', <API key>); _.each(<API key>, function (audit) { var parentBulkAudit = _.findWhere(<API key>, { fileName: audit.fileName, createdDate: DateUtils.asValueNoTime(audit.updateTime) }); if (parentBulkAudit) { audit.uploadSessionId = parentBulkAudit.$id(); saveAudit(audit); } else { logger.error('no match for audit record', audit); } }); $q.all(<API key>).then(function (values) { logger.debug('saved', values.length, 'audit records'); }); }); }); } function <API key>() { if (<API key>.<API key>()) { // migrateAudits(); if ($scope.filters.uploadSession.selected && $scope.filters.uploadSession.selected.$id) { var uploadSessionId = $scope.filters.uploadSession.selected.$id(); var query = {uploadSessionId: uploadSessionId}; if ($scope.filters.memberUpdateAudit.query.status) { angular.extend(query, {memberAction: $scope.filters.memberUpdateAudit.query.status}) } logger.debug('querying member audit records with', query); return <API key>.query(query, {sort: {updateTime: -1}}).then(function (memberUpdateAudit) { $scope.memberUpdateAudit = memberUpdateAudit; logger.debug('refreshed', memberUpdateAudit && memberUpdateAudit.length, 'member audit records'); return $scope.memberUpdateAudit; }); } else { $scope.memberUpdateAudit = []; logger.debug('no member audit records'); return $q.when($scope.memberUpdateAudit); } } } function auditSummary() { return _.groupBy($scope.memberUpdateAudit, function (auditItem) { return auditItem.memberAction || 'unknown'; }); } function <API key>(auditSummary) { var total = _.reduce(auditSummary, function (memo, value) { return memo + value.length; }, 0); var summary = _.map(auditSummary, function (items, key) { return items.length + ':' + key; }).join(', '); return total + " Member audits " + (total ? '(' + summary + ')' : ''); } $scope.<API key> = function () { return <API key>(auditSummary()); }; function <API key>() { logger.debug('<API key>:$scope.filters.uploadSession', $scope.filters.uploadSession); if ($scope.filters.uploadSession.selected.error) { notify.error({title: 'Bulk upload failed', message: $scope.filters.uploadSession.selected.error}); } else { var summary = auditSummary(); var summaryFormatted = <API key>(summary); logger.debug('summary', summary, 'summaryFormatted', summaryFormatted); if (summary.error) { notify.error({ title: "Bulk upload was not successful", message: "One or more errors occurred - " + summaryFormatted }); return false; } else return $scope.<API key>(); } } }] ) ; /* concatenated from client/src/app/js/<API key>.js */ angular.module('ekwgApp') .controller('<API key>', ["$log", "$q", "$scope", "$filter", "DateUtils", "DbUtils", "<API key>", "ErrorMessageService", "<API key>", "<API key>", "<API key>", "MailchimpConfig", "Notifier", "members", "close", function ($log, $q, $scope, $filter, DateUtils, DbUtils, <API key>, ErrorMessageService, <API key>, <API key>, <API key>, MailchimpConfig, Notifier, members, close) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; var notify = Notifier($scope); notify.setBusy(); var <API key> = "welcome"; var <API key> = "passwordReset"; var <API key> = "<API key>"; var <API key> = "expiredMembers"; $scope.today = DateUtils.momentNowNoTime().valueOf(); $scope.members = members; $scope.<API key> = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.<API key>.opened = true; } }; $scope.showHelp = function (show) { $scope.display.showHelp = show; }; $scope.cancel = function () { close(); }; $scope.display = { showHelp: false, selectableMembers: [], emailMembers: [], saveInProgress: false, monthsInPast: 1, memberFilterDate: undefined, emailType: {name: "(loading)"}, <API key>: function () { return 'About to send a ' + $scope.display.emailType.name + ' to ' + $scope.display.emailMembers.length + ' member' + ($scope.display.emailMembers.length === 1 ? '' : 's'); }, <API key>: function () { var returnValue = $scope.display.emailType.type === <API key> || $scope.display.emailType.type === <API key>; logger.debug('<API key> -> ', returnValue); return returnValue; }, <API key>: function () { return $scope.display.emailType.type === <API key> || $scope.display.emailType.type === <API key>; } }; $scope.<API key> = function () { $scope.display.selectableMembers = _.chain($scope.members) .filter(function (member) { return <API key>.<API key>('general', member); }) .map(<API key>) .value(); logger.debug('<API key>:found', $scope.display.selectableMembers.length, 'members'); }; $scope.<API key>(); $scope.<API key> = function () { $scope.display.memberFilterDate = DateUtils.momentNowNoTime().subtract($scope.display && $scope.display.emailType.monthsInPast, 'months').valueOf(); }; $scope.<API key> = function () { $scope.display.emailMembers = []; notify.warning({ title: 'Member selection', message: 'current member selection was cleared' }); }; function <API key>(member) { return $scope.display.<API key>() ? <API key>(member) : <API key>(member); } function <API key>(member) { var expiredActive = member.<API key> < $scope.today ? 'expired' : 'active'; var memberGrouping = member.<API key> ? expiredActive : 'missing from last bulk load'; var datePrefix = memberGrouping === 'expired' ? ': ' : ', ' + (member.<API key> < $scope.today ? 'expired' : 'expiry') + ': '; var text = $filter('fullNameWithAlias')(member) + ' (' + memberGrouping + datePrefix + (DateUtils.displayDate(member.<API key>) || 'not known') + ')'; return angular.extend({}, member, {id: member.$id(), text: text, memberGrouping: memberGrouping}); } function <API key>(member) { var memberGrouping = member.<API key> < $scope.today ? 'expired' : 'active'; var text = $filter('fullNameWithAlias')(member) + ' (created ' + (DateUtils.displayDate(member.createdDate) || 'not known') + ')'; return angular.extend({}, member, {id: member.$id(), text: text, memberGrouping: memberGrouping}); } $scope.memberGrouping = function (member) { return member.memberGrouping; }; function <API key>(filter) { logger.debug('<API key>: display.emailType ->', $scope.display.emailType); notify.setBusy(); notify.warning({ title: 'Automatically adding expired members', message: ' - please wait for list to be populated' }); $scope.display.memberFilterDate = DateUtils.convertDateField($scope.display.memberFilterDate); $scope.display.emailMembers = _($scope.display.selectableMembers) .filter(filter); notify.warning({ title: 'Members added to email selection', message: 'automatically added ' + $scope.display.emailMembers.length + ' members' }); notify.clearBusy(); } $scope.populateMembers = function (<API key>) { logger.debug('$scope.display.memberSelection', $scope.display.emailType.memberSelection); this.<API key>(); switch ($scope.display.emailType.memberSelection) { case 'recently-added': $scope.<API key>(<API key>); break; case 'expired-members': $scope.<API key>(<API key>); break } }; $scope.<API key> = function (<API key>) { if (<API key>) { $scope.<API key>(); } <API key>(function (member) { return member.groupMember && (member.createdDate >= $scope.display.memberFilterDate); }); }; $scope.<API key> = function (<API key>) { if (<API key>) { $scope.<API key>(); } <API key>(function (member) { return member.groupMember && member.<API key> && (member.<API key> < $scope.display.memberFilterDate); }); }; $scope.<API key> = function (<API key>) { if (<API key>) { $scope.<API key>(); } <API key>(function (member) { return member.groupMember && member.<API key> && !member.<API key>; }) }; function <API key>() { return _.chain($scope.display.emailMembers) .map(function (memberId) { return _.find($scope.members, function (member) { return member.$id() === memberId.id; }) }) .filter(function (member) { return member && member.email; }).value(); } function add<API key>() { var saveMemberPromises = []; _.map(<API key>(), function (member) { <API key>.setPasswordResetId(member); <API key>.<API key>(member); saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member)) }); return $q.all(saveMemberPromises).then(function () { return notify.success('Password reset prepared for ' + saveMemberPromises.length + ' member(s)'); }); } function <API key>() { var saveMemberPromises = []; _.map(<API key>(), function (member) { <API key>.<API key>(member); saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member)) }); return $q.all(saveMemberPromises).then(function () { return notify.success('Member expiration prepared for ' + saveMemberPromises.length + ' member(s)'); }); } function noAction() { } function <API key>() { logger.debug('removing ', $scope.display.emailMembers.length, 'members from group'); var saveMemberPromises = []; _($scope.display.emailMembers) .map(function (memberId) { return _.find($scope.members, function (member) { return member.$id() === memberId.id; }) }).map(function (member) { member.groupMember = false; <API key>.<API key>(member); saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member)) }); return $q.all(saveMemberPromises) .then(function () { return notify.success('EKWG group membership removed for ' + saveMemberPromises.length + ' member(s)'); }) } $scope.cancelSendEmails = function () { $scope.cancel(); }; $scope.sendEmailsDisabled = function () { return $scope.display.emailMembers.length === 0 }; $scope.sendEmails = function () { $scope.<API key> = true; $scope.display.saveInProgress = true; $scope.display.duplicate = false; $q.when(notify.success('Preparing to email ' + $scope.display.emailMembers.length + ' member' + ($scope.display.emailMembers.length === 1 ? '' : 's'), true)) .then($scope.display.emailType.preSend) .then(updateGeneralList) .then(<API key>) .then(<API key>) .then(sendEmailCampaign) .then($scope.display.emailType.postSend) .then(notify.clearBusy) .then($scope.cancel) .then(resetSendFlags) .catch(handleSendError); }; function resetSendFlags() { logger.debug('resetSendFlags'); $scope.display.saveInProgress = false; } function updateGeneralList() { return <API key>.<API key>('general', $scope.members).then(function (updatedMembers) { $scope.members = updatedMembers; }); } function <API key>() { return <API key>.saveSegment('general', {segmentId: $scope.display.emailType.segmentId}, $scope.display.emailMembers, $scope.display.emailType.name, $scope.members); } function <API key>(segmentResponse) { logger.debug('<API key>:segmentResponse', segmentResponse); return MailchimpConfig.getConfig() .then(function (config) { config.mailchimp.segments.general[$scope.display.emailType.type + 'SegmentId'] = segmentResponse.segment.id; return MailchimpConfig.saveConfig(config) .then(function () { logger.debug('<API key>:returning segment id', segmentResponse.segment.id); return segmentResponse.segment.id; }); }); } function sendEmailCampaign(segmentId) { var members = $scope.display.emailMembers.length + ' member(s)'; notify.success('Sending ' + $scope.display.emailType.name + ' email to ' + members); logger.debug('about to sendEmailCampaign:', $scope.display.emailType.type, 'campaign Id', $scope.display.emailType.campaignId, 'segmentId', segmentId, 'campaignName', $scope.display.emailType.name); return <API key>.<API key>({ campaignId: $scope.display.emailType.campaignId, campaignName: $scope.display.emailType.name, segmentId: segmentId }).then(function () { notify.success('Sending of ' + $scope.display.emailType.name + ' to ' + members + ' was successful'); }); } $scope.emailMemberList = function () { return _($scope.display.emailMembers) .sortBy(function (emailMember) { return emailMember.text; }).map(function (emailMember) { return emailMember.text; }).join(', '); }; function handleSendError(errorResponse) { $scope.display.saveInProgress = false; notify.error({ title: 'Your notification could not be sent', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + ErrorMessageService.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } MailchimpConfig.getConfig() .then(function (config) { $scope.display.emailTypes = [ { preSend: add<API key>, type: <API key>, name: config.mailchimp.campaigns.welcome.name, monthsInPast: config.mailchimp.campaigns.welcome.monthsInPast, campaignId: config.mailchimp.campaigns.welcome.campaignId, segmentId: config.mailchimp.segments.general.welcomeSegmentId, memberSelection: 'recently-added', postSend: noAction, dateTooltip: "All members created in the last " + config.mailchimp.campaigns.welcome.monthsInPast + " month are displayed as a default, as these are most likely to need a welcome email sent" }, { preSend: add<API key>, type: <API key>, name: config.mailchimp.campaigns.passwordReset.name, monthsInPast: config.mailchimp.campaigns.passwordReset.monthsInPast, campaignId: config.mailchimp.campaigns.passwordReset.campaignId, segmentId: config.mailchimp.segments.general.<API key>, memberSelection: 'recently-added', postSend: noAction, dateTooltip: "All members created in the last " + config.mailchimp.campaigns.passwordReset.monthsInPast + " month are displayed as a default" }, { preSend: <API key>, type: <API key>, name: config.mailchimp.campaigns.<API key>.name, monthsInPast: config.mailchimp.campaigns.<API key>.monthsInPast, campaignId: config.mailchimp.campaigns.<API key>.campaignId, segmentId: config.mailchimp.segments.general.<API key>, memberSelection: 'expired-members', postSend: noAction, dateTooltip: "Using the expiry date field, you can choose which members will automatically be included. " + "A date " + config.mailchimp.campaigns.<API key>.monthsInPast + " months in the past has been pre-selected, to avoid including members whose membership renewal is still progress" }, { preSend: <API key>, type: <API key>, name: config.mailchimp.campaigns.expiredMembers.name, monthsInPast: config.mailchimp.campaigns.expiredMembers.monthsInPast, campaignId: config.mailchimp.campaigns.expiredMembers.campaignId, segmentId: config.mailchimp.segments.general.<API key>, memberSelection: 'expired-members', postSend: <API key>, dateTooltip: "Using the expiry date field, you can choose which members will automatically be included. " + "A date 3 months in the past has been pre-selected, to avoid including members whose membership renewal is still progress" } ]; $scope.display.emailType = $scope.display.emailTypes[0]; $scope.populateMembers(true); }); }] ); /* concatenated from client/src/app/js/memberResources.js */ angular.module('ekwgApp') .factory('<API key>', ["$<API key>", function ($<API key>) { return $<API key>('memberResources'); }]) .factory('<API key>', ["$log", "URLService", "<API key>", "FileUtils", "<API key>", "SiteEditService", function ($log, URLService, <API key>, FileUtils, <API key>, SiteEditService) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; const subjects = [ { id: "newsletter", description: "Newsletter" }, { id: "siteReleaseNote", description: "Site Release Note" }, { id: "walkPlanning", description: "Walking Planning Advice" } ]; const resourceTypes = [ { id: "email", description: "Email", action: "View email", icon: function () { return "assets/images/local/mailchimp.ico" }, resourceUrl: function (memberResource) { var data = _.property(['data', 'campaign', 'archive_url_long'])(memberResource); logger.debug('email:resourceUrl for', memberResource, data); return data; } }, { id: "file", description: "File", action: "Download", icon: function (memberResource) { return FileUtils.icon(memberResource, 'data') }, resourceUrl: function (memberResource) { var data = memberResource && memberResource.data.fileNameData ? URLService.baseUrl() + <API key>.baseUrl("memberResources") + "/" + memberResource.data.fileNameData.awsFileName : ""; logger.debug('file:resourceUrl for', memberResource, data); return data; } }, { id: "url", action: "View page", description: "External Link", icon: function () { return "assets/images/ramblers/favicon.ico" }, resourceUrl: function () { return "TBA"; } } ]; const accessLevels = [ { id: "hidden", description: "Hidden", filter: function () { return SiteEditService.active() || false; } }, { id: "committee", description: "Committee", filter: function () { return SiteEditService.active() || <API key>.allowCommittee(); } }, { id: "loggedInMember", description: "Logged-in member", filter: function () { return SiteEditService.active() || <API key>.memberLoggedIn(); } }, { id: "public", description: "Public", filter: function () { return true; } }]; function resourceTypeFor(resourceType) { var type = _.find(resourceTypes, function (type) { return type.id === resourceType; }); logger.debug('resourceType for', type, type); return type; } function accessLevelFor(accessLevel) { var level = _.find(accessLevels, function (level) { return level.id === accessLevel; }); logger.debug('accessLevel for', accessLevel, level); return level; } return { subjects: subjects, resourceTypes: resourceTypes, accessLevels: accessLevels, resourceTypeFor: resourceTypeFor, accessLevelFor: accessLevelFor }; }]); /* concatenated from client/src/app/js/memberServices.js */ angular.module('ekwgApp') .factory('<API key>', ["$<API key>", function ($<API key>) { return $<API key>('memberUpdateAudit'); }]) .factory('<API key>', ["$<API key>", function ($<API key>) { return $<API key>('memberBulkLoadAudit'); }]) .factory('MemberAuditService', ["$<API key>", function ($<API key>) { return $<API key>('memberAudit'); }]) .factory('<API key>', ["$<API key>", function ($<API key>) { return $<API key>('expenseClaims'); }]) .factory('MemberNamingService', ["$log", "StringUtils", function ($log, StringUtils) { var logger = $log.getInstance('MemberNamingService'); $log.logLevels['MemberNamingService'] = $log.LEVEL.OFF; var createUserName = function (member) { return StringUtils.replaceAll(' ', '', (member.firstName + '.' + member.lastName).toLowerCase()); }; function createDisplayName(member) { return member.firstName.trim() + ' ' + member.lastName.trim().substring(0, 1).toUpperCase(); } function <API key>(member, members) { return <API key>(createUserName, 'userName', member, members) } function <API key>(member, members) { return <API key>(createDisplayName, 'displayName', member, members) } function <API key>(nameFunction, field, member, members) { var attempts = 0; var suffix = ""; while (true) { var createdName = nameFunction(member) + suffix; if (!memberFieldExists(field, createdName, members)) { return createdName } else { attempts++; suffix = attempts; } } } function memberFieldExists(field, value, members) { var member = _(members).find(function (member) { return member[field] === value; }); var returnValue = member && member[field]; logger.debug('field', field, 'matching', value, member, '->', returnValue); return returnValue; } return { createDisplayName: createDisplayName, createUserName: createUserName, <API key>: <API key>, <API key>: <API key> }; }]) .factory('MemberService', ["$<API key>", "$log", function ($<API key>, $log) { var logger = $log.getInstance('MemberService'); var noLogger = $log.getInstance('MemberServiceMuted'); $log.logLevels['MemberServiceMuted'] = $log.LEVEL.OFF; $log.logLevels['MemberService'] = $log.LEVEL.OFF; var memberService = $<API key>('members'); memberService.filterFor = { <API key>: function (member) { return member.groupMember && member.socialMember && member.mailchimpLists.socialEvents.subscribed }, <API key>: function (member) { return member.groupMember && member.mailchimpLists.walks.subscribed }, <API key>: function (member) { return member.groupMember && member.mailchimpLists.general.subscribed }, GROUP_MEMBERS: function (member) { return member.groupMember; }, COMMITTEE_MEMBERS: function (member) { return member.groupMember && member.committee; }, SOCIAL_MEMBERS: function (member) { return member.groupMember && member.socialMember; }, }; memberService.allLimitedFields = function allLimitedFields(filterFunction) { return memberService.all({ fields: { mailchimpLists: 1, groupMember: 1, socialMember: 1, financeAdmin: 1, treasuryAdmin: 1, fileAdmin: 1, committee: 1, <API key>: 1, email: 1, displayName: 1, contactId: 1, mobileNumber: 1, $id: 1, firstName: 1, lastName: 1, nameAlias: 1 } }).then(function (members) { return _.chain(members) .filter(filterFunction) .sortBy(function (member) { return member.firstName + member.lastName; }).value(); }); }; memberService.toMember = function (memberIdOrObject, members) { var memberId = (_.has(memberIdOrObject, 'id') ? memberIdOrObject.id : memberIdOrObject); noLogger.info('toMember:memberIdOrObject', memberIdOrObject, '->', memberId); var member = _.find(members, function (member) { return member.$id() === memberId; }); noLogger.info('toMember:', memberIdOrObject, '->', member); return member; }; memberService.<API key> = function (privilege, members) { var filteredMembers = _.filter(members, function (member) { return member.groupMember && member[privilege]; }); logger.debug('<API key>:privilege', privilege, 'filtered from', members.length, '->', filteredMembers.length, 'members ->', filteredMembers); return filteredMembers; }; memberService.<API key> = function (privilege, members) { return memberService.<API key>(privilege, members).map(extractMemberId); function extractMemberId(member) { return member.$id() } }; return memberService; }]); /* concatenated from client/src/app/js/notificationUrl.js */ angular.module("ekwgApp") .component("notificationUrl", { templateUrl: "partials/components/notification-url.html", controller: ["$log", "URLService", "FileUtils", function ($log, URLService, FileUtils) { var ctrl = this; var logger = $log.getInstance("<API key>"); $log.logLevels['<API key>'] = $log.LEVEL.OFF; ctrl.anchor_href = function () { return URLService.notificationHref(ctrl); }; ctrl.anchor_target = function () { return "_blank"; }; ctrl.anchor_text = function () { var text = (!ctrl.text && ctrl.name) ? FileUtils.basename(ctrl.name) : ctrl.text || ctrl.anchor_href(); logger.debug("text", text); return text; }; }], bindings: { name: "@", text: "@", type: "@", id: "@", area: "@" } }); /* concatenated from client/src/app/js/notifier.js */ angular.module('ekwgApp') .factory('Notifier', ["$log", "ErrorMessageService", function ($log, ErrorMessageService) { var ALERT_ERROR = {class: 'alert-danger', icon: '<API key>', failure: true}; var ALERT_WARNING = {class: 'alert-warning', icon: 'glyphicon-info-sign'}; var ALERT_INFO = {class: 'alert-success', icon: 'glyphicon-info-sign'}; var ALERT_SUCCESS = {class: 'alert-success', icon: 'glyphicon-ok'}; var logger = $log.getInstance('Notifier'); $log.logLevels['Notifier'] = $log.LEVEL.OFF; return function (scope) { scope.alertClass = ALERT_SUCCESS.class; scope.alert = ALERT_SUCCESS; scope.alertMessages = []; scope.alertHeading = []; scope.ready = false; function setReady() { clearBusy(); return scope.ready = true; } function clearBusy() { logger.debug('clearing busy'); return scope.busy = false; } function setBusy() { logger.debug('setting busy'); return scope.busy = true; } function showContactUs(state) { logger.debug('setting showContactUs', state); return scope.showContactUs = state; } function notifyAlertMessage(alertType, message, append, busy) { var messageText = message && ErrorMessageService.stringify(_.has(message, 'message') ? message.message : message); if (busy) setBusy(); if (!append || alertType === ALERT_ERROR) scope.alertMessages = []; if (messageText) scope.alertMessages.push(messageText); scope.alertTitle = message && _.has(message, 'title') ? message.title : undefined; scope.alert = alertType; scope.alertClass = alertType.class; scope.showAlert = scope.alertMessages.length > 0; scope.alertMessage = scope.alertMessages.join(', '); if (alertType === ALERT_ERROR && !_.has(message, 'continue')) { logger.error('notifyAlertMessage:', 'class =', alertType, 'messageText =', messageText, 'append =', append); clearBusy(); throw message; } else { return logger.debug('notifyAlertMessage:', 'class =', alertType, 'messageText =', messageText, 'append =', append, 'showAlert =', scope.showAlert); } } function progress(message, busy) { return notifyAlertMessage(ALERT_INFO, message, false, busy) } function hide() { notifyAlertMessage(ALERT_SUCCESS); return clearBusy(); } function success(message, busy) { return notifyAlertMessage(ALERT_SUCCESS, message, false, busy) } function successWithAppend(message, busy) { return notifyAlertMessage(ALERT_SUCCESS, message, true, busy) } function error(message, append, busy) { return notifyAlertMessage(ALERT_ERROR, message, append, busy) } function warning(message, append, busy) { return notifyAlertMessage(ALERT_WARNING, message, append, busy) } return { success: success, successWithAppend: successWithAppend, progress: progress, progressWithAppend: successWithAppend, error: error, warning: warning, showContactUs: showContactUs, setBusy: setBusy, clearBusy: clearBusy, setReady: setReady, hide: hide } } }]); /* concatenated from client/src/app/js/profile.js */ angular.module('ekwgApp') .factory('<API key>', ["$filter", "<API key>", "DateUtils", function ($filter, <API key>, DateUtils) { var confirmProfile = function (member) { if (member) { member.<API key> = true; member.<API key> = DateUtils.nowAsValue(); member.<API key> = $filter('fullNameWithAlias')(<API key>.loggedInMember()); } }; var unconfirmProfile = function (member) { if (member) { delete member.<API key>; delete member.<API key>; delete member.<API key>; } }; var processMember = function (member) { if (member) { if (member.<API key>) { confirmProfile(member) } else { unconfirmProfile(member) } } }; return { confirmProfile: confirmProfile, unconfirmProfile: unconfirmProfile, processMember: processMember }; }]) .controller('ProfileController', ["$q", "$rootScope", "$routeParams", "$scope", "<API key>", "MemberService", "URLService", "<API key>", "<API key>", "<API key>", function ($q, $rootScope, $routeParams, $scope, <API key>, MemberService, URLService, <API key>, <API key>, <API key>) { $scope.showArea = function (area) { URLService.navigateTo('admin', area) }; $scope.contactUs = { ready: function () { return <API key>.ready; } }; function isArea(area) { return (area === $routeParams.area); } var LOGIN_DETAILS = 'login details'; var PERSONAL_DETAILS = 'personal details'; var CONTACT_PREFERENCES = 'contact preferences'; var ALERT_CLASS_DANGER = 'alert-danger'; var ALERT_CLASS_SUCCESS = 'alert-success'; $scope.currentMember = {}; $scope.<API key> = {}; $scope.alertClass = ALERT_CLASS_SUCCESS; $scope.alertType = LOGIN_DETAILS; $scope.alertMessages = []; $scope.personalDetailsOpen = isArea('personal-details'); $scope.loginDetailsOpen = isArea('login-details'); $scope.<API key> = isArea('contact-preferences'); $scope.<API key> = false; $scope.<API key> = false; $scope.<API key> = false; applyAllowEdits('controller init'); refreshMember(); $scope.$on('memberLoginComplete', function () { $scope.alertMessages = []; refreshMember(); applyAllowEdits('memberLoginComplete'); }); $scope.$on('<API key>', function () { $scope.alertMessages = []; applyAllowEdits('<API key>'); }); $scope.undoChanges = function () { refreshMember(); }; function <API key>() { $scope.<API key>.newPassword = null; $scope.<API key>.newPasswordConfirm = null; $scope.alertMessages.push('Your ' + $scope.alertType + ' were saved successfully and will be effective on your next login.'); showAlert(ALERT_CLASS_SUCCESS, $scope.alertType); } function <API key>(message) { var messageDefaulted = message || 'Please try again later.'; $scope.alertMessages.push('Changes to your ' + $scope.alertType + ' could not be saved. ' + messageDefaulted); showAlert(ALERT_CLASS_DANGER, $scope.alertType); } $scope.saveLoginDetails = function () { $scope.alertMessages = []; <API key>(); }; $scope.$on('<API key>', function () { validatePassword(); validateUserName(); if ($scope.alertMessages.length === 0) { saveMemberDetails(LOGIN_DETAILS) } else { showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); } }); $scope.savePersonalDetails = function () { $scope.alertMessages = []; saveMemberDetails(PERSONAL_DETAILS); }; $scope.<API key> = function () { $scope.alertMessages = []; <API key>.confirmProfile($scope.currentMember); saveMemberDetails(CONTACT_PREFERENCES); }; $scope.loggedIn = function () { return <API key>.memberLoggedIn(); }; function validatePassword() { if ($scope.<API key>.newPassword || $scope.<API key>.newPasswordConfirm) { // console.log('validating password change old=', $scope.<API key>.newPassword, 'new=', $scope.<API key>.newPasswordConfirm); if ($scope.currentMember.password === $scope.<API key>.newPassword) { $scope.alertMessages.push('The new password was the same as the old one.'); } else if ($scope.<API key>.newPassword !== $scope.<API key>.newPasswordConfirm) { $scope.alertMessages.push('The new password was not confirmed correctly.'); } else if ($scope.<API key>.newPassword.length < 6) { $scope.alertMessages.push('The new password needs to be at least 6 characters long.'); } else { $scope.currentMember.password = $scope.<API key>.newPassword; // console.log('validating password change - successful'); } } } function validateUserName() { if ($scope.<API key>.userName !== $scope.currentMember.userName) { $scope.<API key>.userName = $scope.<API key>.userName.trim(); if ($scope.<API key>.userName.length === 0) { $scope.alertMessages.push('The new user name cannot be blank.'); } else { $scope.currentMember.userName = $scope.<API key>.userName; } } } function undoChangesTo(alertType) { refreshMember(); $scope.alertMessages = ['Changes to your ' + alertType + ' were reverted.']; showAlert(ALERT_CLASS_SUCCESS, alertType); } $scope.undoLoginDetails = function () { undoChangesTo(LOGIN_DETAILS); }; $scope.undoPersonalDetails = function () { undoChangesTo(PERSONAL_DETAILS); }; $scope.<API key> = function () { undoChangesTo(CONTACT_PREFERENCES); }; function saveMemberDetails(alertType) { $scope.alertType = alertType; <API key>.<API key>($scope.currentMember); <API key>.saveMember($scope.currentMember, <API key>, <API key>); } function showAlert(alertClass, alertType) { if ($scope.alertMessages.length > 0) { $scope.alertClass = alertClass; $scope.alertMessage = $scope.alertMessages.join(', '); $scope.<API key> = alertType === LOGIN_DETAILS; $scope.<API key> = alertType === PERSONAL_DETAILS; $scope.<API key> = alertType === CONTACT_PREFERENCES; } else { $scope.<API key> = false; $scope.<API key> = false; $scope.<API key> = false; } } function applyAllowEdits(event) { $scope.allowEdits = <API key>.memberLoggedIn(); $scope.isAdmin = <API key>.<API key>(); } function refreshMember() { if (<API key>.memberLoggedIn()) { <API key>.<API key>(<API key>.loggedInMember().userName) .then(function (member) { if (!_.isEmpty(member)) { $scope.currentMember = member; $scope.<API key> = {userName: $scope.currentMember.userName}; } else { $scope.alertMessages.push('Could not refresh member'); showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); } }, function (response) { $scope.alertMessages.push('Unexpected error occurred: ' + response); showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); }) } } function <API key>() { if ($scope.<API key>.userName !== $scope.currentMember.userName) { <API key>.<API key>($scope.<API key>.userName) .then(function (member) { if (!_.isEmpty(member)) { $scope.alertMessages.push('The user name ' + $scope.<API key>.userName + ' is already used by another member. Please choose another.'); $scope.<API key>.userName = $scope.currentMember.userName; } $rootScope.$broadcast('<API key>'); }, function (response) { $scope.alertMessages.push('Unexpected error occurred: ' + response); showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); }); } else { $rootScope.$broadcast('<API key>'); } } }]); /* concatenated from client/src/app/js/<API key>.js */ angular.module('ekwgApp') .factory('RamblersHttpService', ["$q", "$http", function ($q, $http) { function call(serviceCallType, method, url, data, params) { var deferredTask = $q.defer(); deferredTask.notify(serviceCallType); $http({ method: method, data: data, params: params, url: url }).then(function (response) { var responseData = response.data; if (responseData.error) { deferredTask.reject(response); } else { deferredTask.notify(responseData.information); deferredTask.resolve(responseData) } }).catch(function (response) { deferredTask.reject(response); }); return deferredTask.promise; } return { call: call } }]) .factory('<API key>', ["$log", "$rootScope", "$http", "$q", "$filter", "DateUtils", "RamblersHttpService", "<API key>", "<API key>", function ($log, $rootScope, $http, $q, $filter, DateUtils, RamblersHttpService, <API key>, <API key>) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; function uploadRamblersWalks(data) { return RamblersHttpService.call('Upload Ramblers walks', 'POST', '<API key>/uploadWalks', data); } function listRamblersWalks() { return RamblersHttpService.call('List Ramblers walks', 'GET', '<API key>/listWalks'); } var <API key> = function () { return RamblersHttpService.call('Ramblers description Prefix', 'GET', '<API key>/<API key>'); }; var walkBaseUrl = function () { return RamblersHttpService.call('Ramblers walk url', 'GET', '<API key>/walkBaseUrl'); }; function exportWalksFileName() { return 'walks-export-' + DateUtils.asMoment().format('DD-MMMM-YYYY-HH-mm') + '.csv' } function exportableWalks(walkExports) { return _.chain(walkExports) .filter(function (walkExport) { return walkExport.selected; }) .sortBy(function (walkExport) { return walkExport.walk.walkDate; }) .value(); } function exportWalks(walkExports, members) { return _(exportableWalks(walkExports)).pluck('walk').map(function (walk) { return walkToCsvRecord(walk, members) }); } function <API key>(walks, members) { return listRamblersWalks() .then(<API key>(walks)) .then(function (updatedWalks) { return returnWalksExport(updatedWalks, members); }); } function <API key>(walks) { var unreferencedList = <API key>(walks); logger.debug(unreferencedList.length, ' existing ramblers walk(s) found', unreferencedList); return function (<API key>) { var savePromises = []; _(<API key>.responseData).each(function (<API key>) { var foundWalk = _.find(walks, function (walk) { return DateUtils.asString(walk.walkDate, undefined, 'dddd, Do MMMM YYYY') === <API key>.ramblersWalkDate }); if (!foundWalk) { logger.debug('no match found for <API key>', <API key>); } else { unreferencedList = _.without(unreferencedList, <API key>.ramblersWalkId); if (foundWalk && foundWalk.ramblersWalkId !== <API key>.ramblersWalkId) { logger.debug('updating walk from', foundWalk.ramblersWalkId || 'empty', '->', <API key>.ramblersWalkId, 'on', $filter('displayDate')(foundWalk.walkDate)); foundWalk.ramblersWalkId = <API key>.ramblersWalkId; savePromises.push(foundWalk.$saveOrUpdate()) } else { logger.debug('no update required for walk', foundWalk.ramblersWalkId, foundWalk.walkDate, DateUtils.displayDay(foundWalk.walkDate)); } } }); if (unreferencedList.length > 0) { logger.debug('removing old ramblers walk(s)', unreferencedList, 'from existing walks'); _.chain(unreferencedList) .each(function (ramblersWalkId) { var walk = _.findWhere(walks, {ramblersWalkId: ramblersWalkId}); if (walk) { logger.debug('removing ramblers walk', walk.ramblersWalkId, 'from walk on', $filter('displayDate')(walk.walkDate)); delete walk.ramblersWalkId; savePromises.push(walk.$saveOrUpdate()) } }).value(); } return $q.all(savePromises).then(function () { return walks; }); } } function <API key>(walks) { return _.chain(walks) .filter(function (walk) { return walk.ramblersWalkId; }) .map(function (walk) { return walk.ramblersWalkId; }) .value(); } function returnWalksExport(walks, members) { var todayValue = DateUtils.momentNowNoTime().valueOf(); return _.chain(walks) .filter(function (walk) { return (walk.walkDate >= todayValue) && walk.<API key>; }) .sortBy(function (walk) { return walk.walkDate; }) .map(function (walk) { return validateWalk(walk, members); }) .value(); } function uploadToRamblers(walkExports, members, notify) { notify.setBusy(); logger.debug('sourceData', walkExports); var deleteWalks = _.chain(exportableWalks(walkExports)).pluck('walk') .filter(function (walk) { return walk.ramblersWalkId; }).map(function (walk) { return walk.ramblersWalkId; }).value(); let rows = exportWalks(walkExports, members); let fileName = exportWalksFileName(); var data = { headings: <API key>(), rows: rows, fileName: fileName, deleteWalks: deleteWalks, ramblersUser: <API key>.loggedInMember().firstName }; logger.debug('exporting', data); notify.warning({ title: 'Ramblers walks upload', message: 'Uploading ' + rows.length + ' walk(s) to Ramblers...' }); return uploadRamblersWalks(data) .then(function (response) { notify.warning({ title: 'Ramblers walks upload', message: 'Upload of ' + rows.length + ' walk(s) to Ramblers has been submitted. Monitor the Walk upload audit tab for progress' }); logger.debug('success response data', response); notify.clearBusy(); return fileName; }) .catch(function (response) { logger.debug('error response data', response); notify.error({ title: 'Ramblers walks upload failed', message: response }); notify.clearBusy(); }); } function validateWalk(walk, members) { var walkValidations = []; if (_.isEmpty(walk)) { walkValidations.push('walk does not exist'); } else { if (_.isEmpty(walkTitle(walk))) walkValidations.push('title is missing'); if (_.isEmpty(walkDistanceMiles(walk))) walkValidations.push('distance is missing'); if (_.isEmpty(walk.startTime)) walkValidations.push('start time is missing'); if (walkStartTime(walk) === 'Invalid date') walkValidations.push('start time [' + walk.startTime + '] is invalid'); if (_.isEmpty(walk.grade)) walkValidations.push('grade is missing'); if (_.isEmpty(walk.longerDescription)) walkValidations.push('description is missing'); if (_.isEmpty(walk.postcode) && _.isEmpty(walk.gridReference)) walkValidations.push('both postcode and grid reference are missing'); if (_.isEmpty(walk.contactId)) { var contactIdMessage = <API key>.allowWalkAdminEdits() ? 'this can be supplied for this walk on Walk Leader tab' : 'this will need to be setup for you by ' + <API key>.contactUsField('walks', 'fullName'); walkValidations.push('walk leader has no Ramblers contact Id setup on their member record (' + contactIdMessage + ')'); } if (_.isEmpty(walk.displayName) && _.isEmpty(walk.displayName)) walkValidations.push('displayName for walk leader is missing'); } return { walk: walk, walkValidations: walkValidations, publishedOnRamblers: walk && !_.isEmpty(walk.ramblersWalkId), selected: walk && walkValidations.length === 0 && _.isEmpty(walk.ramblersWalkId) } } var nearestTown = function (walk) { return walk.nearestTown ? 'Nearest Town is ' + walk.nearestTown : ''; }; function walkTitle(walk) { var walkDescription = []; if (walk.<API key>) walkDescription.push(walk.<API key>); return _.chain(walkDescription).map(<API key>).value().join('. '); } function walkDescription(walk) { return <API key>(walk.longerDescription); } function walkType(walk) { return walk.walkType || "Circular"; } function asString(value) { return value ? value : ''; } function contactDisplayName(walk) { return walk.displayName ? <API key>(_.first(walk.displayName.split(' '))) : ''; } function contactIdLookup(walk, members) { if (walk.contactId) { return walk.contactId; } else { var member = _(members).find(function (member) { return member.$id() === walk.walkLeaderMemberId; }); var returnValue = member && member.contactId; logger.debug('contactId: for walkLeaderMemberId', walk.walkLeaderMemberId, '->', returnValue); return returnValue; } } function <API key>(value) { return value ? value .replace("’", "'") .replace("é", "e") .replace("’", "'") .replace('…', '…') .replace('–', '–') .replace('’', '’') .replace('“', '“') : ''; } function walkDistanceMiles(walk) { return walk.distance ? String(parseFloat(walk.distance).toFixed(1)) : ''; } function walkStartTime(walk) { return walk.startTime ? DateUtils.asString(walk.startTime, 'HH mm', 'HH:mm') : ''; } function walkGridReference(walk) { return walk.gridReference ? walk.gridReference : ''; } function walkPostcode(walk) { return walk.gridReference ? '' : walk.postcode ? walk.postcode : ''; } function walkDate(walk) { return DateUtils.asString(walk.walkDate, undefined, 'DD-MM-YYYY'); } function <API key>() { return [ "Date", "Title", "Description", "Linear or Circular", "Starting postcode", "Starting gridref", "Starting location details", "Show exact starting point", "Start time", "Show exact meeting point?", "Meeting time", "Restriction", "Difficulty", "Local walk grade", "Distance miles", "Contact id", "Contact display name" ]; } function walkToCsvRecord(walk, members) { return { "Date": walkDate(walk), "Title": walkTitle(walk), "Description": walkDescription(walk), "Linear or Circular": walkType(walk), "Starting postcode": walkPostcode(walk), "Starting gridref": walkGridReference(walk), "Starting location details": nearestTown(walk), "Show exact starting point": "Yes", "Start time": walkStartTime(walk), "Show exact meeting point?": "Yes", "Meeting time": walkStartTime(walk), "Restriction": "Public", "Difficulty": asString(walk.grade), "Local walk grade": asString(walk.grade), "Distance miles": walkDistanceMiles(walk), "Contact id": contactIdLookup(walk, members), "Contact display name": contactDisplayName(walk) }; } return { uploadToRamblers: uploadToRamblers, validateWalk: validateWalk, <API key>: <API key>, walkBaseUrl: walkBaseUrl, exportWalksFileName: exportWalksFileName, <API key>: <API key>, exportWalks: exportWalks, exportableWalks: exportableWalks, <API key>: <API key> } }] ); /* concatenated from client/src/app/js/<API key>.js */ angular.module("ekwgApp") .controller("<API key>", ["$q", "$log", "$scope", "<API key>, "ValidationUtils", "<API key>", "URLService", "Notifier", "userName", "message", "close", function ($q, $log, $scope, <API key>, ValidationUtils, <API key>, URLService, Notifier, userName, message, close) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; $scope.notify = {}; $scope.memberCredentials = {userName: userName}; var notify = Notifier($scope.notify); if (message) { notify.progress({ title: "Reset password", message: message }); } $scope.actions = { submittable: function () { var <API key> = ValidationUtils.fieldPopulated($scope.memberCredentials, "newPassword"); var new<API key> = ValidationUtils.fieldPopulated($scope.memberCredentials, "newPasswordConfirm"); logger.info("notSubmittable: new<API key>, new<API key>, "<API key>", <API key>); return <API key> && new<API key>; }, close: function () { close() }, resetPassword: function () { notify.showContactUs(false); notify.setBusy(); notify.progress({ busy: true, title: "Reset password", message: "Attempting reset of password for " + $scope.memberCredentials.userName }); <API key>.resetPassword($scope.memberCredentials.userName, $scope.memberCredentials.newPassword, $scope.memberCredentials.newPasswordConfirm).then(function () { var loginResponse = <API key>.loginResponse(); if (<API key>.memberLoggedIn()) { notify.hide(); close(); if (!<API key>.loggedInMember().<API key>) { return URLService.navigateTo("mailing-preferences"); } return true; } else { notify.showContactUs(true); notify.error({ title: "Reset password failed", message: loginResponse.alertMessage }); } return true; }); } } }] ); /* concatenated from client/src/app/js/reset<API key>.js */ angular.module('ekwgApp') .controller('Reset<API key>, ["$log", "$scope", "URLService", "Notifier", "<API key>", "close", function ($log, $scope, URLService, Notifier, <API key>, close) { var logger = $log.getInstance('Reset<API key>); $log.logLevels['<API key>'] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); logger.info("<API key>:", <API key>.ready); notify.showContactUs(true); notify.error({ continue: true, title: "Reset password failed", message: "The password reset link you followed has either expired or is invalid. Click Restart Forgot Password to try again" }); $scope.actions = { close: function () { close() }, forgotPassword: function () { URLService.navigateTo("forgot-password"); }, } }]); /* concatenated from client/src/app/js/services.js */ angular.module('ekwgApp') .factory('DateUtils', ["$log", function ($log) { var logger = $log.getInstance('DateUtils'); $log.logLevels['DateUtils'] = $log.LEVEL.OFF; var formats = { displayDateAndTime: 'ddd DD-MMM-YYYY, h:mm:ss a', displayDateTh: 'MMMM Do YYYY', displayDate: 'ddd DD-MMM-YYYY', displayDay: 'dddd MMMM D, YYYY', ddmmyyyyWithSlashes: 'DD/MM/YYYY', yyyymmdd: 'YYYYMMDD' }; function isDate(value) { return value && asMoment(value).isValid(); } function asMoment(dateValue, inputFormat) { return moment(dateValue, inputFormat).tz("Europe/London"); } function momentNow() { return asMoment(); } function asString(dateValue, inputFormat, outputFormat) { var returnValue = dateValue ? asMoment(dateValue, inputFormat).format(outputFormat) : undefined; logger.debug('asString: dateValue ->', dateValue, 'inputFormat ->', inputFormat, 'outputFormat ->', outputFormat, 'returnValue ->', returnValue); return returnValue; } function asValue(dateValue, inputFormat) { return asMoment(dateValue, inputFormat).valueOf(); } function nowAsValue() { return asMoment(undefined, undefined).valueOf(); } function mailchimpDate(dateValue) { return asString(dateValue, undefined, formats.ddmmyyyyWithSlashes); } function displayDateAndTime(dateValue) { return asString(dateValue, undefined, formats.displayDateAndTime); } function displayDate(dateValue) { return asString(dateValue, undefined, formats.displayDate); } function displayDay(dateValue) { return asString(dateValue, undefined, formats.displayDay); } function asValueNoTime(dateValue, inputFormat) { var returnValue = asMoment(dateValue, inputFormat).startOf('day').valueOf(); logger.debug('asValueNoTime: dateValue ->', dateValue, 'returnValue ->', returnValue, '->', displayDateAndTime(returnValue)); return returnValue; } function <API key>() { return asString(momentNowNoTime().startOf('month'), undefined, formats.yyyymmdd); } function momentNowNoTime() { return asMoment().startOf('day'); } function <API key>(object, field) { var inputValue = object[field]; object[field] = convertDateField(inputValue); return object; } function convertDateField(inputValue) { if (inputValue) { var dateValue = asValueNoTime(inputValue); if (dateValue !== inputValue) { logger.debug('Converting date from', inputValue, '(' + displayDateAndTime(inputValue) + ') to', dateValue, '(' + displayDateAndTime(dateValue) + ')'); return dateValue; } else { logger.debug(inputValue, inputValue, 'is already in correct format'); return inputValue; } } else { logger.debug(inputValue, 'is not a date - no conversion'); return inputValue; } } return { formats: formats, displayDateAndTime: displayDateAndTime, displayDay: displayDay, displayDate: displayDate, mailchimpDate: mailchimpDate, <API key>: <API key>, convertDateField: convertDateField, isDate: isDate, asMoment: asMoment, nowAsValue: nowAsValue, momentNow: momentNow, momentNowNoTime: momentNowNoTime, asString: asString, asValue: asValue, asValueNoTime: asValueNoTime, <API key>: <API key> }; }]) .factory('DbUtils', ["$log", "DateUtils", "<API key>", "AUDIT_CONFIG", function ($log, DateUtils, <API key>, AUDIT_CONFIG) { var logger = $log.getInstance('DbUtilsLogger'); $log.logLevels['DbUtilsLogger'] = $log.LEVEL.OFF; function removeEmptyFieldsIn(obj) { _.each(obj, function (value, field) { logger.debug('processing', typeof(field), 'field', field, 'value', value); if (_.contains([null, undefined, ""], value)) { logger.debug('removing non-populated', typeof(field), 'field', field); delete obj[field]; } }); } function auditedSaveOrUpdate(resource, updateCallback, errorCallback) { if (AUDIT_CONFIG.auditSave) { if (resource.$id()) { resource.updatedDate = DateUtils.nowAsValue(); resource.updatedBy = <API key>.loggedInMember().memberId; logger.debug('Auditing save of existing document', resource); } else { resource.createdDate = DateUtils.nowAsValue(); resource.createdBy = <API key>.loggedInMember().memberId; logger.debug('Auditing save of new document', resource); } } else { resource = DateUtils.<API key>(resource, 'createdDate'); logger.debug('Not auditing save of', resource); } return resource.$saveOrUpdate(updateCallback, updateCallback, errorCallback || updateCallback, errorCallback || updateCallback) } return { removeEmptyFieldsIn: removeEmptyFieldsIn, auditedSaveOrUpdate: auditedSaveOrUpdate, } }]) .factory('FileUtils', ["$log", "DateUtils", "URLService", "<API key>", function ($log, DateUtils, URLService, <API key>) { var logger = $log.getInstance('FileUtils'); $log.logLevels['FileUtils'] = $log.LEVEL.OFF; function basename(path) { return path.split(/[\\/]/).pop() } function path(path) { return path.split(basename(path))[0]; } function attachmentTitle(resource, container, resourceName) { return (resource && _.isEmpty(getFileNameData(resource, container)) ? 'Attach' : 'Replace') + ' ' + resourceName; } function getFileNameData(resource, container) { return container ? resource[container].fileNameData : resource.fileNameData; } function resourceUrl(resource, container, metaDataPathSegment) { var fileNameData = getFileNameData(resource, container); return resource && fileNameData ? URLService.baseUrl() + <API key>.baseUrl(metaDataPathSegment) + '/' + fileNameData.awsFileName : ''; } function previewUrl(memberResource) { if (memberResource) { switch (memberResource.resourceType) { case "email": return memberResource.data.campaign.archive_url_long; case "file": return memberResource.data.campaign.archive_url_long; } } var fileNameData = getFileNameData(resource, container); return resource && fileNameData ? URLService.baseUrl() + <API key>.baseUrl(metaDataPathSegment) + '/' + fileNameData.awsFileName : ''; } function resourceTitle(resource) { logger.debug('resourceTitle:resource =>', resource); return resource ? (DateUtils.asString(resource.resourceDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + (resource.data ? resource.data.fileNameData.title : "")) : ''; } function fileExtensionIs(fileName, extensions) { return _.contains(extensions, fileExtension(fileName)); } function fileExtension(fileName) { return fileName ? _.last(fileName.split('.')).toLowerCase() : ''; } function icon(resource, container) { var icon = 'icon-default.jpg'; var fileNameData = getFileNameData(resource, container); if (fileNameData && fileExtensionIs(fileNameData.awsFileName, ['doc', 'docx', 'jpg', 'pdf', 'ppt', 'png', 'txt', 'xls', 'xlsx'])) { icon = 'icon-' + fileExtension(fileNameData.awsFileName).substring(0, 3) + '.jpg'; } return "assets/images/ramblers/" + icon; } return { fileExtensionIs: fileExtensionIs, fileExtension: fileExtension, basename: basename, path: path, attachmentTitle: attachmentTitle, resourceUrl: resourceUrl, resourceTitle: resourceTitle, icon: icon } }]) .factory('StringUtils', ["DateUtils", "$filter", function (DateUtils, $filter) { function replaceAll(find, replace, str) { return str ? str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace) : str; } function stripLineBreaks(str, andTrim) { var replacedValue = str.replace(/(\r\n|\n|\r)/gm, ''); return andTrim && replacedValue ? replacedValue.trim() : replacedValue; } function left(str, chars) { return str.substr(0, chars); } function formatAudit(who, when, members) { var by = who ? 'by ' + $filter('memberIdToFullName')(who, members) : ''; return (who || when) ? by + (who && when ? ' on ' : '') + DateUtils.displayDateAndTime(when) : '(not audited)'; } return { left: left, replaceAll: replaceAll, stripLineBreaks: stripLineBreaks, formatAudit: formatAudit } }]).factory('ValidationUtils', function () { function fieldPopulated(object, path) { return (_.property(path)(object) || "").length > 0; } return { fieldPopulated: fieldPopulated, } }) .factory('NumberUtils', ["$log", function ($log) { var logger = $log.getInstance('NumberUtils'); $log.logLevels['NumberUtils'] = $log.LEVEL.OFF; function sumValues(items, fieldName) { if (!items) return 0; return _.chain(items).pluck(fieldName).reduce(function (memo, num) { return memo + asNumber(num); }, 0).value(); } function generateUid() { return '<API key>'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } function asNumber(numberString, decimalPlaces) { if (!numberString) return 0; var isNumber = typeof numberString === 'number'; if (isNumber && !decimalPlaces) return numberString; var number = isNumber ? numberString : parseFloat(numberString.replace(/[^\d\.\-]/g, "")); if (isNaN(number)) return 0; var returnValue = (decimalPlaces) ? (parseFloat(number).toFixed(decimalPlaces)) / 1 : number; logger.debug('asNumber:', numberString, decimalPlaces, '->', returnValue); return returnValue; } return { asNumber: asNumber, sumValues: sumValues, generateUid: generateUid }; }]) .factory('ContentMetaData', ["$<API key>", function ($<API key>) { return $<API key>('contentMetaData'); }]) .factory('ConfigData', ["$<API key>", function ($<API key>) { return $<API key>('config'); }]) .factory('Config', ["$log", "ConfigData", "ErrorMessageService", function ($log, ConfigData, ErrorMessageService) { var logger = $log.getInstance('Config'); $log.logLevels['Config'] = $log.LEVEL.OFF; function getConfig(key, defaultOnEmpty) { logger.debug('getConfig:', key, 'defaultOnEmpty:', defaultOnEmpty); var queryObject = {}; queryObject[key] = {$exists: true}; return ConfigData.query(queryObject, {limit: 1}) .then(function (results) { if (results && results.length > 0) { return results[0]; } else { queryObject[key] = {}; return new ConfigData(defaultOnEmpty || queryObject); } }, function (response) { throw new Error('Query of ' + key + ' config failed: ' + response); }); } function saveConfig(key, config, saveCallback, errorSaveCallback) { logger.debug('saveConfig:', key); if (_.has(config, key)) { return config.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback || saveCallback, errorSaveCallback || saveCallback); } else { throw new Error('Attempt to save ' + ErrorMessageService.stringify(key) + ' config when ' + ErrorMessageService.stringify(key) + ' parent key not present in data: ' + ErrorMessageService.stringify(config)); } } return { getConfig: getConfig, saveConfig: saveConfig } }]) .factory('<API key>', ["$<API key>", function ($<API key>) { return $<API key>('expenseClaims'); }]) .factory('RamblersUploadAudit', ["$<API key>", function ($<API key>) { return $<API key>('ramblersUploadAudit'); }]) .factory('<API key>', ["ErrorMessageService", function (ErrorMessageService) { function transform(errorResponse) { var message = ErrorMessageService.stringify(errorResponse); var duplicate = s.include(errorResponse, 'duplicate'); if (duplicate) { message = 'Duplicate data was detected. A member record must have a unique Contact Email, Display Name, Ramblers Membership Number and combination of First Name, Last Name and Alias. Please amend the current member and try again.'; } return {duplicate: duplicate, message: message} } return {transform: transform} }]) .factory('ErrorMessageService', function () { function stringify(message) { return _.isObject(message) ? JSON.stringify(message, censor(message)) : message; } function censor(censor) { var i = 0; return function (key, value) { if (i !== 0 && typeof(censor) === 'object' && typeof(value) === 'object' && censor === value) return '[Circular]'; if (i >= 29) // seems to be a hard maximum of 30 serialized objects? return '[Unknown]'; ++i; // so we know we aren't using the original object anymore return value; } } return { stringify: stringify } }); /* concatenated from client/src/app/js/siteEditActions.js */ angular.module('ekwgApp') .component('siteEditActions', { templateUrl: 'partials/components/site-edit.html', controller: ["$log", "SiteEditService", function ($log, SiteEditService){ var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; var ctrl = this; logger.info("initialised with SiteEditService.active()", SiteEditService.active()); ctrl.userEdits = {preview: true, saveInProgress: false, revertInProgress: false}; ctrl.editSiteActive = function () { return SiteEditService.active() ? "active" : ""; }; ctrl.editSiteCaption = function () { return SiteEditService.active() ? "editing site" : "edit site"; }; ctrl.toggleEditSite = function () { SiteEditService.toggle(); }; }], bindings: { name: '@', description: '@', } }); /* concatenated from client/src/app/js/siteEditService.js */ angular.module('ekwgApp') .factory('SiteEditService', ["$log", "$cookieStore", "$rootScope", function ($log, $cookieStore, $rootScope) { var logger = $log.getInstance('SiteEditService'); $log.logLevels['SiteEditService'] = $log.LEVEL.OFF; function active() { var active = Boolean($cookieStore.get("editSite")); logger.debug("active:", active); return active; } function toggle() { var priorState = active(); var newState = !priorState; logger.debug("toggle:priorState", priorState, "newState", newState); $cookieStore.put("editSite", newState); return $rootScope.$broadcast("editSite", newState); } return { active: active, toggle: toggle } }]); /* concatenated from client/src/app/js/<API key>.js */ angular.module('ekwgApp') .controller('<API key>', ["<API key>", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "<API key>", "MemberService", "<API key>", "<API key>", "<API key>", "<API key>", "MailchimpConfig", "Notifier", "<API key>", "socialEvent", "close", function (<API key>, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, <API key>, MemberService, <API key>, <API key>, <API key>, <API key>, MailchimpConfig, Notifier, <API key>, socialEvent, close) { var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); logger.debug('created with social event', socialEvent); $scope.attachmentBaseUrl = <API key>.baseUrl('socialEvents'); $scope.destinationType = ''; $scope.members = []; $scope.<API key> = []; $scope.committeeFiles = []; $scope.alertMessages = []; $scope.allowConfirmDelete = false; $scope.latestYearOpen = true; $scope.roles = {signoff: [], replyTo: []}; $scope.showAlertMessage = function () { return ($scope.notify.alert.class === 'alert-danger') || $scope.userEdits.sendInProgress; }; function <API key>(socialEvent) { if (socialEvent) { $scope.socialEvent = socialEvent; <API key>(); <API key>(); } else { logger.error('no socialEvent - problem!'); } function <API key>() { if (!$scope.socialEvent.notification) { $scope.socialEvent.notification = { destinationType: 'all-ekwg-social', recipients: [], addresseeType: 'Hi *|FNAME|*,', items: { title: {include: true}, notificationText: {include: true, value: ''}, description: {include: true}, attendees: {include: socialEvent.attendees.length > 0}, attachment: {include: socialEvent.attachment}, replyTo: { include: $scope.socialEvent.displayName, value: $scope.socialEvent.displayName ? 'organiser' : 'social' }, signoffText: { include: true, value: 'If you have any questions about the above, please don\'t hesitate to contact me.\n\nBest regards,' } } }; logger.debug('<API key> - creating $scope.socialEvent.notification ->', $scope.socialEvent.notification); } } function <API key>() { $scope.socialEvent.notification.items.signoffAs = { include: true, value: loggedOnRole().type || 'social' }; logger.debug('<API key> - $scope.socialEvent.notification.signoffAs ->', $scope.socialEvent.notification.signoffAs); } } function loggedOnRole() { var memberId = <API key>.loggedInMember().memberId; var loggedOnRoleData = _(<API key>.<API key>()).find(function (role) { return role.memberId === memberId }); logger.debug('loggedOnRole for', memberId, '->', loggedOnRoleData); return loggedOnRoleData || {}; } function roleForType(type) { var role = _($scope.roles.replyTo).find(function (role) { return role.type === type; }); logger.debug('roleForType for', type, '->', role); return role; } function initialiseRoles() { $scope.roles.signoff = <API key>.<API key>(); $scope.roles.replyTo = _.clone($scope.roles.signoff); if ($scope.socialEvent.<API key>) { $scope.roles.replyTo.unshift({ type: 'organiser', fullName: $scope.socialEvent.displayName, memberId: $scope.socialEvent.<API key>, description: 'Organiser (' + $scope.socialEvent.displayName + ')', email: $scope.socialEvent.contactEmail }); } logger.debug('initialiseRoles -> $scope.roles ->', $scope.roles); } $scope.formattedText = function () { return $filter('lineFeedsToBreaks')($scope.socialEvent.notification.items.notificationText.value); }; $scope.attachmentTitle = function (socialEvent) { return socialEvent && socialEvent.attachment ? (socialEvent.attachment.title || socialEvent.attachmentTitle || 'Attachment: ' + socialEvent.attachment.originalFileName) : ''; }; $scope.attachmentUrl = function (socialEvent) { return socialEvent && socialEvent.attachment ? URLService.baseUrl() + $scope.attachmentBaseUrl + '/' + socialEvent.attachment.awsFileName : ''; }; $scope.<API key> = function () { $scope.socialEvent.notification.destinationType = 'custom'; $scope.socialEvent.notification.recipients = $scope.userEdits.socialList(); }; $scope.<API key> = function () { $scope.socialEvent.notification.destinationType = 'custom'; $scope.socialEvent.notification.recipients = $scope.socialEvent.attendees; }; $scope.clearRecipients = function () { $scope.socialEvent.notification.recipients = []; }; $scope.<API key> = function () { return $filter('lineFeedsToBreaks')($scope.socialEvent.notification.items.signoffText.value); }; $scope.attendeeList = function () { return _($scope.socialEvent.notification && $scope.socialEvent.attendees) .sortBy(function (attendee) { return attendee.text; }).map(function (attendee) { return attendee.text; }).join(', '); }; $scope.memberGrouping = function (member) { return member.memberGrouping; }; function toSelectMember(member) { var memberGrouping; var order; if (member.socialMember && member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Subscribed to social emails'; order = 0; } else if (member.socialMember && !member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Not subscribed to social emails'; order = 1; } else if (!member.socialMember) { memberGrouping = 'Not a social member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } function refreshMembers() { if (<API key>.memberLoggedIn()) { MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) { $scope.members = members; logger.debug('refreshMembers -> populated ->', $scope.members.length, 'members'); $scope.<API key> = _.chain(members) .map(toSelectMember) .sortBy(function (member) { return member.order + member.text }) .value(); logger.debug('refreshMembers -> populated ->', $scope.<API key>.length, '<API key>'); notify.clearBusy(); }); } } $scope.contactUs = { ready: function () { return <API key>.ready; } }; $scope.userEdits = { sendInProgress: false, cancelFlow: false, socialList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.<API key>) .map(toSelectMember).value(); }, replyToRole: function () { return _($scope.roles.replyTo).find(function (role) { return role.type === $scope.socialEvent.notification.items.replyTo.value; }); }, notReady: function () { return $scope.members.length === 0 || $scope.userEdits.sendInProgress; } }; $scope.<API key> = function () { close(); $('#social-event-dialog').modal('show'); }; $scope.completeInMailchimp = function () { notify.warning({ title: 'Complete in Mailchimp', message: 'You can close this dialog now as the message was presumably completed and sent in Mailchimp' }); $scope.<API key>(true); }; $scope.<API key> = function (dontSend) { notify.setBusy(); var campaignName = $scope.socialEvent.briefDescription; logger.debug('<API key>:notification->', $scope.socialEvent.notification); notify.progress({title: campaignName, message: 'preparing and sending notification'}); $scope.userEdits.sendInProgress = true; $scope.userEdits.cancelFlow = false; function getTemplate() { return $templateRequest($sce.<API key>('partials/socialEvents/social-notification.html')) } return $q.when(<API key>()) .then(getTemplate) .then(<API key>) .then(<API key>) .then(sendEmailCampaign) .then(saveSocialEvent) .then(<API key>) .catch(handleError); function handleError(errorResponse) { $scope.userEdits.sendInProgress = false; notify.error({ title: 'Your notification could not be sent', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } function <API key>(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction($scope); $timeout(function () { $scope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function <API key>(notificationText) { logger.debug('<API key> -> notificationText', notificationText); return { sections: { notification_text: notificationText } }; } function <API key>(segmentResponse) { $scope.socialEvent.mailchimp = { segmentId: segmentResponse.segment.id }; if (segmentResponse.members) $scope.socialEvent.mailchimp.members = segmentResponse.members; } function <API key>() { var members = segmentMembers(); if (members.length > 0) { return <API key>.saveSegment('socialEvents', $scope.socialEvent.mailchimp, members, <API key>.formatSegmentName($scope.socialEvent.briefDescription), $scope.members) .then(<API key>) .catch(handleError); } else { logger.debug('not saving segment data as destination type is whole mailing list ->', $scope.socialEvent.notification.destinationType); return true; } } function segmentMembers() { switch ($scope.socialEvent.notification.destinationType) { case 'attendees': return $scope.socialEvent.attendees; case 'custom': return $scope.socialEvent.notification.recipients; default: return []; } } function sendEmailCampaign(contentSections) { var replyToRole = roleForType($scope.socialEvent.notification.items.replyTo.value || 'social'); var otherOptions = ($scope.socialEvent.notification.items.replyTo.include && replyToRole.fullName && replyToRole.email) ? { from_name: replyToRole.fullName, from_email: replyToRole.email } : {}; notify.progress(dontSend ? ('Preparing to complete ' + campaignName + ' in Mailchimp') : ('Sending ' + campaignName)); logger.debug('Sending ' + campaignName, 'with otherOptions', otherOptions); return MailchimpConfig.getConfig() .then(function (config) { var campaignId = config.mailchimp.campaigns.socialEvents.campaignId; switch ($scope.socialEvent.notification.destinationType) { case 'all-ekwg-social': logger.debug('about to <API key> to all-ekwg-social with campaignName', campaignName, 'campaign Id', campaignId); return <API key>.<API key>({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); default: if (!$scope.socialEvent.mailchimp) notify.warning('Cant send campaign due to previous request failing. This could be due to network problems - please try this again'); var segmentId = $scope.socialEvent.mailchimp.segmentId; logger.debug('about to <API key> to social with campaignName', campaignName, 'campaign Id', campaignId, 'segmentId', segmentId); return <API key>.<API key>({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, segmentId: segmentId, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); } }) } function openInMailchimpIf(dontSend) { return function (<API key>) { logger.debug('openInMailchimpIf:<API key>', <API key>, 'dontSend', dontSend); if (dontSend) { return $window.open(<API key>.apiServer + "/campaigns/wizard/neapolitan?id=" + <API key>.web_id, '_blank'); } else { return true; } } } function saveSocialEvent() { return $scope.socialEvent.$saveOrUpdate(); } function <API key>() { notify.success('Sending of ' + campaignName + ' was successful.', false); $scope.userEdits.sendInProgress = false; if (!$scope.userEdits.cancelFlow) { close(); } notify.clearBusy(); } }; refreshMembers(); <API key>(socialEvent); initialiseRoles(<API key>); }] ); /* concatenated from client/src/app/js/socialEvents.js */ angular.module('ekwgApp') .factory('SocialEventsService', ["$<API key>", function ($<API key>) { return $<API key>('socialEvents'); }]) .factory('<API key>', ["$<API key>", function ($<API key>) { return $<API key>('<API key>'); }]) .controller('<API key>', ["$routeParams", "$log", "$q", "$scope", "$filter", "URLService", "Upload", "SocialEventsService", "SiteEditService", "<API key>", "<API key>", "MemberService", "AWSConfig", "<API key>", "DateUtils", "<API key>", "ClipboardService", "Notifier", "EKWGFileUpload", "<API key>", "ModalService", function ($routeParams, $log, $q, $scope, $filter, URLService, Upload, SocialEventsService, SiteEditService, <API key>, <API key>, MemberService, AWSConfig, <API key>, DateUtils, <API key>, ClipboardService, Notifier, EKWGFileUpload, <API key>, ModalService) { $scope.userEdits = { copyToClipboard: ClipboardService.copyToClipboard, <API key>: true, socialEventLink: function (socialEvent) { return socialEvent && socialEvent.$id() ? URLService.notificationHref({ type: "socialEvent", area: "social", id: socialEvent.$id() }) : undefined; } }; $scope.<API key> = function () { logger.debug('<API key>'); $scope.userEdits.<API key> = true; }; $scope.<API key> = function () { logger.debug('<API key>'); $scope.userEdits.<API key> = false; }; $scope.contactUs = { ready: function () { return <API key>.ready; } }; var logger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; var notify = Notifier($scope); $scope.attachmentBaseUrl = <API key>.baseUrl('socialEvents'); $scope.selectMembers = []; $scope.display = {attendees: []}; $scope.<API key> = true; $scope.<API key> = true; $scope.<API key> = true; $scope.todayValue = DateUtils.momentNowNoTime().valueOf(); applyAllowEdits('<API key>'); $scope.eventDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.eventDateCalendar.opened = true; } }; $scope.$on('memberLoginComplete', function () { applyAllowEdits('memberLoginComplete'); refreshMembers(); refreshSocialEvents(); }); $scope.$on('<API key>', function () { applyAllowEdits('<API key>'); }); $scope.$on('editSite', function () { applyAllowEdits('editSite'); }); $scope.addSocialEvent = function () { <API key>(new SocialEventsService({eventDate: $scope.todayValue, attendees: []}), 'Add New'); }; $scope.viewSocialEvent = function (socialEvent) { <API key>(socialEvent, 'View'); }; $scope.editSocialEvent = function (socialEvent) { <API key>(socialEvent, 'Edit Existing'); }; $scope.<API key> = function () { $scope.allowDelete = false; $scope.allowConfirmDelete = true; }; $scope.<API key> = function () { <API key>(); }; $scope.<API key> = function () { $q.when(notify.progress({title: 'Save in progress', message: 'Saving social event'}, true)) .then(prepareToSave, notify.error, notify.progress) .then(saveSocialEvent, notify.error, notify.progress) .then(notify.clearBusy, notify.error, notify.progress) .catch(notify.error); }; function prepareToSave() { DateUtils.<API key>($scope.currentSocialEvent, 'eventDate'); } function saveSocialEvent() { return $scope.currentSocialEvent.$saveOrUpdate(<API key>, <API key>); } $scope.<API key> = function () { $q.when(notify.progress('Deleting social event', true)) .then(<API key>, notify.error, notify.progress) .then(<API key>, notify.error, notify.progress) .then(notify.clearBusy, notify.error, notify.progress) .catch(notify.error); }; var <API key> = function () { if ($scope.currentSocialEvent.mailchimp && $scope.currentSocialEvent.mailchimp.segmentId) { return <API key>.deleteSegment('socialEvents', $scope.currentSocialEvent.mailchimp.segmentId); } }; var <API key> = function () { $scope.currentSocialEvent.$remove(<API key>) }; $scope.<API key> = function () { var copiedSocialEvent = new SocialEventsService($scope.currentSocialEvent); delete copiedSocialEvent._id; delete copiedSocialEvent.mailchimp; DateUtils.<API key>(copiedSocialEvent, 'eventDate'); <API key>(copiedSocialEvent, 'Copy Existing'); notify.success({ title: 'Existing social event copied!', message: 'Make changes here and save to create a new social event.' }); }; $scope.<API key> = function () { var socialEvent = $scope.currentSocialEvent; var memberId = socialEvent.<API key>; if (memberId === null) { delete socialEvent.<API key>; delete socialEvent.displayName; delete socialEvent.contactPhone; delete socialEvent.contactEmail; // console.log('deleted contact details from', socialEvent); } else { var selectedMember = _.find($scope.members, function (member) { return member.$id() === memberId; }); socialEvent.displayName = selectedMember.displayName; socialEvent.contactPhone = selectedMember.mobileNumber; socialEvent.contactEmail = selectedMember.email; // console.log('set contact details on', socialEvent); } }; $scope.dataQueryParameters = { query: '', selectType: '1', newestFirst: 'false' }; $scope.removeAttachment = function () { delete $scope.currentSocialEvent.attachment; delete $scope.currentSocialEvent.attachmentTitle; $scope.uploadedFile = undefined; }; $scope.resetMailchimpData = function () { delete $scope.currentSocialEvent.mailchimp; }; $scope.<API key> = function () { $('#hidden-input').click(); }; $scope.attachmentTitle = function (socialEvent) { return socialEvent && socialEvent.attachment ? (socialEvent.attachment.title || socialEvent.attachmentTitle || 'Attachment: ' + socialEvent.attachment.originalFileName) : ''; }; $scope.attachmentUrl = function (socialEvent) { return socialEvent && socialEvent.attachment ? $scope.attachmentBaseUrl + '/' + socialEvent.attachment.awsFileName : ''; }; $scope.onFileSelect = function (file) { if (file) { $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, 'socialEvents').then(function (fileNameData) { $scope.currentSocialEvent.attachment = fileNameData; }); } }; function allowSummaryView() { return (<API key>.<API key>() || !<API key>.<API key>()); } function applyAllowEdits(event) { $scope.allowDelete = false; $scope.allowConfirmDelete = false; $scope.allowDetailView = <API key>.<API key>(); $scope.allowEdits = <API key>.<API key>(); $scope.allowCopy = <API key>.<API key>(); $scope.allowContentEdits = SiteEditService.active() && <API key>.allowContentEdits(); $scope.allowSummaryView = allowSummaryView(); } $scope.showLoginTooltip = function () { return !<API key>.memberLoggedIn(); }; $scope.login = function () { if (!<API key>.memberLoggedIn()) { URLService.navigateTo("login"); } }; function <API key>(socialEvent, socialEventEditMode) { $scope.uploadedFile = undefined; $scope.showAlert = false; $scope.allowConfirmDelete = false; if (!socialEvent.attendees) socialEvent.attendees = []; $scope.allowEdits = <API key>.<API key>(); var <API key> = $scope.allowEdits && s.startsWith(socialEventEditMode, 'Edit'); $scope.allowCopy = <API key>; $scope.allowDelete = <API key>; $scope.socialEventEditMode = socialEventEditMode; $scope.currentSocialEvent = socialEvent; $('#social-event-dialog').modal('show'); } $scope.attendeeCaption = function () { return $scope.currentSocialEvent && $scope.currentSocialEvent.attendees.length + ($scope.currentSocialEvent.attendees.length === 1 ? ' member is attending' : ' members are attending'); }; $scope.attendeeList = function () { return _($scope.display.attendees) .sortBy(function (attendee) { return attendee.text; }).map(function (attendee) { return attendee.text; }).join(', '); }; function <API key>() { $('#social-event-dialog').modal('hide'); refreshSocialEvents(); } function refreshMembers() { if (<API key>.memberLoggedIn()) { MemberService.allLimitedFields(MemberService.filterFor.SOCIAL_MEMBERS).then(function (members) { $scope.members = members; logger.debug('found', $scope.members.length, 'members'); $scope.selectMembers = _($scope.members).map(function (member) { return {id: member.$id(), text: $filter('fullNameWithAlias')(member)}; }) }); } } $scope.<API key> = function () { $('#social-event-dialog').modal('hide'); ModalService.showModal({ templateUrl: "partials/socialEvents/<API key>.html", controller: "<API key>", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, inputs: { socialEvent: $scope.currentSocialEvent } }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; function refreshSocialEvents() { if (URLService.hasRouteParameter('socialEventId')) { return SocialEventsService.getById($routeParams.socialEventId) .then(function (socialEvent) { if (!socialEvent) notify.error('Social event could not be found'); $scope.socialEvents = [socialEvent]; }); } else { var socialEvents = <API key>.<API key>() ? SocialEventsService.all() : SocialEventsService.all({ fields: { briefDescription: 1, eventDate: 1, thumbnail: 1 } }); socialEvents.then(function (socialEvents) { $scope.socialEvents = _.chain(socialEvents) .filter(function (socialEvent) { return socialEvent.eventDate >= $scope.todayValue }) .sortBy(function (socialEvent) { return socialEvent.eventDate; }) .value(); logger.debug('found', $scope.socialEvents.length, 'social events'); }); } } $q.when(refreshSocialEvents()) .then(refreshMembers) .then(refreshImages); function refreshImages() { <API key>.getMetaData('imagesSocialEvents').then(function (contentMetaData) { $scope.interval = 5000; $scope.slides = contentMetaData.files; logger.debug('found', $scope.slides.length, 'slides'); }, function (response) { throw new Error(response); }); } }]); /* concatenated from client/src/app/js/urlServices.js */ angular.module('ekwgApp') .factory('URLService', ["$window", "$rootScope", "$timeout", "$location", "$routeParams", "$log", "PAGE_CONFIG", "<API key>", function ($window, $rootScope, $timeout, $location, $routeParams, $log, PAGE_CONFIG, <API key>) { var logger = $log.getInstance('URLService'); $log.logLevels['URLService'] = $log.LEVEL.OFF; function baseUrl(optionalUrl) { return _.first((optionalUrl || $location.absUrl()).split('/ } function relativeUrl(optionalUrl) { var relativeUrlValue = _.last((optionalUrl || $location.absUrl()).split("/ logger.debug("relativeUrlValue:", relativeUrlValue); return relativeUrlValue; } function <API key>(optionalUrl) { var relativeUrlValue = relativeUrl(optionalUrl); var index = relativeUrlValue.indexOf("/", 1); var <API key> = index === -1 ? relativeUrlValue : relativeUrlValue.substring(0, index); logger.debug("relativeUrl:", relativeUrlValue, "<API key>:", <API key>); return <API key>; } function resourceUrl(area, type, id) { return baseUrl() + '/#/' + area + '/' + type + 'Id/' + id; } function notificationHref(ctrl) { var href = (ctrl.name) ? <API key>(ctrl.name) : resourceUrl(ctrl.area, ctrl.type, ctrl.id); logger.debug("href:", href); return href; } function <API key>(fileName) { return baseUrl() + <API key>.baseUrl(fileName); } function hasRouteParameter(parameter) { var hasRouteParameter = !!($routeParams[parameter]); logger.debug('hasRouteParameter', parameter, hasRouteParameter); return hasRouteParameter; } function isArea(areas) { logger.debug('isArea:areas', areas, '$routeParams', $routeParams); return _.some(_.isArray(areas) ? areas : [areas], function (area) { var matched = area === $routeParams.area; logger.debug('isArea', area, 'matched =', matched); return matched; }); } let pageUrl = function (page) { var pageOrEmpty = (page ? page : ""); return s.startsWith(pageOrEmpty, "/") ? pageOrEmpty : "/" + pageOrEmpty; }; function navigateTo(page, area) { $timeout(function () { var url = pageUrl(page) + (area ? "/" + area : ""); logger.info("navigating to page:", page, "area:", area, "->", url); $location.path(url); logger.info("$location.path is now", $location.path()) }, 1); } function <API key>() { var lastPage = _.chain($rootScope.pageHistory.reverse()) .find(function (page) { return _.contains(_.values(PAGE_CONFIG.mainPages), <API key>(page)); }) .value(); logger.info("<API key>:$rootScope.pageHistory", $rootScope.pageHistory, "lastPage->", lastPage); navigateTo(lastPage || "/") } function noArea() { return !$routeParams.area; } function setRoot() { return navigateTo(); } function area() { return $routeParams.area; } return { setRoot: setRoot, <API key>: <API key>, navigateTo: navigateTo, hasRouteParameter: hasRouteParameter, noArea: noArea, isArea: isArea, baseUrl: baseUrl, area: area, <API key>: <API key>, notificationHref: notificationHref, resourceUrl: resourceUrl, <API key>: <API key>, relativeUrl: relativeUrl } }]); /* concatenated from client/src/app/js/walkNotifications.js */ angular.module('ekwgApp') .controller('<API key>', ["$log", "$scope", "<API key>", "<API key>", function ($log, $scope, <API key>, <API key>) { $scope.dataAuditDelta = <API key>.dataAuditDelta($scope.walk, $scope.status); $scope.validateWalk = <API key>.validateWalk($scope.walk); <API key>.walkBaseUrl().then(function (walkBaseUrl) { $scope.ramblersWalkBaseUrl = walkBaseUrl; }); }]) .factory('<API key>', ["$sce", "$log", "$timeout", "$filter", "$location", "$rootScope", "$q", "$compile", "$templateRequest", "$routeParams", "$cookieStore", "URLService", "MemberService", "MailchimpConfig", "<API key>", "<API key>", "MemberAuditService", "<API key>", "<API key>", "<API key>", "DateUtils", function ($sce, $log, $timeout, $filter, $location, $rootScope, $q, $compile, $templateRequest, $routeParams, $cookieStore, URLService, MemberService, MailchimpConfig, <API key>, <API key>, MemberAuditService, <API key>, <API key>, <API key>, DateUtils) { var logger = $log.getInstance('<API key>'); var noLogger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; $log.logLevels['<API key>'] = $log.LEVEL.OFF; var basePartialsUrl = 'partials/walks/notifications'; var auditedFields = ['grade', 'walkDate', 'walkType', 'startTime', '<API key>', 'longerDescription', 'distance', 'nearestTown', 'gridReference', 'meetupEventUrl', 'meetupEventTitle', 'osMapsRoute', 'osMapsTitle', 'postcode', 'walkLeaderMemberId', 'contactPhone', 'contactEmail', 'contactId', 'displayName', 'ramblersWalkId']; function currentDataValues(walk) { return _.compactObject(_.pick(walk, auditedFields)); } function previousDataValues(walk) { var event = latestWalkEvent(walk); return event && event.data || {}; } function latestWalkEvent(walk) { return (walk.events && _.last(walk.events)) || {}; } function eventsLatestFirst(walk) { var events = walk.events && _(walk.events).clone().reverse() || []; noLogger.info('eventsLatestFirst:', events); return events; } function <API key>(walk) { return _(eventsLatestFirst(walk)).find(function (event) { return (<API key>.toEventType(event.eventType) || {}).statusChange; }) || {}; } function dataAuditDelta(walk, status) { if (!walk) return {}; var currentData = currentDataValues(walk); var previousData = previousDataValues(walk); var changedItems = <API key>(); var eventExists = <API key>(walk, status); var dataChanged = changedItems.length > 0; var dataAuditDelta = { currentData: currentData, previousData: previousData, changedItems: changedItems, eventExists: eventExists, dataChanged: dataChanged, <API key>: dataChanged || !eventExists, eventType: dataChanged && eventExists ? <API key>.eventTypes.walkDetailsUpdated.eventType : status }; dataAuditDelta.dataChanged && noLogger.info('dataAuditDelta', dataAuditDelta); return dataAuditDelta; function <API key>() { return _.compact(_.map(auditedFields, function (key) { var currentValue = currentData[key]; var previousValue = previousData[key]; noLogger.info('auditing', key, 'now:', currentValue, 'previous:', previousValue); if (previousValue !== currentValue) return { fieldName: key, previousValue: previousValue, currentValue: currentValue } })); } } function <API key>(walk, eventType) { if (!walk) return false; return <API key>(walk).eventType === toEventTypeValue(eventType); } function toEventTypeValue(eventType) { return _.has(eventType, 'eventType') ? eventType.eventType : eventType; } function <API key>(walk, eventType) { if (walk) { var eventTypeString = toEventTypeValue(eventType); return eventsLatestFirst(walk).find(function (event) { return event.eventType === eventTypeString; }); } } function <API key>(walks) { return _(walks).map(function (walk) { if (_.isArray(walk.events)) { return walk } else { var event = <API key>(walk, <API key>.eventTypes.approved.eventType, 'Marking past walk as approved'); <API key>(walk, event); walk.$saveOrUpdate(); return walk; } }) } function <API key>(walk, status, reason) { var dataAuditDeltaInfo = dataAuditDelta(walk, status); logger.debug('<API key>:', dataAuditDeltaInfo); if (dataAuditDeltaInfo.<API key>) { var event = { "date": DateUtils.nowAsValue(), "memberId": <API key>.loggedInMember().memberId, "data": dataAuditDeltaInfo.currentData, "eventType": dataAuditDeltaInfo.eventType }; if (reason) event.reason = reason; if (dataAuditDeltaInfo.dataChanged) event.description = 'Changed: ' + $filter('<API key>')(dataAuditDeltaInfo.changedItems); logger.debug('<API key>: event created:', event); return event; } else { logger.debug('<API key>: event creation not necessary'); } } function <API key>(walk, event) { if (event) { logger.debug('writing event', event); if (!_.isArray(walk.events)) walk.events = []; walk.events.push(event); } else { logger.debug('no event to write'); } } function <API key>(members, walk, status, notify, sendNotification, reason) { notify.setBusy(); var event = <API key>(walk, status, reason); var notificationScope = $rootScope.$new(); notificationScope.walk = walk; notificationScope.members = members; notificationScope.event = event; notificationScope.status = status; var eventType = event && <API key>.toEventType(event.eventType); if (event && sendNotification) { return <API key>() .then(function () { return <API key>(walk, event); }) .then(function () { return true; }) .catch(function (error) { logger.debug('failed with error', error); return notify.error({title: error.message, message: error.error}) }); } else { logger.debug('Not sending notification'); return $q.when(<API key>(walk, event)) .then(function () { return false; }); } function <API key>(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction(notificationScope); $timeout(function () { notificationScope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function <API key>() { return <API key>.<API key>(walk.walkLeaderMemberId) .then(function (member) { logger.debug('sendNotification:', 'memberId', walk.walkLeaderMemberId, 'member', member); var walkLeaderName = $filter('fullNameWithAlias')(member); var walkDate = $filter('displayDate')(walk.walkDate); return $q.when(notify.progress('Preparing to send email notifications')) .then(<API key>, notify.error, notify.progress) .then(<API key>, notify.error, notify.progress); function <API key>() { if (eventType.notifyLeader) return sendNotificationsTo({ templateUrl: templateForEvent('leader', eventType.eventType), memberIds: [walk.walkLeaderMemberId], segmentType: 'walkLeader', segmentName: <API key>.formatSegmentName('Walk leader notifications for ' + walkLeaderName), emailSubject: 'Your walk on ' + walkDate, destination: 'walk leader' }); logger.debug('not sending leader notification'); } function <API key>() { if (eventType.notifyCoordinator) { var memberIds = MemberService.<API key>('<API key>', members); if (memberIds.length > 0) { return sendNotificationsTo({ templateUrl: templateForEvent('coordinator', eventType.eventType), memberIds: memberIds, segmentType: 'walkCoordinator', segmentName: <API key>.formatSegmentName('Walk co-ordinator notifications for ' + walkLeaderName), emailSubject: walkLeaderName + "'s walk on " + walkDate, destination: 'walk co-ordinators' }); } else { logger.debug('not sending coordinator notifications as none are configured with <API key>'); } } else { logger.debug('not sending coordinator notifications as event type is', eventType.eventType); } } function templateForEvent(role, eventTypeString) { return basePartialsUrl + '/' + role + '/' + s.dasherize(eventTypeString) + '.html'; } function sendNotificationsTo(<API key>) { if (<API key>.memberIds.length === 0) throw new Error('No members have been configured as ' + <API key>.destination + ' therefore notifications cannot be sent'); var memberFullNames = $filter('<API key>')(<API key>.memberIds, members); logger.debug('sendNotificationsTo:', <API key>); var campaignName = <API key>.emailSubject + ' (' + eventType.description + ')'; var segmentName = <API key>.segmentName; return $templateRequest($sce.<API key>(<API key>.templateUrl)) .then(<API key>, notify.error) .then(<API key>, notify.error) .then(sendNotification(<API key>), notify.error); function <API key>(<API key>) { logger.debug('<API key> -> <API key>', <API key>); return { sections: { notification_text: <API key> } }; } function sendNotification(<API key>) { return function (contentSections) { return <API key>() .then(<API key>, notify.error, notify.progress) .then(sendEmailCampaign, notify.error, notify.progress) .then(<API key>, notify.error, notify.success); function <API key>() { return <API key>.saveSegment('walks', {segmentId: <API key>.getMemberSegmentId(member, <API key>.segmentType)}, <API key>.memberIds, segmentName, members); } function <API key>(segmentResponse) { <API key>.setMemberSegmentId(member, <API key>.segmentType, segmentResponse.segment.id); return <API key>.saveMember(member); } function sendEmailCampaign() { notify.progress('Sending ' + campaignName); return MailchimpConfig.getConfig() .then(function (config) { var campaignId = config.mailchimp.campaigns.walkNotification.campaignId; var segmentId = <API key>.getMemberSegmentId(member, <API key>.segmentType); logger.debug('about to send campaign', campaignName, 'campaign Id', campaignId, 'segmentId', segmentId); return <API key>.<API key>({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, segmentId: segmentId }); }) .then(function () { notify.progress('Sending of ' + campaignName + ' was successful', true); }); } function <API key>() { notify.success('Sending of ' + campaignName + ' was successful. Check your inbox for details.'); return true; } } } } }); } } return { dataAuditDelta: dataAuditDelta, eventsLatestFirst: eventsLatestFirst, <API key>: <API key>, <API key>: <API key>, <API key>: <API key>, <API key>: <API key>, <API key>: <API key>, <API key>: <API key> } }]); /* concatenated from client/src/app/js/walkSlots.js.js */ angular.module('ekwgApp') .controller('WalkSlotsController', ["$rootScope", "$log", "$scope", "$filter", "$q", "WalksService", "WalksQueryService", "<API key>", "<API key>", "<API key>", "DateUtils", "Notifier", function ($rootScope, $log, $scope, $filter, $q, WalksService, WalksQueryService, <API key>, <API key>, <API key>, DateUtils, Notifier) { var logger = $log.getInstance('WalkSlotsController'); $log.logLevels['WalkSlotsController'] = $log.LEVEL.OFF; $scope.slotsAlert = {}; $scope.todayValue = DateUtils.momentNowNoTime().valueOf(); $scope.slot = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.slot.opened = true; }, validDate: function (date) { return DateUtils.isDate(date); }, until: DateUtils.momentNowNoTime().day(7 * 12).valueOf(), bulk: true }; var notify = Notifier($scope.slotsAlert); function createSlots(requiredSlots, confirmAction, prompt) { $scope.requiredWalkSlots = requiredSlots.map(function (date) { var walk = new WalksService({ walkDate: date }); walk.events = [<API key>.<API key>(walk, <API key>.eventTypes.awaitingLeader.eventType, 'Walk slot created')]; return walk; }); logger.debug('$scope.requiredWalkSlots', $scope.requiredWalkSlots); if ($scope.requiredWalkSlots.length > 0) { $scope.confirmAction = confirmAction; notify.warning(prompt) } else { notify.error({title: "Nothing to do!", message: "All slots are already created between today and " + $filter('displayDate')($scope.slot.until)}); delete $scope.confirmAction; } } $scope.addWalkSlots = function () { WalksService.query({walkDate: {$gte: $scope.todayValue}}, {fields: {events: 1, walkDate: 1}, sort: {walkDate: 1}}) .then(function (walks) { var sunday = DateUtils.momentNowNoTime().day(7); var untilDate = DateUtils.asMoment($scope.slot.until).startOf('day'); var weeks = untilDate.clone().diff(sunday, 'weeks'); var allGeneratedSlots = _.times(weeks, function (index) { return DateUtils.asValueNoTime(sunday.clone().add(index, 'week')); }).filter(function (date) { return DateUtils.asString(date, undefined, 'DD-MMM') !== '25-Dec'; }); var existingDates = _.pluck(WalksQueryService.activeWalks(walks), 'walkDate'); logger.debug('sunday', sunday, 'untilDate', untilDate, 'weeks', weeks); logger.debug('<API key>', _(existingDates).map($filter('displayDateAndTime'))); logger.debug('<API key>', _(allGeneratedSlots).map($filter('displayDateAndTime'))); var requiredSlots = _.difference(allGeneratedSlots, existingDates); var requiredDates = $filter('displayDates')(requiredSlots); createSlots(requiredSlots, {addSlots: true}, { title: "Add walk slots", message: " - You are about to add " + requiredSlots.length + " empty walk slots up to " + $filter('displayDate')($scope.slot.until) + '. Slots are: ' + requiredDates }); }); }; $scope.addWalkSlot = function () { createSlots([DateUtils.asValueNoTime($scope.slot.single)], {addSlot: true}, { title: "Add walk slots", message: " - You are about to add 1 empty walk slot for " + $filter('displayDate')($scope.slot.single) }); }; $scope.selectBulk = function (bulk) { $scope.slot.bulk = bulk; delete $scope.confirmAction; notify.hide(); }; $scope.allow = { addSlot: function () { return !$scope.confirmAction && !$scope.slot.bulk && <API key>.allowWalkAdminEdits(); }, addSlots: function () { return !$scope.confirmAction && $scope.slot.bulk && <API key>.allowWalkAdminEdits(); }, close: function () { return !$scope.confirmAction; } }; $scope.<API key> = function () { delete $scope.confirmAction; notify.hide(); }; $scope.confirmAddWalkSlots = function () { notify.success({title: "Add walk slots - ", message: "now creating " + $scope.requiredWalkSlots.length + " empty walk slots up to " + $filter('displayDate')($scope.slot.until)}); $q.all($scope.requiredWalkSlots.map(function (slot) { return slot.$saveOrUpdate(); })).then(function () { notify.success({title: "Done!", message: "Choose Close to see your newly created slots"}); delete $scope.confirmAction; }); }; $scope.$on('<API key>', function () { $('#add-slots-dialog').modal(); delete $scope.confirmAction; notify.hide(); }); $scope.<API key> = function () { $('#add-slots-dialog').modal('hide'); $rootScope.$broadcast('walkSlotsCreated'); }; }] ); /* concatenated from client/src/app/js/walks.js */ angular.module('ekwgApp') .factory('WalksService', ["$<API key>", function ($<API key>) { return $<API key>('walks') }]) .factory('WalksQueryService', ["<API key>", "<API key>", function (<API key>, <API key>) { function activeWalks(walks) { return _.filter(walks, function (walk) { return !<API key>.<API key>(walk, <API key>.eventTypes.deleted) }) } return { activeWalks: activeWalks } }]) .factory('<API key>', function () { var eventTypes = { awaitingLeader: { statusChange: true, eventType: 'awaitingLeader', description: 'Awaiting walk leader' }, awaitingWalkDetails: { mustHaveLeader: true, statusChange: true, eventType: 'awaitingWalkDetails', description: 'Awaiting walk details from leader', notifyLeader: true, notifyCoordinator: true }, <API key>: { mustHaveLeader: true, eventType: '<API key>', description: 'Walk details requested from leader', notifyLeader: true, notifyCoordinator: true }, walkDetailsUpdated: { eventType: 'walkDetailsUpdated', description: 'Walk details updated', notifyLeader: true, notifyCoordinator: true }, walkDetailsCopied: { eventType: 'walkDetailsCopied', description: 'Walk details copied' }, awaitingApproval: { mustHaveLeader: true, mustPassValidation: true, statusChange: true, eventType: 'awaitingApproval', readyToBe: 'approved', description: 'Awaiting confirmation of walk details', notifyLeader: true, notifyCoordinator: true }, approved: { mustHaveLeader: true, mustPassValidation: true, showDetails: true, statusChange: true, eventType: 'approved', readyToBe: 'published', description: 'Approved', notifyLeader: true, notifyCoordinator: true }, deleted: { statusChange: true, eventType: 'deleted', description: 'Deleted', notifyLeader: true, notifyCoordinator: true } }; return { toEventType: function (eventTypeString) { if (eventTypeString) { if (_.includes(eventTypeString, ' ')) eventTypeString = s.camelcase(eventTypeString.toLowerCase()); var eventType = eventTypes[eventTypeString]; if (!eventType) throw new Error("Event Type '" + eventTypeString + "' does not exist. Must be one of: " + _.keys(eventTypes).join(', ')); return eventType; } }, walkEditModes: { add: {caption: 'add', title: 'Add new'}, edit: {caption: 'edit', title: 'Edit existing', editEnabled: true}, more: {caption: 'more', title: 'View'}, lead: {caption: 'lead', title: 'Lead this', <API key>: true} }, eventTypes: eventTypes, walkStatuses: _(eventTypes).filter(function (eventType) { return eventType.statusChange; }) } }) .controller('WalksController', ["$sce", "$log", "$routeParams", "$interval", "$rootScope", "$location", "$scope", "$filter", "$q", "RamblersUploadAudit", "WalksService", "WalksQueryService", "URLService", "ClipboardService", "<API key>", "<API key>", "<API key>", "MemberService", "DateUtils", "<API key>", "<API key>", "Notifier", "<API key>", "GoogleMapsConfig", "MeetupService", function ($sce, $log, $routeParams, $interval, $rootScope, $location, $scope, $filter, $q, RamblersUploadAudit, WalksService, WalksQueryService, URLService, ClipboardService, <API key>, <API key>, <API key>, MemberService, DateUtils, <API key>, <API key>, Notifier, <API key>, GoogleMapsConfig, MeetupService) { var logger = $log.getInstance('WalksController'); var noLogger = $log.getInstance('<API key>'); $log.logLevels['<API key>'] = $log.LEVEL.OFF; $log.logLevels['WalksController'] = $log.LEVEL.OFF; $scope.contactUs = { ready: function () { return <API key>.ready; } }; $scope.$watch('filterParameters.quickSearch', function (quickSearch, oldQuery) { <API key>(); }); $scope.finalStatusError = function () { return _.findWhere($scope.ramblersUploadAudit, {status: "error"}); }; $scope.fileNameChanged = function () { logger.debug('filename changed to', $scope.userEdits.fileName); $scope.<API key>(); }; $scope.<API key> = function (stop) { logger.debug('refreshing audit trail records related to', $scope.userEdits.fileName); return RamblersUploadAudit.query({fileName: $scope.userEdits.fileName}, {sort: {auditTime: -1}}) .then(function (auditItems) { logger.debug('Filtering', auditItems.length, 'audit trail records related to', $scope.userEdits.fileName); $scope.ramblersUploadAudit = _.chain(auditItems) .filter(function (auditItem) { return $scope.userEdits.showDetail || auditItem.type !== "detail"; }) .map(function (auditItem) { if (auditItem.status === "complete") { logger.debug('Upload complete'); notifyWalkExport.success("Ramblers upload completed"); $interval.cancel(stop); $scope.userEdits.saveInProgress = false; } return auditItem; }) .value(); }); }; $scope.ramblersUploadAudit = []; $scope.walksForExport = []; $scope.walkEditModes = <API key>.walkEditModes; $scope.walkStatuses = <API key>.walkStatuses; $scope.walkAlert = {}; $scope.walkExport = {}; var notify = Notifier($scope); var notifyWalkExport = Notifier($scope.walkExport); var notifyWalkEdit = Notifier($scope.walkAlert); var SHOW_START_POINT = "show-start-point"; var <API key> = "<API key>"; notify.setBusy(); $scope.copyFrom = {walkTemplates: [], walkTemplate: {}}; $scope.userEdits = { copyToClipboard: ClipboardService.copyToClipboard, meetupEvent: {}, copySource: '<API key>', <API key>: undefined, expandedWalks: [], mapDisplay: SHOW_START_POINT, <API key>: true, walkExportActive: function (activeTab) { return activeTab === $scope.walkExportActive; }, <API key>: true, <API key>: false, walkExportTabActive: 0, status: undefined, sendNotifications: true, saveInProgress: false, fileNames: [], walkLink: function (walk) { return walk && walk.$id() ? URLService.notificationHref({ type: "walk", area: "walks", id: walk.$id() }) : undefined } }; $scope.walks = []; $scope.busy = false; $scope.walksProgrammeOpen = URLService.isArea('programme', 'walkId') || URLService.noArea(); $scope.<API key> = URLService.isArea('information'); $scope.walksMapViewOpen = URLService.isArea('mapview'); $scope.todayValue = DateUtils.momentNowNoTime().valueOf(); $scope.userEdits.walkDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.userEdits.walkDateCalendar.opened = true; } }; $scope.addWalk = function () { showWalkDialog(new WalksService({ status: <API key>.eventTypes.awaitingLeader.eventType, walkType: $scope.type[0], walkDate: $scope.todayValue }), <API key>.walkEditModes.add); }; $scope.addWalkSlotsDialog = function () { $rootScope.$broadcast('<API key>'); }; $scope.<API key> = function () { delete $scope.currentWalk.ramblersWalkId; notify.progress('Previous Ramblers walk has now been unlinked.') }; $scope.canUnlinkRamblers = function () { return <API key>.allowWalkAdminEdits() && $scope.ramblersWalkExists(); }; $scope.<API key> = function () { return !$scope.ramblersWalkExists(); }; $scope.<API key> = function () { return <API key>.allowWalkAdminEdits() && $scope.currentWalk && !($scope.currentWalk.gridReference || $scope.currentWalk.postcode); }; $scope.canExportToRamblers = function () { return <API key>.allowWalkAdminEdits() && $scope.validateWalk().selected; }; $scope.validateWalk = function () { return <API key>.validateWalk($scope.currentWalk, $scope.members); }; $scope.walkValidations = function () { var walkValidations = $scope.validateWalk().walkValidations; return 'This walk cannot be included in the Ramblers Walks and Events Manager export due to the following ' + walkValidations.length + ' problem(s): ' + walkValidations.join(", ") + '.'; }; $scope.grades = ['Easy access', 'Easy', 'Leisurely', 'Moderate', 'Strenuous', 'Technical']; $scope.walkTypes = ['Circular', 'Linear']; $scope.<API key> = function (walk) { walk.meetupEventTitle = $scope.userEdits.meetupEvent.title; walk.meetupEventUrl = $scope.userEdits.meetupEvent.url; }; $scope.meetupSelectSync = function (walk) { $scope.userEdits.meetupEvent = _.findWhere($scope.meetupEvents, {url: walk.meetupEventUrl}); }; $scope.ramblersWalkExists = function () { return $scope.validateWalk().publishedOnRamblers }; function <API key>(walk) { return walk && walk.walkLeaderMemberId === <API key>.loggedInMember().memberId } $scope.loggedIn = function () { return <API key>.memberLoggedIn(); }; $scope.toWalkEditMode = function (walk) { if (<API key>.memberLoggedIn()) { if (<API key>(walk) || <API key>.allowWalkAdminEdits()) { return <API key>.walkEditModes.edit; } else if (!walk.walkLeaderMemberId) { return <API key>.walkEditModes.lead; } } }; $scope.actionWalk = function (walk) { showWalkDialog(walk, $scope.toWalkEditMode(walk)); }; $scope.deleteWalkDetails = function () { $scope.confirmAction = {delete: true}; notifyWalkEdit.warning({ title: 'Confirm delete of walk details.', message: 'If you confirm this, the slot for ' + $filter('displayDate')($scope.currentWalk.walkDate) + ' will be deleted from the site.' }); }; $scope.cancelWalkDetails = function () { $scope.confirmAction = {cancel: true}; notifyWalkEdit.warning({ title: 'Cancel changes.', message: 'Click Confirm to lose any changes you\'ve just made for ' + $filter('displayDate')($scope.currentWalk.walkDate) + ', or Cancel to carry on editing.' }); }; $scope.<API key> = function () { <API key>(); }; function <API key>(eventType) { notifyWalkEdit.hide(); logger.info('<API key> ->', eventType); var walkValidations = $scope.validateWalk().walkValidations; if (eventType.mustHaveLeader && !$scope.currentWalk.walkLeaderMemberId) { notifyWalkEdit.warning( { title: 'Walk leader needed', message: ' - this walk cannot be changed to ' + eventType.description + ' yet.' }); <API key>(); return false; } else if (eventType.mustPassValidation && walkValidations.length > 0) { notifyWalkEdit.warning( { title: 'This walk is not ready to be ' + eventType.readyToBe + ' yet due to the following ' + walkValidations.length + ' problem(s): ', message: walkValidations.join(", ") + '. You can still save this walk, then come back later on to complete the rest of the details.' }); <API key>(); return false; } else { return true; } } function initiateEvent() { $scope.userEdits.saveInProgress = true; var walk = DateUtils.<API key>($scope.currentWalk, 'walkDate'); return <API key>.<API key>($scope.members, walk, $scope.userEdits.status, notifyWalkEdit, $scope.userEdits.sendNotifications && walk.walkLeaderMemberId); } $scope.<API key> = function () { $scope.userEdits.status = <API key>.eventTypes.deleted.eventType; return initiateEvent() .then(function () { return $scope.currentWalk.$saveOrUpdate(<API key>, <API key>); }) .catch(function () { $scope.userEdits.saveInProgress = false; }); }; $scope.saveWalkDetails = function () { return initiateEvent() .then(function (notificationSent) { return $scope.currentWalk.$saveOrUpdate(afterSaveWith(notificationSent), afterSaveWith(notificationSent)); }) .catch(function () { $scope.userEdits.saveInProgress = false; }); }; $scope.requestApproval = function () { logger.info('requestApproval called with current status:', $scope.userEdits.status); if (<API key>(<API key>.eventTypes.awaitingApproval)) { $scope.confirmAction = {requestApproval: true}; notifyWalkEdit.warning({ title: 'Confirm walk details complete.', message: 'If you confirm this, your walk details will be emailed to ' + <API key>() + ' and they will publish these to the site.' }); } }; $scope.contactOther = function () { notifyWalkEdit.warning({ title: 'Confirm walk details complete.', message: 'If you confirm this, your walk details will be emailed to ' + <API key>() + ' and they will publish these to the site.' }); }; $scope.walkStatusChange = function (status) { $scope.userEdits.priorStatus = status; notifyWalkEdit.hide(); logger.info('walkStatusChange - was:', status, 'now:', $scope.userEdits.status); if (<API key>(<API key>.toEventType($scope.userEdits.status))) switch ($scope.userEdits.status) { case <API key>.eventTypes.awaitingLeader.eventType: { var walkDate = $scope.currentWalk.walkDate; $scope.userEdits.status = <API key>.eventTypes.awaitingLeader.eventType; $scope.currentWalk = new WalksService(_.pick($scope.currentWalk, ['_id', 'events', 'walkDate'])); return notifyWalkEdit.success({ title: 'Walk details reset for ' + $filter('displayDate')(walkDate) + '.', message: 'Status is now ' + <API key>.eventTypes.awaitingLeader.description }); } case <API key>.eventTypes.approved.eventType: { return $scope.approveWalkDetails(); } } }; $scope.approveWalkDetails = function () { var walkValidations = $scope.validateWalk().walkValidations; if (walkValidations.length > 0) { notifyWalkEdit.warning({ title: 'This walk still has the following ' + walkValidations.length + ' field(s) that need attention: ', message: walkValidations.join(", ") + '. You\'ll have to get the rest of these details completed before you mark the walk as approved.' }); <API key>(); } else { notifyWalkEdit.success({ title: 'Ready to publish walk details!', message: 'All fields appear to be filled in okay, so next time you save this walk it will be published.' }); } }; $scope.<API key> = function () { $scope.userEdits.status = <API key>.eventTypes.awaitingApproval.eventType; $scope.saveWalkDetails(); }; $scope.<API key> = function () { delete $scope.confirmAction; notify.hide(); notifyWalkEdit.hide(); }; function <API key>() { logger.info('<API key>:', $scope.userEdits.status, '->', $scope.userEdits.priorStatus); if ($scope.userEdits.priorStatus) $scope.userEdits.status = $scope.userEdits.priorStatus; } $scope.<API key> = function () { var walkTemplate = _.clone($scope.copyFrom.walkTemplate); if (walkTemplate) { var templateDate = $filter('displayDate')(walkTemplate.walkDate); delete walkTemplate._id; delete walkTemplate.events; delete walkTemplate.ramblersWalkId; delete walkTemplate.walkDate; delete walkTemplate.displayName; delete walkTemplate.contactPhone; delete walkTemplate.contactEmail; angular.extend($scope.currentWalk, walkTemplate); var event = <API key>.<API key>($scope.currentWalk, <API key>.eventTypes.walkDetailsCopied.eventType, 'Copied from previous walk on ' + templateDate); <API key>.<API key>($scope.currentWalk, event); notifyWalkEdit.success({ title: 'Walk details were copied from ' + templateDate + '.', message: 'Make any further changes here and save when you are done.' }); } }; $scope.filterParameters = { quickSearch: '', selectType: '1', ascending: "true" }; $scope.<API key> = function () { $scope.userEdits.copySource = '<API key>'; $scope.<API key>(); }; $scope.<API key> = function (injectedMemberId) { var memberId = $scope.currentWalk.walkLeaderMemberId || injectedMemberId; var criteria; switch ($scope.userEdits.copySource) { case "<API key>": { criteria = { walkLeaderMemberId: $scope.userEdits.<API key>, <API key>: {$exists: true} }; break } case "<API key>": { criteria = {osMapsRoute: {$exists: true}}; break } default: { criteria = {walkLeaderMemberId: memberId}; } } logger.info('selecting walks', $scope.userEdits.copySource, criteria); WalksService.query(criteria, {sort: {walkDate: -1}}) .then(function (walks) { $scope.copyFrom.walkTemplates = walks; }); }; $scope.<API key> = function () { notifyWalkEdit.hide(); var walk = $scope.currentWalk; var memberId = walk.walkLeaderMemberId; if (!memberId) { $scope.userEdits.status = <API key>.eventTypes.awaitingLeader.eventType; delete walk.walkLeaderMemberId; delete walk.contactId; delete walk.displayName; delete walk.contactPhone; delete walk.contactEmail; } else { var selectedMember = _.find($scope.members, function (member) { return member.$id() === memberId; }); if (selectedMember) { $scope.userEdits.status = <API key>.eventTypes.awaitingWalkDetails.eventType; walk.contactId = selectedMember.contactId; walk.displayName = selectedMember.displayName; walk.contactPhone = selectedMember.mobileNumber; walk.contactEmail = selectedMember.email; $scope.<API key>(memberId); } } }; $scope.myOrWalkLeader = function () { return <API key>($scope.currentWalk) ? 'my' : $scope.currentWalk && $scope.currentWalk.displayName + "'s"; }; $scope.meOrWalkLeader = function () { return <API key>($scope.currentWalk) ? 'me' : $scope.currentWalk && $scope.currentWalk.displayName; }; $scope.personToNotify = function () { return <API key>($scope.currentWalk) ? <API key>() : $scope.currentWalk && $scope.currentWalk.displayName; }; function <API key>() { return <API key>.contactUsField('walks', 'fullName'); } function <API key>(walk) { var walkDate = DateUtils.asValueNoTime(walk.walkDate); if (walkDate !== walk.walkDate) { logger.info('Converting date from', walk.walkDate, '(' + $filter('displayDateAndTime')(walk.walkDate) + ') to', walkDate, '(' + $filter('displayDateAndTime')(walkDate) + ')'); walk.walkDate = walkDate; } else { logger.info('Walk date', walk.walkDate, 'is already in correct format'); } return walk; } function <API key>(eventType) { return <API key>.<API key>($scope.currentWalk, eventType); } $scope.dataHasChanged = function () { var dataAuditDelta = <API key>.dataAuditDelta($scope.currentWalk, $scope.userEdits.status); var <API key> = dataAuditDelta.<API key>; dataAuditDelta.<API key> && noLogger.info('dataAuditDelta - eventExists:', dataAuditDelta.eventExists, 'dataChanged:', dataAuditDelta.dataChanged, $filter('<API key>')(dataAuditDelta.changedItems)); dataAuditDelta.dataChanged && noLogger.info('dataAuditDelta - previousData:', dataAuditDelta.previousData, 'currentData:', dataAuditDelta.currentData); return <API key>; }; function <API key>() { return <API key>($scope.currentWalk) && $scope.userEdits.status === <API key>.eventTypes.awaitingWalkDetails.eventType; } function editable() { return !$scope.confirmAction && (<API key>.allowWalkAdminEdits() || <API key>($scope.currentWalk)); } function allowSave() { return editable() && $scope.dataHasChanged(); } $scope.allow = { close: function () { return !$scope.userEdits.saveInProgress && !$scope.confirmAction && !allowSave() }, save: allowSave, cancel: function () { return !$scope.userEdits.saveInProgress && editable() && $scope.dataHasChanged(); }, delete: function () { return !$scope.confirmAction && <API key>.allowWalkAdminEdits() && $scope.walkEditMode && $scope.walkEditMode.editEnabled; }, notifyConfirmation: function () { return (allowSave() || $scope.confirmAction && $scope.confirmAction.delete) && $scope.currentWalk.walkLeaderMemberId; }, adminEdits: function () { return <API key>.allowWalkAdminEdits(); }, edits: editable, historyView: function () { return <API key>($scope.currentWalk) || <API key>.allowWalkAdminEdits(); }, detailView: function () { return <API key>.memberLoggedIn(); }, approve: function () { return !$scope.confirmAction && <API key>.allowWalkAdminEdits() && <API key>(<API key>.eventTypes.awaitingApproval); }, requestApproval: function () { return !$scope.confirmAction && <API key>(); } }; $scope.<API key> = function () { logger.debug('<API key>'); $scope.userEdits.<API key> = true; }; $scope.<API key> = function () { logger.debug('<API key>'); $scope.userEdits.<API key> = false; }; $scope.trustSrc = function (src) { return $sce.trustAsResourceUrl(src); }; $scope.showAllWalks = function () { $scope.expensesOpen = true; $location.path('/walks/programme') }; $scope.googleMaps = function (walk) { return $scope.userEdits.mapDisplay === <API key> ? "https: "https: }; $scope.<API key> = function () { var <API key> = $scope.<API key>() && $scope.userEdits.mapDisplay === <API key>; var <API key> = !$scope.<API key>() && $scope.userEdits.mapDisplay === SHOW_START_POINT; if (<API key>) { $scope.userEdits.mapDisplay = SHOW_START_POINT; } else if (<API key>) { $scope.userEdits.mapDisplay = <API key>; } }; $scope.<API key> = function () { return $scope.userEdits.fromPostcode.length < 3; }; $scope.eventTypeFor = function (walk) { var <API key> = <API key>.<API key>(walk); var eventType = <API key>.toEventType(<API key>.eventType) || walk.status || <API key>.eventTypes.awaitingWalkDetails.eventType; noLogger.info('<API key>', <API key>, 'eventType', eventType, 'walk.events', walk.events); return eventType; }; $scope.viewWalkField = function (walk, field) { var eventType = $scope.eventTypeFor(walk); if (eventType.showDetails) { return walk[field] || ''; } else if (field === '<API key>') { return eventType.description; } else { return ''; } }; function showWalkDialog(walk, walkEditMode) { delete $scope.confirmAction; $scope.userEdits.sendNotifications = true; $scope.walkEditMode = walkEditMode; $scope.currentWalk = walk; if (walkEditMode.<API key>) { $scope.userEdits.status = <API key>.eventTypes.awaitingWalkDetails.eventType; walk.walkLeaderMemberId = <API key>.loggedInMember().memberId; $scope.<API key>(); notifyWalkEdit.success({ title: 'Thanks for offering to lead this walk ' + <API key>.loggedInMember().firstName + '!', message: 'Please complete as many details you can, then save to allocate this slot on the walks programme. ' + 'It will be published to the public once it\'s approved. If you want to release this slot again, just click cancel.' }); } else { var eventTypeIfExists = <API key>.<API key>($scope.currentWalk).eventType; if (eventTypeIfExists) { $scope.userEdits.status = eventTypeIfExists } $scope.userEdits.<API key> = walk.walkLeaderMemberId || <API key>.loggedInMember().memberId; $scope.<API key>(); $scope.meetupSelectSync($scope.currentWalk); notifyWalkEdit.hide(); } $('#walk-dialog').modal(); } function walksCriteriaObject() { switch ($scope.filterParameters.selectType) { case '1': return {walkDate: {$gte: $scope.todayValue}}; case '2': return {walkDate: {$lt: $scope.todayValue}}; case '3': return {}; case '4': return {displayName: {$exists: false}}; case '5': return {<API key>: {$exists: false}}; } } function walksSortObject() { switch ($scope.filterParameters.ascending) { case 'true': return {sort: {walkDate: 1}}; case 'false': return {sort: {walkDate: -1}}; } } function query() { if (URLService.hasRouteParameter('walkId')) { return WalksService.getById($routeParams.walkId) .then(function (walk) { if (!walk) notify.error('Walk could not be found. Try opening again from the link in the notification email, or choose the Show All Walks button'); return [walk]; }); } else { return WalksService.query(walksCriteriaObject(), walksSortObject()); } } function <API key>() { notify.setBusy(); $scope.filteredWalks = $filter('filter')($scope.walks, $scope.filterParameters.quickSearch); var walksCount = ($scope.filteredWalks && $scope.filteredWalks.length) || 0; notify.progress('Showing ' + walksCount + ' walk(s)'); if ($scope.filteredWalks.length > 0) { $scope.userEdits.expandedWalks = [$scope.filteredWalks[0].$id()]; } notify.clearBusy(); } $scope.showTableHeader = function (walk) { return $scope.filteredWalks.indexOf(walk) === 0 || $scope.isExpandedFor($scope.filteredWalks[$scope.filteredWalks.indexOf(walk) - 1]); }; $scope.nextWalk = function (walk) { return walk && walk.$id() === $scope.nextWalkId; }; $scope.durationInFutureFor = function (walk) { return walk && walk.walkDate === $scope.todayValue ? 'today' : (DateUtils.asMoment(walk.walkDate).fromNow()); }; $scope.toggleViewFor = function (walk) { function arrayRemove(arr, value) { return arr.filter(function (ele) { return ele !== value; }); } var walkId = walk.$id(); if (_.contains($scope.userEdits.expandedWalks, walkId)) { $scope.userEdits.expandedWalks = arrayRemove($scope.userEdits.expandedWalks, walkId); logger.debug('toggleViewFor:', walkId, '-> collapsing'); } else { $scope.userEdits.expandedWalks.push(walkId); logger.debug('toggleViewFor:', walkId, '-> expanding'); } logger.debug('toggleViewFor:', walkId, '-> expandedWalks contains', $scope.userEdits.expandedWalks) }; $scope.isExpandedFor = function (walk) { return _.contains($scope.userEdits.expandedWalks, walk.$id()); }; $scope.tableRowOdd = function (walk) { return $scope.filteredWalks.indexOf(walk) % 2 === 0; }; function getNextWalkId(walks) { var nextWalk = _.chain(walks).sortBy('walkDate').find(function (walk) { return walk.walkDate >= $scope.todayValue; }).value(); return nextWalk && nextWalk.$id(); } $scope.refreshWalks = function (notificationSent) { notify.setBusy(); notify.progress('Refreshing walks...'); return query() .then(function (walks) { $scope.nextWalkId = URLService.hasRouteParameter('walkId') ? undefined : getNextWalkId(walks); $scope.walks = URLService.hasRouteParameter('walkId') ? walks : WalksQueryService.activeWalks(walks); <API key>(); notify.clearBusy(); if (!notificationSent) { notifyWalkEdit.hide(); } $scope.userEdits.saveInProgress = false; }); }; $scope.hideWalkDialog = function () { $('#walk-dialog').modal('hide'); delete $scope.confirmAction; }; function <API key>() { logger.info('<API key>'); $scope.hideWalkDialog(); $scope.refreshWalks(); } function afterSaveWith(notificationSent) { return function () { if (!notificationSent) $('#walk-dialog').modal('hide'); notifyWalkEdit.clearBusy(); delete $scope.confirmAction; $scope.refreshWalks(notificationSent); $scope.userEdits.saveInProgress = false; } } function <API key>() { <API key>.walkBaseUrl().then(function (walkBaseUrl) { $scope.ramblersWalkBaseUrl = walkBaseUrl; }); } function <API key>() { GoogleMapsConfig.getConfig().then(function (googleMapsConfig) { $scope.googleMapsConfig = googleMapsConfig; $scope.googleMapsConfig.zoomLevel = 12; }); } function refreshMeetupData() { MeetupService.config().then(function (meetupConfig) { $scope.meetupConfig = meetupConfig; }); MeetupService.eventsForStatus('past') .then(function (pastEvents) { MeetupService.eventsForStatus('upcoming') .then(function (futureEvents) { $scope.meetupEvents = _.sortBy(pastEvents.concat(futureEvents), 'date,').reverse(); }); }) } function refreshHomePostcode() { $scope.userEdits.fromPostcode = <API key>.memberLoggedIn() ? <API key>.loggedInMember().postcode : ""; logger.debug('set from postcode to', $scope.userEdits.fromPostcode); $scope.<API key>(); } $scope.$on('memberLoginComplete', function () { refreshMembers(); refreshHomePostcode(); }); $scope.$on('walkSlotsCreated', function () { $scope.refreshWalks(); }); function refreshMembers() { if (<API key>.memberLoggedIn()) MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS) .then(function (members) { $scope.members = members; return members; }); } $scope.<API key> = function () { return <API key>.exportWalks($scope.walks, $scope.members); }; $scope.<API key> = function () { return <API key>.exportWalksFileName(); }; $scope.<API key> = function () { return <API key>.<API key>(); }; $scope.exportableWalks = function () { return <API key>.exportableWalks($scope.walksForExport); }; $scope.walksDownloadFile = function () { return <API key>.exportWalks($scope.exportableWalks(), $scope.members); }; $scope.uploadToRamblers = function () { $scope.ramblersUploadAudit = []; $scope.userEdits.<API key> = false; $scope.userEdits.<API key> = true; $scope.userEdits.saveInProgress = true; <API key>.uploadToRamblers($scope.walksForExport, $scope.members, notifyWalkExport).then(function (fileName) { $scope.userEdits.fileName = fileName; var stop = $interval(callAtInterval, 2000, false); if (!_.contains($scope.userEdits.fileNames, $scope.userEdits.fileName)) { $scope.userEdits.fileNames.push($scope.userEdits.fileName); logger.debug('added', $scope.userEdits.fileName, 'to filenames of', $scope.userEdits.fileNames.length, 'audit trail records'); } delete $scope.finalStatusError; function callAtInterval() { logger.debug("Refreshing audit trail for file", $scope.userEdits.fileName, 'count =', $scope.ramblersUploadAudit.length); $scope.<API key>(stop); } }); }; $scope.<API key> = function () { return <API key>.exportWalksFileName(); }; $scope.walksDownloadHeader = function () { return <API key>.<API key>(); }; $scope.<API key> = function () { <API key>(); }; $scope.<API key> = function (walk) { if (walk.walkValidations.length === 0) { walk.selected = !walk.selected; notifyWalkExport.hide(); } else { notifyWalkExport.error({ title: 'You can\'t export the walk for ' + $filter('displayDate')(walk.walk.walkDate), message: walk.walkValidations.join(', ') }); } }; $scope.<API key> = function () { $('#walk-export-dialog').modal('hide'); }; function populateWalkExport(walksForExport) { $scope.walksForExport = walksForExport; notifyWalkExport.success('Found total of ' + $scope.walksForExport.length + ' walk(s), ' + $scope.walksDownloadFile().length + ' preselected for export'); notifyWalkExport.clearBusy(); } function <API key>() { $scope.walksForExport = []; notifyWalkExport.warning('Determining which walks to export', true); RamblersUploadAudit.all({limit: 1000, sort: {auditTime: -1}}) .then(function (auditItems) { logger.debug('found total of', auditItems.length, 'audit trail records'); $scope.userEdits.fileNames = _.chain(auditItems).pluck('fileName').unique().value(); logger.debug('unique total of', $scope.userEdits.fileNames.length, 'audit trail records'); }); <API key>.<API key>($scope.walks, $scope.members) .then(populateWalkExport) .catch(function (error) { logger.debug('error->', error); notifyWalkExport.error({title: 'Problem with Ramblers export preparation', message: JSON.stringify(error)}); }); $('#walk-export-dialog').modal(); } refreshMembers(); $scope.refreshWalks(); <API key>(); <API key>(); refreshMeetupData(); refreshHomePostcode(); }] ) ;
angular.module('MEANcraftApp', ['ngRoute', 'MEANcraftApp.login', 'MEANcraftApp.overview', 'btford.socket-io'/*,'socket-io', 'flow'*/]) .config(function ($httpProvider, $routeProvider) { $httpProvider.interceptors.push('TokenInterceptor'); $routeProvider .when('/login', { templateUrl: 'app/login/login', controller: 'loginCtrl', protect: false }) .when('/overview', { templateUrl: 'app/overview/overview', //controller: 'overviewCtrl', protect: true, resolve: { initialData: function (ServerSocket, FetchData, $q) { return $q(function (resolve, reject) { ServerSocket.emit('info'); ServerSocket.once('info', function (data) { console.log(data); FetchData = angular.extend(FetchData, data); resolve(); }); }); } } }) .otherwise({ redirectTo: '/overview' }); }) .run(function ($rootScope, $location, $window, $routeParams, UserAuth) { if (!UserAuth.isLogged) { $location.path('/login'); } $rootScope.$on('$routeChangeStart', function (event, nextRoute, prevRoute) { console.groupCollapsed('%cAPP.RUN -> ROUTE CHANGE START', 'background: #222; color: #bada55;'); console.log('%cTOKEN -> %c' + $window.sessionStorage.token, 'font-weight: bold', ''); console.log('%cLOGGIN STATUS -> %c' + UserAuth.isLogged, 'font-weight: bold', UserAuth.isLogged ? 'color: green;' : 'color: red;'); console.groupEnd('APP.RUN -> ROUTE CHANGE START'); if (nextRoute.protect && UserAuth.isLogged === false && !$window.sessionStorage.token) { $location.path('/login'); console.error('Route protected, user not logged in'); } else if (!nextRoute.protect && UserAuth.isLogged) { $location.path('/overview'); } }); });
var GridLayout = require("ui/layouts/grid-layout").GridLayout; var ListView = require("ui/list-view").ListView; var StackLayout = require("ui/layouts/stack-layout").StackLayout; var Image = require("ui/image").Image; var Label = require("ui/label").Label; var ScrapbookList = (function (_super) { global.__extends(ScrapbookList, _super); Object.defineProperty(ScrapbookList.prototype, "items", { get: function() { return this._items; }, set: function(value) { this._items = value; this.bindData(); } }); function ScrapbookList() { _super.call(this); this._items; this.rows = "*"; this.columns = "*"; var listView = new ListView(); listView.className = "list-group"; listView.itemTemplate = function() { var stackLayout = new StackLayout(); stackLayout.orientation = "horizontal"; stackLayout.bind({ targetProperty: "className", sourceProperty: "$value", expression: "isActive ? 'list-group-item active' : 'list-group-item'" }); var image = new Image(); image.className = "thumb img-circle"; image.bind({ targetProperty: "src", sourceProperty: "image" }); stackLayout.addChild(image); var label = new Label(); label.className = "<API key>"; label.style.width = "100%"; label.textWrap = true; label.bind({ targetProperty: "text", sourceProperty: "title", expression: "(title === null || title === undefined ? 'New' : title + '\\\'s') + ' Scrapbook Page'" }); stackLayout.addChild(label); return stackLayout; }; listView.on(ListView.itemTapEvent, function(args) { onItemTap(this, args.index); }.bind(listView)); this.addChild(listView); this.bindData = function () { listView.bind({ sourceProperty: "$value", targetProperty: "items", twoWay: "true" }, this._items); }; var onItemTap = function(args, index) { this.notify({ eventName: "itemTap", object: this, index: index }); }.bind(this); } return ScrapbookList; })(GridLayout); ScrapbookList.itemTapEvent = "itemTap"; exports.ScrapbookList = ScrapbookList;
<?php /** * @package toolkit */ /** * The Datasource class provides functionality to mainly process any parameters * that the fields will use in filters find the relevant Entries and return these Entries * data as XML so that XSLT can be applied on it to create your website. In Symphony, * there are four Datasource types provided, Section, Author, Navigation and Dynamic * XML. Section is the mostly commonly used Datasource, which allows the filtering * and searching for Entries in a Section to be returned as XML. Navigation datasources * expose the Symphony Navigation structure of the Pages in the installation. Authors * expose the Symphony Authors that are registered as users of the backend. Finally, * the Dynamic XML datasource allows XML pages to be retrieved. This is especially * helpful for working with Restful XML API's. Datasources are saved through the * Symphony backend, which uses a Datasource template defined in * `TEMPLATE . /datasource.tpl`. */ class DataSource { /** * A constant that represents if this filter is an AND filter in which * an Entry must match all these filters. This filter is triggered when * the filter string contains a ` + `. * * @since Symphony 2.3.2 * @var integer */ const FILTER_AND = 1; /** * A constant that represents if this filter is an OR filter in which an * entry can match any or all of these filters * * @since Symphony 2.3.2 * @var integer */ const FILTER_OR = 2; /** * Holds all the environment variables which include parameters set by * other Datasources or Events. * @var array */ protected $_env = array(); /** * If true, this datasource only will be outputting parameters from the * Entries, and no actual content. * @var boolean */ protected $_param_output_only; /** * An array of datasource dependancies. These are datasources that must * run first for this datasource to be able to execute correctly * @var array */ protected $_dependencies = array(); /** * When there is no entries found by the Datasource, this parameter will * be set to true, which will inject the default Symphony 'No records found' * message into the datasource's result * @var boolean */ protected $_force_empty_result = false; /** * When there is a negating parameter, this parameter will * be set to true, which will inject the default Symphony 'Results Negated' * message into the datasource's result * @var boolean */ protected $_negate_result = false; /** * Constructor for the datasource sets the parent, if `$process_params` is set, * the `$env` variable will be run through `Datasource::processParameters`. * * @see toolkit.Datasource#processParameters() * @param array $env * The environment variables from the Frontend class which includes * any params set by Symphony or Events or by other Datasources * @param boolean $process_params * If set to true, `Datasource::processParameters` will be called. By default * this is true * @throws <API key> */ public function __construct(array $env = null, $process_params = true) { // Support old the __construct (for the moment anyway). // The old signature was array/array/boolean // The new signature is array/boolean $arguments = func_get_args(); if (count($arguments) == 3 && is_bool($arguments[1]) && is_bool($arguments[2])) { $env = $arguments[0]; $process_params = $arguments[1]; } if ($process_params) { $this->processParameters($env); } } /** * This function is required in order to edit it in the datasource editor page. * Do not overload this function if you are creating a custom datasource. It is only * used by the datasource editor. If this is set to false, which is default, the * Datasource's `about()` information will be displayed. * * @return boolean * True if the Datasource can be edited, false otherwise. Defaults to false */ public function allowEditorToParse() { return false; } /** * This function is required in order to identify what section this Datasource is for. It * is used in the datasource editor. It must remain intact. Do not overload this function in * custom events. Other datasources may return a string here defining their datasource * type when they do not query a section. * * @return mixed */ public function getSource() { return null; } /** * Accessor function to return this Datasource's dependencies * * @return array */ public function getDependencies() { return $this->_dependencies; } /** * Returns an associative array of information about a datasource. * * @return array */ public function about() { return array(); } /** * @deprecated This function has been renamed to `execute` as of * Symphony 2.3.1, please use `execute()` instead. This function will * be removed in Symphony 2.5 * @see execute() */ public function grab(array &$param_pool = null) { return $this->execute($param_pool); } /** * The meat of the Datasource, this function includes the datasource * type's file that will preform the logic to return the data for this datasource * It is passed the current parameters. * * @param array $param_pool * The current parameter pool that this Datasource can use when filtering * and finding Entries or data. * @return XMLElement * The XMLElement to add into the XML for a page. */ public function execute(array &$param_pool = null) { $result = new XMLElement($this->dsParamROOTELEMENT); try { $result = $this->execute($param_pool); } catch (<API key> $e) { // Work around. This ensures the 404 page is displayed and // is not picked up by the default catch() statement below <API key>::render($e); } catch (Exception $e) { $result->appendChild(new XMLElement('error', $e->getMessage())); return $result; } if ($this->_force_empty_result) { $result = $this->emptyXMLSet(); } if ($this->_negate_result) { $result = $this->negateXMLSet(); } return $result; } /** * By default, all Symphony filters are considering to be AND filters, that is * they are all used and Entries must match each filter to be included. It is * possible to use OR filtering in a field by using an + to separate the values. * eg. If the filter is test1 + test2, this will match any entries where this field * is test1 OR test2. This function is run on each filter (ie. each field) in a * datasource * * @param string $value * The filter string for a field. * @return integer * DataSource::FILTER_OR or DataSource::FILTER_AND */ public function <API key>($value) { return (preg_match('/\s+\+\s+/', $value) ? DataSource::FILTER_AND : DataSource::FILTER_OR); } /** * If there is no results to return this function calls `Datasource::__noRecordsFound` * which appends an XMLElement to the current root element. * * @param XMLElement $xml * The root element XMLElement for this datasource. By default, this will * the handle of the datasource, as defined by `$this->dsParamROOTELEMENT` * @return XMLElement */ public function emptyXMLSet(XMLElement $xml = null) { if (is_null($xml)) { $xml = new XMLElement($this->dsParamROOTELEMENT); } $xml->appendChild($this->__noRecordsFound()); return $xml; } /** * If the datasource has been negated this function calls `Datasource::__negateResult` * which appends an XMLElement to the current root element. * * @param XMLElement $xml * The root element XMLElement for this datasource. By default, this will * the handle of the datasource, as defined by `$this->dsParamROOTELEMENT` * @return XMLElement */ public function negateXMLSet(XMLElement $xml = null) { if (is_null($xml)) { $xml = new XMLElement($this->dsParamROOTELEMENT); } $xml->appendChild($this->__negateResult()); return $xml; } /** * Returns an error XMLElement with 'No records found' text * * @return XMLElement */ public function __noRecordsFound() { return new XMLElement('error', __('No records found.')); } /** * Returns an error XMLElement with 'Result Negated' text * * @return XMLElement */ public function __negateResult() { $error = new XMLElement('error', __("Data source not executed, forbidden parameter was found."), array( 'forbidden-param' => $this->dsParamNEGATEPARAM )); return $error; } /** * This function will iterates over the filters and replace any parameters with their * actual values. All other Datasource variables such as sorting, ordering and * pagination variables are also set by this function * * @param array $env * The environment variables from the Frontend class which includes * any params set by Symphony or Events or by other Datasources * @throws <API key> */ public function processParameters(array $env = null) { if ($env) { $this->_env = $env; } if ((isset($this->_env) && is_array($this->_env)) && isset($this->dsParamFILTERS) && is_array($this->dsParamFILTERS) && !empty($this->dsParamFILTERS)) { foreach ($this->dsParamFILTERS as $key => $value) { $value = stripslashes($value); $new_value = $this-><API key>($value, $this->_env); // If a filter gets evaluated to nothing, eg. ` + ` or ``, then remove // the filter. RE: #1759 if (strlen(trim($new_value)) == 0 || !preg_match('/\w+/', $new_value)) { unset($this->dsParamFILTERS[$key]); } else { $this->dsParamFILTERS[$key] = $new_value; } } } if (isset($this->dsParamORDER)) { $this->dsParamORDER = $this-><API key>($this->dsParamORDER, $this->_env); } if (isset($this->dsParamSORT)) { $this->dsParamSORT = $this-><API key>($this->dsParamSORT, $this->_env); } if (isset($this->dsParamSTARTPAGE)) { $this->dsParamSTARTPAGE = $this-><API key>($this->dsParamSTARTPAGE, $this->_env); if ($this->dsParamSTARTPAGE == '') { $this->dsParamSTARTPAGE = '1'; } } if (isset($this->dsParamLIMIT)) { $this->dsParamLIMIT = $this-><API key>($this->dsParamLIMIT, $this->_env); } if ( isset($this-><API key>) && strlen(trim($this-><API key>)) > 0 && $this-><API key>(trim($this-><API key>), $this->_env, false) == '' ) { $this->_force_empty_result = true; // don't output any XML $this->dsParamPARAMOUTPUT = null; // don't output any parameters $this-><API key> = null; // don't query any fields in this section return; } if ( isset($this->dsParamNEGATEPARAM) && strlen(trim($this->dsParamNEGATEPARAM)) > 0 && $this-><API key>(trim($this->dsParamNEGATEPARAM), $this->_env, false) != '' ) { $this->_negate_result = true; // don't output any XML $this->dsParamPARAMOUTPUT = null; // don't output any parameters $this-><API key> = null; // don't query any fields in this section return; } $this->_param_output_only = ((!isset($this-><API key>) || !is_array($this-><API key>) || empty($this-><API key>)) && !isset($this->dsParamGROUP)); if (isset($this-><API key>) && $this-><API key> == 'yes' && $this->_force_empty_result) { throw new <API key>; } } /** * This function will parse a string (usually a URL) and fully evaluate any * parameters (defined by {$param}) to return the absolute string value. * * @since Symphony 2.3 * @param string $url * The string (usually a URL) that contains the parameters (or doesn't) * @return string * The parsed URL */ public function parseParamURL($url = null) { if (!isset($url)) { return null; } // urlencode parameters $params = array(); if (preg_match_all('@{([^}]+)}@i', $url, $matches, PREG_SET_ORDER)) { foreach ($matches as $m) { $params[$m[1]] = array( 'param' => preg_replace('/:encoded$/', null, $m[1]), 'encode' => preg_match('/:encoded$/', $m[1]) ); } } foreach ($params as $key => $info) { $replacement = $this-><API key>($info['param'], $this->_env, false); if ($info['encode'] == true) { $replacement = urlencode($replacement); } $url = str_replace("{{$key}}", $replacement, $url); } return $url; } /** * This function will replace any parameters in a string with their value. * Parameters are defined by being prefixed by a `$` character. In certain * situations, the parameter will be surrounded by `{}`, which Symphony * takes to mean, evaluate this parameter to a value, other times it will be * omitted which is usually used to indicate that this parameter exists * * @param string $value * The string with the parameters that need to be evaluated * @param array $env * The environment variables from the Frontend class which includes * any params set by Symphony or Events or by other Datasources * @param boolean $includeParenthesis * Parameters will sometimes not be surrounded by `{}`. If this is the case * setting this parameter to false will make this function automatically add * them to the parameter. By default this is true, which means all parameters * in the string already are surrounded by `{}` * @param boolean $escape * If set to true, the resulting value will passed through `urlencode` before * being returned. By default this is `false` * @return string * The string with all parameters evaluated. If a parameter is not found, it will * not be replaced and remain in the `$value`. */ public function <API key>($value, array $env, $includeParenthesis = true, $escape = false) { if (trim($value) == '') { return null; } if (!$includeParenthesis) { $value = '{'.$value.'}'; } if (preg_match_all('@{([^}]+)}@i', $value, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { list($source, $cleaned) = $match; $replacement = null; $bits = preg_split('/:/', $cleaned, -1, PREG_SPLIT_NO_EMPTY); foreach ($bits as $param) { if ($param{0} != '$') { $replacement = $param; break; } $param = trim($param, '$'); $replacement = Datasource::findParameterInEnv($param, $env); if (is_array($replacement)) { $replacement = array_map(array('Datasource', 'escapeCommas'), $replacement); if (count($replacement) > 1) { $replacement = implode(',', $replacement); } else { $replacement = end($replacement); } } if (!empty($replacement)) { break; } } if ($escape == true) { $replacement = urlencode($replacement); } $value = str_replace($source, $replacement, $value); } } return $value; } /** * Using regexp, this escapes any commas in the given string * * @param string $string * The string to escape the commas in * @return string */ public static function escapeCommas($string) { return preg_replace('/(?<!\\\\),/', "\\,", $string); } /** * Used in conjunction with escapeCommas, this function will remove * the escaping pattern applied to the string (and commas) * * @param string $string * The string with the escaped commas in it to remove * @return string */ public static function removeEscapedCommas($string) { return preg_replace('/(?<!\\\\)\\\\,/', ',', $string); } /** * Parameters can exist in three different facets of Symphony; in the URL, * in the parameter pool or as an Symphony param. This function will attempt * to find a parameter in those three areas and return the value. If it is not found * null is returned * * @param string $needle * The parameter name * @param array $env * The environment variables from the Frontend class which includes * any params set by Symphony or Events or by other Datasources * @return mixed * If the value is not found, null, otherwise a string or an array is returned */ public static function findParameterInEnv($needle, $env) { if (isset($env['env']['url'][$needle])) { return $env['env']['url'][$needle]; } if (isset($env['env']['pool'][$needle])) { return $env['env']['pool'][$needle]; } if (isset($env['param'][$needle])) { return $env['param'][$needle]; } return null; } } require_once TOOLKIT . '/data-sources/class.datasource.author.php'; require_once TOOLKIT . '/data-sources/class.datasource.section.php'; require_once TOOLKIT . '/data-sources/class.datasource.static.php'; require_once TOOLKIT . '/data-sources/class.datasource.dynamic_xml.php'; require_once TOOLKIT . '/data-sources/class.datasource.navigation.php';
NAME = airdock/redis VERSION = dev-2.8 .PHONY: all clean build tag_latest release debug run run_client all: build clean: @CID=$(shell docker ps -a | awk '{ print $$1 " " $$2 }' | grep $(NAME) | awk '{ print $$1 }'); if [ ! -z "$$CID" ]; then echo "Removing container which reference $(NAME)"; for container in $(CID); do docker rm -f $$container; done; fi; @if docker images $(NAME) | awk '{ print $$2 }' | grep -q -F $(VERSION); then docker rmi -f $(NAME):$(VERSION); fi @if docker images $(NAME) | awk '{ print $$2 }' | grep -q -F latest; then docker rmi -f $(NAME):latest; fi build: clean docker build -t $(NAME):$(VERSION) --rm . tag_latest: @docker tag $(NAME):$(VERSION) $(NAME):latest release: build tag_latest docker push $(NAME) @echo "Create a tag v-$(VERSION)" @git tag v-$(VERSION) @git push origin v-$(VERSION) debug: docker run -t -i $(NAME):$(VERSION) run: @echo "IPAddress =" $$(docker inspect --format '{{.NetworkSettings.IPAddress}}' $$(docker run -d -p 6379:6379 --name redis $(NAME):$(VERSION))) run_client: docker run -it --rm --link redis:redis $(NAME):$(VERSION) bash -c 'redis-cli -h redis'
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; const double EPS = 1e-9; inline char DBLCMP(double d) { if (fabs(d) < EPS) return 0; return d>0 ? 1 : -1; } struct spoint { double x, y, z; spoint() {} spoint(double xx, double yy, double zz): x(xx), y(yy), z(zz) {} void read() {scanf("%lf%lf%lf", &x, &y, &z);} }; spoint operator - (const spoint &v1, const spoint &v2) {return spoint(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z);} double dot(const spoint &v1, const spoint &v2) {return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z;} double norm(const spoint &v) {return sqrt(v.x*v.x+v.y*v.y+v.z*v.z);} double dis(const spoint &p1, const spoint &p2) {return norm(p2-p1);} spoint c, n, s, v, p; double r, t1, t2, i, j, k; //ax+b=0 //0 for no solution, 1 for one solution, 2 for infinitive solution char lneq(double a, double b, double &x) { if (DBLCMP(a) == 0) { if (DBLCMP(b) == 0) return 2; return 0; } x = -b/a; return 1; } //ax^2+bx+c=0, a!=0 //0 for no solution, 1 for one solution, 2 for 2 solutions //x1 <= x2 char qdeq(double a, double b, double c, double &x1, double &x2) { double delta = b*b-4*a*c; if (delta < 0) return 0; x1 = (-b+sqrt(delta))/(2*a); x2 = (-b-sqrt(delta))/(2*a); if (x1 > x2) swap(x1, x2); return DBLCMP(delta) ? 2 : 1; } int main() { c.read(); n.read(); scanf("%lf", &r); //printf("##%f\n", dis(spoint(0,0,0), spoint(1,1,1))); s.read(); v.read(); i = -5.0*n.z; j = dot(n, v); k = dot(n, s-c); if (DBLCMP(i)==0) { char sta = lneq(j, k, t1); if (sta==0 || sta==2 || DBLCMP(t1) <= 0) { puts("MISSED"); return 0; } p.x = s.x+v.x*t1; p.y = s.y+v.y*t1; p.z = s.z+v.z*t1-5.0*t1*t1; if (DBLCMP(dis(p, c)-r) < 0) { puts("HIT"); return 0; } puts("MISSED"); return 0; } if (!qdeq(i, j, k, t1, t2)) { puts("MISSED"); return 0; } if (DBLCMP(t1) > 0) { p.x = s.x+v.x*t1; p.y = s.y+v.y*t1; p.z = s.z+v.z*t1-5.0*t1*t1; if (DBLCMP(dis(p, c)-r) < 0) { puts("HIT"); return 0; } } if (DBLCMP(t2) > 0) { p.x = s.x+v.x*t2; p.y = s.y+v.y*t2; p.z = s.z+v.z*t2-5.0*t2*t2; if (DBLCMP(dis(p, c)-r) < 0) { puts("HIT"); return 0; } } puts("MISSED"); return 0; }
<?php include '../src/SharesCounter.php'; include '../src/Networks.php'; include '../src/Exception.php'; $url = 'http: // 1. return shares from Facebook and Twitter $shares = new \SharesCounter\SharesCounter($url); $counts = $shares->getShares([\SharesCounter\Networks::NETWORK_FACEBOOK, \SharesCounter\Networks::NETWORK_TWITTER]); var_dump($counts); // 2. return shares from all available networks $shares = new \SharesCounter\SharesCounter($url); $counts = $shares->getShares([]); var_dump($counts); // 3. return shares from disabled by default network $url = 'http: $shares = new \SharesCounter\SharesCounter($url); $counts = $shares->getShares([\SharesCounter\Networks::NETWORK_VK, \SharesCounter\Networks::<API key>]); var_dump($counts); // 4. wykop.pl $url = 'http://pokazywarka.pl/margaryna/'; $shares = new \SharesCounter\SharesCounter($url); $counts = $shares->getShares([\SharesCounter\Networks::NETWORK_WYKOP]); var_dump($counts); // 4. helper method - return list of available networks $networks = new \SharesCounter\Networks(); $availableNetworks = $networks-><API key>(); var_export($availableNetworks);
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class <API key> extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Create the characters_lang table Schema::create('characters_lang', function($table) { $default_locale = \Config::get('app.locale'); $locales = \Config::get('app.locales', array($default_locale)); $table->increments('id'); $table->mediumInteger('character_id'); $table->string('firstname')->nullable(); $table->string('lastname')->nullable(); $table->string('nickname')->nullable(); $table->string('overview')->nullable(); $table->enum('locale', $locales); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Drop the characters_lang table Schema::dropIfExists('characters_lang'); } }
<!DOCTYPE html PUBLIC "- <html xmlns='http: <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta> <title>124-10-7.smi.png.html</title> </head> <body>ID124-10-7<br/> <img border="0" src="124-10-7.smi.png" alt="124-10-7.smi.png"></img><br/> <br/> <table border="1"> <tr> <td></td><td>ID</td><td>Formula</td><td>FW</td><td>DSSTox_CID</td><td>DSSTox_RID</td><td>DSSTox_GSID</td><td>DSSTox_FileID_Sort</td><td>TS_ChemName</td><td><API key></td><td>TS_CASRN</td><td><API key></td><td>TS_Description</td><td>ChemNote</td><td>STRUCTURE_Shown</td><td>STRUCTURE_Formula</td><td>STRUCTURE_MW</td><td>STRUCTURE_ChemType</td><td><API key></td><td>STRUCTURE_IUPAC</td><td>STRUCTURE_SMILES</td><td><API key></td><td><API key></td></tr> <tr> <td>124-10-7</td><td>4886</td><td>C15H30O2</td><td>242.3975</td><td>7019</td><td>78281</td><td>27019</td><td>2964</td><td>Methyl tetradecanoate</td><td>Methyl tetradecanoate (Tetradecanoic acid, methyl ester) (Methyl myristate)</td><td>124-10-7</td><td>primary</td><td>single chemical compound</td><td></td><td>tested chemical</td><td>C15H30O2</td><td>242.3975</td><td>defined organic</td><td>parent</td><td>methyl tetradecanoate</td><td>O=C(CCCCCCCCCCCCC)OC</td><td>O=C(CCCCCCCCCCCCC)OC</td><td>20080429</td></tr> </table> <br/><br/><font size="-2">(Page generated on Wed Sep 17 03:57:12 2014 by <a href="http: </body></html>
import React, {Component} from 'react'; import {Typeahead} from '<API key>'; import {inject, observer} from 'mobx-react'; import {action, toJS, autorunAsync} from 'mobx'; import myClient from '../agents/client' require('<API key>/css/ClearButton.css'); require('<API key>/css/Loader.css'); require('<API key>/css/Token.css'); require('<API key>/css/Typeahead.css'); @inject('controlsStore', 'designStore') @observer export default class EroTypeahead extends Component { constructor(props) { super(props); } state = { options: [] }; // this will keep updating the next -ERO options as the ERO changes; <API key> = autorunAsync('ero options update', () => { let ep = this.props.controlsStore.editPipe; let submitEro = toJS(ep.ero.hops); // keep track of the last hop; if we've reached Z we shouldn't keep going let lastHop = ep.a; if (ep.ero.hops.length > 0) { lastHop = ep.ero.hops[ep.ero.hops.length - 1]; } else { // if there's _nothing_ in our ERO then ask for options from pipe.a submitEro.push(ep.a); } // if this is the last hop, don't provide any options if (lastHop === ep.z) { this.setState({options: []}); return; } myClient.submit('POST', '/api/pce/nextHopsForEro', submitEro) .then( action((response) => { let nextHops = JSON.parse(response); if (nextHops.length > 0) { let opts = []; nextHops.map(h => { let entry = { id: h.urn, label: h.urn + ' through ' + h.through + ' to ' + h.to, through: h.through, to: h.to }; opts.push(entry); }); this.setState({options: opts}); } })); }, 500); <API key>() { this.<API key>(); } <API key> = selection => { if (selection.length === 0) { return; } let wasAnOption = false; let through = ''; let urn = ''; let to = ''; this.state.options.map(opt => { if (opt.label === selection) { wasAnOption = true; through = opt.through; urn = opt.id; to = opt.to; } }); if (wasAnOption) { let ep = this.props.controlsStore.editPipe; let ero = []; ep.manual.ero.map(e => { ero.push(e); }); ero.push(through); ero.push(urn); ero.push(to); this.props.controlsStore.<API key>({ ero: { hops: ero }, manual: {ero: ero} }); this.typeAhead.getInstance().clear(); } }; render() { return ( <Typeahead minLength={0} ref={(ref) => { this.typeAhead = ref; }} placeholder='choose from selection' options={this.state.options} onInputChange={this.<API key>} clearButton /> ); } }
'use strict'; var convert = require('./convert'), func = convert('lt', require('../lt')); func.placeholder = require('./placeholder'); module.exports = func; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2x0LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsSUFBSSxVQUFVLFFBQVEsV0FBUixDQUFWO0lBQ0EsT0FBTyxRQUFRLElBQVIsRUFBYyxRQUFRLE9BQVIsQ0FBZCxDQUFQOztBQUVKLEtBQUssV0FBTCxHQUFtQixRQUFRLGVBQVIsQ0FBbkI7QUFDQSxPQUFPLE9BQVAsR0FBaUIsSUFBakIiLCJmaWxlIjoibHQuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgY29udmVydCA9IHJlcXVpcmUoJy4vY29udmVydCcpLFxuICAgIGZ1bmMgPSBjb252ZXJ0KCdsdCcsIHJlcXVpcmUoJy4uL2x0JykpO1xuXG5mdW5jLnBsYWNlaG9sZGVyID0gcmVxdWlyZSgnLi9wbGFjZWhvbGRlcicpO1xubW9kdWxlLmV4cG9ydHMgPSBmdW5jO1xuIl19
<?php /** * UserAccount * * This class has been auto-generated by the Doctrine ORM Framework * * @package blueprint * @subpackage model * @author Your name here * @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $ */ class UserAccount extends BaseUserAccount { }
# Rounded Button Twitch Chat ![alt text](https://raw.githubusercontent.com/WolfgangAxel/Random-Projects/master/Streaming/RoundButtonExample.png) This CSS file overrides the Twitch chat popout window to make the chat slightly more visually appealing. It was created to be used with the OBS plugin Linux Browser, and presumably will work with the default Browser source for Mac and Windows. ## Instructions For Use 1. Add a (Linux) Browser source to a scene 2. Set the URL to `https: 3. Select this CSS file for the custom CSS 4. Adjust page size, zoom, and crop until only the chat area is visible 5. Add a Chroma Key filter 6. Set the Key Color Type to Custom and change the Key Color to `#123123` 7. Adjust the similarity, smoothness, and key color spillreduction to your liking (1, 35, 100 are what I found to work best) 8. Sit back and enjoy! ## Notes Dark Theme Check the comments in the file for recommended hex values for a dark theme! Badges To add badges back into the chat, simply comment out or delete the last section of the file: .badges { /* Hide badges */ position:absolute!important; visibility:hidden; } Browser Sizing What I found works well is 150% zoom and a minimum width of 450px. From here, add a crop filter with 76px top and 168px bottom. This should perfectly frame your chat without losing any space.
purescript-three ============= Purescript bindings for Threejs # Build purescript-three bower install pulp build bower link # Build examples cd examples/ bower link purescript-three pulp browserify --main Examples.CircleToSquare --to output/circleToSquare.js pulp browserify --main Examples.LineArray --to output/lineArray.js pulp browserify --main Examples.MotionStretch --to output/motionStretch.js pulp browserify --main Examples.SimpleCube --to output/simpleCube.js pulp browserify --main Examples.SimpleLine --to output/simpleLine.js
TOP_DIR = ../.. LIB_DIR = lib/ DEPLOY_RUNTIME ?= /kb/runtime TARGET ?= /kb/deployment include $(TOP_DIR)/tools/Makefile.common SPEC_FILE = handle_mngr.spec SERVICE_NAME = HandleMngr SERVICE_CAPS = HandleMngr SERVICE_PORT = 9001 SERVICE_DIR = handle_mngr SERVICE_CONFIG = HandleMngr ifeq ($(SELF_URL),) SELF_URL = http://localhost:$(SERVICE_PORT) endif SERVICE_PSGI = $(SERVICE_NAME).psgi TPAGE_ARGS = --define kb_runas_user=$(SERVICE_USER) --define kb_top=$(TARGET) --define kb_runtime=$(DEPLOY_RUNTIME) --define kb_service_name=$(SERVICE_NAME) --define <API key>=$(SERVICE_CONFIG) --define kb_service_dir=$(SERVICE_DIR) --define kb_service_port=$(SERVICE_PORT) --define kb_psgi=$(SERVICE_PSGI) # to wrap scripts and deploy them to $(TARGET)/bin using tools in # the dev_container. right now, these vars are defined in # Makefile.common, so it's redundant here. TOOLS_DIR = $(TOP_DIR)/tools WRAP_PERL_TOOL = wrap_perl WRAP_PERL_SCRIPT = bash $(TOOLS_DIR)/$(WRAP_PERL_TOOL).sh
<?php use PDFfiller\OAuth2\Client\Provider\Token; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = Token::one($provider, 3329); dd($e);
package sql.fredy.sqltools; import sql.fredy.share.t_connect; import java.io.InputStream; import java.io.IOException; import java.io.<API key>; import java.io.FileInputStream; import java.io.FileOutputStream; import java.sql.*; import java.util.logging.*; import java.util.Date; import org.apache.poi.xssf.usermodel.*; import org.apache.poi.hssf.record.*; import org.apache.poi.hssf.model.*; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.*; import java.util.ArrayList; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; public class XLSExport { private Logger logger; Connection con = null; /** * Get the value of con. * * @return value of con. */ public Connection getCon() { return con; } /** * Set the value of con. * * @param v Value to assign to con. */ public void setCon(Connection v) { this.con = v; } String query=null; /** * Get the value of query. * * @return value of query. */ public String getQuery() { return query; } /** * Set the value of query. * * @param v Value to assign to query. */ public void setQuery(String v) { this.query = v; } java.sql.SQLException exception; /** * Get the value of exception. * * @return value of exception. */ public java.sql.SQLException getException() { return exception; } /** * Set the value of exception. * * @param v Value to assign to exception. */ public void setException(java.sql.SQLException v) { this.exception = v; } private PreparedStatement pstmt = null; /* is this file xlsx or xls? we detect this out of the filename extension */ private boolean xlsx = false; private void checkXlsx(String fileName) { String[] extension = fileName.split("\\."); int l = extension.length - 1; String fileType = extension[l].toLowerCase(); if ("xlsx".equals(fileType)) { setXlsx(true); } } /* we need to check, if the extension of the Filename is either xls or xlsx if not, we set to xlsx as default */ private String fixFileName(String f) { String prefix = "", postfix = ""; String fixed = f; int i = f.lastIndexOf("."); // no postfix at all set if (i < 0) { fixed = f + ".xlsx"; } else { prefix = f.substring(0, i); postfix = f.substring(i + 1); logger.log(Level.FINE, "Prefix: " + prefix + " Postfix: " + postfix); if ((postfix.equalsIgnoreCase("xlsx")) || (postfix.equalsIgnoreCase("xls"))) { // nothing to do } else { postfix = "xlsx"; } fixed = prefix + "." + postfix; } logger.log(Level.INFO, "Filename: " + fixed); return fixed; } /** * Create the XLS-File named fileName * * @param fileName is the Name (incl. Path) of the XLS-file to create * * */ public int createXLS(String fileName) { // I need to have a query to process if ((getQuery() == null) && (getPstmt() == null)) { logger.log(Level.WARNING, "Need to have a query to process"); return 0; } // I also need to have a file to write into if (fileName == null) { logger.log(Level.WARNING, "Need to know where to write into"); return 0; } fileName = fixFileName(fileName); checkXlsx(fileName); // I need to have a connection to the RDBMS if (getCon() == null) { logger.log(Level.WARNING, "Need to have a connection to process"); return 0; } //Statement stmt = null; ResultSet resultSet = null; ResultSetMetaData rsmd = null; try { // first we have to create the Statement if (getPstmt() == null) { pstmt = getCon().prepareStatement(getQuery()); } //stmt = getCon().createStatement(); } catch (SQLException sqle1) { setException(sqle1); logger.log(Level.WARNING, "Can not create Statement. Message: " + sqle1.getMessage().toString()); return 0; } logger.log(Level.FINE, "FileName: " + fileName); logger.log(Level.FINE, "Query : " + getQuery()); logger.log(Level.FINE, "Starting export..."); // create an empty sheet Workbook wb; Sheet sheet; Sheet sqlsheet; CreationHelper createHelper = null; //XSSFSheet xsheet; //HSSFSheet sheet; if (isXlsx()) { wb = new SXSSFWorkbook(); createHelper = wb.getCreationHelper(); } else { wb = new HSSFWorkbook(); createHelper = wb.getCreationHelper(); } sheet = wb.createSheet("Data Export"); // create a second sheet just containing the SQL Statement sqlsheet = wb.createSheet("SQL Statement"); Row sqlrow = sqlsheet.createRow(0); Cell sqltext = sqlrow.createCell(0); try { if ( getQuery() != null ) { sqltext.setCellValue(getQuery()); } else { sqltext.setCellValue(pstmt.toString()); } } catch (Exception lex) { } CellStyle style = wb.createCellStyle(); style.setWrapText(true); sqltext.setCellStyle(style); Row r = null; int row = 0; // row number int col = 0; // column number int columnCount = 0; try { //resultSet = stmt.executeQuery(getQuery()); resultSet = pstmt.executeQuery(); logger.log(Level.FINE, "query executed"); } catch (SQLException sqle2) { setException(sqle2); logger.log(Level.WARNING, "Can not execute query. Message: " + sqle2.getMessage().toString()); return 0; } // create Header in XLS-file ArrayList<String> head = new ArrayList(); try { rsmd = resultSet.getMetaData(); logger.log(Level.FINE, "Got MetaData of the resultset"); columnCount = rsmd.getColumnCount(); logger.log(Level.FINE, Integer.toString(columnCount) + " Columns in this resultset"); r = sheet.createRow(row); // titlerow if ((!isXlsx()) && (columnCount > 255)) { columnCount = 255; } for (int i = 0; i < columnCount; i++) { // we create the cell Cell cell = r.createCell(col); // set the value of the cell cell.setCellValue(rsmd.getColumnName(i + 1)); head.add(rsmd.getColumnName(i + 1)); // then we align center CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // now we make it bold //HSSFFont f = wb.createFont(); Font headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); cellStyle.setFont(headerFont); //cellStyle.setFont(f); // adapt this font to the cell cell.setCellStyle(cellStyle); col++; } } catch (SQLException sqle3) { setException(sqle3); logger.log(Level.WARNING, "Can not create XLS-Header. Message: " + sqle3.getMessage().toString()); return 0; } // looping the resultSet int wbCounter = 0; try { while (resultSet.next()) { // this is the next row col = 0; // put column counter back to 0 to start at the next row row++; // next row // create a new sheet if more then 60'000 Rows and xls file if ((!isXlsx()) && (row % 65530 == 0)) { wbCounter++; row = 0; sheet = wb.createSheet("Data Export " + Integer.toString(wbCounter)); logger.log(Level.INFO, "created a further page because of a huge amount of data"); // create the head r = sheet.createRow(row); // titlerow for (int i = 0; i < head.size(); i++) { // we create the cell Cell cell = r.createCell(col); // set the value of the cell cell.setCellValue((String) head.get(i)); // then we align center CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // now we make it bold //HSSFFont f = wb.createFont(); Font headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); cellStyle.setFont(headerFont); //cellStyle.setFont(f); // adapt this font to the cell cell.setCellStyle(cellStyle); col++; } row++; } try { r = sheet.createRow(row); } catch (Exception e) { logger.log(Level.WARNING, "Error while creating row number " + row + " " + e.getMessage()); wbCounter++; row = 0; sheet = wb.createSheet("Data Export " + Integer.toString(wbCounter)); logger.log(Level.WARNING, "created a further page in the hope it helps..."); // create the head r = sheet.createRow(row); // titlerow for (int i = 0; i < head.size(); i++) { // we create the cell Cell cell = r.createCell(col); // set the value of the cell cell.setCellValue((String) head.get(i)); // then we align center CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // now we make it bold //HSSFFont f = wb.createFont(); Font headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); cellStyle.setFont(headerFont); //cellStyle.setFont(f); // adapt this font to the cell cell.setCellStyle(cellStyle); col++; } row++; } col = 0; // put column counter back to 0 to start at the next row String previousMessage = ""; for (int i = 0; i < columnCount; i++) { try { // depending on the type, create the cell switch (rsmd.getColumnType(i + 1)) { case java.sql.Types.INTEGER: r.createCell(col).setCellValue(resultSet.getInt(i + 1)); break; case java.sql.Types.FLOAT: r.createCell(col).setCellValue(resultSet.getFloat(i + 1)); break; case java.sql.Types.DOUBLE: r.createCell(col).setCellValue(resultSet.getDouble(i + 1)); break; case java.sql.Types.DECIMAL: r.createCell(col).setCellValue(resultSet.getFloat(i + 1)); break; case java.sql.Types.NUMERIC: r.createCell(col).setCellValue(resultSet.getFloat(i + 1)); break; case java.sql.Types.BIGINT: r.createCell(col).setCellValue(resultSet.getInt(i + 1)); break; case java.sql.Types.TINYINT: r.createCell(col).setCellValue(resultSet.getInt(i + 1)); break; case java.sql.Types.SMALLINT: r.createCell(col).setCellValue(resultSet.getInt(i + 1)); break; case java.sql.Types.DATE: // first we get the date java.sql.Date dat = resultSet.getDate(i + 1); java.util.Date date = new java.util.Date(dat.getTime()); r.createCell(col).setCellValue(date); break; case java.sql.Types.TIMESTAMP: // first we get the date java.sql.Timestamp ts = resultSet.getTimestamp(i + 1); Cell c = r.createCell(col); try { c.setCellValue(ts); // r.createCell(col).setCellValue(ts); // Date Format CellStyle cellStyle = wb.createCellStyle(); cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy/mm/dd hh:mm:ss")); c.setCellStyle(cellStyle); } catch (Exception e) { c.setCellValue(" "); } break; case java.sql.Types.TIME: // first we get the date java.sql.Time time = resultSet.getTime(i + 1); r.createCell(col).setCellValue(time); break; case java.sql.Types.BIT: boolean b1 = resultSet.getBoolean(i + 1); r.createCell(col).setCellValue(b1); break; case java.sql.Types.BOOLEAN: boolean b2 = resultSet.getBoolean(i + 1); r.createCell(col).setCellValue(b2); break; case java.sql.Types.CHAR: r.createCell(col).setCellValue(resultSet.getString(i + 1)); break; case java.sql.Types.NVARCHAR: r.createCell(col).setCellValue(resultSet.getString(i + 1)); break; case java.sql.Types.VARCHAR: try { r.createCell(col).setCellValue(resultSet.getString(i + 1)); } catch (Exception e) { r.createCell(col).setCellValue(" "); logger.log(Level.WARNING, "Exception while writing column {0} row {3} type: {1} Message: {2}", new Object[]{col, rsmd.getColumnType(i + 1), e.getMessage(), row}); } break; default: r.createCell(col).setCellValue(resultSet.getString(i + 1)); break; } } catch (Exception e) { //e.printStackTrace(); if (resultSet.wasNull()) { r.createCell(col).setCellValue(" "); } else { logger.log(Level.WARNING, "Unhandled type at column {0}, row {3} type: {1}. Filling up with blank {2}", new Object[]{col, rsmd.getColumnType(i + 1), e.getMessage(), row}); r.createCell(col).setCellValue(" "); } } col++; } } //pstmt.close(); } catch (SQLException sqle3) { setException(sqle3); logger.log(Level.WARNING, "Exception while writing data into sheet. Message: " + sqle3.getMessage().toString()); } try { // Write the output to a file FileOutputStream fileOut = new FileOutputStream(fileName); wb.write(fileOut); fileOut.close(); logger.log(Level.INFO, "File created"); logger.log(Level.INFO, "Wrote: {0} lines into XLS-File", Integer.toString(row)); } catch (Exception e) { logger.log(Level.WARNING, "Exception while writing xls-File: " + e.getMessage().toString()); } return row; } public XLSExport(Connection con) { logger = Logger.getLogger("sql.fredy.sqltools"); setCon(con); } public XLSExport() { logger = Logger.getLogger("sql.fredy.sqltools"); } public static void main(String args[]) { String host = "localhost"; String user = System.getProperty("user.name"); String schema = "%"; String database = null; String password = null; String query = null; String file = null; System.out.println("XLSExport\n" + " + "Syntax: java sql.fredy.sqltools.XLSExport\n" + " Parameters: -h Host (default: localhost)\n" + " -u User (default: " + System.getProperty("user.name") + ")\n" + " -p Password\n" + " -q Query\n" + " -Q Filename of the file containing the Query\n" + " -d database\n" + " -f File to write into (.xls or xlsx)\n"); int i = 0; while (i < args.length) { if (args[i].equals("-h")) { i++; host = args[i]; } if (args[i].equals("-u")) { i++; user = args[i]; } if (args[i].equals("-p")) { i++; password = args[i]; } if (args[i].equals("-d")) { i++; database = args[i]; } if (args[i].equals("-q")) { i++; query = args[i]; } if (args[i].equals("-Q")) { i++; sql.fredy.io.ReadFile rf = new sql.fredy.io.ReadFile(args[i]); query = rf.getText(); } if (args[i].equals("-f")) { i++; file = args[i]; } i++; }; t_connect tc = new t_connect(host, user, password, database); XLSExport xe = new XLSExport(tc.con); xe.setQuery(query); xe.createXLS(file); tc.close(); } /** * @return the xlsx */ public boolean isXlsx() { return xlsx; } /** * @param xlsx the xlsx to set */ public void setXlsx(boolean xlsx) { this.xlsx = xlsx; } /** * @return the pstmt */ public PreparedStatement getPstmt() { return pstmt; } /** * @param pstmt the pstmt to set */ public void setPstmt(PreparedStatement pstmt) { this.pstmt = pstmt; } }
# -*- coding: utf-8 -*- # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # all copies or substantial portions of the Software. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ TODO... """ __all__ = ['GreedyPlayer'] import random from jdhp.tictactoe.player.abstract import Player class GreedyPlayer(Player): """ TODO... """ def play(self, game, state): """ TODO... """ action_list = game.<API key>(state) choosen_action = None # Choose actions that lead to immediate victory... for action in action_list: next_state = game.nextState(state, action, self) if game.hasWon(self, next_state): choosen_action = action break # ... otherwise choose randomly if choosen_action is None: #print("randomly choose action") # debug choosen_action = random.choice(action_list) return choosen_action
package com.vinexs.view; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.<API key>; import android.widget.LinearLayout; @SuppressWarnings("unused") public class <API key> extends LinearLayout { private <API key> scaleDetector; private float scaleFactor = 1.f; private float maxScaleFactor = 1.5f; private float minScaleFactor = 0.5f; public <API key>(Context context) { super(context); scaleDetector = new <API key>(context, new ScaleListener()); } public <API key>(Context context, AttributeSet attrs) { super(context, attrs); scaleDetector = new <API key>(context, new ScaleListener()); } @SuppressLint("<API key>") @Override public boolean onTouchEvent(MotionEvent event) { // Let the <API key> inspect all events. scaleDetector.onTouchEvent(event); return true; } @Override public void dispatchDraw(Canvas canvas) { canvas.save(); canvas.scale(scaleFactor, scaleFactor); super.dispatchDraw(canvas); canvas.restore(); } public <API key> setMaxScale(float scale) { maxScaleFactor = scale; return this; } public <API key> setMinScale(float scale) { minScaleFactor = scale; return this; } public <API key> <API key>() { return scaleDetector; } private class ScaleListener extends <API key>.<API key> { @Override public boolean onScale(<API key> detector) { scaleFactor *= detector.getScaleFactor(); scaleFactor = Math.max(minScaleFactor, Math.min(scaleFactor, maxScaleFactor)); invalidate(); return true; } } }
body { margin: 0; padding: 32px; font-family: Arial, Helvetica, sans-serif; font-size: 13px; color: #333333; } /* Gridlist */ .gridlist { margin: 0; } .gridlist .control .icon { vertical-align: top; }
// DRHMotorUnitData.h // TAFPlotter #import <Foundation/Foundation.h> @interface DRHMotorUnitData : NSObject <NSCoding>{ NSNumber *unitNumber; NSNumber *unitSet; NSString *unitType; NSNumber *onsetTime; NSNumber *peakTime; NSNumber *endTime; NSNumber *inspTime; NSNumber *onsetFreq; NSNumber *peakFreq; NSNumber *endFreq; NSNumber *tonicFreq; NSNumber *normOnsetTime; NSNumber *normPeakTime; NSNumber *normEndTime; } @property NSNumber *unitNumber; @property NSNumber *unitSet; @property NSString *unitType; @property NSNumber *onsetTime; @property NSNumber *peakTime; @property NSNumber *endTime; @property NSNumber *inspTime; @property NSNumber *onsetFreq; @property NSNumber *peakFreq; @property NSNumber *endFreq; @property NSNumber *tonicFreq; @property NSNumber *normOnsetTime; @property NSNumber *normPeakTime; @property NSNumber *normEndTime; -(DRHMotorUnitData *)initWith:(NSDictionary *)unitData; +(DRHMotorUnitData *)unitWith:(NSDictionary *)unitData; -(DRHMotorUnitData *)initBlank; +(DRHMotorUnitData *)blankUnit; @end
__author__ = 'besta' class BestaPlayer: def __init__(self, fichier, player): self.fichier = fichier self.grille = self.getFirstGrid() self.best_hit = 0 self.players = player def getFirstGrid(self): """ Implements function to get the first grid. :return: the grid. """ li = [] with open(self.fichier, 'r') as fi: for line in fi.readlines(): li.append(line) return li def updateGrid(self): """ Implements function to update the grid to alter n-1 round values """ with open(self.fichier, 'r') as fi: for line in fi.readlines(): i = 0 for car in line: j = 0 if car != '\n': self.grille[i][j] = car j += 1 i += 1 def grilleEmpty(self): """ Implement function to check if the grid is empty. """ for line in self.grille: for car in line[:len(line) - 1]: if car != '0': return False return True def checkLines(self, player, inARow): """ Implements function to check the current lines setup to evaluate best combinaison. :param player: check for your numbers (your player number) or those of your opponent. :param inARow: how many tokens in a row (3 or 2). :return: true or false """ count = 0 flag = False for line_number, line in enumerate(self.grille): count = 0 for car_pos, car in enumerate(line[:len(line) - 1]): if int(car) == player and not flag: count = 1 flag = True elif int(car) == player and flag: count += 1 if count == inARow: if car_pos - inARow >= 0 and self.canPlayLine(line_number, car_pos - inARow): return True, car_pos - inARow if car_pos + 1 <= 6 and self.canPlayLine(line_number, car_pos + 1): return True, car_pos + 1 else: count = 0 return False, 0 def canPlayLine(self, line, col): """ Function to check if we can fill the line with a token. :param line: which line :param col: which column :return: true or false """ if line == 5: return self.grille[line][col] == '0' else: return self.grille[line][col] == '0' and self.grille[line + 1][col] != '0' def changeColumnInLines(self): """ Implements function to transform columns in lines to make tests eaiser. :return: a reverse matrice """ column = [] for x in xrange(7): col = '' for y in xrange(6): col += self.grille[y][x] column.append(col) return column def checkColumns(self, player, inARow): """ Implements function to check the current columns setup to evaluate best combinaison. :param player: check for your numbers (your player number) or those of your opponent. :param inARow: how many tokens in a row (3 or 2). :return: true or false """ column = self.changeColumnInLines() count = 0 flag = False for col_number, line in enumerate(column): count = 0 for car_pos, car in enumerate(line): if int(car) == player and not flag: count = 1 flag = True elif int(car) == player and flag: count += 1 if count == inARow and car_pos - inARow >= 0 and self.grille[car_pos - inARow][col_number] == '0': return True, col_number else: count = 0 return False, 0 def <API key>(self, player, inARow): """ Implements function to check the current diagonal to evaluate best combinaison. :param player: check for your numbers or opponent ones. :param inARow: how many tokens in a row (3 or 2). :return: """ x = 3 flag = False while x < 6: count = 0 x_int = x y_int = 0 while x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int + 1 <= 6 and x_int - 1 >= 0 and self.grille[x_int][y_int + 1] != '0': return True, y_int + 1 else: count = 0 flag = False x_int -= 1 y_int += 1 x += 1 y = 1 flag = False while y <= 3: count = 0 x_int = 5 y_int = y while y_int <= 6 and x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int + 1 <= 6 and x_int - 1 >= 0 and self.grille[x_int][y + 1] != '0': return True, y_int + 1 else: count = 0 flage = False x_int -= 1 y_int += 1 y += 1 return False, 0 def <API key>(self, player, inARow): """ Implements function to check the current diagonal to evaluate best combinaison. :param player: check for your numbers or opponent ones. :param inARow: how many tokens in a row (3 or 2). :return: """ x = 3 flag = False while x < 6: count = 0 x_int = x y_int = 6 while x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int - 1 >= 0 and x_int - 1 >= 0 and self.grille[x_int][y_int - 1] != '0': return True, y_int - 1 else: count = 0 flag = False x_int -= 1 y_int -= 1 x += 1 y = 5 flag = False while y <= 3: count = 0 x_int = 5 y_int = y while y_int >= 3 and x_int >= 0: if int(self.grille[x_int][y_int]) == player and not flag: count = 1 flag = True elif int(self.grille[x_int][y_int]) == player and flag: count += 1 if count == inARow and y_int - 1 >= 0 and x_int - 1 >= 0 and self.grille[x_int][y - 1] != '0': return True, y_int - 1 else: count = 0 flage = False x_int -= 1 y_int -= 1 y -= 1 return False, 0 def checkDiagonals(self, player, inARow): """ Calls two diagonal functional. :return: an int, representing the column where to play or 0 and False if there is no pattern search. """ check = self.<API key>(player, inARow) if check[0]: return check else: return self.<API key>(player, inARow) def playSomeColumn(self, player, inARow): """ Call all function for a player and a number of tokens given. :param player: which player :param inARow: how many token :return: true or false (col number if true) """ methods = {'checklines': self.checkLines, 'checkcolumn': self.checkColumns, 'checkdiagonal': self.checkDiagonals} for key, function in methods.items(): which_col = function(player, inARow) if which_col[0]: return which_col return False, 0 def <API key>(self): """ Implements function to get the first column where a slot remain. :return: the column """ for col in xrange(7): if self.grille[0][col] == '0': return col return -1 def decideColumn(self): """ Implements main function : to decide what is the better hit to do. :return: an int, representing the column where we play """ if self.grilleEmpty(): return 3 li_sequence = [3, 2, 1] li_players = [self.players[0], self.players[1]] for sequence in li_sequence: for player in li_players: choosen_col = self.playSomeColumn(player, sequence) if choosen_col[0]: return choosen_col[1] return self.<API key>()
PP.lib.shader.shaders.color = { info: { name: 'color adjustement', author: 'Evan Wallace', link: 'https://github.com/evanw/glfx.js' }, uniforms: { textureIn: { type: "t", value: 0, texture: null }, brightness: { type: "f", value: 0.0 }, contrast: { type: "f", value: 0.0 }, hue: { type: "f", value: 0.0 }, saturation: { type: "f", value: 0.0 }, exposure: { type: "f", value: 0.0 }, negative: { type: "i", value: 0 } }, controls: { brightness: {min:-1, max: 1, step:.05}, contrast: {min:-1, max: 1, step:.05}, hue: {min:-1, max: 1, step:.05}, saturation: {min:-1, max: 1, step:.05}, exposure: {min:0, max: 1, step:.05}, negative: {} }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "varying vec2 vUv;", "uniform sampler2D textureIn;", "uniform float brightness;", "uniform float contrast;", "uniform float hue;", "uniform float saturation;", "uniform float exposure;", "uniform int negative;", "const float sqrtoftwo = 1.41421356237;", "void main() {", "vec4 color = texture2D(textureIn, vUv);", "color.rgb += brightness;", "if (contrast > 0.0) {", "color.rgb = (color.rgb - 0.5) / (1.0 - contrast) + 0.5;", "} else {", "color.rgb = (color.rgb - 0.5) * (1.0 + contrast) + 0.5;", "}", "/* hue adjustment, wolfram alpha: RotationTransform[angle, {1, 1, 1}][{x, y, z}] */", "float angle = hue * 3.14159265;", "float s = sin(angle), c = cos(angle);", "vec3 weights = (vec3(2.0 * c, -sqrt(3.0) * s - c, sqrt(3.0) * s - c) + 1.0) / 3.0;", "float len = length(color.rgb);", "color.rgb = vec3(", "dot(color.rgb, weights.xyz),", "dot(color.rgb, weights.zxy),", "dot(color.rgb, weights.yzx)", ");", "/* saturation adjustment */", "float average = (color.r + color.g + color.b) / 3.0;", "if (saturation > 0.0) {", "color.rgb += (average - color.rgb) * (1.0 - 1.0 / (1.0 - saturation));", "} else {", "color.rgb += (average - color.rgb) * (-saturation);", "}", "if(negative == 1){", " color.rgb = 1.0 - color.rgb;", "}", "if(exposure > 0.0){", " color = log2(vec4(pow(exposure + sqrtoftwo, 2.0))) * color;", "}", "gl_FragColor = color;", "}", ].join("\n") }; PP.lib.shader.shaders.bleach = { info: { name: 'Bleach', author: 'Brian Chirls @bchirls', link: 'https://github.com/brianchirls/Seriously.js' }, uniforms: { textureIn: { type: "t", value: 0, texture: null }, amount: { type: "f", value: 1.0 } }, controls: { amount: {min:0, max: 1, step:.1} }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ 'varying vec2 vUv;', 'uniform sampler2D textureIn;', 'uniform float amount;', 'const vec4 one = vec4(1.0);', 'const vec4 two = vec4(2.0);', 'const vec4 lumcoeff = vec4(0.2125,0.7154,0.0721,0.0);', 'vec4 overlay(vec4 myInput, vec4 previousmix, vec4 amount) {', ' float luminance = dot(previousmix,lumcoeff);', ' float mixamount = clamp((luminance - 0.45) * 10.0, 0.0, 1.0);', ' vec4 branch1 = two * previousmix * myInput;', ' vec4 branch2 = one - (two * (one - previousmix) * (one - myInput));', ' vec4 result = mix(branch1, branch2, vec4(mixamount) );', ' return mix(previousmix, result, amount);', '}', 'void main (void) {', ' vec4 pixel = texture2D(textureIn, vUv);', ' vec4 luma = vec4(vec3(dot(pixel,lumcoeff)), pixel.a);', ' gl_FragColor = overlay(luma, pixel, vec4(amount));', '}' ].join("\n") }; PP.lib.shader.shaders.plasma = { info: { name: 'plasma', author: 'iq', link: 'http: }, uniforms: { resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 }, saturation: { type: "f", value: 1.0 }, waves: { type: "f", value: .2 }, wiggle: { type: "f", value: 1000.0 }, scale: { type: "f", value: 1.0 } }, controls: { speed: {min:0, max: .1, step:.001}, saturation: {min:0, max: 10, step:.01}, waves: {min:0, max: .4, step:.0001}, wiggle: {min:0, max: 10000, step:1}, scale: {min:0, max: 10, step:.01} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "varying vec2 vUv;", "uniform float time;", "uniform float saturation;", "uniform vec2 resolution;", "uniform float waves;", "uniform float wiggle;", "uniform float scale;", "void main() {", "float x = gl_FragCoord.x*scale;", "float y = gl_FragCoord.y*scale;", "float mov0 = x+y+cos(sin(time)*2.)*100.+sin(x/100.)*wiggle;", "float mov1 = y / resolution.y / waves + time;", "float mov2 = x / resolution.x / waves;", "float r = abs(sin(mov1+time)/2.+mov2/2.-mov1-mov2+time);", "float g = abs(sin(r+sin(mov0/1000.+time)+sin(y/40.+time)+sin((x+y)/100.)*3.));", "float b = abs(sin(g+cos(mov1+mov2+g)+cos(mov2)+sin(x/1000.)));", "vec3 plasma = vec3(r,g,b) * saturation;", "gl_FragColor = vec4( plasma ,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasma2 = { info: { name: 'plasma2', author: 'mrDoob', link: 'http://mrdoob.com' }, uniforms: { resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 }, qteX: { type: "f", value: 80.0 }, qteY: { type: "f", value: 10.0 }, intensity: { type: "f", value: 10.0 }, hue: { type: "f", value: .25 } }, controls: { speed: {min:0, max: 1, step:.001}, qteX: {min:0, max: 200, step:1}, qteY: {min:0, max: 200, step:1}, intensity: {min:0, max: 50, step:.1}, hue: {min:0, max: 2, step:.001} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform float time;", "uniform vec2 resolution;", "uniform float qteX;", "uniform float qteY;", "uniform float intensity;", "uniform float hue;", "void main() {", "vec2 position = gl_FragCoord.xy / resolution.xy;", "float color = 0.0;", "color += sin( position.x * cos( time / 15.0 ) * qteX ) + cos( position.y * cos( time / 15.0 ) * qteY );", "color += sin( position.y * sin( time / 10.0 ) * 40.0 ) + cos( position.x * sin( time / 25.0 ) * 40.0 );", "color += sin( position.x * sin( time / 5.0 ) * 10.0 ) + sin( position.y * sin( time / 35.0 ) * 80.0 );", "color *= sin( time / intensity ) * 0.5;", "gl_FragColor = vec4( vec3( color, color * (hue*2.0), sin( color + time / (hue*12.0) ) * (hue*3.0) ), 1.0 );", "}" ].join("\n") }; PP.lib.shader.shaders.plasma3 = { info: { name: 'plasma 3', author: 'Hakim El Hattab', link: 'http://hakim.se' }, uniforms: { color: { type: "c", value: new THREE.Color( 0x8CC6DA ) }, resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.05 }, scale: { type: "f", value: 10.0 }, quantity: { type: "f", value: 5.0 }, lens: { type: "f", value: 2.0 }, intensity: { type: "f", value: .5 } }, controls: { speed: {min:0, max: 1, step:.001}, scale: {min:0, max: 100, step:.1}, quantity: {min:0, max: 100, step:1}, lens: {min:0, max: 100, step:1}, intensity: {min:0, max: 5, step:.01} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform float time;", "uniform vec2 resolution;", "uniform vec3 color;", "uniform float scale;", "uniform float quantity;", "uniform float lens;", "uniform float intensity;", "void main() {", "vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;", "p = p * scale;", "vec2 uv;", "float a = atan(p.y,p.x);", "float r = sqrt(dot(p,p));", "uv.x = 2.0*a/3.1416;", "uv.y = -time+ sin(7.0*r+time) + .7*cos(time+7.0*a);", "float w = intensity+1.0*(sin(time+lens*r)+ 1.0*cos(time+(quantity * 2.0)*a));", "gl_FragColor = vec4(color*w,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasma4 = { info: { name: 'plasma 4 (vortex)', author: 'Hakim El Hattab', link: 'http://hakim.se' }, uniforms: { color: { type: "c", value: new THREE.Color( 0xff5200 ) }, // 0x8CC6DA resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.05 }, scale: { type: "f", value: 20.0 }, wobble: { type: "f", value: 1.0 }, ripple: { type: "f", value: 5.0 }, light: { type: "f", value: 2.0 } }, controls: { speed: {min:0, max: 1, step:.001}, scale: {min:0, max: 100, step:.1}, wobble: {min:0, max: 50, step:1}, ripple: {min:0, max: 50, step:.1}, light: {min:1, max: 50, step:1} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform float time;", "uniform vec2 resolution;", "uniform vec3 color;", "uniform float scale;", "uniform float wobble;", "uniform float ripple;", "uniform float light;", "void main() {", "vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;", "vec2 uv;", "float a = atan(p.y,p.x);", "float r = sqrt(dot(p,p));", "float u = cos(a*(wobble * 2.0) + ripple * sin(-time + scale * r));", "float intensity = sqrt(pow(abs(p.x),light) + pow(abs(p.y),light));", "vec3 result = u*intensity*color;", "gl_FragColor = vec4(result,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasma5 = { info: { name: 'plasma 5', author: 'Silexars', link: 'http: }, uniforms: { resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 } }, controls: { speed: {min:0, max: .2, step:.001} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform vec2 resolution;", "uniform float time;", "void main() {", "vec3 col;", "float l,z=time;", "for(int i=0;i<3;i++){", "vec2 uv;", "vec2 p=gl_FragCoord.xy/resolution.xy;", "uv=p;", "p-=.5;", "p.x*=resolution.x/resolution.y;", "z+=.07;", "l=length(p);", "uv+=p/l*(sin(z)+1.)*abs(sin(l*9.-z*2.));", "col[i]=.01/length(abs(mod(uv,1.)-.5));", "}", "gl_FragColor=vec4(col/l,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasmaByTexture = { info: { name: 'plasma by texture', author: 'J3D', link: 'http: }, uniforms: { textureIn: { type: "t", value: 0, texture: null }, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 } }, controls: { speed: {min:0, max: .1, step:.001} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "varying vec2 vUv;", "uniform sampler2D textureIn;", "uniform float time;", "void main() {", "vec2 ca = vec2(0.1, 0.2);", "vec2 cb = vec2(0.7, 0.9);", "float da = distance(vUv, ca);", "float db = distance(vUv, cb);", "float t = time * 0.5;", "float c1 = sin(da * cos(t) * 16.0 + t * 4.0);", "float c2 = cos(vUv.y * 8.0 + t);", "float c3 = cos(db * 14.0) + sin(t);", "float p = (c1 + c2 + c3) / 3.0;", "gl_FragColor = texture2D(textureIn, vec2(p, p));", "}" ].join("\n") };
CKEDITOR.plugins.setLang( 'save', 'de-ch', { toolbar: 'Speichern' } );
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "command/socket_command.h" #include "component/socket_component.h" #include "component/tunnel_component.h" #include "entity/entity.h" #include "http/http_socket.h" #include "message/request/request_message.h" #include "message/response/response_message.h" namespace eja { // Client <API key>::ptr <API key>::execute(const entity::ptr router) { return <API key>::create(); } void <API key>::execute(const entity::ptr router, const std::shared_ptr<<API key>> response) { } // Router <API key>::ptr <API key>::execute(const entity::ptr client, const http_socket::ptr socket, const <API key>::ptr request) { // Socket const auto socket_set = m_entity->get<<API key>>(); { thread_lock(socket_set); socket_set->erase(socket); } // Tunnel const auto tunnel_list = client->get<<API key>>(); { thread_lock(tunnel_list); tunnel_list->push_back(socket); } return <API key>::create(); } }
cookbook_path ["berks-cookbooks", "cookbooks", "site-cookbooks"] node_path "nodes" role_path "roles" environment_path "environments" data_bag_path "data_bags" #<API key> "data_bag_key" knife[:berkshelf_path] = "berks-cookbooks" Chef::Config[:ssl_verify_mode] = :verify_peer if defined? ::Chef
// Specifically test buffer module regression. import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding, constants, kMaxLength, kStringMaxLength, Blob, } from 'buffer'; const utf8Buffer = new Buffer('test'); const base64Buffer = new Buffer('', 'base64'); const octets: Uint8Array = new Uint8Array(123); const octetBuffer = new Buffer(octets); const sharedBuffer = new Buffer(octets.buffer); const copiedBuffer = new Buffer(utf8Buffer); console.log(Buffer.isBuffer(octetBuffer)); console.log(Buffer.isEncoding('utf8')); console.log(Buffer.byteLength('xyz123')); console.log(Buffer.byteLength('xyz123', 'ascii')); const result1 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>); const result2 = Buffer.concat([utf8Buffer, base64Buffer] as ReadonlyArray<Uint8Array>, 9999999); // Module constants { const value1: number = constants.MAX_LENGTH; const value2: number = constants.MAX_STRING_LENGTH; const value3: number = kMaxLength; const value4: number = kStringMaxLength; } // Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64() { const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); buf.swap16(); buf.swap32(); buf.swap64(); } // Class Method: Buffer.from(data) { // Array const buf1: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72] as ReadonlyArray<number>); // Buffer const buf2: Buffer = Buffer.from(buf1, 1, 2); // String const buf3: Buffer = Buffer.from('this is a tést'); // ArrayBuffer const arrUint16: Uint16Array = new Uint16Array(2); arrUint16[0] = 5000; arrUint16[1] = 4000; const buf4: Buffer = Buffer.from(arrUint16.buffer); const arrUint8: Uint8Array = new Uint8Array(2); const buf5: Buffer = Buffer.from(arrUint8); const buf6: Buffer = Buffer.from(buf1); const sb: SharedArrayBuffer = {} as any; const buf7: Buffer = Buffer.from(sb); // $ExpectError Buffer.from({}); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) { const arr: Uint16Array = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; let buf: Buffer; buf = Buffer.from(arr.buffer, 1); buf = Buffer.from(arr.buffer, 0, 1); // $ExpectError Buffer.from("this is a test", 1, 1); // Ideally passing a normal Buffer would be a type error too, but it's not // since Buffer is assignable to ArrayBuffer currently } // Class Method: Buffer.from(str[, encoding]) { const buf2: Buffer = Buffer.from('<API key>', 'hex'); /* tslint:disable-next-line no-construct */ Buffer.from(new String("DEADBEEF"), "hex"); // $ExpectError Buffer.from(buf2, 'hex'); } // Class Method: Buffer.from(object, [, byteOffset[, length]]) (Implicit coercion) { const pseudoBuf = { valueOf() { return Buffer.from([1, 2, 3]); } }; let buf: Buffer = Buffer.from(pseudoBuf); const pseudoString = { valueOf() { return "Hello"; }}; buf = Buffer.from(pseudoString); buf = Buffer.from(pseudoString, "utf-8"); // $ExpectError Buffer.from(pseudoString, 1, 2); const pseudoArrayBuf = { valueOf() { return new Uint16Array(2); } }; buf = Buffer.from(pseudoArrayBuf, 1, 1); } // Class Method: Buffer.alloc(size[, fill[, encoding]]) { const buf1: Buffer = Buffer.alloc(5); const buf2: Buffer = Buffer.alloc(5, 'a'); const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); } // Class Method: Buffer.allocUnsafe(size) { const buf: Buffer = Buffer.allocUnsafe(5); } // Class Method: Buffer.allocUnsafeSlow(size) { const buf: Buffer = Buffer.allocUnsafeSlow(10); } // Class Method byteLenght { let len: number; len = Buffer.byteLength("foo"); len = Buffer.byteLength("foo", "utf8"); const b = Buffer.from("bar"); len = Buffer.byteLength(b); len = Buffer.byteLength(b, "utf16le"); const ab = new ArrayBuffer(15); len = Buffer.byteLength(ab); len = Buffer.byteLength(ab, "ascii"); const dv = new DataView(ab); len = Buffer.byteLength(dv); len = Buffer.byteLength(dv, "utf16le"); } // Class Method poolSize { let s: number; s = Buffer.poolSize; Buffer.poolSize = 4096; } // Test that TS 1.6 works with the 'as Buffer' annotation // on isBuffer. let a: Buffer | number; a = new Buffer(10); if (Buffer.isBuffer(a)) { a.writeUInt8(3, 4); } // write* methods return offsets. const b = new Buffer(16); let result: number = b.writeUInt32LE(0, 0); result = b.writeUInt16LE(0, 4); result = b.writeUInt8(0, 6); result = b.writeInt8(0, 7); result = b.writeDoubleLE(0, 8); result = b.write('asd'); result = b.write('asd', 'hex'); result = b.write('asd', 123, 'hex'); result = b.write('asd', 123, 123, 'hex'); // fill returns the input buffer. b.fill('a').fill('b'); { const buffer = new Buffer('123'); let index: number; index = buffer.indexOf("23"); index = buffer.indexOf("23", 1); index = buffer.indexOf("23", 1, "utf8"); index = buffer.indexOf(23); index = buffer.indexOf(buffer); } { const buffer = new Buffer('123'); let index: number; index = buffer.lastIndexOf("23"); index = buffer.lastIndexOf("23", 1); index = buffer.lastIndexOf("23", 1, "utf8"); index = buffer.lastIndexOf(23); index = buffer.lastIndexOf(buffer); } { const buffer = new Buffer('123'); const val: [number, number] = [1, 1]; /* comment out for --target es5 for (let entry of buffer.entries()) { val = entry; } */ } { const buffer = new Buffer('123'); let includes: boolean; includes = buffer.includes("23"); includes = buffer.includes("23", 1); includes = buffer.includes("23", 1, "utf8"); includes = buffer.includes(23); includes = buffer.includes(23, 1); includes = buffer.includes(23, 1, "utf8"); includes = buffer.includes(buffer); includes = buffer.includes(buffer, 1); includes = buffer.includes(buffer, 1, "utf8"); } { const buffer = new Buffer('123'); const val = 1; /* comment out for --target es5 for (let key of buffer.keys()) { val = key; } */ } { const buffer = new Buffer('123'); const val = 1; /* comment out for --target es5 for (let value of buffer.values()) { val = value; } */ } // Imported Buffer from buffer module works properly { const b = new ImportedBuffer('123'); b.writeUInt8(0, 6); const sb = new ImportedSlowBuffer(43); b.writeUInt8(0, 6); } // Buffer has Uint8Array's buffer field (an ArrayBuffer). { const buffer = new Buffer('123'); const octets = new Uint8Array(buffer.buffer); } // Inherited from Uint8Array but return buffer { const b = Buffer.from('asd'); let res: Buffer = b.reverse(); res = b.subarray(); res = b.subarray(1); res = b.subarray(1, 2); } // Buffer module, transcode function { transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer const source: TranscodeEncoding = 'utf8'; const target: TranscodeEncoding = 'ascii'; transcode(Buffer.from('€'), source, target); // $ExpectType Buffer } { const a = Buffer.alloc(1000); a.writeBigInt64BE(123n); a.writeBigInt64LE(123n); a.writeBigUInt64BE(123n); a.writeBigUInt64LE(123n); let b: bigint = a.readBigInt64BE(123); b = a.readBigInt64LE(123); b = a.readBigUInt64LE(123); b = a.readBigUInt64BE(123); } async () => { const blob = new Blob(['asd', Buffer.from('test'), new Blob(['dummy'])], { type: 'application/javascript', encoding: 'base64', }); blob.size; // $ExpectType number blob.type; // $ExpectType string blob.arrayBuffer(); // $ExpectType Promise<ArrayBuffer> blob.text(); // $ExpectType Promise<string> blob.slice(); // $ExpectType Blob blob.slice(1); // $ExpectType Blob blob.slice(1, 2); // $ExpectType Blob blob.slice(1, 2, 'other'); // $ExpectType Blob };
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="layoutclass_pic"><div class="<API key>"><table class="ztable"><tr><th class="ztd1"><b>&nbsp;</b></th><td class="ztd2"></td></tr> <tr><th class="ztd1"><b>&nbsp;</b></th><td class="ztd2"> ※<font class="dianuan_mark"></font><font size=-2 color="#999900"><font class="dianyuanfont"><b><i>1></i></b></font></font><br><font size=4 color="#808080"></font></font> <br><font class="dianuan_mark2"></font><br></font> <div class="Rulediv"><font class="english_word">(1)</font> </font><font size=4 ></div><br><font class="dianuan_mark2"></font><br></font> <font class="dianuan_mark"></font><br></td></tr> </td></tr></table></div> <!-- <API key> --><div class="<API key>"></div> <!-- <API key> --></div> <!-- layoutclass_pic --></td></tr></table>
// Karma configuration // Generated on Tue Sep 09 2014 13:58:24 GMT-0700 (PDT) 'use strict'; var browsers = ['Chrome', 'PhantomJS']; if ( /^win/.test(process.platform) ) { browsers = ['IE']; } if (process.env.TRAVIS ) { browsers = ['PhantomJS']; } module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use frameworks: ['browserify', 'mocha'], browserify: { debug: true, transform: ['6to5ify'] }, // list of files / patterns to load in the browser files: [ 'node_modules/chai/chai.js', 'test/front-end/<API key>.js', '**/*.swp' 'test*-spec.js': ['browserify']
"use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.<API key>(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function <API key>(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _ = require("../../../"); var _2 = <API key>(_); describe(".toString()", function () { var User = (function (_Model) { _inherits(User, _Model); function User() { _classCallCheck(this, User); _get(Object.getPrototypeOf(User.prototype), "constructor", this).apply(this, arguments); } return User; })(_2["default"]); describe("User.find.one.where(\"id\", 1)", function () { it("should return a string representation of the chain", function () { User.find.one.where("id", 1).toString().should.eql("User.find.one.where(\"id\", 1)"); }); it("should not matter which order the chain is called in", function () { User.find.where("id", 1).one.toString().should.eql("User.find.one.where(\"id\", 1)"); }); }); describe("User.find.all.where(\"id\", 1)", function () { it("should return a string representation of the chain", function () { User.find.all.where("id", 1).toString().should.eql("User.find.all.where(\"id\", 1)"); }); }); describe("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1)", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).andWhere("id", ">", 1).toString().should.eql("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1)"); }); }); describe("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1).andWhere(\"id\", \"!=\", 3)", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).andWhere("id", ">", 1).andWhere("id", "!=", 3).toString().should.eql("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1).andWhere(\"id\", \"!=\", 3)"); }); }); describe("User.find.where(\"id\", \"<\", 10).orWhere(\"id\", \">\", 1)", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).orWhere("id", ">", 1).toString().should.eql("User.find.where(\"id\", \"<\", 10).orWhere(\"id\", \">\", 1)"); }); }); describe("User.find.where(\"id\", \"<\", 10).groupBy(\"categoryId\")", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).groupBy("categoryId").toString().should.eql("User.find.where(\"id\", \"<\", 10).groupBy(\"categoryId\")"); }); }); describe("User.find.where(\"id\", \"<\", 10).orderBy(\"categoryId\")", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).orderBy("categoryId", "desc").toString().should.eql("User.find.where(\"id\", \"<\", 10).orderBy(\"categoryId\", \"desc\")"); }); }); describe("User.find.where(\"id\", \">\", 2).limit(4)", function () { it("should return a string representation of the chain", function () { User.find.where("id", ">", 2).limit(4).toString().should.eql("User.find.where(\"id\", \">\", 2).limit(4)"); }); }); describe("User.count.where(\"id\", 1)", function () { it("should return a string representation of the chain", function () { User.count.where("id", 1).toString().should.eql("User.count.where(\"id\", 1)"); }); }); });
<?php //Announce.php namespace litepubl\post; use litepubl\view\Lang; use litepubl\view\Schema; use litepubl\view\Vars; /** * Post announces * * @property-write callable $before * @property-write callable $after * @property-write callable $onHead * @method array before(array $params) * @method array after(array $params) * @method array onHead(array $params) */ class Announce extends \litepubl\core\Events { use \litepubl\core\PoolStorageTrait; protected function create() { parent::create(); $this->basename = 'announce'; $this->addEvents('before', 'after', 'onhead'); } public function getHead(array $items): string { $result = ''; if (count($items)) { Posts::i()->loadItems($items); foreach ($items as $id) { $post = Post::i($id); $result.= $post->rawhead; } } $r = $this->onHead(['content' => $result, 'items' => $items]); return $r['content']; } public function getPosts(array $items, Schema $schema): string { $r = $this->before(['content' => '', 'items' => $items, 'schema' => $schema]); $result = $r['content']; $theme = $schema->theme; $items = $r['items']; if (count($items)) { Posts::i()->loadItems($items); $vars = new Vars(); $vars->lang = Lang::i('default'); foreach ($items as $id) { $post = Post::i($id); $view = $post->view; $vars->post = $view; $view->setTheme($theme); $result.= $view->getAnnounce($schema->postannounce); // has $author.* tags in tml if (isset($vars->author)) { unset($vars->author); } } } if ($tmlContainer = $theme->templates['content.excerpts' . ($schema->postannounce == 'excerpt' ? '' : '.' . $schema->postannounce) ]) { $result = str_replace('$excerpt', $result, $theme->parse($tmlContainer)); } $r = $this->after(['content' => $result, 'items' => $items, 'schema' => $schema]); return $r['content']; } public function getNavi(array $items, Schema $schema, string $url, int $count): string { $result = $this->getPosts($items, $schema); $result .= $this->getPages($schema, $url, $count); return $result; } public function getPages(Schema $schema, string $url, int $count): string { $app = $this->getApp(); if ($schema->perpage) { $perpage = $schema->perpage; } else { $perpage = $app->options->perpage; } return $schema->theme->getPages($url, $app->context->request->page, ceil($count / $perpage)); } //used in plugins such as singlecat public function getLinks(string $where, string $tml): string { $db = $this->getApp()->db; $t = $db->posts; $items = $db->res2assoc( $db->query( "select $t.id, $t.title, $db->urlmap.url as url from $t, $db->urlmap where $t.status = 'published' and $where and $db->urlmap.id = $t.idurl" ) ); if (!count($items)) { return ''; } $result = ''; $args = new Args(); $theme = Theme::i(); foreach ($items as $item) { $args->add($item); $result.= $theme->parseArg($tml, $args); } return $result; } } //Factory.php namespace litepubl\post; use litepubl\comments\Comments; use litepubl\comments\Pingbacks; use litepubl\core\Users; use litepubl\pages\Users as UserPages; use litepubl\tag\Cats; use litepubl\tag\Tags; class Factory { use \litepubl\core\Singleton; public function __get($name) { return $this->{'get' . $name}(); } public function getPosts() { return Posts::i(); } public function getFiles() { return Files::i(); } public function getFileView() { return FileView::i(); } public function getTags() { return Tags::i(); } public function getCats() { return Cats::i(); } public function getCategories() { return $this->getcats(); } public function getTemplatecomments() { return Templates::i(); } public function getComments($id) { return Comments::i($id); } public function getPingbacks($id) { return Pingbacks::i($id); } public function getMeta($id) { return Meta::i($id); } public function getUsers() { return Users::i(); } public function getUserpages() { return UserPages::i(); } public function getView() { return View::i(); } } //Files.php namespace litepubl\post; use litepubl\core\Event; use litepubl\core\Str; use litepubl\view\Filter; /** * Manage uploaded files * * @property-read FilesItems $itemsPosts * @property-write callable $changed * @property-write callable $edited * @method array changed(array $params) * @method array edited(array $params) */ class Files extends \litepubl\core\Items { protected function create() { $this->dbversion = true; parent::create(); $this->basename = 'files'; $this->table = 'files'; $this->addEvents('changed', 'edited'); } public function getItemsPosts(): FilesItems { return FilesItems::i(); } public function preload(array $items) { $items = array_diff($items, array_keys($this->items)); if (count($items)) { $this->select(sprintf('(id in (%1$s)) or (parent in (%1$s))', implode(',', $items)), ''); } } public function getUrl(int $id): string { $item = $this->getItem($id); return $this->getApp()->site->files . '/files/' . $item['filename']; } public function getLink(int $id): string { $item = $this->getItem($id); return sprintf('<a href="%1$s/files/%2$s" title="%3$s">%4$s</a>', $this->getApp()->site->files, $item['filename'], $item['title'], $item['description']); } public function getHash(string $filename): string { return trim(base64_encode(md5_file($filename, true)), '='); } public function addItem(array $item): int { $realfile = $this->getApp()->paths->files . str_replace('/', DIRECTORY_SEPARATOR, $item['filename']); $item['author'] = $this->getApp()->options->user; $item['posted'] = Str::sqlDate(); $item['hash'] = $this->gethash($realfile); $item['size'] = filesize($realfile); //fix empty props foreach (['mime', 'title', 'description', 'keywords'] as $prop) { if (!isset($item[$prop])) { $item[$prop] = ''; } } return $this->insert($item); } public function insert(array $item): int { $item = $this->escape($item); $id = $this->db->add($item); $this->items[$id] = $item; $this->changed([]); $this->added(['id' => $id]); return $id; } public function escape(array $item): array { foreach (['title', 'description', 'keywords'] as $name) { $item[$name] = Filter::escape(Filter::unescape($item[$name])); } return $item; } public function edit(int $id, string $title, string $description, string $keywords) { $item = $this->getItem($id); if (($item['title'] == $title) && ($item['description'] == $description) && ($item['keywords'] == $keywords)) { return false; } $item['title'] = $title; $item['description'] = $description; $item['keywords'] = $keywords; $item = $this->escape($item); $this->items[$id] = $item; $this->db->updateassoc($item); $this->changed([]); $this->edited(['id' => $id]); return true; } public function delete($id) { if (!$this->itemExists($id)) { return false; } $list = $this->itemsposts->getposts($id); $this->itemsPosts->deleteItem($id); $this->itemsPosts->updatePosts($list, 'files'); $item = $this->getItem($id); if ($item['idperm'] == 0) { @unlink($this->getApp()->paths->files . str_replace('/', DIRECTORY_SEPARATOR, $item['filename'])); } else { @unlink($this->getApp()->paths->files . 'private' . DIRECTORY_SEPARATOR . basename($item['filename'])); $this->getApp()->router->delete('/files/' . $item['filename']); } parent::delete($id); if ((int)$item['preview']) { $this->delete($item['preview']); } if ((int)$item['midle']) { $this->delete($item['midle']); } $this->getdb('imghashes')->delete("id = $id"); $this->changed([]); $this->deleted(['id' => $id]); return true; } public function setContent(int $id, string $content): bool { if (!$this->itemExists($id)) { return false; } $item = $this->getitem($id); $realfile = $this->getApp()->paths->files . str_replace('/', DIRECTORY_SEPARATOR, $item['filename']); if (file_put_contents($realfile, $content)) { $item['hash'] = $this->gethash($realfile); $item['size'] = filesize($realfile); $this->items[$id] = $item; $item['id'] = $id; $this->db->updateassoc($item); } return true; } public function exists(string $filename): bool { return $this->indexOf('filename', $filename); } public function postEdited(Event $event) { $post = Post::i($event->id); $this->itemsPosts->setItems($post->id, $post->files); } } //FilesItems.php namespace litepubl\post; class FilesItems extends \litepubl\core\ItemsPosts { protected function create() { $this->dbversion = true; parent::create(); $this->basename = 'fileitems'; $this->table = 'filesitemsposts'; } } //FileView.php namespace litepubl\post; use litepubl\core\Str; use litepubl\view\Args; use litepubl\view\Theme; use litepubl\view\Vars; /** * View file list * * @property-write callable $onGetFilelist * @property-write callable $onlist * @method array onGetFilelist(array $params) * @method array onlist(array $params) */ class FileView extends \litepubl\core\Events { protected $templates; protected function create() { parent::create(); $this->basename = 'fileview'; $this->addEvents('ongetfilelist', 'onlist'); $this->templates = []; } public function getFiles(): Files { return Files::i(); } public function getFileList(array $list, bool $excerpt, Theme $theme): string { $r = $this->onGetFilelist(['list' => $list, 'excerpt' => $excerpt, 'result' => false]); if ($r['result']) { return $r['result']; } if (!count($list)) { return ''; } $tml = $excerpt ? $this->getTml($theme, 'content.excerpts.excerpt.filelist') : $this->getTml($theme, 'content.post.filelist'); return $this->getList($list, $tml); } public function getTml(Theme $theme, string $basekey): array { if (isset($this->templates[$theme->name][$basekey])) { return $this->templates[$theme->name][$basekey]; } $result = [ 'container' => $theme->templates[$basekey], ]; $key = $basekey . '.'; foreach ($theme->templates as $k => $v) { if (Str::begin($k, $key)) { $result[substr($k, strlen($key)) ] = $v; } } if (!isset($this->templates[$theme->name])) { $this->templates[$theme->name] = []; } $this->templates[$theme->name][$basekey] = $result; return $result; } public function getList(array $list, array $tml): string { if (!count($list)) { return ''; } $this->onList(['list' => $list]); $result = ''; $files = $this->getFiles(); $files->preLoad($list); //sort by media type $items = []; foreach ($list as $id) { if (!isset($files->items[$id])) { continue; } $item = $files->items[$id]; $type = $item['media']; if (isset($tml[$type])) { $items[$type][] = $id; } else { $items['file'][] = $id; } } $theme = Theme::i(); $args = new Args(); $args->count = count($list); $url = $this->getApp()->site->files . '/files/'; $preview = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); $vars = new Vars(); $vars->preview = $preview; $midle = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); $vars->midle = $midle; $index = 0; foreach ($items as $type => $subitems) { $args->subcount = count($subitems); $sublist = ''; foreach ($subitems as $typeindex => $id) { $item = $files->items[$id]; $args->add($item); $args->link = $url . $item['filename']; $args->id = $id; $args->typeindex = $typeindex; $args->index = $index++; $args->preview = ''; $preview->exchangeArray([]); if ($idmidle = (int)$item['midle']) { $midle->exchangeArray($files->getItem($idmidle)); $midle->link = $url . $midle->filename; $midle->json = $this->getJson($idmidle); } else { $midle->exchangeArray([]); $midle->link = ''; $midle->json = ''; } if ((int)$item['preview']) { $preview->exchangeArray($files->getItem($item['preview'])); } elseif ($type == 'image') { $preview->exchangeArray($item); $preview->id = $id; } elseif ($type == 'video') { $args->preview = $theme->parseArg($tml['videos.fallback'], $args); $preview->exchangeArray([]); } if ($preview->count()) { $preview->link = $url . $preview->filename; $args->preview = $theme->parseArg($tml['preview'], $args); } $args->json = $this->getJson($id); $sublist.= $theme->parseArg($tml[$type], $args); } $args->__set($type, $sublist); $result.= $theme->parseArg($tml[$type . 's'], $args); } $args->files = $result; return $theme->parseArg($tml['container'], $args); } public function getFirstImage(array $items): string { $files = $this->getFiles(); foreach ($items as $id) { $item = $files->getItem($id); if (('image' == $item['media']) && ($idpreview = (int)$item['preview'])) { $baseurl = $this->getApp()->site->files . '/files/'; $args = new Args(); $args->add($item); $args->link = $baseurl . $item['filename']; $args->json = $this->getJson($id); $preview = new \ArrayObject($files->getItem($idpreview), \ArrayObject::ARRAY_AS_PROPS); $preview->link = $baseurl . $preview->filename; $midle = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); if ($idmidle = (int)$item['midle']) { $midle->exchangeArray($files->getItem($idmidle)); $midle->link = $baseurl . $midle->filename; $midle->json = $this->getJson($idmidle); } else { $midle->json = ''; } $vars = new Vars(); $vars->preview = $preview; $vars->midle = $midle; $theme = Theme::i(); return $theme->parseArg($theme->templates['content.excerpts.excerpt.firstimage'], $args); } } return ''; } public function getJson(int $id): string { $item = $this->getFiles()->getItem($id); return Str::jsonAttr( [ 'id' => $id, 'link' => $this->getApp()->site->files . '/files/' . $item['filename'], 'width' => $item['width'], 'height' => $item['height'], 'size' => $item['size'], 'midle' => $item['midle'], 'preview' => $item['preview'], ] ); } } //Meta.php namespace litepubl\post; use litepubl\core\Str; class Meta extends \litepubl\core\Item { public static function getInstancename() { return 'postmeta'; } protected function create() { $this->table = 'postsmeta'; } public function getDbversion() { return true; } public function __set($name, $value) { if ($name == 'id') { return $this->setId($value); } $exists = isset($this->data[$name]); if ($exists && ($this->data[$name] == $value)) { return true; } $this->data[$name] = $value; $name = Str::quote($name); $value = Str::quote($value); if ($exists) { $this->db->update("value = $value", "id = $this->id and name = $name"); } else { $this->db->insertrow("(id, name, value) values ($this->id, $name, $value)"); } } public function __unset($name) { $this->remove($name); } public function load() { $this->LoadFromDB(); return true; } protected function LoadFromDB() { $db = $this->db; $res = $db->select("id = $this->id"); if (is_object($res)) { while ($r = $res->fetch_assoc()) { $this->data[$r['name']] = $r['value']; } } return true; } protected function SaveToDB() { $db = $this->db; $db->delete("id = $this->id"); foreach ($this->data as $name => $value) { if ($name == 'id') { continue; } $name = Str::quote($name); $value = Str::quote($value); $this->db->insertrow("(id, name, value) values ($this->id, $name, $value)"); } } public function remove($name) { if ($name == 'id') { return; } unset($this->data[$name]); $this->db->delete("id = $this->id and name = '$name'"); } public static function loaditems(array $items) { if (!count($items)) { return; } //exclude already loaded items if (isset(static ::$instances['postmeta'])) { $items = array_diff($items, array_keys(static ::$instances['postmeta'])); if (!count($items)) { return; } } else { static ::$instances['postmeta'] = []; } $instances = & static ::$instances['postmeta']; $db = static::getAppInstance()->db; $db->table = 'postsmeta'; $res = $db->select(sprintf('id in (%s)', implode(',', $items))); while ($row = $db->fetchassoc($res)) { $id = (int)$row['id']; if (!isset($instances[$id])) { $instances[$id] = new static(); $instances[$id]->data['id'] = $id; } $instances[$id]->data[$row['name']] = $row['value']; } return $items; } } //Post.php namespace litepubl\post; use litepubl\core\Arr; use litepubl\core\Str; use litepubl\view\Filter; /** * This is the post base class * * @property int $idschema * @property int $idurl * @property int $parent * @property int $author * @property int $revision * @property int $idperm * @property string $class * @property int $posted timestamp * @property string $title * @property string $title2 * @property string $filtered * @property string $excerpt * @property string $keywords * @property string $description * @property string $rawhead * @property string $moretitle * @property array $categories * @property array $tags * @property array $files * @property string $status enum * @property string $comstatus enum * @property int $pingenabled bool * @property string $password * @property int $commentscount * @property int $pingbackscount * @property int $pagescount * @property string $url * @property int $created timestamp * @property int $modified timestamp * @property array $pages * @property string $rawcontent * @property-read string $instanceName * @property-read string $childTable * @property-read Factory $factory * @property-read View $view * @property-read Meta $meta * @property string $link absolute url * @property-read string isoDate * @property string pubDate * @property-read string sqlDate * @property string $tagNames tags title separated by , * @property string $catNames categories title separated by , * @property-read string $category first category title * @property-read int $idCat first category ID * @property-read bool $hasPages true if has content or comments pages * @property-read int $pagesCount index from 1 * @property-read int $countPages maximum of content or comments pages * @property-read int commentPages * @property-read string lastCommentUrl * @property-read string schemaLink to generate new url */ class Post extends \litepubl\core\Item { use \litepubl\core\Callbacks; protected $childTable; protected $rawTable; protected $pagesTable; protected $childData; protected $cacheData; protected $rawData; protected $factory; private $metaInstance; public static function i($id = 0) { if ($id = (int) $id) { if (isset(static::$instances['post'][$id])) { $result = static::$instances['post'][$id]; } elseif ($result = static::loadPost($id)) { // nothing: set $instances in afterLoad method } else { $result = null; } } else { $result = parent::itemInstance(get_called_class(), $id); } return $result; } public static function loadPost(int $id) { if ($a = static::loadAssoc($id)) { $self = static::newPost($a['class']); $self->setAssoc($a); if ($table = $self->getChildTable()) { $items = static::selectChildItems( $table, [ $id ] ); $self->childData = $items[$id]; unset($self->childData['id']); } $self->afterLoad(); return $self; } return false; } public static function loadAssoc(int $id) { $db = static::getAppInstance()->db; $table = static::getChildTable(); if ($table) { return $db->selectAssoc( "select $db->posts.*, $db->prefix$table.*, $db->urlmap.url as url from $db->posts, $db->prefix$table, $db->urlmap where $db->posts.id = $id and $db->prefix$table.id = $id and $db->urlmap.id = $db->posts.idurl limit 1" ); } else { return $db->selectAssoc( "select $db->posts.*, $db->urlmap.url as url from $db->posts, $db->urlmap where $db->posts.id = $id and $db->urlmap.id = $db->posts.idurl limit 1" ); } } public static function newPost(string $classname): Post { $classname = $classname ? str_replace('-', '\\', $classname) : get_called_class(); return new $classname(); } public static function getInstanceName(): string { return 'post'; } public static function getChildTable(): string { return ''; } public static function selectChildItems(string $table, array $items): array { if (! $table || ! count($items)) { return []; } $db = static::getAppInstance()->db; $childTable = $db->prefix . $table; $list = implode(',', $items); $count = count($items); return $db->res2items($db->query("select $childTable.* from $childTable where id in ($list) limit $count")); } protected function create() { $this->table = 'posts'; $this->rawTable = 'rawposts'; $this->pagesTable = 'pages'; $this->childTable = static::getChildTable(); $options = $this->getApp()->options; $this->data = [ 'id' => 0, 'idschema' => 1, 'idurl' => 0, 'parent' => 0, 'author' => 0, 'revision' => 0, 'idperm' => 0, 'class' => str_replace('\\', '-', get_class($this)), 'posted' => static::ZERODATE, 'title' => '', 'title2' => '', 'filtered' => '', 'excerpt' => '', 'keywords' => '', 'description' => '', 'rawhead' => '', 'moretitle' => '', 'categories' => '', 'tags' => '', 'files' => '', 'status' => 'published', 'comstatus' => $options->comstatus, 'pingenabled' => $options->pingenabled ? '1' : '0', 'password' => '', 'commentscount' => 0, 'pingbackscount' => 0, 'pagescount' => 0 ]; $this->rawData = []; $this->childData = []; $this->cacheData = [ 'posted' => 0, 'categories' => [], 'tags' => [], 'files' => [], 'url' => '', 'created' => 0, 'modified' => 0, 'pages' => [] ]; $this->factory = $this->getfactory(); } public function getFactory() { return Factory::i(); } public function getView(): View { $view = $this->factory->getView(); $view->setPost($this); return $view; } public function __get($name) { if ($name == 'id') { $result = (int) $this->data['id']; } elseif (method_exists($this, $get = 'get' . $name)) { $result = $this->$get(); } elseif (array_key_exists($name, $this->cacheData)) { $result = $this->cacheData[$name]; } elseif (method_exists($this, $get = 'getCache' . $name)) { $result = $this->$get(); $this->cacheData[$name] = $result; } elseif (array_key_exists($name, $this->data)) { $result = $this->data[$name]; } elseif (array_key_exists($name, $this->childData)) { $result = $this->childData[$name]; } elseif (array_key_exists($name, $this->rawData)) { $result = $this->rawData[$name]; } else { $result = parent::__get($name); } return $result; } public function __set($name, $value) { if ($name == 'id') { $this->setId($value); } elseif (method_exists($this, $set = 'set' . $name)) { $this->$set($value); } elseif (array_key_exists($name, $this->cacheData)) { $this->cacheData[$name] = $value; } elseif (array_key_exists($name, $this->data)) { $this->data[$name] = $value; } elseif (array_key_exists($name, $this->childData)) { $this->childData[$name] = $value; } elseif (array_key_exists($name, $this->rawData)) { $this->rawData[$name] = $value; } else { return parent::__set($name, $value); } return true; } public function __isset($name) { return parent::__isset($name) || array_key_exists($name, $this->cacheData) || array_key_exists($name, $this->childData) || array_key_exists($name, $this->rawData) || method_exists($this, 'getCache' . $name); } public function load() { return true; } public function afterLoad() { static::$instances['post'][$this->id] = $this; parent::afterLoad(); } public function setAssoc(array $a) { $this->cacheData = []; foreach ($a as $k => $v) { if (array_key_exists($k, $this->data)) { $this->data[$k] = $v; } elseif (array_key_exists($k, $this->childData)) { $this->childData[$k] = $v; } elseif (array_key_exists($k, $this->rawData)) { $this->rawData[$k] = $v; } else { $this->cacheData[$k] = $v; } } } public function save() { if ($this->lockcount > 0) { return; } $this->saveToDB(); } protected function saveToDB() { if (! $this->id) { return $this->add(); } $this->db->updateAssoc($this->data); $this->modified = time(); $this->getDB($this->rawTable)->setValues($this->id, $this->rawData); if ($this->childTable) { $this->getDB($this->childTable)->setValues($this->id, $this->childData); } } public function add(): int { $a = $this->data; unset($a['id']); $id = $this->db->add($a); $rawData = $this->prepareRawData(); $rawData['id'] = $id; $this->getDB($this->rawTable)->insert($rawData); $this->setId($id); $this->savePages(); if ($this->childTable) { $childData = $this->childData; $childData['id'] = $id; $this->getDB($this->childTable)->insert($childData); } $this->idurl = $this->createUrl(); $this->db->setValue($id, 'idurl', $this->idurl); $this->triggerOnId(); return $id; } protected function prepareRawData() { if (! $this->created) { $this->created = time(); } if (! $this->modified) { $this->modified = time(); } if (! isset($this->rawData['rawcontent'])) { $this->rawData['rawcontent'] = ''; } return $this->rawData; } public function createUrl() { return $this->getApp()->router->add($this->url, get_class($this), (int) $this->id); } public function onId(callable $callback) { $this->addCallback('onid', $callback); } protected function triggerOnId() { $this->triggerCallback('onid'); $this->clearCallbacks('onid'); if (isset($this->metaInstance)) { $this->metaInstance->id = $this->id; $this->metaInstance->save(); } } public function free() { if (isset($this->metaInstance)) { $this->metaInstance->free(); } parent::free(); } public function getComments() { return $this->factory->getcomments($this->id); } public function getPingbacks() { return $this->factory->getpingbacks($this->id); } public function getMeta() { if (! isset($this->metaInstance)) { $this->metaInstance = $this->factory->getmeta($this->id); } return $this->metaInstance; } // props protected function setDataProp($name, $value, $sql) { $this->cacheData[$name] = $value; if (array_key_exists($name, $this->data)) { $this->data[$name] = $sql; } elseif (array_key_exists($name, $this->childData)) { $this->childData[$name] = $sql; } elseif (array_key_exists($name, $this->rawData)) { $this->rawData[$name] = $sql; } } protected function setArrProp($name, array $list) { Arr::clean($list); $this->setDataProp($name, $list, implode(',', $list)); } protected function setBoolProp($name, $value) { $this->setDataProp($name, $value, $value ? '1' : '0'); } // cache props protected function getArrProp($name) { if ($s = $this->data[$name]) { return explode(',', $s); } else { return []; } } protected function getCacheCategories() { return $this->getArrProp('categories'); } protected function getCacheTags() { return $this->getArrProp('tags'); } protected function getCacheFiles() { return $this->getArrProp('files'); } public function setFiles(array $list) { $this->setArrProp('files', $list); } public function setCategories(array $list) { $this->setArrProp('categories', $list); } public function setTags(array $list) { $this->setArrProp('tags', $list); } protected function getCachePosted() { return $this->data['posted'] == static::ZERODATE ? 0 : strtotime($this->data['posted']); } public function setPosted($timestamp) { $this->data['posted'] = Str::sqlDate($timestamp); $this->cacheData['posted'] = $timestamp; } protected function getCacheModified() { return ! isset($this->rawData['modified']) || $this->rawData['modified'] == static::ZERODATE ? 0 : strtotime($this->rawData['modified']); } public function setModified($timestamp) { $this->rawData['modified'] = Str::sqlDate($timestamp); $this->cacheData['modified'] = $timestamp; } protected function getCacheCreated() { return ! isset($this->rawData['created']) || $this->rawData['created'] == static::ZERODATE ? 0 : strtotime($this->rawData['created']); } public function setCreated($timestamp) { $this->rawData['created'] = Str::sqlDate($timestamp); $this->cacheData['created'] = $timestamp; } public function Getlink() { return $this->getApp()->site->url . $this->url; } public function Setlink($link) { if ($a = @parse_url($link)) { if (empty($a['query'])) { $this->url = $a['path']; } else { $this->url = $a['path'] . '?' . $a['query']; } } } public function setTitle($title) { $this->data['title'] = Filter::escape(Filter::unescape($title)); } public function getIsoDate() { return date('c', $this->posted); } public function getPubDate() { return date('r', $this->posted); } public function setPubDate($date) { $this->setDateProp('posted', strtotime($date)); } public function getSqlDate() { return $this->data['posted']; } public function getTagnames() { if (count($this->tags)) { $tags = $this->factory->tags; return implode(', ', $tags->getnames($this->tags)); } return ''; } public function setTagNames(string $names) { $tags = $this->factory->tags; $this->tags = $tags->createnames($names); } public function getCatnames() { if (count($this->categories)) { $categories = $this->factory->categories; return implode(', ', $categories->getnames($this->categories)); } return ''; } public function setCatNames($names) { $categories = $this->factory->categories; $catItems = $categories->createnames($names); if (! count($catItems)) { $defaultid = $categories->defaultid; if ($defaultid > 0) { $catItems[] = $defaultid; } } $this->categories = $catItems; } public function getCategory(): string { if ($idcat = $this->getidcat()) { return $this->factory->categories->getName($idcat); } return ''; } public function getIdCat(): int { if (($cats = $this->categories) && count($cats)) { return $cats[0]; } return 0; } public function checkRevision() { $this->updateRevision((int) $this->factory->posts->revision); } public function updateRevision($value) { if ($value != $this->revision) { $this->updateFiltered(); $posts = $this->factory->posts; $this->revision = (int) $posts->revision; if ($this->id > 0) { $this->save(); } } } public function updateFiltered() { Filter::i()->filterPost($this, $this->rawcontent); } public function setRawContent($s) { $this->rawData['rawcontent'] = $s; } public function getRawContent() { if (isset($this->rawData['rawcontent'])) { return $this->rawData['rawcontent']; } if (! $this->id) { return ''; } $this->rawData = $this->getDB($this->rawTable)->getItem($this->id); unset($this->rawData['id']); return $this->rawData['rawcontent']; } public function getPage(int $i) { if (isset($this->cacheData['pages'][$i])) { return $this->cacheData['pages'][$i]; } if ($this->id > 0) { if ($r = $this->getdb($this->pagesTable)->getAssoc("(id = $this->id) and (page = $i) limit 1")) { $s = $r['content']; } else { $s = false; } $this->cacheData['pages'][$i] = $s; return $s; } return false; } public function addPage($s) { $this->cacheData['pages'][] = $s; $this->data['pagescount'] = count($this->cacheData['pages']); if ($this->id > 0) { $this->getdb($this->pagesTable)->insert( [ 'id' => $this->id, 'page' => $this->data['pagescount'] - 1, 'content' => $s ] ); } } public function deletePages() { $this->cacheData['pages'] = []; $this->data['pagescount'] = 0; if ($this->id > 0) { $this->getdb($this->pagesTable)->idDelete($this->id); } } public function savePages() { if (isset($this->cacheData['pages'])) { $db = $this->getDB($this->pagesTable); foreach ($this->cacheData['pages'] as $index => $content) { $db->insert( [ 'id' => $this->id, 'page' => $index, 'content' => $content ] ); } } } public function getHasPages(): bool { return ($this->pagescount > 1) || ($this->commentpages > 1); } public function getPagesCount() { return $this->data['pagescount'] + 1; } public function getCountPages() { return max($this->pagescount, $this->commentpages); } public function getCommentPages() { $options = $this->getApp()->options; if (! $options->commentpages || ($this->commentscount <= $options->commentsperpage)) { return 1; } return ceil($this->commentscount / $options->commentsperpage); } public function getLastCommentUrl() { $c = $this->commentpages; $url = $this->url; if (($c > 1) && ! $this->getApp()->options-><API key>) { $url = rtrim($url, '/') . "/page/$c/"; } return $url; } public function clearCache() { $this->getApp()->cache->clearUrl($this->url); } public function getSchemalink(): string { return 'post'; } public function setContent($s) { if (! is_string($s)) { $this->error('Error! Post content must be string'); } $this->rawcontent = $s; Filter::i()->filterpost($this, $s); } } //Posts.php namespace litepubl\post; use litepubl\core\Cron; use litepubl\core\Str; use litepubl\utils\LinkGenerator; use litepubl\view\Schemes; /** * Main class to manage posts * * @property int $archivescount * @property int $revision * @property bool $syncmeta * @property-write callable $edited * @property-write callable $changed * @property-write callable $singleCron * @property-write callable $onSelect * @method array edited(array $params) * @method array changed(array $params) * @method array singleCron(array $params) * @method array onselect(array $params) */ class Posts extends \litepubl\core\Items { const POSTCLASS = __NAMESPACE__ . '/Post'; public $itemcoclasses; public $archives; public $rawtable; public $childTable; public static function unsub($obj) { static ::i()->unbind($obj); } protected function create() { $this->dbversion = true; parent::create(); $this->table = 'posts'; $this->childTable = ''; $this->rawtable = 'rawposts'; $this->basename = 'posts/index'; $this->addEvents('edited', 'changed', 'singlecron', 'onselect'); $this->data['archivescount'] = 0; $this->data['revision'] = 0; $this->data['syncmeta'] = false; $this->addmap('itemcoclasses', []); } public function getItem($id) { if ($result = Post::i($id)) { return $result; } $this->error("Item $id not found in class " . get_class($this)); } public function findItems(string $where, string $limit): array { if (isset(Post::$instances['post']) && (count(Post::$instances['post']))) { $result = $this->db->idSelect($where . ' ' . $limit); $this->loadItems($result); return $result; } else { return $this->select($where, $limit); } } public function loadItems(array $items) { //exclude already loaded items if (!isset(Post::$instances['post'])) { Post::$instances['post'] = []; } $loaded = array_keys(Post::$instances['post']); $newitems = array_diff($items, $loaded); if (!count($newitems)) { return $items; } $newitems = $this->select(sprintf('%s.id in (%s)', $this->thistable, implode(',', $newitems)), 'limit ' . count($newitems)); return array_merge($newitems, array_intersect($loaded, $items)); } public function setAssoc(array $items) { if (!count($items)) { return []; } $result = []; $fileitems = []; foreach ($items as $a) { $post = Post::newPost($a['class']); $post->setAssoc($a); $post->afterLoad(); $result[] = $post->id; $f = $post->files; if (count($f)) { $fileitems = array_merge($fileitems, array_diff($f, $fileitems)); } } if ($this->syncmeta) { Meta::loadItems($result); } if (count($fileitems)) { Files::i()->preLoad($fileitems); } $this->onSelect(['items' => $result]); return $result; } public function select(string $where, string $limit): array { $db = $this->getApp()->db; if ($this->childTable) { $childTable = $db->prefix . $this->childTable; return $this->setAssoc( $db->res2items( $db->query( "select $db->posts.*, $childTable.*, $db->urlmap.url as url from $db->posts, $childTable, $db->urlmap where $where and $db->posts.id = $childTable.id and $db->urlmap.id = $db->posts.idurl $limit" ) ) ); } $items = $db->res2items( $db->query( "select $db->posts.*, $db->urlmap.url as url from $db->posts, $db->urlmap where $where and $db->urlmap.id = $db->posts.idurl $limit" ) ); if (!count($items)) { return []; } $subclasses = []; foreach ($items as $id => $item) { if (empty($item['class'])) { $items[$id]['class'] = static ::POSTCLASS; } elseif ($item['class'] != static ::POSTCLASS) { $subclasses[$item['class']][] = $id; } } foreach ($subclasses as $class => $list) { $class = str_replace('-', '\\', $class); $childDataItems = $class::selectChildItems($class::getChildTable(), $list); foreach ($childDataItems as $id => $childData) { $items[$id] = array_merge($items[$id], $childData); } } return $this->setAssoc($items); } public function getCount() { return $this->db->getcount("status<> 'deleted'"); } public function getChildsCount($where) { if (!$this->childTable) { return 0; } $db = $this->getApp()->db; $childTable = $db->prefix . $this->childTable; $res = $db->query( "SELECT COUNT($db->posts.id) as count FROM $db->posts, $childTable where $db->posts.status <> 'deleted' and $childTable.id = $db->posts.id $where" ); if ($res && ($r = $db->fetchassoc($res))) { return $r['count']; } return 0; } private function beforeChange($post) { $post->title = trim($post->title); $post->modified = time(); $post->revision = $this->revision; $post->class = str_replace('\\', '-', ltrim(get_class($post), '\\')); if (($post->status == 'published') && ($post->posted > time())) { $post->status = 'future'; } elseif (($post->status == 'future') && ($post->posted <= time())) { $post->status = 'published'; } } public function add(Post $post): int { $this->beforeChange($post); if (!$post->posted) { $post->posted = time(); } if ($post->posted <= time()) { if ($post->status == 'future') { $post->status = 'published'; } } else { if ($post->status == 'published') { $post->status = 'future'; } } if ($post->idschema == 1) { $schemes = Schemes::i(); if (isset($schemes->defaults['post'])) { $post->data['idschema'] = $schemes->defaults['post']; } } $post->url = LinkGenerator::i()->addUrl($post, $post->schemaLink); $id = $post->add(); $this->updated($post); $this->added(['id' => $id]); $this->changed([]); $this->getApp()->cache->clear(); return $id; } public function edit(Post $post) { $this->beforeChange($post); $linkgen = LinkGenerator::i(); $linkgen->editurl($post, $post->schemaLink); if ($post->posted <= time()) { if ($post->status == 'future') { $post->status = 'published'; } } else { if ($post->status == 'published') { $post->status = 'future'; } } $this->lock(); $post->save(); $this->updated($post); $this->unlock(); $this->edited(['id' => $post->id]); $this->changed([]); $this->getApp()->cache->clear(); } public function delete($id) { if (!$this->itemExists($id)) { return false; } $this->db->setvalue($id, 'status', 'deleted'); if ($this->childTable) { $db = $this->getdb($this->childTable); $db->delete("id = $id"); } $this->lock(); $this->PublishFuture(); $this->UpdateArchives(); $this->unlock(); $this->deleted(['id' => $id]); $this->changed([]); $this->getApp()->cache->clear(); return true; } public function updated(Post $post) { $this->PublishFuture(); $this->UpdateArchives(); Cron::i()->add('single', get_class($this), 'dosinglecron', $post->id); } public function UpdateArchives() { $this->archivescount = $this->db->getcount("status = 'published' and posted <= '" . Str::sqlDate() . "'"); } public function doSingleCron($id) { $this->PublishFuture(); Theme::$vars['post'] = Post::i($id); $this->singleCron(['id' => $id]); unset(Theme::$vars['post']); } public function hourcron() { $this->PublishFuture(); } private function publish($id) { $post = Post::i($id); $post->status = 'published'; $this->edit($post); } public function PublishFuture() { if ($list = $this->db->idselect(sprintf('status = \'future\' and posted <= \'%s\' order by posted asc', Str::sqlDate()))) { foreach ($list as $id) { $this->publish($id); } } } public function getRecent($author, $count) { $author = (int)$author; $where = "status != 'deleted'"; if ($author > 1) { $where.= " and author = $author"; } return $this->findItems($where, ' order by posted desc limit ' . (int)$count); } public function getPage(int $author, int $page, int $perpage, bool $invertorder): array { $from = ($page - 1) * $perpage; $t = $this->thistable; $where = "$t.status = 'published'"; if ($author > 1) { $where.= " and $t.author = $author"; } $order = $invertorder ? 'asc' : 'desc'; return $this->findItems($where, " order by $t.posted $order limit $from, $perpage"); } public function stripDrafts(array $items): array { if (count($items) == 0) { return []; } $list = implode(',', $items); $t = $this->thistable; return $this->db->idSelect("$t.status = 'published' and $t.id in ($list)"); } public function addRevision(): int { $this->data['revision']++; $this->save(); $this->getApp()->cache->clear(); return $this->data['revision']; } public function getSitemap($from, $count) { return $this->externalfunc( __class__, 'Getsitemap', [ $from, $count ] ); } } //View.php namespace litepubl\post; use litepubl\comments\Templates; use litepubl\core\Context; use litepubl\core\Str; use litepubl\view\Args; use litepubl\view\Lang; use litepubl\view\MainView; use litepubl\view\Schema; use litepubl\view\Theme; /** * Post view * * @property-write callable $beforeContent * @property-write callable $afterContent * @property-write callable $beforeExcerpt * @property-write callable $afterExcerpt * @property-write callable $onHead * @property-write callable $onTags * @method array beforeContent(array $params) * @method array afterContent(array $params) * @method array beforeExcerpt(array $params) * @method array afterExcerpt(array $params) * @method array onHead(array $params) * @method array onTags(array $params) */ class View extends \litepubl\core\Events implements \litepubl\view\ViewInterface { use \litepubl\core\PoolStorageTrait; public $post; public $context; private $prevPost; private $nextPost; private $themeInstance; protected function create() { parent::create(); $this->basename = 'postview'; $this->addEvents('beforecontent', 'aftercontent', 'beforeexcerpt', 'afterexcerpt', 'onhead', 'ontags'); $this->table = 'posts'; } public function setPost(Post $post) { $this->post = $post; $this->themeInstance = null; } public function getView() { return $this; } public function __get($name) { if (method_exists($this, $get = 'get' . $name)) { $result = $this->$get(); } else { switch ($name) { case 'catlinks': $result = $this->get_taglinks('categories', false); break; case 'taglinks': $result = $this->get_taglinks('tags', false); break; case 'excerptcatlinks': $result = $this->get_taglinks('categories', true); break; case 'excerpttaglinks': $result = $this->get_taglinks('tags', true); break; default: if (isset($this->post->$name)) { $result = $this->post->$name; } else { $result = parent::__get($name); } } } return $result; } public function __set($name, $value) { if (parent::__set($name, $value)) { return true; } if (isset($this->post->$name)) { $this->post->$name = $value; return true; } return false; } public function __call($name, $args) { if (method_exists($this->post, $name)) { return <API key>([$this->post, $name], $args); } else { return parent::__call($name, $args); } } public function getPrev() { if (!is_null($this->prevPost)) { return $this->prevPost; } $this->prevPost = false; if ($id = $this->db->findid("status = 'published' and posted < '$this->sqldate' order by posted desc")) { $this->prevPost = Post::i($id); } return $this->prevPost; } public function getNext() { if (!is_null($this->nextPost)) { return $this->nextPost; } $this->nextPost = false; if ($id = $this->db->findid("status = 'published' and posted > '$this->sqldate' order by posted asc")) { $this->nextPost = Post::i($id); } return $this->nextPost; } public function getTheme(): Theme { if (!$this->themeInstance) { $this->themeInstance = $this->post ? $this->schema->theme : Theme::context(); } $this->themeInstance->setvar('post', $this); return $this->themeInstance; } public function setTheme(Theme $theme) { $this->themeInstance = $theme; } public function parseTml(string $path): string { $theme = $this->theme; return $theme->parse($theme->templates[$path]); } public function getExtra() { $theme = $this->theme; return $theme->parse($theme->extratml); } public function getBookmark() { return $this->theme->parse($this->theme->templates['content.post.bookmark']); } public function getRssComments(): string { return $this->getApp()->site->url . "/comments/$this->id.xml"; } public function getIdImage(): int { if (!count($this->files)) { return 0; } $files = $this->factory->files; foreach ($this->files as $id) { $item = $files->getItem($id); if ('image' == $item['media']) { return $id; } } return 0; } public function getImage(): string { if ($id = $this->getIdImage()) { return $this->factory->files->getUrl($id); } return ''; } public function getThumb(): string { if (!count($this->files)) { return ''; } $files = $this->factory->files; foreach ($this->files as $id) { $item = $files->getItem($id); if ((int)$item['preview']) { return $files->getUrl($item['preview']); } } return ''; } public function getFirstImage(): string { $items = $this->files; if (count($items)) { return $this->factory->fileView->getFirstImage($items); } return ''; } //template protected function get_taglinks($name, $excerpt) { $items = $this->__get($name); if (!count($items)) { return ''; } $theme = $this->theme; $tmlpath = $excerpt ? 'content.excerpts.excerpt' : 'content.post'; $tmlpath.= $name == 'tags' ? '.taglinks' : '.catlinks'; $tmlitem = $theme->templates[$tmlpath . '.item']; $tags = Str::begin($name, 'tag') ? $this->factory->tags : $this->factory->categories; $tags->loaditems($items); $args = new Args(); $list = []; foreach ($items as $id) { if ($id && ($item = $tags->getItem($id))) { $args->add($item); $list[] = $theme->parseArg($tmlitem, $args); } } $args->items = ' ' . implode($theme->templates[$tmlpath . '.divider'], $list); $result = $theme->parseArg($theme->templates[$tmlpath], $args); $r = $this->onTags(['tags' => $tags, 'excerpt' => $excerpt, 'content' => $result]); return $r['content']; } public function getDate(): string { return Lang::date($this->posted, $this->theme->templates['content.post.date']); } public function getExcerptDate(): string { return Lang::date($this->posted, $this->theme->templates['content.excerpts.excerpt.date']); } public function getDay(): string { return date($this->posted, 'D'); } public function getMonth(): string { return Lang::date($this->posted, 'M'); } public function getYear(): string { return date($this->posted, 'Y'); } public function getMoreLink(): string { if ($this->moretitle) { return $this->parsetml('content.excerpts.excerpt.morelink'); } return ''; } public function request(Context $context) { $app = $this->getApp(); if ($this->status != 'published') { if (!$app->options->show_draft_post) { $context->response->status = 404; return; } $groupname = $app->options->group; if (($groupname == 'admin') || ($groupname == 'editor')) { return; } if ($this->author == $app->options->user) { return; } $context->response->status = 404; return; } $this->context = $context; } public function getPage(): int { return $this->context->request->page; } public function getTitle(): string { return $this->post->title; } public function getHead(): string { $result = $this->rawhead; MainView::i()->ltoptions['idpost'] = $this->id; $theme = $this->theme; $result.= $theme->templates['head.post']; if ($prev = $this->prev) { Theme::$vars['prev'] = $prev; $result.= $theme->templates['head.post.prev']; } if ($next = $this->next) { Theme::$vars['next'] = $next; $result.= $theme->templates['head.post.next']; } if ($this->hascomm) { Lang::i('comment'); $result.= $theme->templates['head.post.rss']; } $result = $theme->parse($result); $r = $this->onHead(['post' => $this->post, 'content' => $result]); return $r['content']; } public function getKeywords(): string { if ($result = $this->post->keywords) { return $result; } else { return $this->Gettagnames(); } } public function getDescription(): string { return $this->post->description; } public function getIdSchema(): int { return $this->post->idschema; } public function setIdSchema(int $id) { if ($id != $this->idschema) { $this->post->idschema = $id; if ($this->id) { $this->post->db->setvalue($this->id, 'idschema', $id); } } } public function getSchema(): Schema { return Schema::getSchema($this); } //to override schema in post, id schema not changed public function getFileList(): string { $items = $this->files; if (!count($items) || (($this->page > 1) && $this->getApp()->options->hidefilesonpage)) { return ''; } $fileView = $this->factory->fileView; return $fileView->getFileList($items, false, $this->theme); } public function getExcerptFileList(): string { $items = $this->files; if (count($items) == 0) { return ''; } $fileView = $this->factory->fileView; return $fileView->getFileList($items, true, $this->theme); } public function getIndexTml() { $theme = $this->theme; if (!empty($theme->templates['index.post'])) { return $theme->templates['index.post']; } return false; } public function getCont(): string { return $this->parsetml('content.post'); } public function getRssLink(): string { if ($this->hascomm) { return $this->parseTml('content.post.rsslink'); } return ''; } public function onRssItem($item) { } public function getRss(): string { $this->getApp()->getLogManager()->trace('get rss deprecated post property'); return $this->post->excerpt; } public function getPrevNext(): string { $prev = ''; $next = ''; $theme = $this->theme; if ($prevpost = $this->prev) { Theme::$vars['prevpost'] = $prevpost; $prev = $theme->parse($theme->templates['content.post.prevnext.prev']); } if ($nextpost = $this->next) { Theme::$vars['nextpost'] = $nextpost; $next = $theme->parse($theme->templates['content.post.prevnext.next']); } if (($prev == '') && ($next == '')) { return ''; } $result = strtr( $theme->parse($theme->templates['content.post.prevnext']), [ '$prev' => $prev, '$next' => $next ] ); unset(Theme::$vars['prevpost'], Theme::$vars['nextpost']); return $result; } public function getCommentsLink(): string { $tml = sprintf('<a href="%s%s#comments">%%s</a>', $this->getApp()->site->url, $this->getlastcommenturl()); if (($this->comstatus == 'closed') || !$this->getApp()->options->commentspool) { if (($this->commentscount == 0) && (($this->comstatus == 'closed'))) { return ''; } return sprintf($tml, $this->getcmtcount()); } //inject php code return sprintf('<?php echo litepubl\comments\Pool::i()->getLink(%d, \'%s\'); ?>', $this->id, $tml); } public function getCmtCount(): string { $l = Lang::i()->ini['comment']; switch ($this->commentscount) { case 0: return $l[0]; case 1: return $l[1]; default: return sprintf($l[2], $this->commentscount); } } public function getTemplateComments(): string { $result = ''; $countpages = $this->countpages; if ($countpages > 1) { $result.= $this->theme->getpages($this->url, $this->page, $countpages); } if (($this->commentscount > 0) || ($this->comstatus != 'closed') || ($this->pingbackscount > 0)) { if (($countpages > 1) && ($this->commentpages < $this->page)) { $result.= $this->getCommentsLink(); } else { $result.= Templates::i()->getcomments($this); } } return $result; } public function getHasComm(): bool { return ($this->comstatus != 'closed') && ((int)$this->commentscount > 0); } public function getAnnounce(string $announceType): string { $tmlKey = 'content.excerpts.' . ($announceType == 'excerpt' ? 'excerpt' : $announceType . '.excerpt'); return $this->parseTml($tmlKey); } public function getExcerptContent(): string { $this->post->checkRevision(); $r = $this->beforeExcerpt(['post' => $this->post, 'content' => $this->excerpt]); $result = $this->replaceMore($r['content'], true); if ($this->getApp()->options->parsepost) { $result = $this->theme->parse($result); } $r = $this->afterExcerpt(['post' => $this->post, 'content' => $result]); return $r['content']; } public function replaceMore(string $content, string $excerpt): string { $more = $this->parseTml($excerpt ? 'content.excerpts.excerpt.morelink' : 'content.post.more'); $tag = '<!--more if (strpos($content, $tag)) { return str_replace($tag, $more, $content); } else { return $excerpt ? $content : $more . $content; } } protected function getTeaser(): string { $content = $this->filtered; $tag = '<!--more if ($i = strpos($content, $tag)) { $content = substr($content, $i + strlen($tag)); if (!Str::begin($content, '<p>')) { $content = '<p>' . $content; } return $content; } return ''; } protected function getContentPage(int $page): string { $result = ''; if ($page == 1) { $result.= $this->filtered; $result = $this->replaceMore($result, false); } elseif ($s = $this->post->getPage($page - 2)) { $result.= $s; } elseif ($page <= $this->commentpages) { } else { $result.= Lang::i()->notfound; } return $result; } public function getContent(): string { $this->post->checkRevision(); $r = $this->beforeContent(['post' => $this->post, 'content' => '']); $result = $r['content']; $result.= $this->getContentPage($this->page); if ($this->getApp()->options->parsepost) { $result = $this->theme->parse($result); } $r = $this->afterContent(['post' => $this->post, 'content' => $result]); return $r['content']; } //author protected function getAuthorName(): string { return $this->getusername($this->author, false); } protected function getAuthorLink() { return $this->getusername($this->author, true); } protected function getUserName($id, $link) { if ($id <= 1) { if ($link) { return sprintf('<a href="%s/" rel="author" title="%2$s">%2$s</a>', $this->getApp()->site->url, $this->getApp()->site->author); } else { return $this->getApp()->site->author; } } else { $users = $this->factory->users; if (!$users->itemExists($id)) { return ''; } $item = $users->getitem($id); if (!$link || ($item['website'] == '')) { return $item['name']; } return sprintf('<a href="%s/users.htm%sid=%s">%s</a>', $this->getApp()->site->url, $this->getApp()->site->q, $id, $item['name']); } } public function getAuthorPage() { $id = $this->author; if ($id <= 1) { return sprintf('<a href="%s/" rel="author" title="%2$s">%2$s</a>', $this->getApp()->site->url, $this->getApp()->site->author); } else { $pages = $this->factory->userpages; if (!$pages->itemExists($id)) { return ''; } $pages->id = $id; if ($pages->url == '') { return ''; } return sprintf('<a href="%s%s" title="%3$s" rel="author"><%3$s</a>', $this->getApp()->site->url, $pages->url, $pages->name); } } }
#ifndef GLMESH_H #define GLMESH_H #include <GLplus.hpp> namespace tinyobj { struct shape_t; } // end namespace tinyobj namespace GLmesh { class StaticMesh { std::shared_ptr<GLplus::Buffer> mpPositions; std::shared_ptr<GLplus::Buffer> mpTexcoords; std::shared_ptr<GLplus::Buffer> mpNormals; std::shared_ptr<GLplus::Buffer> mpIndices; size_t mVertexCount = 0; std::shared_ptr<GLplus::Texture2D> mpDiffuseTexture; public: void LoadShape(const tinyobj::shape_t& shape); void Render(GLplus::Program& program) const; }; } // end namespace GLmesh #endif // GLMESH_H
<API key> ================= Static site for your orgs gh-pages that shows off a feed of great things your team have been doing on github recently
# 888. Fair Candy Swap Difficulty: Easy https://leetcode.com/problems/fair-candy-swap/ Alice and Bob have candy bars of different sizes: A[i] is the size of the i-th bar of candy that Alice has, and B[j] is the size of the j-th bar of candy that Bob has. Since they are friends, they would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy. (The total amount of candy a person has is the sum of the sizes of candy bars they have.) Return an integer array ans where ans[0] is the size of the candy bar that Alice must exchange, and ans[1] is the size of the candy bar that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed an answer exists. **Example 1:** Input: A = [1,1], B = [2,2] Output: [1,2] **Example 2:** Input: A = [1,2], B = [2,3] Output: [1,2] **Example 3:** Input: A = [2], B = [1,3] Output: [2,3] **Example 4:** Input: A = [1,2,5], B = [2,4] Output: [5,4] **Note:** * 1 <= A.length <= 10000 * 1 <= B.length <= 10000 * 1 <= A[i] <= 100000 * 1 <= B[i] <= 100000 * It is guaranteed that Alice and Bob have different total amounts of candy. * It is guaranteed there exists an answer. Companies: Fidessa Related Topics: Array
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>smooth scroll polyfill</title> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css"> <link href='https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700' rel='stylesheet' type='text/css'> <!-- rAF polyfill --> <script> (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.<API key>; ++x) { window.<API key> = window[vendors[x]+'<API key>']; window.<API key> = window[vendors[x]+'<API key>'] || window[vendors[x]+'<API key>']; } if (!window.<API key>) window.<API key> = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.<API key>) window.<API key> = function(id) { clearTimeout(id); }; }()); </script> <!-- smooth scroll behavior polyfill --> <script src="src/smoothscroll.js"></script> <!-- site styles --> <style> body { background-color: #fefefe; color: #212121; font-family: 'Roboto Condensed', Arial, sans-serif; font-size: 20px; text-rendering: optimizeLegibility; -<API key>: antialiased; -<API key>: grayscale; } .container { margin: 0 auto; max-width: 800px; padding: 40px; overflow: hidden; position: relative; } a { color: #f44336; text-decoration: none; } a:hover { text-decoration: underline; } header { background-color: #f44336; color: #fefefe; } .featured { background-color: #efefef; } .featured__link { display: inline-block; margin-right: 45px; } h1 { font-size: 2.75em; font-weight: 400; letter-spacing: -.03em; line-height: 1em; } p { line-height: 1.5em; } small { font-weight: 400; } code { font-family: Menlo, monospace; font-size: 15px; vertical-align: middle; } pre { overflow: auto; width: 100%; } pre code { font-size: 14px; } .actions { margin-top: 30px; } .btn { background-color: #f44336; border-width: 0; border-radius: 4px; color: #fefefe; cursor: pointer; font-weight: 700; padding: 6px 12px; text-transform: uppercase; transition: all .35s ease; } .btn:active { background-color: #d32f2f; } .scrollable-parent { background-color: #efefef; border-radius: 4px; margin: 20px 0 0; max-height: 200px; overflow: scroll; padding: 30px 50px; } .hello { text-align: center; } footer { background-color: #404040; color: #fefefe; font-size: 18px; } footer a { color: inherit; } </style> </head> <body> <header> <div class="container"> <h1>smooth scroll polyfill</h1> </div> </header> <main class="featured"> <div class="container"> <p>The <strong>Scroll Behavior</strong> specification has been introduced as an extension of the <strong>Window</strong> interface to allow for the developer to opt in to native smooth scrolling.</p> <p>Check the repository on <a href="https: </div> </main> <section class="sample <API key>"> <div class="container"> <h2>window.scroll <small>or</small> window.scrollTo</h2> <pre><code>window.scroll({ top: 2500, left: 0, behavior: 'smooth' });</code></pre> <div class="actions"> <button class="btn js-scroll-to-bottom">scroll to bottom</button> </div> </div> </section> <section class="sample sample-scrollBy"> <div class="container"> <h2>window.scrollBy</h2> <pre><code>window.scrollBy({ top: 100, left: 0, behavior: 'smooth' });</code></pre> <div class="actions"> <button class="btn js-scroll-by">scroll by 100 pixels</button> </div> </div> </section> <section class="sample sample-scrollBack"> <div class="container"> <h2>window.scrollBy</h2> <pre><code>window.scrollBy({ top: -100, left: 0, behavior: 'smooth' });</code></pre> <div class="actions"> <button class="btn js-scroll-back">scroll back 100 pixels</button> </div> </div> </section> <section class=" sample <API key>"> <div class="container"> <h2>element.scrollIntoView</h2> <pre><code>document.querySelector('.hello').scrollIntoView({ behavior: 'smooth' });</code></pre> <div class="actions"> <button class="btn <API key>">Scroll into view</button> </div> <article class="scrollable-parent"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iure obcaecati, repudiandae aspernatur cumque recusandae adipisci consequuntur maiores, quo in nulla ratione facere distinctio beatae, quae consequatur ab labore dolorum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iure obcaecati, repudiandae aspernatur cumque recusandae adipisci consequuntur maiores, quo in nulla ratione facere distinctio beatae, quae consequatur ab labore dolorum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iure obcaecati, repudiandae aspernatur cumque recusandae adipisci consequuntur maiores, quo in nulla ratione facere distinctio beatae, quae consequatur ab labore dolorum.</p> <h3 class="hello"><em>hello!</em></h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iure obcaecati, repudiandae aspernatur cumque recusandae adipisci consequuntur maiores, quo in nulla ratione facere distinctio beatae, quae consequatur ab labore dolorum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iure obcaecati, repudiandae aspernatur cumque recusandae adipisci consequuntur maiores, quo in nulla ratione facere distinctio beatae, quae consequatur ab labore dolorum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iure obcaecati, repudiandae aspernatur cumque recusandae adipisci consequuntur maiores, quo in nulla ratione facere distinctio beatae, quae consequatur ab labore dolorum.</p> </article> </div> </section> <section class="sample sample-scrollToTop"> <div class="container"> <h2>Scroll to top</h2> <pre><code>window.scroll({ top: 0, left: 0, behavior: 'smooth' });</code></pre> <p><strong>or</strong></p> <pre><code>document.querySelector('header').scrollIntoView({ behavior: 'smooth' });</code></pre> <div class="actions"> <button class="btn js-scroll-to-top">scroll to top</button> </div> </div> </section> <section> <div class="container"></div> </section> <section class="featured"> <div class="container"> <a class="featured__link" href="https://github.com/iamdustan/smoothscroll">Polyfill on <strong>GitHub</strong></a> <a class="featured__link" href="https://github.com/iamdustan/<API key>">Polyfill on <strong>npm</strong></a> <a class="featured__link" href="https://drafts.csswg.org/cssom-view/#<API key>">Draft on <strong>W3C</strong></a> <a class="featured__link" href="https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior">Documentation on <strong>MDN</strong></a> </div> </section> <footer> <div class="container"> <p>Polyfill written by <a href="https: <p>All rights reserved &copy; <a href="https: </div> </footer> <script> // add event listener on load window.addEventListener('load', function() { // scroll to bottom document.querySelector('.js-scroll-to-bottom').addEventListener('click', function(e) { e.preventDefault(); window.scrollTo({ top: document.body.clientHeight - window.innerHeight, left: 0, behavior: 'smooth' }); }); // scroll to top document.querySelector('.js-scroll-to-top').addEventListener('click', function(e) { e.preventDefault(); document.querySelector('header').scrollIntoView({ behavior: 'smooth' }); }); // scroll by document.querySelector('.js-scroll-by').addEventListener('click', function(e) { e.preventDefault(); window.scrollBy({ top: 100, left: 0, behavior: 'smooth' }); }); // scroll back document.querySelector('.js-scroll-back').addEventListener('click', function(e) { e.preventDefault(); window.scrollBy({ top: -100, left: 0, behavior: 'smooth' }); }); // scroll into view document.querySelector('.<API key>').addEventListener('click', function(e) { e.preventDefault(); document.querySelector('.hello').scrollIntoView({ behavior: 'smooth' }); }); }); </script> </body> </html>
<?php namespace spec\Welp\MailchimpBundle\Event; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class WebhookEventSpec extends ObjectBehavior { function let($data = ['test' => 0, 'data' => 154158]) { $this->beConstructedWith($data); } function it_is_initializable() { $this->shouldHaveType('Welp\MailchimpBundle\Event\WebhookEvent'); $this->shouldHaveType('Symfony\Component\EventDispatcher\Event'); } function it_has_data($data) { $this->getData()->shouldReturn($data); } }
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) require 'bundler/setup' # Set up gems listed in the Gemfile. require 'rubygems' require 'rails/commands/server' =begin module Rails class Server alias :default_options_bk :default_options def default_options default_options_bk.merge!(Host: '120.27.94.221') end end end =end
<!DOCTYPE html> <html lang="en"> <head> <?php include "htmlheader.php" ?> <title>The War of 1812</title> </head> <body> <?php include "pageheader.php"; ?> <!-- Page Header --> <!-- Set your background image for this header on the line below. --> <header class="intro-header" style="background-image: url('img/1812ships.jpg')"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="post-heading"> <h1>The Second American War for Independence</h1> <h2 class="subheading">And what caused it</h2> <span class="meta">Content created by Wat Adair and Scotty Fulgham</span> </div> </div> </div> </div> </header> <!-- Post Content --> <article> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <p>At the outset of the 19th century, Great Britain was locked in a long and bitter conflict with Napoleon Bonaparte’s France. In an attempt to cut off supplies from reaching the enemy, both sides attempted to block the United States from trading with the other. In 1807, Britain passed the Orders in Council, which required neutral countries to obtain a license from its authorities before trading with France or French colonies.</p> <p>The Royal Navy also outraged Americans by its practice of impressment, or removing seamen from U.S. merchant vessels and forcing them to serve on behalf of the British. In 1809, the U.S. Congress repealed Thomas Jefferson’s unpopular Embargo Act, which by restricting trade had hurt Americans more than either Britain or France. Its replacement, the Non-Intercourse Act, specifically prohibited trade with Britain and France. It also proved ineffective, and in turn was replaced with a May 1810 bill stating that if either power dropped trade restrictions against the United States, Congress would in turn resume non-intercourse with the opposing power</p> <h2 class="section-heading">Causes of the War</h2> <p>In the War of 1812, the United States took on the greatest naval power in the world, Great Britain, in a conflict that would have an immense impact on the young country’s future. Causes of the war included British attempts to restrict U.S. trade, the Royal Navy’s impressment of American seamen and America’s desire to expand its territory.</p> <h2 class="section-heading">Effects of the War</h2> <p>The war of 1812 was thought of as a relatively minor war but it had some lasting results, It is thought of as a decisive turning point in canadians and native americans losing efforts to govern themselves. The war also put an end to the federalist party. The party had been accused of being unpatriotic because they were against war. Some people think the most important effect of the war was the confidence that it gave america.</p> <blockquote> "The war has renewed and reinstated the national feelings and character which the Revolution had given, and which were daily lessened. The people . . . . are more American; they feel and act more as a nation; and I hope the permanency of the Union is thereby better secured." - First Lady Dolley Madison, 24 August 1814, writing to her sister as the British attacked Washington, D.C. </blockquote> <p><i>Page content written by Wat Adair and Scotty Fulgham.</i></p> </div> </div> </div> </article> <hr> <?php include "pagefooter.php"; ?> </body> </html>
body { font-family: Helvetica; color: #111; overflow: hidden; margin: 0; background: #f2f2f2; line-height: 1.5; } header { display: block; margin: 20% auto; text-align: center; font-size: 50px; font-weight: bold; } header span { position: relative; display: inline-block; } button { display: block; margin: 5px auto; padding: 5px; font-size: 15px; }
package org.spongepowered.api.data.types; import org.spongepowered.api.CatalogType; import org.spongepowered.api.util.annotation.CatalogedBy; /** * Represents a type of instrument. */ @CatalogedBy(InstrumentTypes.class) public interface InstrumentType extends CatalogType { }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <title>EMAT20005</title> </head> <body> <h1>EMAT20005: Product Realisation<br /> Personal Rapid Transit </h1> <p> Fall 2010, Weeks 6-10<br/> 11:00-13:00 on Wednesdays in QB 1.59<br/> Instructor: <a href="..">John Lees-Miller</a> </p> <h2>News</h2> <h3>8 Dec, 2010</h3> <ul> <li>To submit the <a href="#report">final report</a>: either upload the document and supporting sim files to <a href="http: href="http: me the link, or drop them in the appropriate box in the Queen's School Office.</li> </ul> <h3>2 Dec, 2010</h3> <ul> <li>Some additional help on gravity models is available <a href="<API key>.pdf">here</a>.</li> <li>Clarification: hand-drawn sketches are fine for task 4.</li> </ul> <h3>26 Nov, 2010</h3> <ul> <li>More details for the <a href="#presentation">presentation</a> and <a href="#report">final report</a> have been added.</li> <li>The page limit for the individual report has increased from 5 pages to 6, in order to allow two pages for each of the three iterations.</li> </ul> <h2>Outline</h2> <ul> <li>Week 6 (first class Wednesday, 17 Nov) <ul> <li>lecture: introduction to PRT + advice on choosing a site (<a href="https: <li>form groups</li> <li>set up <a href="#sim">ATS/CityMobil design and simulation tool</a></li> <li>choose a site</li> <li>start on demand estimates</li> </ul></li> <li>Week 7 <ul> <li>lecture: simulator demo, gravity models (<a href="https: <li>work on <a href="#demand">task 2</a> and <a href="#design">task 3a</a></li> <li><strong>Deliverable:</strong> in class, show me <ul> <li>a map of your site,</li> <li>the scale of the map, in meters per pixel, and</li> <li>the major demand generators in the area.</li> </ul></li> </ul></li> <li>Week 8 <ul> <li>questions and answers</li> <li>work on <a href="#design">task 3b/3c</a></li> <li><strong>Deliverable:</strong> at the start of class, show me a simulation file containing your group's preliminary network (<a href="#design">task 3a</a>), including stations and network.</li> </ul></li> <li>Week 9 <ul> <li>questions and answers</li> <li>work on <a href="#design">task 3c</a> and <a href="#design-stations">task 4</a></li> </ul></li> <li>Week 10 <ul> <li><strong>Deliverable:</strong> 10 minute <a href="#presentation">presentation</a> in class</li> <li><strong>Deliverable:</strong> <a href="#report">final report</a> due at 4pm on Friday, 17 December</li> </ul></li> </ul> <h2>Assessment</h2> <table border="1" cellpadding="4"> <tr><th>Item</th><th>Weight</th></tr> <tr><td>deliverable in week 7</td><td>5%</td></tr> <tr><td>deliverable in week 8</td><td>5%</td></tr> <tr><td>final presentation</td><td>30%</td></tr> <tr><td>final report: group component</td><td>40%</td></tr> <tr><td>final report: individual component</td><td>20%</td></tr> </table> <a name="sim"></a> <h2>Task 0 &nbsp; Get the simulation tool.</h2> <h3>For the Lab Machines</h3> <ol> <li>Download <a href="<API key>.zip"><API key>.zip</a> (2.5MB). (Right click and choose Save Target As...)</li> <li>Extract the zip file to your university drive.</li> <li>Double click <em>atscitymobil.exe</em> to launch.</li> </ol> <h3>For your Laptop / PC</h3> <p> Please use this <a href="http: </p> <h3>Tutorial</h3> <p>This <a href="http: <a name="site"></a> <h2>Task 1 &nbsp; Choose a site.</h2> <p>You will need a map of the area, and you will have to know the scale of the map image, in meters per pixel. (Hint: A screenshot from <a href="http: <p>You will need to identify the major demand generators in the area. (Hint: Google Earth and Google Maps label most major facilities and land marks.)</p> <p>Your site can be anywhere, but keep in mind that you have to estimate what the potential passenger demand will be. For ideas, you can go to <a href="http: <p>Alternatively, you can work from a <a href="http://en.wikipedia.org/wiki/Greenfield_land">greenfield</a> (undeveloped) site, and develop your site around your PRT system, rather than trying to fit the system into an existing site. Keep in mind, however, that designing both the site and the PRT system will require more work. If your group wants to do this, please discuss with me before the end of week 6.</p> <p>Also note that your service area must not exceed 5km by 5km, due to limitations of the simulator.</p> <a name="site-outputs"></a> <h3>Outputs</h3> <ul> <li>A map of your site.</li> <li>The scale of the map, in meters per pixel.</li> <li>A list of the major demand generators in the area.</li> </ul> <a name="demand"></a> <h2>Task 2 &nbsp; Place stations and create demand scenarios.</h2> <p>Now you are ready to place stations near your site's demand generators. Exactly how many stations you place and where you place them depends on your estimates for the demand between pairs of stations. For this project, you will have to make several (educated) guesses at what the demand will be.</p> <p>When deciding where to place stations, you should be thinking about the following guidelines.</p> <ul> <li>Passengers will typically walk to or from the PRT stations. A good rule of thumb is that walking distances from each station to any nearby demand generators should be less than about 400m, because very few people will be willing to walk farther than this.</li> <li>You can build stations inside or on top of existing buildings, or you can build free-standing stations.</li> <li>To get an idea of the area required for a station, see these <a href="http: <li>You must be able to access the stations with guideways.</li> <li>Stations cost money.</li> <li>The maximum number of stations is 20, due to simulator limitations.</li> <li>The minimum number of stations is 12.</li> <li>The total flow of vehicles (in flow plus out flow) at any station must not exceed 300 vehicles per hour. If you have a large demand generator, you should split the demand between several stations.</li> </ul> <p>To represent the passenger demand, you will create one <em>demand scenario</em> per group member. Each scenario describes the passenger demand at a particular time. For example, a large urban system might have an <em>AM peak</em> during morning rush hour, in which most of the demand is from the outskirts to the center. The evening rush hour is the <em>PM peak</em> demand. Outside of peak times, the passenger flows are typically smaller and more <em>balanced</em>; that is, the average flow into each region tends to equal the average flow out. Other scenarios might come from special events, for example at a stadium or convention centre. Each scenario will suggest different system optimisations.</p> <p>The data required to define a scenario are the in flow and out flow of vehicles at every station. As mentioned above, the total flow (in plus out) for each station must be less than 300 vehicles per hour. Also, the <em>sum</em> of all the in flows must equal the sum of all the out flows for each scenario; these sums are written <em>T<sub>i</sub></em> in the table below. Your scenarios must include one <em>balanced flow</em> scenario, in which the flow in and out of each station is (roughly) equal. The others should represent peaks with different spatial distribution and intensity. The total flow (<em>T<sub>i</sub></em>) for the whole system must be at least 700 vehicle trips per hour for the balanced scenario and at least 1300 trips per hour for the peak scenarios.</p> <p>Note that the simulator needs to know the demand in vehicles per hour; the average <em>vehicle occupancy</em> relates this to passengers per hour. To help calibrate your numbers, a reasonable guess at vehicle occupancy is 1.2 passengers per vehicle, but it will be higher for some sites, for example if there are many couples or families using the system. Different scenarios may also have different vehicle occupancies.</p> <p>Finally, for each scenario you will have to estimate how many hours per day (or per week) each scenario will occur. We will assume here that the actual demand will always be like one of the scenarios. This allows us to estimate the system's annual patronage, which will be important in subsequent sections.</p> <p>You may want to organize these data in a table like the following (it would be a good idea to use a spreadsheet).</p> <a name="scenario-table"></a> <table border="1" cellpadding="4"> <tr><th></th> <th colspan="6">Vehicle Flows (vehicles/hour)</th> </tr> <tr><th align="right">Scenario:</th> <th colspan="2">Balanced</th> <th colspan="2">AM Peak</th> <th colspan="2">PM Peak</th> </tr> <tr><th align="left">Station</th> <th>In</th><th>Out</th> <th>In</th><th>Out</th> <th>In</th><th>Out</th> </tr> <tr><td>Park Plaza East</td> <td align="right">80</td><td align="right">80</td> <td align="right">50</td><td align="right">250</td> <td align="right">200</td><td align="right">80</td> </tr> <tr><td>Park Plaza West</td> <td align="right">80</td><td align="right">80</td> <td align="right">50</td><td align="right">150</td> <td align="right">200</td><td align="right">30</td> </tr> <tr><td>...</td> <td align="right">...</td><td align="right">...</td> <td align="right">...</td><td align="right">...</td> <td align="right">...</td><td align="right">...</td> </tr> <tr><th align="left">Total In/Out</th> <td align="center">T<sub>1</sub></td> <td align="center">T<sub>1</sub></td> <td align="center">T<sub>2</sub></td> <td align="center">T<sub>2</sub></td> <td align="center">T<sub>3</sub></td> <td align="center">T<sub>3</sub></td> </tr> <tr><th align="left">Total Hourly Flow</th> <td align="center" colspan="2">T<sub>1</sub></td> <td align="center" colspan="2">T<sub>2</sub></td> <td align="center" colspan="2">T<sub>3</sub></td> </tr> <tr><td colspan="7">&nbsp;</td></tr> <tr><th align="left">Hours / Day</th> <td align="center" colspan="2">...</td> <td align="center" colspan="2">...</td> <td align="center" colspan="2">...</td> </tr> <tr><th align="left">Total Daily Vehicle Flow</th> <td align="center" colspan="6">...</td> </tr> <tr><th align="left">Vehicle Occupancy</th> <td align="center" colspan="6">1.2 passengers / vehicle</td> </tr> <tr><th align="left">Total Passengers / Day</th> <td align="center" colspan="6">...</td> </tr> <tr><th align="left">Total Passengers / Year</th> <td align="center" colspan="6">...</td> </tr> </table> <p>The next step is to run a <a href="http://en.wikipedia.org/wiki/Trip_distribution <p>The equations for the gravity model and an algorithm for running it will be described in class. Use the straight-line distances between stations as "costs." (<strong>Note</strong>: the version of the sim that you downloaded in the first week did not report straight-line distances in the output; the <a href="#sim">latest version</a> does.) The suggested dispersion factor is 0.5. You are free to tweak this factor, or to edit the resulting OD matrix directly, if you wish, provided that the resulting matrix still satisfies the constraints on total flow at stations and for the system as a whole. You can implement the algorithm however you like; it's possible to do it in MATLAB or in Excel (hint: use the <a href="<API key>.pdf">solver add-in</a>).</p> <h3>Outputs</h3> <ul> <li>An ATS/CityMobil simulator (.atscm) file with <ul> <li>your map as the background image,</li> <li>the background image scale (meters per pixel) set properly, and</li> <li>your stations in the simulator (place them with the Build tool).</li> </ul></li> <li>One scenario per group member.</li> <li>One origin-destination demand matrix per scenario.</li> <li>See also section 1 of the <a href="#report">final report</a>.</li> </ul> <a name="design"></a> <h2>Task 3&nbsp; Design a PRT network.</h2> <p>Now you are ready to connect the stations with guideways. We'll do this in three stages.</p> <ol type="a"> <li>As a group, create a preliminary network design based on the given guidelines (below). Here you should just aim to connect all the stations and add one depot, in order to get the simulation running.</li> <li>Individually, pick a demand scenario and optimise the network for that scenario using the given cost structure.</li> <li>As a group, agree on a final design that takes all of the scenarios into account.</li> </ol> <p>For (a), you will have to show me the simulation in class in week 8. For (b), each group member must write an appendix to the final report that documents the optimisation process for his/her scenario.</p> <h3>Guidelines</h3> <ul> <li>The vehicles can only run on dedicated guideway. Pedestrians and road traffic cannot mix with moving PRT vehicles. The usual way to accommodate this is to build elevated guideway, but you can also run at-grade (on the ground, protected by a fence), or below-grade (in a tunnel). At-grade guideway is much less expensive than elevated guideway (see below). (Note that the simulator does not distinguish between grades.)</li> <li>A good network design strategy is to connect the stations in one-way loops, like in the Urban Case Study network that comes bundled with the simulator.</li> <li>However, your loops should not be too long, because travel times for trips that go the long way around the loop become too large. For example, in the Urban Case Study, the trip time from station 8 to station 7 is only about 40s, but the travel time from 7 to 8 (the long way around) is nearly 8 minutes.</li> <li>Whether a long travel time between a pair of stations is acceptable depends on how much demand you expect between those stations. You may choose to build extra guideway to make some loops shorter or connect loops more directly, or you may choose to reverse the direction of a loop. Note that this depends on the scenario.</li> <li>Your guideways should follow existing rights of way (roads, alleys, railway lines, bridges) where possible. You can cut through buildings, especially if it allows you to put a station inside.</li> <li>Guideway costs money. However, you must connect all of the stations, and building extra guideway for more direct routes reduces travel times and the number of vehicles that you need.</li> <li>To reduce passenger waiting times at a station, you can construct a depot upstream of the station. Depots help the system's empty vehicle management algorithm to keep vehicles close to where they will be needed.</li> <li>See these <a href="http: </ul> <h3>Cost Structure for Optimisation</h3> <p>Your objective is to minimize the sum of system costs and user costs, according to the following cost estimates.</p> <a name="costs"></a> <table border="1" cellpadding="4"> <tr><th>Capital Costs</th><th>&pound;</th></tr> <tr><td>1 vehicle</td><td align="right">50k</td></tr> <tr><td>1 station</td><td align="right">0.5M</td></tr> <tr><td>1 depot</td><td align="right">0.4M</td></tr> <tr><td>1 km at-grade guideway</td><td align="right">1M</td></tr> <tr><td>1 km elevated guideway</td><td align="right">2.5M</td></tr> <tr><td>other</td><td align="right">+50%</td></tr> <tr><th>Operating Costs</th><th>&pound;</th></tr> <tr><td>1 passenger km</td><td align="right">0.15</td></tr> <tr><th>User Costs</th><th>&pound;</th></tr> <tr><td>1 minute passenger travel time</td><td align="right">0.1</td></tr> <tr><td>1 minute passenger waiting time</td><td align="right">0.2</td></tr> </table> <p>Some of the costing inputs you can read directly from the network, but the number of vehicles and the mean passenger waiting time must be estimated by simulation. You should run 5 simulations and average the results, in order to get reliable numbers.</p> <p>The simulator output includes the total track length, but the simulator does not know anything about grades. For costing, you should estimate roughly what percentage of your track is at-grade. Do not worry about getting this exactly right, because all of the costs are rough; just try to estimate to within 10% or so.</p> <p>Once you have computed the base capital costs (vehicles, stations, depots and guideway), add 50% to cover related expenses, such as central control software and hardware, and a contingency.</p> <p>The system operating costs are given as a rough total cost per passenger kilometer. The simulator output includes the 'mean demand-weighted passenger trip distance,' which you can use to compute the operating cost per passenger trip. To scale this up to an annual operating cost, you will use the passenger trips / year figure from task 2. (Note that when you are optimising for a single scenario, multiplication by the total passengers per year effectively assumes that the demand is <em>always</em> like this scenario; this is not really true, but it is good enough for our purposes here.)</p> <p>You can approach the user costs similarly; here the relevant simulator outputs are the 'mean demand-weighted passenger trip time' and the mean passenger waiting time. The user costs are based on a standard <a href="http://en.wikipedia.org/wiki/Value_of_time">value of time</a> calculation.</p> <p>These costs are rough estimates. The main point is that there are trade-offs between capital costs, operating costs and user costs. For example, you can build more guideway to reduce travel times, which increases your capital cost but decreases your operating and user costs.</p> <p>Operating and user costs occur over time, so you should use <a href="http://en.wikipedia.org/wiki/Net_present_value">present values</a> to weigh them against capital costs. Assume the standard public works discount rate of 6% per year, and discount over 30 years.</p> <p>These costs give you a way of evaluating networks objectively. However, you should be mindful of externalities. For example, this does not include a cost for visual intrusion in culturally sensitive areas. It also does not account for changes in pedestrian flows; areas that were once quiet could become busy, and vice versa. You may reject a design that is "optimal" by cost but undesirable for other reasons.</p> <p>I strongly recommend that you create a spreadsheet to keep track of the cost calculations.</p> <h3>Constraints</h3> <ul> <li>Maximum number of depots is 5.</li> <li>90% of passengers should wait less than 60s (but somewhat longer tails are fine for peak demand scenarios).</li> <li>You may add new stations or remove stations that have low value for some or all scenarios (e.g. low demand and/or requiring a lot of extra infrastructure). However, you will then have to modify the scenarios and regenerate demand matrices. The total demand must stay within the limits given in task 2.</li> </ul> <a name="design-composite"></a> <h3>Optimising for Multiple Scenarios</h3> <p>Once each member of your group has optimised your initial network for one scenario, you will apply what you've learned to design a network that works for all of them.</p> <p>To evaluate your final network, use a <em>composite cost</em> that describes its combined performance on all of the demand scenarios. The capital costs apply to all scenarios equally, but the operating and user costs depend on the demand. So, you should evaluate your final network on each scenario and record the trip distance, trip time and passenger waiting time for each one. Then you should weight these by how frequently each scenario occurs (as estimated in task 2) and apply the cost model. (Also note that the number of vehicles you need is the largest number needed in any single scenario.)</p> <p>You should do several iterations to improve the composite cost. Again, be mindful of externalities.</p> <p>Note: The simulator will only let you enter one OD matrix at a time, but you can copy and paste OD matrices to/from the sim. The best way to do this is to copy the matrix from one simulation into Excel, delete the last row and the last column (the totals), and then paste it into another simulation.</p> <h3>Cost/Benefit Analysis</h3> <p>To measure the user benefits that could come from building a PRT system, one must compare user costs with PRT to user costs with existing modes. Here we will compare PRT with a very simplistic model of a bus system. Assume that users wait an average of 5 minutes for the bus, and that the average travel time by bus is the time taken to travel the <em>straight-line distance</em> from origin to destination at 12km/h. (<strong>Note</strong>: the version of the sim that you downloaded in the first week did not report straight-line distances in the output; the <a href="#sim">latest version</a> does.) Use the travel and waiting time savings (or not) with the <a href="#costs">cost table</a> to compute user benefits and system costs.</p> <h3>Outputs</h3> <p>See section 2 in the <a href="#report">final report</a>.</p> <a name="design-stations"></a> <h2>4 &nbsp; Design two stations in detail.</h2> <p>Pick two stations that are interesting or challenging, for example due to large size or passenger volumes, culturally sensitive surroundings or an architecturally interesting setting (e.g. integrated into a building), and produce a conceptual design for each one.</p> <p>You should produce a plan view of the station, keeping the following questions in mind.</p> <ul> <li>Precisely where will the station be built? Is it a standalone station, or is it part of an existing building? If it is standalone, is the station area on the ground, or is it elevated?</li> <li>How will you connect the guideways into and out of the station?</li> <li>How will passengers enter and exit the station?</li> <li>How many berths will the station have? (Hint: use the largest number of berths assigned by the simulation in any demand scenario.)</li> </ul> <p>The "vehicle side" of the station should be consistent with these <a href="http: guidelines</a>; see also <a href="http: overview</a>. The <a href="http: design template</a> (in SketchUp) is particularly helpful. You should consider where the main line and the on- and off-ramps will go. </p> <p>Note: hand-drawn sketches are fine.</p> <p><strong>Bonus</strong>: Construct an architectural rendering (e.g. in SketchUp) of the station. You can use the 3D design template in the guidelines to get started.</p> <h3>Outputs</h3> <p>See section 3 in the <a href="#report">final report</a>.</p> <a name="presentation"></a> <h2>Details for Presentation</h2> <p>Each group's presentation will last around 10 minutes with a few minutes for questions. Your presentation should cover essentially the same content as the main body of the <a href="#report">final report</a> (sections 1-3), with a focus on the visual and qualitative aspects of your design. Every group member must participate in the presentation.</p> <a name="report"></a> <h2>Details for Final Report</h2> <p>Each group should submit a report as described below. The main body of the report (sections 1-3) is limited to 5000 words on 20 pages. In addition, each group member should submit an appendix (see below) of up to 600 words on 6 pages. Note that these are word and page <em>maxima</em>: you should aim to be concise (and use lots of pictures!).</p> <p>In addition to the written report, please submit the following ATS/CityMobil (.atscm) simulation files.</p> <ul> <li>An .atscm file for your group's final network.</li> <li>An .atscm file for each group member's final network, including the demand matrix for the corresponding demand scenario.</li> </ul> <p>To submit: either upload the document and supporting sim files to <a href="http: href="http: me the link, or drop them in the appropriate box in the Queen's School Office.</p> <h3>Marking Criteria</h3> <p>The report will be marked according to the following five equally weighted criteria.</p> <ul> <li>Clarity and Conciseness</li> <li>Problem Analysis</li> <li>Down-select Logic (comparison of iterations / alternatives)</li> <li>Technology Employed</li> <li>Overall Design and Solution</li> </ul> <h3>Final Report Content</h3> <h4>Section 1: Site, Stations and Demand</h4> <ul> <li>A map of your site with labels for the main demand generators.</li> <li>Where is your site?</li> <li>Why might a PRT system be appropriate for this site?</li> <li>Table of scenarios (one per group member) like <a href="#scenario-table">this one</a>.</li> <li>How did you guess the in and out flows for your scenarios?</li> <li>How did you implement the gravity model?</li> <li>What is the effect of the dispersion parameter?</li> <li>What dispersion parameter value(s) did you use?</li> </ul> <h4>Section 2: System Optimisation</h4> <ul> <li>A screenshot of your group's initial network (<a href="#design">task 3a</a>).</li> <li>A record of three iterations / design alternatives evaluated according to <a href="#design-composite">composite cost</a>, one of which should be selected as your group's "final" (preferred) network. For each alternative, include <ul> <li>a screen shot of the network,</li> <li>a table of costs (capital, operating, user, total and net present value), and</li> <li>a brief description of how it relates to other alternatives and/or the networks you designed for individual scenarios.</li> </ul> </li> <li>Cost/benefit analysis for the final network: <ul> <li>Explain your cost/benefit calculations.</li> <li>Do the benefits outweigh the costs?</li> <li>What are the most important variables (travel times, waiting times, discount factor, ...)? (sensitivity)</li> <li>Are there other benefits or costs (not included in the cost function here) that could change the conclusion?</li> </ul></li> </ul> <h4>Section 3: Detailed Design for Two Stations</h4> <p>For each of the two stations:</p> <ul> <li>Why is the station interesting and/or challenging? What other stations did you consider before selecting these two?</li> <li>How many berths does the station need?</li> <li>What are the effects of the station on its surrounding area, in terms of economic, environmental and social impact?</li> <li>Plan view of the station (see <a href="#design-stations">guidelines</a>).</li> <li><strong>Bonus:</strong> include architectural renderings of one or both stations (see <a href="#design-stations">guidelines</a>).</li> </ul> <h4>Appendices (one per group member)</h4> <p>Your appendix should describe the process that you (individually) went through to optimise the system for your scenario. In particular, you should provide a record of three iterations; for each one, you should include </p> <ul> <li>a screen shot of the network,</li> <li>a table of costs (capital, operating, user, total and net present value), and</li> <li>a brief description of what changes you made and your rationale.</li> </ul> <h2>Other Resources</h2> <ul> <li><a href="http://en.wikipedia.org/wiki/Personal Rapid Transit">Personal Rapid Transit</a> on Wikipedia</li> <li><a href="http: <li>ULTra PRT <a href="http: for Bath</a></li> <li>Other PRT vendors: <a href="http: <a href="http: </li> </ul> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http: document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-8962570-4"); pageTracker._trackPageview(); } catch(err) {}</script> </body> </html>
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Potlatch!</title> <link href="./static/css/skeleton.css" rel="stylesheet"> <link href="./static/css/style.css" rel="stylesheet"> </head> <body> <div id="potlatch"></div> <script src="./static/js/potlatch.js"></script> <script type="text/javascript"> var node = document.getElementById("potlatch"); var flags = { itemsUrl: "./items.json" }; Elm.Main.embed(node, flags); </script> </body> </html>
import React, { PropTypes } from 'react'; class Link extends React.Component { render() { return <article key={this.props.item.id} className="List-Item"> <header className="List-Item-Header"> <cite className="List-Item-Title"><a href={this.props.item.href}>{this.props.item.title}</a></cite> </header> <p className="<API key> <API key>">{this.props.item.short_description}</p> </article> } } export default Link;
# Udacity Software Debugging ## Introduction - Course: [**Udacity CS259 Software Debugging**](https: - Fee: **Free** - Approx. **1 ~ 2 Weeks** - Prerequisites - Python Experience - Review: **Excellent** - Content - [x] **Video + Script** - [x] **Quiz** - [x] **My Solutions** - [x] **Official Solutions** - **Syllabs** - Lesson 1: How Debuggers work - Lesson 2: Asserting Expectations - Lesson 3: Simplifying Failures - Lesson 4: Tracking Origins - Lesson 5: Reproducing Failures - Lesson 6: Learning from Mistakes - **What I Learned** - How to Manage Problems (Problem Life Cycle) - How to Analyse and Solve Problems ($\Phi$ Function, Delta Debugging) - How to Writer a Debugger in Python (Use `inspect` Object)
<!DOCTYPE html> <html lang="cs"> <head> <meta charset="utf-8"> <title>Cooland</title> <meta name="description" content=""> <meta name="author" content="Cooland"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="//fonts.googleapis.com/css?family=Merriweather:300,400,700&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link rel="icon" type="image/png" href="../img/favicon.png"> <link href="css/base.css" rel="stylesheet" type="text/css"> <link href="css/style.css" rel="stylesheet" type="text/css"> <link href="css/navmenu.css" rel="stylesheet" type="text/css"> <link href="css/gallery.css" rel="stylesheet" type="text/css"> </head> <body> <div id="header"> <div class="container main-nav"> <a href="/index" class="main-nav__logo"> <img src="img/cooland_logo.jpg" alt="Cooland"> </a> <nav class="fl"> <a href="" class="main-nav__burger js-nav"> <i class="icon-reorder"></i> </a> <div class="main-nav__block"> <div class="nav__left"> <a href="/o_nas" class=" ">O nás</a> <a href="/vize" class="">Vize</a> <a href="/nabizime" class="">Nabízíme</a> </div> <div class="nav__right"> <a href="/akce" class="">Akce</a> <a href="/media" class="">Média</a> <a href="/partaci" class="">Parťáci</a> </div> </div> </nav> </div> </div> <div id="main" class="container"> <h2>PARTNEŘI</h2> <h4>Domácí Květinářství</h4> <p>Květinářství, kde se pěstují, váží a prodávají kytice z českého venkova, pěstované pod širým nebem s láskou a péčí. </p> <p>Od roku 2016 je Domácí květinářství součástí iniciativy komunitou podporovaného zemědělství <a href="https://plus.google.com/u/0/communities/<API key>" target="_blank">KPZ CooLAND</a>.</p> <p><a href="http: <h4>Ekumenická akademie</h4> <p>Akademie prosazuje alternativní přístupy při řešení současných světových ekonomických, sociálních a ekologických problémů a zároveň je přenáší do praxe v podobě konkrétních projektů.</p> <p>CooLAND je partnerem kampaně <a href="http: <p><a href="http: <h4>Farma Lukava</h4> <p>Rodinná ekologická farma hospodařící v Jindřichovicích pod Smrkem a Dětřichovci, kde se zabývá především chovem dojných ovcí a zpracováním ovčího mléka. </p> <p>Od roku 2016 je farma součástí iniciativy komunitou podporovaného zemědělství <a href="https://plus.google.com/u/0/communities/<API key>" target="_blank">KPZ CooLAND</a>.</p> <p><a href="http: <h4>Glopolis</h4> <p>Nezávislé analytické centrum (think-tank) se zaměřením na globální výzvy a příslušné odpovědi České republiky a EU.</p> <p>CooLAND se aktivně účastnil diskusí v rámci festivalu <a href="http: <p><a href="http: <h4>Harvest Films</h4> <p>Občanské sdružení hledá a nabízí divákům filmy, které dokáží zajímavým a srozumitelným způsobem uchopit, vysvětlit a prezentovat vědecká témata. </p> <p>CooLAND se podílel na přípravě a realizaci projektu <a href="http: <p><a href="http: <h4>Institut cirkulární ekonomiky</h4> <p>Nevládní organizace, která v podmínkách ČR usiluje o rozvoj cirkulární ekonomiky - konceptu založeného na vytváření funkčních vztahů mezi lidskou společností a přírodou.</p> <p>CooLAND se v roli moderátora účastní vybraných diskusí v rámci projektu <a href="http://incien.org/buzz-talks/" target="_blank">Buzz Talks</a>.</p> <p><a href="http: <h4>Kytky od potoka</h4> <p>Květinářství, kde vážou netradiční kytice z květin, které si sami pěstují nebo sbírají na loukách, v lesích nebo i na rumištích.</p> <p>CooLAND si kupuje kytky od potoka pro radost a potěšení a občas také holkám pomůžeme nějakou tu kytku zasadit.</p> <p><a href="http: <h4>Na ovoce</h4> <p>Na ovoce slouží jako komunitní platforma lidem, kteří chtějí zodpovědně využívat přírodní bohatství v podobě volně rostoucích ovocných stromů, keřů či bylinek. Iniciativa se rozhodla taková místa nejen mapovat, ale také přispívat k jejich udržitelnosti, zakládat nová a dbát na hodnoty, které rostliny pro člověka představují, tím přispívat ke zvýšení biodiverzity a udržení pozitiv kulturní krajiny, ve které člověk žije.</p> <p>CooLAND ve spolupráci s Na ovoce realizuje projekt Pražské sady a jejich popularizace</p> <p><a href="https: <h4>PRO-BIO LIGA</h4> <p>PRO-BIO liga je samostatnou spotřebitelskou pobočkou největšího českého spolku ekologických hospodářů – Svazu ekologických zemědělců PRO-BIO Šumperk. Posláním PRO-BIO ligy je informovat a chránit spotřebitele potravin, přispívat k celoživotnímu vzdělávání a zvyšovat všeobecnou ekogramotnost.</p> <p>CooLAND spolupracuje s PRO-BIO liga na realizaci přednášek a workshopů o ochraně zemědělské půdy.</p> <p><a href="http: <h4>Statek Karel Tachecí</h4> <p>Ekologický zemědělec hospodařící v Budyni nad Ohří, kde pěstuje zeleninu, obiloviny, mák a další rostliny bez použití chemie a umělých hnojiv.</p> <p>CooLAND s Karlem Tachecím spolupracuje od roku 2015 a je prvním zemědělcem, který se stal součástí iniciativy komunitou podporovaného zemědělství <a href="https://plus.google.com/u/0/communities/<API key>" target="_blank">KPZ CooLAND</a>.</p> <p><a href="http: <h4>Kevin V. Ton</h4> <p>Kevin V. Ton patří mezi fotografy „uličníky“, tématem jeho fotografií je totiž především běžný život na ulici. Na jeho fotografiích se často objevují lidé, kteří žijí na okraji společnosti, mimo systém, a proto své fotografie Kevin chápe jako pouliční a sociální dokument. </p> <p>Kevin V. Ton svými fotografiemi pravidelně dokumentuje akce a setkání KPZ CooLAND. CooLAND ve spolupráci s PRO-BIO LIGA realizoval výstavu “Láska ke krajině prochází žaludkem” - fotografie Kevina Tona s příběhem první sezóny <a href="https://plus.google.com/u/0/communities/<API key>" target="_blank">KPZ CooLAND</a>.</p> <p><a href="http: <h4>PRO - BIO s r.o.</h4> <p>PRO-BIO, obchodní společnost s r. o. je první český výrobce a významný dodavatel širokého sortimentu kvalitních biopotravin. Podporuje a rozvíjí ekologické zemědělství, svou činností přispívá k zachování zdravé planety. Vrací zapomenuté tradiční plodiny a potraviny do života lidí.</p> <p>CooLAND spolupracuje s PRO - BIO na výzkumu vlivu ekologického hospodaření na krajinu.</p> <p><a href="http: <h4>Pozemkový úřad Nymburk</h4> <p>Pozemkové úřady mají mimo jiné na starosti realizaci pozemkových úprav. Ty jsou jedním z nejefektivnějších nástrojů, jak pomoci zemědělské krajině k tomu, aby byla zdravá a zároveň v ní mohli hospodařit zodpovědní zemědělci.</p> <p>CooLAND s Pozemkovým úřadem Nymburk spolupracuje při osvětě v oblasti pozemkových úprav a pořádá exkurze na realizovaná opatření v krajině.</p> <p><a href="http: <h2>KOALICE A SÍTĚ</h2> <h4>Asociace místních potravinových iniciativ AMPI</h4> <p>Poslání Asociace místních potravinových iniciativ (AMPI) je podporovat blízký vztah lidí ke krajině, ve které žijí, a to prostřednictvím rozvoje místních potravinových systémů (komunitou podporovaného zemědělství, komunitních zahrad aj.) v České republice, které zde zastřešuje. </p> <p>CooLAND se jako člen AMPI podílí na organizaci akcí, realizaci projektů, spoluprací se zahraničními partnery a šíření myšlenky komunitou podporovaného zemědělství u nás. Jsme společnými koordinátory projektu Erasmus + Projekty mobility osob / Vzdělávání dospělých s názvem: Learning toward Access to Land.</p> <p><a href="http: <h4>Iniciativa potravinové suverenity</h4> <p>Iniciativa vznikla v roce 2015 jako diskusní platforma jednotlivců i organizací a klade si za cíl prosazovat potravinovou suverenitu jako politický koncept přístupu k zemědělství a potravinářství v ČR i v Evropě, propojovat aktéry v ČR, napomáhat vzniku a rozvoji aktivit podporující potravinovou suverenitu a fungovat jako spojka na podobné iniciativy v dzahraničí.</p> <p>CooLAND je jedním ze zakládajících členů iniciativy a v roce 2015 jsme byli spolupořadatelem prvního <a href="https: <p><a href="https: <h4>Českomoravská komora pozemkových úprav</h4> <p>Českomoravská komora pro pozemkové úpravy (ČMKPÚ) byla založena již v r. 1990, jako zájmové sdružení pracovníků v oboru pozemkových úprav. Sdružuje projektanty, pracovníky státní správy – pozemkových a dalších úřadů, pracovníky výzkumných ústavů a vysokých škol, pracovníky dodavatelských stavebních organizací i další zájemce. Od svého vzniku spolupracovala a stále spolupracuje na tvorbě a novelizaci zákonů, vyhlášek, vládních nařízení, metodik, norem a dalších směrnic, souvisejících s oborem pozemkových úprav.</p> <p>CooLAND spolupracuje s ČMKPÚ popularizací tématu pozemkových úprav pořádáním exkurzí a psaním popularizačních článků, jelikož pozemkové úpravy jsou jedním z efektivních nástrojů pro ochranu zemědělské půdy.</p> <p><a href="http: <h4>URGENCI</h4> <p>URGENCI je mezinárodní síť pro rozvoj komunitou podporovaného zemědělství, která sdružuje jednotlivé občany, malé farmáře, spotřebitele i aktivisty a politiky, jejichž cílem je utváření solidárního partnerství mezi producentem a spotřebitelem potravin.</p> <p>CooLAND je součástí sítě od roku 2015. Jsme součástí <a href="http: <p><a href="http: <h4>Česká společnost ornitologická</h4> <p>Česká společnost ornitologická je dobrovolým spolkem profesionálů i amatérů, zabývajících se výzkumem a ochranou ptáků, zájemců o pozorování ptáků a milovníků přírody.</p> <p>CooLAND se zabývá ochranou ptáků žijících v zemědělské krajině podporou šetrného hospodaření. Zároveň využíváme metodiky ČSO pro výzkum ptačích populací jako indikátoru správného hospodaření zemědělských subjektů. </p> <p><a href="http: <h2>PODPORUJÍ NÁS</h2> <h4>Člověk v tísni</h4> <p>Nevládní nezisková organizace vycházející z myšlenek humanismu, svobody, rovnosti a solidarity, usilující o otevřenou, informovanou, angažovanou a zodpovědnou společnost k problémům doma i za hranicemi naší země.</p> <p>V roce 2016 nám Člověk v tísni umožnil uspořádat v prostorách svého centra Langhans výstavu fotografií <a href="https: <p>V roce 2015 jsem podávali grant Ministerstva průmyslu a obchodu na rozvoj ekologického zemědělství v Gruzii, kde byla místní mise Člověka v tísni lokálním partnerem.</p> <p><a href="https: <h4>Czech PR</h4> <p>Společnost poskytuje poradenské služby v oblasti vztahů s veřejností v České republice, provádí analýzy mediálního trhu a poskytuje komplexní služby v oblasti public relations.</p> <p>V roce 2016 nám agentura pomohla s analýzou našich vlastních strategických cílů a rozvojem CooLAND.</p> <p><a href="http: <h4>Kavárna Havran Café</h4> <p>Havran Café je malá a útulná kavárna v pražském Karlíně.</p> <p>CooLAND má v Havran Café svojí základnu, kde se scházíme a plánujeme. Od roku 2015 zde také každé úterý máme místo pro výdej zeleniny v rámci <a href="https://plus.google.com/u/0/communities/<API key>" target="_blank">KPZ CooLAND</a>.</p> <p><a href="https: <h4>Nadace Via</h4> <p>Posláním nadace je otevírání cest k umění žít spolu a umění darovat. Nadace podporuje, vzdělává a propojuje lidi, kteří společně pečují o své okolí a kteří darují druhým. </p> <p>CooLAND byl v roce 2015-16 zařazen do projektu <a href="http: <p><a href="http: </div> </body> <div id="footer"></div> </html>
#contact-info { font-size: .8em; } .job { background-color: #e9e5dc ; border-radius: 10px; margin-top: 5px; padding: .5px; } .ul { font-size: .8em; } li:last-child { color: blue; } #hula { color: red; }
<div class="modal-header"> <h3 class="modal-title">Ohje</h3> </div> <div class="modal-body"> <div ng-show="createOwnNetwork"> <div class="help-element"> <img class="help-image" src="public/system/assets/img/infoimages/create.png"> <p> Voit perustaa oman verkostosi painamalla Luo oma Verkosto -painiketta. Luotuasi verkoston ilmestyt kartalle antamaasi sijaintiin.</p> </div> <div class="help-element"> <img class="help-image" src="public/system/assets/img/infoimages/gather.png"> <p> Luodessasi verkostosi saat samalla uniikin linkin, jota voit jakaa ystävillesi sosiaalisessa mediassa ja kutsua heidät liittymään osaksi sinun verkostoasi.</p> </div> </div> <div ng-hide="createOwnNetwork"> <div class="help-element"> <img class="help-image" src="public/system/assets/img/infoimages/Join.png"> <p> Tulit sivustolle käyttäjän {{founderName}} linkin kautta</p> <p>Lähde mukaan!-painikkeella pääset mukaan hänen verkostoon.</p> </div> <div class="help-element"> <img class="help-image" src="public/system/assets/img/infoimages/gather.png"> <p> Liittymällä {{founderName}} verkostoon luot oman verkoston, johon voit kutsua ystäviäsi mukaan toimimaan SOS hyväntekijöinä.</p> </div> </div> </div> <div class="modal-footer"> <b style="color: <button class="btn btn-custom btn-lg" ng-click="ok()">Sulje</button> </div>
package components.diagram.edit.commands; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.common.core.command.CommandResult; import org.eclipse.gmf.runtime.common.core.command.ICommand; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.<API key>; import org.eclipse.gmf.runtime.emf.type.core.requests.<API key>; import components.Component; import components.ComponentsFactory; import components.Connection; import components.Port; import components.diagram.edit.policies.<API key>; /** * @generated */ public class <API key> extends EditElementCommand { /** * @generated */ private final EObject source; /** * @generated */ private final EObject target; /** * @generated */ private final Component container; /** * @generated */ public <API key>(<API key> request, EObject source, EObject target) { super(request.getLabel(), null, request); this.source = source; this.target = target; container = deduceContainer(source, target); } /** * @generated */ public boolean canExecute() { if (source == null && target == null) { return false; } if (source != null && false == source instanceof Port) { return false; } if (target != null && false == target instanceof Port) { return false; } if (getSource() == null) { return true; // link creation is in progress; source is not defined yet } // target may be null here but it's possible to check constraint if (getContainer() == null) { return false; } return <API key>.getLinkConstraints().<API key>(getContainer(), getSource(), getTarget()); } /** * @generated */ protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { if (!canExecute()) { throw new ExecutionException("Invalid arguments in create link command"); //$NON-NLS-1$ } Connection newElement = ComponentsFactory.eINSTANCE.createConnection(); getContainer().getConnections().add(newElement); newElement.getTarget().add(getSource()); newElement.getTarget().add(getTarget()); doConfigure(newElement, monitor, info); ((<API key>) getRequest()).setNewElement(newElement); return CommandResult.newOKCommandResult(newElement); } /** * @generated */ protected void doConfigure(Connection newElement, IProgressMonitor monitor, IAdaptable info) throws ExecutionException { IElementType elementType = ((<API key>) getRequest()).getElementType(); ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement, elementType); configureRequest.setClientContext(((<API key>) getRequest()).getClientContext()); configureRequest.addParameters(getRequest().getParameters()); configureRequest.setParameter(<API key>.SOURCE, getSource()); configureRequest.setParameter(<API key>.TARGET, getTarget()); ICommand configureCommand = elementType.getEditCommand(configureRequest); if (configureCommand != null && configureCommand.canExecute()) { configureCommand.execute(monitor, info); } } /** * @generated */ protected void setElementToEdit(EObject element) { throw new <API key>(); } /** * @generated */ protected Port getSource() { return (Port) source; } /** * @generated */ protected Port getTarget() { return (Port) target; } /** * @generated */ public Component getContainer() { return container; } /** * Default approach is to traverse ancestors of the source to find instance of container. * Modify with appropriate logic. * @generated */ private static Component deduceContainer(EObject source, EObject target) { // Find container element for the new link. // Climb up by containment hierarchy starting from the source // and return the first element that is instance of the container class. for (EObject element = source; element != null; element = element.eContainer()) { if (element instanceof Component) { return (Component) element; } } return null; } }
import Vue from 'vue'; import merge from 'element-ui/src/utils/merge'; import PopupManager from 'element-ui/src/utils/popup/popup-manager'; import getScrollBarWidth from '../scrollbar-width'; let idSeed = 1; const transitions = []; const hookTransition = (transition) => { if (transitions.indexOf(transition) !== -1) return; const getVueInstance = (element) => { let instance = element.__vue__; if (!instance) { const textNode = element.previousSibling; if (textNode.__vue__) { instance = textNode.__vue__; } } return instance; }; Vue.transition(transition, { afterEnter(el) { const instance = getVueInstance(el); if (instance) { instance.doAfterOpen && instance.doAfterOpen(); } }, afterLeave(el) { const instance = getVueInstance(el); if (instance) { instance.doAfterClose && instance.doAfterClose(); } } }); }; let scrollBarWidth; const getDOM = function(dom) { if (dom.nodeType === 3) { dom = dom.nextElementSibling || dom.nextSibling; getDOM(dom); } return dom; }; export default { model: { prop: 'visible', event: 'visible-change' }, props: { visible: { type: Boolean, default: false }, transition: { type: String, default: '' }, openDelay: {}, closeDelay: {}, zIndex: {}, modal: { type: Boolean, default: false }, modalFade: { type: Boolean, default: true }, modalClass: {}, modalAppendToBody: { type: Boolean, default: false }, lockScroll: { type: Boolean, default: true }, closeOnPressEscape: { type: Boolean, default: false }, closeOnClickModal: { type: Boolean, default: false } }, created() { if (this.transition) { hookTransition(this.transition); } }, beforeMount() { this._popupId = 'popup-' + idSeed++; PopupManager.register(this._popupId, this); }, beforeDestroy() { PopupManager.deregister(this._popupId); PopupManager.closeModal(this._popupId); if (this.modal && this.bodyOverflow !== null && this.bodyOverflow !== 'hidden') { document.body.style.overflow = this.bodyOverflow; document.body.style.paddingRight = this.bodyPaddingRight; } this.bodyOverflow = null; this.bodyPaddingRight = null; }, data() { return { opened: false, bodyOverflow: null, bodyPaddingRight: null, rendered: false }; }, watch: { visible(val) { if (val) { if (this._opening) return; if (!this.rendered) { this.rendered = true; Vue.nextTick(() => { this.open(); }); } else { this.open(); } } else { this.close(); } } }, methods: { open(options) { if (!this.rendered) { this.rendered = true; this.$emit('visible-change', true); } const props = merge({}, this.$props || this, options); if (this._closeTimer) { clearTimeout(this._closeTimer); this._closeTimer = null; } clearTimeout(this._openTimer); const openDelay = Number(props.openDelay); if (openDelay > 0) { this._openTimer = setTimeout(() => { this._openTimer = null; this.doOpen(props); }, openDelay); } else { this.doOpen(props); } }, doOpen(props) { if (this.$isServer) return; if (this.willOpen && !this.willOpen()) return; if (this.opened) return; this._opening = true; this.$emit('visible-change', true); const dom = getDOM(this.$el); const modal = props.modal; const zIndex = props.zIndex; if (zIndex) { PopupManager.zIndex = zIndex; } if (modal) { if (this._closing) { PopupManager.closeModal(this._popupId); this._closing = false; } PopupManager.openModal(this._popupId, PopupManager.nextZIndex(), this.modalAppendToBody ? undefined : dom, props.modalClass, props.modalFade); if (props.lockScroll) { if (!this.bodyOverflow) { this.bodyPaddingRight = document.body.style.paddingRight; this.bodyOverflow = document.body.style.overflow; } scrollBarWidth = getScrollBarWidth(); let bodyHasOverflow = document.documentElement.clientHeight < document.body.scrollHeight; if (scrollBarWidth > 0 && bodyHasOverflow) { document.body.style.paddingRight = scrollBarWidth + 'px'; } document.body.style.overflow = 'hidden'; } } if (getComputedStyle(dom).position === 'static') { dom.style.position = 'absolute'; } dom.style.zIndex = PopupManager.nextZIndex(); this.opened = true; this.onOpen && this.onOpen(); if (!this.transition) { this.doAfterOpen(); } }, doAfterOpen() { this._opening = false; }, close() { if (this.willClose && !this.willClose()) return; if (this._openTimer !== null) { clearTimeout(this._openTimer); this._openTimer = null; } clearTimeout(this._closeTimer); const closeDelay = Number(this.closeDelay); if (closeDelay > 0) { this._closeTimer = setTimeout(() => { this._closeTimer = null; this.doClose(); }, closeDelay); } else { this.doClose(); } }, doClose() { this.$emit('visible-change', false); this._closing = true; this.onClose && this.onClose(); if (this.lockScroll) { setTimeout(() => { if (this.modal && this.bodyOverflow !== 'hidden') { document.body.style.overflow = this.bodyOverflow; document.body.style.paddingRight = this.bodyPaddingRight; } this.bodyOverflow = null; this.bodyPaddingRight = null; }, 200); } this.opened = false; if (!this.transition) { this.doAfterClose(); } }, doAfterClose() { PopupManager.closeModal(this._popupId); this._closing = false; } } }; export { PopupManager };
package edu.gatech.oad.antlab.pkg1; import edu.cs2335.antlab.pkg3.*; import edu.gatech.oad.antlab.person.*; import edu.gatech.oad.antlab.pkg2.*; /** * CS2335 Ant Lab * * Prints out a simple message gathered from all of the other classes * in the package structure */ public class AntLabMain { /**antlab11.java message class*/ private AntLab11 ant11; /**antlab12.java message class*/ private AntLab12 ant12; /**antlab21.java message class*/ private AntLab21 ant21; /**antlab22.java message class*/ private AntLab22 ant22; /**antlab31 java message class which is contained in a jar resource file*/ private AntLab31 ant31; /** * the constructor that intializes all the helper classes */ public AntLabMain () { ant11 = new AntLab11(); ant12 = new AntLab12(); ant21 = new AntLab21(); ant22 = new AntLab22(); ant31 = new AntLab31(); } /** * gathers a string from all the other classes and prints the message * out to the console * */ public void printOutMessage() { String toPrint = ant11.getMessage() + ant12.getMessage() + ant21.getMessage() + ant22.getMessage() + ant31.getMessage(); //Person1 replace P1 with your name //and gburdell1 with your gt id Person1 p1 = new Person1("Pranov"); toPrint += p1.toString("pduggasani3"); //Person2 replace P2 with your name //and gburdell with your gt id Person2 p2 = new Person2("Austin Dang"); toPrint += p2.toString("adang31"); //Person3 replace P3 with your name //and gburdell3 with your gt id Person3 p3 = new Person3("Jay Patel"); toPrint += p3.toString("jpatel345"); //Person4 replace P4 with your name //and gburdell4 with your gt id Person4 p4 = new Person4("Jin Chung"); toPrint += p4.toString("jchung89"); //Person5 replace P4 with your name //and gburdell5 with your gt id Person5 p5 = new Person5("Zachary Hussin"); toPrint += p5.toString("zhussin3"); System.out.println(toPrint); } /** * entry point for the program */ public static void main(String[] args) { new AntLabMain().printOutMessage(); } }
package net.alloyggp.tournament.internal.admin; import net.alloyggp.escaperope.Delimiters; import net.alloyggp.escaperope.RopeDelimiter; import net.alloyggp.escaperope.rope.Rope; import net.alloyggp.escaperope.rope.ropify.SubclassWeaver; import net.alloyggp.escaperope.rope.ropify.Weaver; import net.alloyggp.tournament.api.TAdminAction; public class <API key> { private <API key>() { //Not instantiable } @SuppressWarnings("deprecation") public static final Weaver<TAdminAction> WEAVER = SubclassWeaver.builder(TAdminAction.class) .add(ReplaceGameAction.class, "ReplaceGame", ReplaceGameAction.WEAVER) .build(); public static RopeDelimiter <API key>() { return Delimiters.<API key>(); } public static TAdminAction fromPersistedString(String persistedString) { Rope rope = <API key>().undelimit(persistedString); return WEAVER.fromRope(rope); } public static String toPersistedString(TAdminAction adminAction) { Rope rope = WEAVER.toRope(adminAction); return <API key>().delimit(rope); } }
<div id="content-alerts"> <table id="conten-2" border="1px"> <tbody> <?php echo $sidemenu ?> <tr> <td style="vertical-align: top;"> <div style="padding: 5px 5px 5px 5px"> <table border="1" cellspacing="1px"> <tr style="background-color: #DBDBDB"> <th>ATM ID</th> <th>ĐẦU ĐỌC THẺ</th> <th>BỘ PHẬN TRẢ TIỀN</th> <th>BÀN PHÍM</th> <th>MÁY IN HÓA ĐƠN</th> <th>MẠNG</th> <th>SẴN SÀNG</th> </tr> <?php foreach ($result as $item) { echo "<tr>"; echo "<td>$item->AtmId</td>"; echo "<td>".(empty($item->CardReader) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->CashDispenser) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->PinPad) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->ReceiptPrinter) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->NetDown) ? "OK" : "Lỗi")."</td>"; echo "<td>".(empty($item->Service) ? "OK" : "Không")."</td>"; echo "</tr>"; } ?> </table> </div> </td> </tr> </tbody> </table> </div>
<?xml version="1.0" ?><!DOCTYPE TS><TS language="hr" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About TelcoCoin</source> <translation>O TelcoCoin-u</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;TelcoCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;TelcoCoin&lt;/b&gt; verzija</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http: This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http: <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The TelcoCoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adresar</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dvostruki klik za uređivanje adrese ili oznake</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Dodajte novu adresu</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopiraj trenutno odabranu adresu u međuspremnik</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Nova adresa</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your TelcoCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Ovo su vaše TelcoCoin adrese za primanje isplate. Možda želite dati drukčiju adresu svakom primatelju tako da možete pratiti tko je platio.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopirati adresu</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Prikaži &amp;QR Kôd</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a TelcoCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Izvoz podataka iz trenutnog taba u datoteku</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified TelcoCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Brisanje</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your TelcoCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopirati &amp;oznaku</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Izmjeniti</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Izvoz podataka adresara</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Datoteka vrijednosti odvojenih zarezom (*. csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Pogreška kod izvoza</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ne mogu pisati u datoteku %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Oznaka</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(bez oznake)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Unesite lozinku</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova lozinka</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ponovite novu lozinku</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Unesite novi lozinku za novčanik. &lt;br/&gt; Molimo Vas da koristite zaporku od &lt;b&gt;10 ili više slučajnih znakova,&lt;/b&gt; ili &lt;b&gt;osam ili više riječi.&lt;/b&gt;</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Šifriranje novčanika</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ova operacija treba lozinku vašeg novčanika kako bi se novčanik otključao.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Otključaj novčanik</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ova operacija treba lozinku vašeg novčanika kako bi se novčanik dešifrirao.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Dešifriranje novčanika.</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Promjena lozinke</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Unesite staru i novu lozinku za novčanik.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Potvrdi šifriranje novčanika</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR TelcoCoinS&lt;/b&gt;!</source> <translation>Upozorenje: Ako šifrirate vaš novčanik i izgubite lozinku, &lt;b&gt;IZGUBIT ĆETE SVE SVOJE TelcoCoinSE!&lt;/b&gt;</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Jeste li sigurni da želite šifrirati svoj novčanik?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Novčanik šifriran</translation> </message> <message> <location line="-56"/> <source>TelcoCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your TelcoCoins from being stolen by malware infecting your computer.</source> <translation>TelcoCoin će se sada zatvoriti kako bi dovršio postupak šifriranja. Zapamtite da šifriranje vašeg novčanika ne može u potpunosti zaštititi vaše TelcoCoine od krađe preko zloćudnog softvera koji bi bio na vašem računalu.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Šifriranje novčanika nije uspjelo</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Šifriranje novčanika nije uspjelo zbog interne pogreške. Vaš novčanik nije šifriran.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Priložene lozinke se ne podudaraju.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Otključavanje novčanika nije uspjelo</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Lozinka za dešifriranje novčanika nije točna.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Dešifriranje novčanika nije uspjelo</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Lozinka novčanika je uspješno promijenjena.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Potpišite poruku...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Usklađivanje s mrežom ...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Pregled</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Prikaži opći pregled novčanika</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transakcije</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Pretraži povijest transakcija</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels for sending</source> <translation>Uređivanje popisa pohranjenih adresa i oznaka</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Prikaži popis adresa za primanje isplate</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Izlaz</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Izlazak iz programa</translation> </message> <message> <location line="+4"/> <source>Show information about TelcoCoin</source> <translation>Prikaži informacije o TelcoCoinu</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Više o &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Prikaži informacije o Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Postavke</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Šifriraj novčanik...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup novčanika...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Promijena lozinke...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importiranje blokova sa diska...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Re-indeksiranje blokova na disku...</translation> </message> <message> <location line="-347"/> <source>Send coins to a TelcoCoin address</source> <translation>Slanje novca na TelcoCoin adresu</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for TelcoCoin</source> <translation>Promijeni postavke konfiguracije za TelcoCoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Napravite sigurnosnu kopiju novčanika na drugoj lokaciji</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Promijenite lozinku za šifriranje novčanika</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>TelcoCoin</source> <translation>TelcoCoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Novčanik</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About TelcoCoin</source> <translation>&amp;O TelcoCoinu</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your TelcoCoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified TelcoCoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Datoteka</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Konfiguracija</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Pomoć</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Traka kartica</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>TelcoCoin client</source> <translation>TelcoCoin klijent</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to TelcoCoin network</source> <translation><numerusform>%n aktivna veza na TelcoCoin mrežu</numerusform><numerusform>%n aktivne veze na TelcoCoin mrežu</numerusform><numerusform>%n aktivnih veza na TelcoCoin mrežu</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Obrađeno %1 blokova povijesti transakcije.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Greška</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Ažurno</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Ažuriranje...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Poslana transakcija</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Dolazna transakcija</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum:%1 Iznos:%2 Tip:%3 Adresa:%4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid TelcoCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Novčanik je &lt;b&gt;šifriran&lt;/b&gt; i trenutno &lt;b&gt;otključan&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Novčanik je &lt;b&gt;šifriran&lt;/b&gt; i trenutno &lt;b&gt;zaključan&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. TelcoCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Izmjeni adresu</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Oznaka</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Oznaka ovog upisa u adresar</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresa</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adresa ovog upisa u adresar. Može se mjenjati samo kod adresa za slanje.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nova adresa za primanje</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nova adresa za slanje</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Uredi adresu za primanje</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Uredi adresu za slanje</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Upisana adresa &quot;%1&quot; je već u adresaru.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid TelcoCoin address.</source> <translation>Upisana adresa &quot;%1&quot; nije valjana TelcoCoin adresa.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Ne mogu otključati novčanik.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Stvaranje novog ključa nije uspjelo.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>TelcoCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation>verzija</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Upotreba:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI postavke</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Pokreni minimiziran</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Postavke</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Glavno</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Plati &amp;naknadu za transakciju</translation> </message> <message> <location line="+31"/> <source>Automatically start TelcoCoin after logging in to the system.</source> <translation>Automatski pokreni TelcoCoin kad se uključi računalo</translation> </message> <message> <location line="+3"/> <source>&amp;Start TelcoCoin on system login</source> <translation>&amp;Pokreni TelcoCoin kod pokretanja sustava</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the TelcoCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatski otvori port TelcoCoin klijenta na ruteru. To radi samo ako ruter podržava UPnP i ako je omogućen.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapiraj port koristeći &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the TelcoCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Spojite se na Bitcon mrežu putem SOCKS proxy-a (npr. kod povezivanja kroz Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Povezivanje putem SOCKS proxy-a:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP adresa proxy-a (npr. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Port od proxy-a (npr. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Prikaži samo ikonu u sistemskoj traci nakon minimiziranja prozora</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimiziraj u sistemsku traku umjesto u traku programa</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimizirati umjesto izaći iz aplikacije kada je prozor zatvoren. Kada je ova opcija omogućena, aplikacija će biti zatvorena tek nakon odabira Izlaz u izborniku.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimiziraj kod zatvaranja</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Prikaz</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting TelcoCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Jedinica za prikazivanje iznosa:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Izaberite željeni najmanji dio TelcoCoina koji će biti prikazan u sučelju i koji će se koristiti za plaćanje.</translation> </message> <message> <location line="+9"/> <source>Whether to show TelcoCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Prikaži adrese u popisu transakcija</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Upozorenje</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting TelcoCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Oblik</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the TelcoCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Stanje:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Nepotvrđene:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Novčanik</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Nedavne transakcije&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Vaše trenutno stanje računa</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Ukupni iznos transakcija koje tek trebaju biti potvrđene, i još uvijek nisu uračunate u trenutni saldo</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start TelcoCoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR Code Dijalog</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Zatraži plaćanje</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Iznos:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Oznaka</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Poruka:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Spremi kao...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Rezultirajući URI je predug, probajte umanjiti tekst za naslov / poruku.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG slike (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Lanac blokova</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Trenutni broj blokova</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Procjenjeni ukupni broj blokova</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Posljednje vrijeme bloka</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the TelcoCoin-Qt help message to get a list with possible TelcoCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>TelcoCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>TelcoCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the TelcoCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the TelcoCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Slanje novca</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Pošalji k nekoliko primatelja odjednom</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Dodaj primatelja</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Obriši sva polja transakcija</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Obriši &amp;sve</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Stanje:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123,456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Potvrdi akciju slanja</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Pošalji</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; do %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Potvrdi slanje novca</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Jeste li sigurni da želite poslati %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>i</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Adresa primatelja je nevaljala, molimo provjerite je ponovo.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Iznos mora biti veći od 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Iznos je veći od stanja računa.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Iznos je veći od stanja računa kad se doda naknada za transakcije od %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Pronašli smo adresu koja se ponavlja. U svakom plaćanju program može svaku adresu koristiti samo jedanput.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Generirani novčići moraju pričekati nastanak 120 blokova prije nego što ih je moguće potrošiti. Kad ste generirali taj blok, on je bio emitiran u mrežu kako bi bio dodan postojećim lancima blokova. Ako ne uspije biti dodan, njegov status bit će promijenjen u &quot;nije prihvatljiv&quot; i on neće biti potrošiv. S vremena na vrijeme tako nešto se može desiti ako neki drugi nod približno istovremeno generira blok.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Oblik</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Iznos:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Primatelj plaćanja:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. <API key>)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Unesite oznaku za ovu adresu kako bi ju dodali u vaš adresar</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Oznaka:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Odaberite adresu iz adresara</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Zalijepi adresu iz međuspremnika</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Ukloni ovog primatelja</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a TelcoCoin address (e.g. <API key>)</source> <translation>Unesite TelcoCoin adresu (npr. <API key>)</translation> </message> </context> <context> <name><API key></name> <message> <location filename="../forms/<API key>.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Potpišite poruku</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Možete potpisati poruke sa svojom adresom kako bi dokazali da ih posjedujete. Budite oprezni da ne potpisujete ništa mutno, jer bi vas phishing napadi mogli na prevaru natjerati da prepišete svoj identitet njima. Potpisujte samo detaljno objašnjene izjave sa kojima se slažete.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. <API key>)</source> <translation>Unesite TelcoCoin adresu (npr. <API key>)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Odaberite adresu iz adresara</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Zalijepi adresu iz međuspremnika</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Upišite poruku koju želite potpisati ovdje</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this TelcoCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Obriši &amp;sve</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. <API key>)</source> <translation>Unesite TelcoCoin adresu (npr. <API key>)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified TelcoCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../<API key>.cpp" line="+27"/> <location line="+3"/> <source>Enter a TelcoCoin address (e.g. <API key>)</source> <translation>Unesite TelcoCoin adresu (npr. <API key>)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter TelcoCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The TelcoCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Otvoren do %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1 nije dostupan</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nepotvrđeno</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 potvrda</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generiran</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Od</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Za</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>oznaka</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Uplaćeno</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>Nije prihvaćeno</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Zaduženje</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Naknada za transakciju</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Neto iznos</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Poruka</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Komentar</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Generirani novčići moraju pričekati nastanak 120 blokova prije nego što ih je moguće potrošiti. Kad ste generirali taj blok, on je bio emitiran u mrežu kako bi bio dodan postojećim lancima blokova. Ako ne uspije biti dodan, njegov status bit će promijenjen u &quot;nije prihvaćen&quot; i on neće biti potrošiv. S vremena na vrijeme tako nešto se može desiti ako neki drugi nod generira blok u približno isto vrijeme.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Iznos</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, još nije bio uspješno emitiran</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>nepoznato</translation> </message> </context> <context> <name><API key></name> <message> <location filename="../forms/<API key>.ui" line="+14"/> <source>Transaction details</source> <translation>Detalji transakcije</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Ova panela prikazuje detaljni opis transakcije</translation> </message> </context> <context> <name><API key></name> <message> <location filename="../<API key>.cpp" line="+225"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tip</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Iznos</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Otvoren do %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Nije na mreži (%1 potvrda)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepotvrđen (%1 od %2 potvrda)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Potvrđen (%1 potvrda)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Generirano - Upozorenje: ovaj blok nije bio primljen od strane bilo kojeg drugog noda i vjerojatno neće biti prihvaćen!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generirano, ali nije prihvaćeno</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Primljeno s</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Primljeno od</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Poslano za</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Plaćanje samom sebi</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Rudareno</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/d)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status transakcije</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum i vrijeme kad je transakcija primljena</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Vrsta transakcije.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Odredište transakcije</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Iznos odbijen od ili dodan k saldu.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Sve</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Danas</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Ovaj tjedan</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Ovaj mjesec</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Prošli mjesec</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Ove godine</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Raspon...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Primljeno s</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Poslano za</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Tebi</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Rudareno</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Ostalo</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Unesite adresu ili oznaku za pretraživanje</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min iznos</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopirati adresu</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopirati oznaku</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopiraj iznos</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Izmjeniti oznaku</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Izvoz podataka transakcija</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Datoteka podataka odvojenih zarezima (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Potvrđeno</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tip</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Oznaka</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Iznos</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Izvoz pogreške</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ne mogu pisati u datoteku %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Raspon:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>za</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Slanje novca</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Izvoz podataka iz trenutnog taba u datoteku</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>TelcoCoin version</source> <translation>TelcoCoin verzija</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Upotreba:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or TelcoCoind</source> <translation>Pošalji komandu usluzi -server ili TelcoCoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Prikaži komande</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Potraži pomoć za komandu</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Postavke:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: TelcoCoin.conf)</source> <translation>Odredi konfiguracijsku datoteku (ugrađeni izbor: TelcoCoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: TelcoCoind.pid)</source> <translation>Odredi proces ID datoteku (ugrađeni izbor: TelcoCoin.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Odredi direktorij za datoteke</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Postavi cache za bazu podataka u MB (zadano:25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 22556 or testnet: 44556)</source> <translation>Slušaj na &lt;port&gt;u (default: 22556 ili testnet: 44556)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Održavaj najviše &lt;n&gt; veza sa članovima (default: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Prag za odspajanje članova koji se čudno ponašaju (default: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Broj sekundi koliko se članovima koji se čudno ponašaju neće dopustiti da se opet spoje (default: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 22555 or testnet: 44555)</source> <translation>Prihvaćaj JSON-RPC povezivanje na portu broj &lt;port&gt; (ugrađeni izbor: 22555 or testnet: 44555)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Prihvati komande iz tekst moda i JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Izvršavaj u pozadini kao uslužnik i prihvaćaj komande</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Koristi test mrežu</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=TelcoCoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;TelcoCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. TelcoCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Upozorenje: -paytxfee je podešen na preveliki iznos. To je iznos koji ćete platiti za obradu transakcije.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong TelcoCoin will not work properly.</source> <translation>Upozorenje: Molimo provjerite jesu li datum i vrijeme na vašem računalu točni. Ako vaš sat ide krivo, TelcoCoin neće raditi ispravno.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opcije za kreiranje bloka:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Poveži se samo sa određenim nodom</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importiraj blokove sa vanjskog blk000??.dat fajla</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Nevaljala -tor adresa: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Prihvati samo lance blokova koji se podudaraju sa ugrađenim checkpoint-ovima (default: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp (default: 1)</source> <translation>Dodaj izlaz debuga na početak sa vremenskom oznakom</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the TelcoCoin Wiki for SSL setup instructions)</source> <translation>SSL postavke: (za detalje o podešavanju SSL opcija vidi TelcoCoin Wiki)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Šalji trace/debug informacije na konzolu umjesto u debug.log datoteku</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Pošalji trace/debug informacije u debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Podesite maksimalnu veličinu bloka u bajtovima (default: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Podesite minimalnu veličinu bloka u bajtovima (default: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Odredi vremenski prozor za spajanje na mrežu u milisekundama (ugrađeni izbor: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Pokušaj koristiti UPnP da otvoriš port za uslugu (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Pokušaj koristiti UPnP da otvoriš port za uslugu (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Korisničko ime za JSON-RPC veze</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Lozinka za JSON-RPC veze</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Dozvoli JSON-RPC povezivanje s određene IP adrese</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Pošalji komande nodu na adresi &lt;ip&gt; (ugrađeni izbor: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Izvršite naredbu kada se najbolji blok promjeni (%s u cmd je zamjenjen sa block hash)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Nadogradite novčanik u posljednji format.</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Podesi memorijski prostor za ključeve na &lt;n&gt; (ugrađeni izbor: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ponovno pretraži lanac blokova za transakcije koje nedostaju</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Koristi OpenSSL (https) za JSON-RPC povezivanje</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Uslužnikov SSL certifikat (ugrađeni izbor: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Uslužnikov privatni ključ (ugrađeni izbor: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Prihvaljivi načini šifriranja (ugrađeni izbor: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Ova poruka za pomoć</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Program ne može koristiti %s na ovom računalu (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Poveži se kroz socks proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Dozvoli DNS upite za dodavanje nodova i povezivanje</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Učitavanje adresa...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Greška kod učitavanja wallet.dat: Novčanik pokvaren</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of TelcoCoin</source> <translation>Greška kod učitavanja wallet.dat: Novčanik zahtjeva noviju verziju TelcoCoina</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart TelcoCoin to complete</source> <translation>Novčanik je trebao prepravak: ponovo pokrenite TelcoCoin</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Greška kod učitavanja wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Nevaljala -proxy adresa: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Nevaljali iznos za opciju -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Nevaljali iznos za opciju</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Nedovoljna sredstva</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Učitavanje indeksa blokova...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Unesite nod s kojim se želite spojiti and attempt to keep the connection open</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. TelcoCoin is probably already running.</source> <translation>Program ne može koristiti %s na ovom računalu. TelcoCoin program je vjerojatno već pokrenut.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Naknada posredniku po KB-u koja će biti dodana svakoj transakciji koju pošalješ</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Učitavanje novčanika...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Nije moguće novčanik vratiti na prijašnju verziju.</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Nije moguće upisati zadanu adresu.</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Rescaniranje</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Učitavanje gotovo</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>Greška</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
Kmom05 ============================ Redovisning av kmom05. <b>Berätta kort om erfarenheterna med din undersökning av webbplatsers laddningstid. </b> <p>Jag valde samma hemsidor som I förra uppgiften då jag vet att dessa hemsidor har varierande belastning och trafiksituationer som de måste hantera. Tre av sidorna är stora internationella företag och speciellt Reddit och Twitch har hundratusentals om inte miljoner användare varje dag så för dessa är det viktigt att ha snabba laddtider. </p> <p>Twitch har en laddtid på mellan 7 – 8 sec och det tycker jag är rätt högt, men samtidigt måste man komma ihåg att det är utan cache och så handlar det om live stream. Vad orsaken kan vara att laddtiden är så hög kan jag inte svara på, men det är lite konstigt att deras blogg som till exempel bara är 1.1MB tar lika lång tid att ladda som deras “directory” med alla spel och som är 4.5MB. När det gäller laddtiden på mobil och data så laddar sidan snabbare på mobilen vilket också är rätt konstigt då sidan inte är speciellt bra anpassad för mobiler.</p> <p>Reddit har lite verierende laddtider, men den förmodligen viktigaste sidan är deras startsida och den har en hyfsat bra laddtid. När det gäller de andra två sidorna som jag testa så känns bloggsidan väldigt stor med sina 21.4 MB och 17 sec I laddtid. Jag tänkte först ta och kolla laddtiden på några subreddits, men jag det vissa sig att dessa ha ungefär samma laddtid som startsidan och det är väl egentligen inte så konstigt då de vissar / hämtar samma typ av innehåll. </p> <p>När det gäller Netflix så tror jag inte deras hemsida är speciellt hårt belastad då den egentligen endast behövs för att skapa konton till nya kunder. </p> <p>Till sist har vi Avanza som är en av de ledande bankerna I sverige när det gäller aktie och fondhandel bland småsparare och något som gör den här sidan intressant är att de erbjuder marknadsdata I realtid vilket påverkar laddtiden negativt.</p> <b>Har du några funderingar kring Cimage och dess nytta och features? </b> <p>Jag tycker Cimage var en väldigt bra lösning speciellt då man slipper hålla på och redigera bilderna så de får rätt storlek I tex Photoshop, nu kunde man istället ange bildens storlek direkt I bildlänken. Men sen kan jag tänka mig att det belastar server och har man massa bilder så kanske det inte är den bästa lösningen, men på en mindre hemsida där man inte har så höga krav på en super snabb sida så skulle Cimage vara en bra lösning. </p> <b>Lyckades du uppnå ett bra sätt och en LESS-struktur för att jobba med dina bilder i webbplatsen? </b> <p>Jag gjorde egentligen inga ändringar I LESS modulen för figures då jag tyckte det fungera bra med min andra kod och bilderna kollapsar på rätt ställe när sidan blir mindre. Jag hade lite planer på att lägga till några klasser för w75 och w100, men eftersom jag använde Cimage för att bestämma storleken så strunta jag I det då jag inte tror jag kommer ha någon nytta för det.</p> <b>I extrauppgiften om picture, srcset och sizes, fick du någon känsla för för- och nackdelar med konceptet? </b> <p>Jag läste lite om srcset för det var ingen jag har hört talas om innan och det verkar intressat så det är helt klart något jag ska ta med mig I framtiden och kanske försöka använda.</p>
{{< layout}} {{$pageTitle}}Upload your photo{{/pageTitle}} {{$header}} <h1>Upload your photo</h1> {{/header}} {{$content}} <p >Your photo must be taken in the last month and meet the <br><a href="/../<API key>/photoguide-static/photorules"> rules for passport photos</a>.</p> <a href="/<API key>/uploadphoto/" class="button">Upload your photo</a><br/><br/> <div class="grid-row photo-upload-eg"> <div class="column-half img"> <object type="image/jpg" data="/public/images/<API key>@2x.jpg" type="image/svg+xml" class="svg" tabindex="-1"> <img src="/public/images/<API key>@2x.jpg" width="206" height= alt=""> </object> </div> <div class="column-half"> <h2>Taking a good photo</h2> <ol class="list list-number"> <li>Get a friend to take your photo.</li> <li>Use a plain background.</li> <li>Don’t crop your photo, include your face, shoulders and upper body.</li> <li>Keep your hair away from your face and brushed down.</li> <li>Make sure there are no shadows on your face or behind you.</li> </ol> </div> </div> <br/> <p> We keep all photos for up to 30 days in line with our <a href="https: </p> {{/content}} {{/ layout}}
<?php namespace BungieNetPlatform\Exceptions\Platform; use BungieNetPlatform\Exceptions\PlatformException; /** * <API key> */ class <API key> extends PlatformException { public function __construct($message, $code = 1608, \Exception $previous = null) { parent::__construct($message, $code, $previous); } }
<!DOCTYPE html> <html xmlns="http: xmlns:th="http: xmlns:sec="http: <head> <title>System Manager Dashboard</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" th:href="@{/webjars/bootstrap/3.3.6/css/bootstrap.min.css}" /> <script th:src="@{/webjars/jquery/2.1.4/jquery.min.js}"></script> <script th:src="@{/webjars/bootstrap/3.3.6/js/bootstrap.min.js}"></script> <script> $(document).ready(function () { (function ($) { $('#filter').keyup(function () { var rex = new RegExp($(this).val(), 'i'); $('.searchable tr').hide(); $('.searchable tr').filter(function () { return rex.test($(this).text()); }).show(); }) }(jQuery)); }); </script> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <p class="navbar-brand">Cardinals Banking</p> </div> <ul class="nav navbar-nav navbar-right"> <li><a th:href="@{/manager/details}">My Dashboard</a></li> <li><a th:href="@{/logout}">Logout</a></li> </ul> </div> </nav> <div class="container"> <h3>System Manager Dashboard</h3> <ul class="nav nav-tabs nav-justified"> <li><a th:href="@{/manager/user}">View External User Accounts</a></li> <li><a th:href="@{/manager/details}">My Profile</a></li> <li><a th:href="@{/manager/user/request}">New External User Requests</a></li> <li><a th:href="@{/manager/employee/authorize}">Authorize Access</a></li> <li><a th:href="@{/manager/employee/request}">View Access Requests</a></li> <li class="active"><a href="#">Pending Transfers</a></li> <li><a th:href="@{/manager/transactions}">Pending Transactions</a></li> </ul> </div> <div class="container"> <div class="input-group"> <span class="input-group-addon">Filter</span> <input id="filter" type="text" class="form-control" placeholder="Type here..." /> </div> <div class="container"> <table class="table table-striped"> <thead> <tr> <th>From</th> <th>Account Number</th> <th>To</th> <th>Account Number</th> <th>Amount</th> </tr> </thead> <tbody class="searchable"> <tr th:each="transfer : ${transfers}"> <td th:text="${transfer.fromAccount.user.username}"></td> <td th:text="${transfer.fromAccount.accountNumber}"></td> <td th:text="${transfer.toAccount.user.username}"></td> <td th:text="${transfer.toAccount.accountNumber}"></td> <td th:text="${transfer.amount}"></td> <td><a th:href="@{/manager/transfer/{id}(id=${transfer.transferId})}">View</a></td> </tr> </tbody> </table> </div> </div> </body> </html>
$LOAD_PATH.unshift File.expand_path('../lib') require 'rspec' RSpec.configure do |conf| conf.color = true conf.formatter = 'documentation' conf.order = 'random' end
(function () { 'use strict'; /** * @ngdoc function * @name app.test:homeTest * @description * # homeTest * Test of the app */ describe('homeCtrl', function () { var controller = null, $scope = null, $location; beforeEach(function () { module('g4mify-client-app'); }); beforeEach(inject(function ($controller, $rootScope, _$location_) { $scope = $rootScope.$new(); $location = _$location_; controller = $controller('HomeCtrl', { $scope: $scope }); })); it('Should HomeCtrl must be defined', function () { expect(controller).toBeDefined(); }); it('Should match the path Module name', function () { $location.path('/home'); expect($location.path()).toBe('/home'); }); }); })();
var eejs = require('ep_etherpad-lite/node/eejs') /* * Handle incoming delete requests from clients */ exports.handleMessage = function(hook_name, context, callback){ var Pad = require('ep_etherpad-lite/node/db/Pad.js').Pad // Firstly ignore any request that aren't about chat var isDeleteRequest = false; if(context) { if(context.message && context.message){ if(context.message.type === 'COLLABROOM'){ if(context.message.data){ if(context.message.data.type){ if(context.message.data.type === 'ep_push2delete'){ isDeleteRequest = true; } } } } } } if(!isDeleteRequest){ callback(false); return false; } console.log('DELETION REQUEST!') var packet = context.message.data; if(packet.action === 'deletePad'){ var pad = new Pad(packet.padId) pad.remove(function(er) { if(er) console.warn('ep_push2delete', er) callback([null]); }) } } exports.<API key> = function(hook_name, args, cb) { if(!args.renderContext.req.url.match(/^\/(p\/r\..{16})/)) { args.content = eejs.require('ep_push2delete/templates/delete_button.ejs') + args.content; } cb(); };
using Microsoft.Xna.Framework; using System; namespace Gem.Gui.Animations { public static class Time { public static Animation<double> Elapsed { get { return Animation.Create(context => context.TotalMilliseconds); } } public static Animation<TTime> Constant<TTime>(TTime time) { return Animation.Create(context => time); } public static Animation<double> Wave { get { return Animation.Create(context => Math.Sin(context.TotalSeconds)); } } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Coq bench</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif] </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../../..">Unstable</a></li> <li><a href=".">8.4.dev / contrib:sudoku 8.4.dev</a></li> <li class="active"><a href="">2015-01-30 03:04:02</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="../../../../../about.html">About</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href=".">« Up</a> <h1> contrib:sudoku <small> 8.4.dev <span class="label label-success">41 s</span> </small> </h1> <p><em><script>document.write(moment("2015-01-30 03:04:02 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2015-01-30 03:04:02 UTC)</em><p> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:sudoku/coq:contrib:sudoku.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>The package is valid. </pre></dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --dry-run coq:contrib:sudoku.8.4.dev coq.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.4.dev). The following actions will be performed: - install coq:contrib:sudoku.8.4.dev 1 to install === =-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= =-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Building coq:contrib:sudoku.8.4.dev: coq_makefile -f Make -o Makefile make -j4 make install Installing coq:contrib:sudoku.8.4.dev. </pre></dd> </dl> <p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ulimit -Sv 2000000; timeout 5m opam install -y --deps-only coq:contrib:sudoku.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ulimit -Sv 2000000; timeout 5m opam install -y --verbose coq:contrib:sudoku.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>41 s</dd> <dt>Output</dt> <dd><pre>The following actions will be performed: - install coq:contrib:sudoku.8.4.dev 1 to install === =-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= [coq:contrib:sudoku] Fetching https://gforge.inria.fr/git/coq-contribs/sudoku.git#v8.4 Initialized empty Git repository in /home/bench/.opam/packages.dev/coq:contrib:sudoku.8.4.dev/.git/ [master (root-commit) 479e1a9] opam-git-init From https://gforge.inria.fr/git/coq-contribs/sudoku * [new branch] v8.4 -&gt; opam-ref * [new branch] v8.4 -&gt; origin/v8.4 Div.v LICENSE ListAux.v ListOp.v Make Makefile Note.pdf OrderedList.v Permutation.v README Sudoku.v Tactic.v Test.v UList.v bench.log description HEAD is now at 71a653c Removing useless calls to injection. =-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Building coq:contrib:sudoku.8.4.dev: coq_makefile -f Make -o Makefile make -j4 make install &quot;coqdep&quot; -c -slash -R . Sudoku &quot;Div.v&quot; &gt; &quot;Div.v.d&quot; || ( RV=$?; rm -f &quot;Div.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;ListAux.v&quot; &gt; &quot;ListAux.v.d&quot; || ( RV=$?; rm -f &quot;ListAux.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;ListOp.v&quot; &gt; &quot;ListOp.v.d&quot; || ( RV=$?; rm -f &quot;ListOp.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;OrderedList.v&quot; &gt; &quot;OrderedList.v.d&quot; || ( RV=$?; rm -f &quot;OrderedList.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;Permutation.v&quot; &gt; &quot;Permutation.v.d&quot; || ( RV=$?; rm -f &quot;Permutation.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;Sudoku.v&quot; &gt; &quot;Sudoku.v.d&quot; || ( RV=$?; rm -f &quot;Sudoku.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;Tactic.v&quot; &gt; &quot;Tactic.v.d&quot; || ( RV=$?; rm -f &quot;Tactic.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;Test.v&quot; &gt; &quot;Test.v.d&quot; || ( RV=$?; rm -f &quot;Test.v.d&quot;; exit ${RV} ) &quot;coqdep&quot; -c -slash -R . Sudoku &quot;UList.v&quot; &gt; &quot;UList.v.d&quot; || ( RV=$?; rm -f &quot;UList.v.d&quot;; exit ${RV} ) &quot;coqc&quot; -q -R . Sudoku Tactic &quot;coqc&quot; -q -R . Sudoku ListAux &quot;coqc&quot; -q -R . Sudoku Div &quot;coqc&quot; -q -R . Sudoku Permutation &quot;coqc&quot; -q -R . Sudoku UList &quot;coqc&quot; -q -R . Sudoku OrderedList &quot;coqc&quot; -q -R . Sudoku ListOp &quot;coqc&quot; -q -R . Sudoku Sudoku &quot;coqc&quot; -q -R . Sudoku Test = 288 : nat = 2 :: 5 :: 8 :: 1 :: 6 :: 4 :: 9 :: 7 :: 3 :: nil : list nat = 6 :: 3 :: 4 :: 9 :: 5 :: 7 :: 2 :: 1 :: 8 :: nil : list nat = 9 :: 7 :: 1 :: 2 :: 3 :: 8 :: 6 :: 4 :: 5 :: nil : list nat = 7 :: 4 :: 5 :: 3 :: 9 :: 1 :: 8 :: 2 :: 6 :: nil : list nat = 8 :: 9 :: 6 :: 4 :: 2 :: 5 :: 1 :: 3 :: 7 :: nil : list nat = 1 :: 2 :: 3 :: 7 :: 8 :: 6 :: 4 :: 5 :: 9 :: nil : list nat = 3 :: 6 :: 9 :: 5 :: 1 :: 2 :: 7 :: 8 :: 4 :: nil : list nat = 4 :: 8 :: 2 :: 6 :: 7 :: 3 :: 5 :: 9 :: 1 :: nil : list nat = 5 :: 1 :: 7 :: 8 :: 4 :: 9 :: 3 :: 6 :: 2 :: nil : list nat = 1 : nat = 4 :: 5 :: 6 :: 9 :: 8 :: 7 :: 2 :: 1 :: 3 :: nil : list nat = 8 :: 3 :: 9 :: 2 :: 1 :: 5 :: 7 :: 6 :: 4 :: nil : list nat = 1 :: 2 :: 7 :: 6 :: 4 :: 3 :: 8 :: 5 :: 9 :: nil : list nat = 7 :: 4 :: 2 :: 3 :: 6 :: 9 :: 5 :: 8 :: 1 :: nil : list nat = 5 :: 6 :: 3 :: 8 :: 2 :: 1 :: 4 :: 9 :: 7 :: nil : list nat = 9 :: 8 :: 1 :: 7 :: 5 :: 4 :: 6 :: 3 :: 2 :: nil : list nat = 2 :: 7 :: 8 :: 1 :: 3 :: 6 :: 9 :: 4 :: 5 :: nil : list nat = 6 :: 1 :: 5 :: 4 :: 9 :: 2 :: 3 :: 7 :: 8 :: nil : list nat = 3 :: 9 :: 4 :: 5 :: 7 :: 8 :: 1 :: 2 :: 6 :: nil : list nat = 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: 8 :: 9 :: nil : list nat = 7 :: 8 :: 9 :: 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: nil : list nat = 4 :: 5 :: 6 :: 9 :: 7 :: 8 :: 1 :: 2 :: 3 :: nil : list nat = 9 :: 1 :: 2 :: 8 :: 6 :: 5 :: 3 :: 4 :: 7 :: nil : list nat = 8 :: 3 :: 4 :: 7 :: 1 :: 2 :: 9 :: 6 :: 5 :: nil : list nat = 5 :: 6 :: 7 :: 3 :: 4 :: 9 :: 8 :: 1 :: 2 :: nil : list nat = 2 :: 9 :: 1 :: 5 :: 3 :: 4 :: 6 :: 7 :: 8 :: nil : list nat = 3 :: 7 :: 5 :: 6 :: 8 :: 1 :: 2 :: 9 :: 4 :: nil : list nat = 6 :: 4 :: 8 :: 2 :: 9 :: 7 :: 5 :: 3 :: 1 :: nil : list nat = Some (1 :: nil) : option (list nat) = Some (1 :: 2 :: 2 :: 1 :: nil) : option (list nat) = Some (1 :: 2 :: 3 :: 4 :: 3 :: 4 :: 1 :: 2 :: 2 :: 1 :: 4 :: 3 :: 4 :: 3 :: 2 :: 1 :: nil) : option (list nat) = Some (1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 5 :: 6 :: 1 :: 2 :: 3 :: 4 :: 3 :: 4 :: 5 :: 6 :: 1 :: 2 :: 2 :: 1 :: 4 :: 3 :: 6 :: 5 :: 6 :: 5 :: 2 :: 1 :: 4 :: 3 :: 4 :: 3 :: 6 :: 5 :: 2 :: 1 :: nil) : option (list nat) = Some (1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: 8 :: 9 :: 7 :: 8 :: 9 :: 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 4 :: 5 :: 6 :: 9 :: 7 :: 8 :: 1 :: 2 :: 3 :: 9 :: 1 :: 2 :: 8 :: 6 :: 5 :: 3 :: 4 :: 7 :: 8 :: 3 :: 4 :: 7 :: 1 :: 2 :: 9 :: 6 :: 5 :: 5 :: ..) : option (list nat) Finished transaction in 1. secs (1.812374u,1.8e-05s) = 7 :: 2 :: 4 :: 9 :: 6 :: 5 :: 8 :: 3 :: 1 :: nil : list nat = 6 :: 3 :: 5 :: 1 :: 4 :: 8 :: 9 :: 2 :: 7 :: nil : list nat = 1 :: 8 :: 9 :: 2 :: 7 :: 3 :: 4 :: 5 :: 6 :: nil : list nat = 2 :: 6 :: 1 :: 4 :: 8 :: 9 :: 3 :: 7 :: 5 :: nil : list nat = 9 :: 5 :: 8 :: 6 :: 3 :: 7 :: 1 :: 4 :: 2 :: nil : list nat = 3 :: 4 :: 7 :: 5 :: 2 :: 1 :: 6 :: 9 :: 8 :: nil : list nat = 5 :: 7 :: 6 :: 3 :: 1 :: 4 :: 2 :: 8 :: 9 :: nil : list nat = 4 :: 9 :: 2 :: 8 :: 5 :: 6 :: 7 :: 1 :: 3 :: nil : list nat = 8 :: 1 :: 3 :: 7 :: 9 :: 2 :: 5 :: 6 :: 4 :: nil : list nat = 25 : nat Finished transaction in 6. secs (6.283789u,1.1e-05s) Finished transaction in 3. secs (3.29798u,8.00000000001e-06s) = 5 :: 8 :: 6 :: 2 :: 3 :: 7 :: 9 :: 1 :: 4 :: nil : list nat = 7 :: 4 :: 2 :: 8 :: 1 :: 9 :: 3 :: 5 :: 6 :: nil : list nat = 1 :: 9 :: 3 :: 4 :: 6 :: 5 :: 7 :: 8 :: 2 :: nil : list nat = 6 :: 5 :: 7 :: 9 :: 8 :: 1 :: 2 :: 4 :: 3 :: nil : list nat = 9 :: 1 :: 4 :: 7 :: 2 :: 3 :: 5 :: 6 :: 8 :: nil : list nat = 2 :: 3 :: 8 :: 5 :: 4 :: 6 :: 1 :: 7 :: 9 :: nil : list nat = 3 :: 6 :: 5 :: 1 :: 9 :: 8 :: 4 :: 2 :: 7 :: nil : list nat = 4 :: 7 :: 9 :: 6 :: 5 :: 2 :: 8 :: 3 :: 1 :: nil : list nat = 8 :: 2 :: 1 :: 3 :: 7 :: 4 :: 6 :: 9 :: 5 :: nil : list nat = 1 : nat Finished transaction in 3. secs (3.310704u,0.s) for i in UList.vo Test.vo Tactic.vo Sudoku.vo Permutation.vo OrderedList.vo ListOp.vo ListAux.vo Div.vo; do \ install -d `dirname &quot;/home/bench/.opam/system/lib/coq/user-contrib&quot;/Sudoku/$i`; \ install -m 0644 $i &quot;/home/bench/.opam/system/lib/coq/user-contrib&quot;/Sudoku/$i; \ done Installing coq:contrib:sudoku.8.4.dev. </pre></dd> </dl> <h2>Installation size</h2> <p>Total: 963 K</p> <ul> <li>413 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/Sudoku.vo</code></li> <li>167 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/Permutation.vo</code></li> <li>111 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/OrderedList.vo</code></li> <li>87 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/ListAux.vo</code></li> <li>69 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/UList.vo</code></li> <li>42 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/ListOp.vo</code></li> <li>32 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/Test.vo</code></li> <li>31 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/Div.vo</code></li> <li>7 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Sudoku/Tactic.vo</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq:contrib:sudoku/opam.config</code></li> <li>1 K <code>/home/bench/.opam/system/install/coq:contrib:sudoku.install</code></li> </ul> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq:contrib:sudoku.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> <dt>Output</dt> <dd><pre>The following actions will be performed: - remove coq:contrib:sudoku.8.4.dev 1 to remove === =-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= [coq:contrib:sudoku] Fetching https://gforge.inria.fr/git/coq-contribs/sudoku.git#v8.4 =-=- Removing Packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Removing coq:contrib:sudoku.8.4.dev. rm -R /home/bench/.opam/system/lib/coq/user-contrib/Sudoku </pre></dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https: </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
using Robust.Shared.GameObjects; namespace Content.Server.MachineLinking.Components { [RegisterComponent] public sealed class <API key> : Component { } }
//#include <stdio.h> //#include <stdlib.h> //#include <stdint.h> //#include <stdbool.h> //#include <string.h> //#include <stddef.h> #include "esp_common.h" #include "coap.h" #include "shell.h" //#include <rtthread.h> //#define shell_printf rt_kshell_printf extern void endpoint_setup(void); extern const coap_endpoint_t endpoints[]; #ifdef MICROCOAP_DEBUG void ICACHE_FLASH_ATTR coap_dumpHeader(coap_header_t *hdr) { shell_printf("Header:\n"); shell_printf(" ver 0x%02X\n", hdr->ver); shell_printf(" t 0x%02X\n", hdr->t); shell_printf(" tkl 0x%02X\n", hdr->tkl); shell_printf(" code 0x%02X\n", hdr->code); shell_printf(" id 0x%02X%02X\n", hdr->id[0], hdr->id[1]); } #endif #ifdef MICROCOAP_DEBUG void ICACHE_FLASH_ATTR coap_dump(const uint8_t *buf, size_t buflen, bool bare) { if (bare) { while(buflen shell_printf("%02X%s", *buf++, (buflen > 0) ? " " : ""); } else { shell_printf("Dump: "); while(buflen shell_printf("%02X%s", *buf++, (buflen > 0) ? " " : ""); shell_printf("\n"); } } #endif int ICACHE_FLASH_ATTR coap_parseHeader(coap_header_t *hdr, const uint8_t *buf, size_t buflen) { if (buflen < 4) return <API key>; hdr->ver = (buf[0] & 0xC0) >> 6; if (hdr->ver != 1) return <API key>; hdr->t = (buf[0] & 0x30) >> 4; hdr->tkl = buf[0] & 0x0F; hdr->code = buf[1]; hdr->id[0] = buf[2]; hdr->id[1] = buf[3]; return 0; } int ICACHE_FLASH_ATTR coap_parseToken(coap_buffer_t *tokbuf, const coap_header_t *hdr, const uint8_t *buf, size_t buflen) { if (hdr->tkl == 0) { tokbuf->p = NULL; tokbuf->len = 0; return 0; } else if (hdr->tkl <= 8) { if (4U + hdr->tkl > buflen) return <API key>; // tok bigger than packet tokbuf->p = buf+4; // past header tokbuf->len = hdr->tkl; return 0; } else { // invalid size return <API key>; } } // advances p int ICACHE_FLASH_ATTR coap_parseOption(coap_option_t *option, uint16_t *running_delta, const uint8_t **buf, size_t buflen) { const uint8_t *p = *buf; uint8_t headlen = 1; uint16_t len, delta; if (buflen < headlen) // too small return <API key>; delta = (p[0] & 0xF0) >> 4; len = p[0] & 0x0F; // These are untested and may be buggy if (delta == 13) { headlen++; if (buflen < headlen) return <API key>; delta = p[1] + 13; p++; } else if (delta == 14) { headlen += 2; if (buflen < headlen) return <API key>; delta = ((p[1] << 8) | p[2]) + 269; p+=2; } else if (delta == 15) return <API key>; if (len == 13) { headlen++; if (buflen < headlen) return <API key>; len = p[1] + 13; p++; } else if (len == 14) { headlen += 2; if (buflen < headlen) return <API key>; len = ((p[1] << 8) | p[2]) + 269; p+=2; } else if (len == 15) return <API key>; if ((p + 1 + len) > (*buf + buflen)) return <API key>; //shell_printf("option num=%d\n", delta + *running_delta); option->num = delta + *running_delta; option->buf.p = p+1; option->buf.len = len; //coap_dump(p+1, len, false); // advance buf *buf = p + 1 + len; *running_delta += delta; return 0; } // http://tools.ietf.org/html/rfc7252#section-3.1 int ICACHE_FLASH_ATTR <API key>(coap_option_t *options, uint8_t *numOptions, coap_buffer_t *payload, const coap_header_t *hdr, const uint8_t *buf, size_t buflen) { size_t optionIndex = 0; uint16_t delta = 0; const uint8_t *p = buf + 4 + hdr->tkl; const uint8_t *end = buf + buflen; int rc; if (p > end) return <API key>; // out of bounds //coap_dump(p, end - p); // 0xFF is payload marker while((optionIndex < *numOptions) && (p < end) && (*p != 0xFF)) { if (0 != (rc = coap_parseOption(&options[optionIndex], &delta, &p, end-p))) return rc; optionIndex++; } *numOptions = optionIndex; if (p+1 < end && *p == 0xFF) // payload marker { payload->p = p+1; payload->len = end-(p+1); } else { payload->p = NULL; payload->len = 0; } return 0; } #ifdef MICROCOAP_DEBUG void ICACHE_FLASH_ATTR coap_dumpOptions(coap_option_t *opts, size_t numopt) { size_t i; shell_printf("Options:\n"); for (i=0;i<numopt;i++) { shell_printf(" 0x%02X [ ", opts[i].num); coap_dump(opts[i].buf.p, opts[i].buf.len, true); shell_printf(" ]\n"); } } #endif #ifdef MICROCOAP_DEBUG void ICACHE_FLASH_ATTR coap_dumpPacket(coap_packet_t *pkt) { coap_dumpHeader(&pkt->hdr); coap_dumpOptions(pkt->opts, pkt->numopts); shell_printf("Payload: \n"); coap_dump(pkt->payload.p, pkt->payload.len, true); shell_printf("\n"); } #endif int ICACHE_FLASH_ATTR coap_parse(coap_packet_t *pkt, const uint8_t *buf, size_t buflen) { int rc; // coap_dump(buf, buflen, false); if (0 != (rc = coap_parseHeader(&pkt->hdr, buf, buflen))) return rc; // coap_dumpHeader(&hdr); if (0 != (rc = coap_parseToken(&pkt->tok, &pkt->hdr, buf, buflen))) return rc; pkt->numopts = MAXOPT; if (0 != (rc = <API key>(pkt->opts, &(pkt->numopts), &(pkt->payload), &pkt->hdr, buf, buflen))) return rc; // coap_dumpOptions(opts, numopt); return 0; } // options are always stored consecutively, so can return a block with same option num const coap_option_t * ICACHE_FLASH_ATTR coap_findOptions(const coap_packet_t *pkt, uint8_t num, uint8_t *count) { // FIXME, options is always sorted, can find faster than this size_t i; const coap_option_t *first = NULL; *count = 0; for (i=0;i<pkt->numopts;i++) { if (pkt->opts[i].num == num) { if (NULL == first) first = &pkt->opts[i]; (*count)++; } else { if (NULL != first) break; } } return first; } int ICACHE_FLASH_ATTR <API key>(char *strbuf, size_t strbuflen, const coap_buffer_t *buf) { if (buf->len+1 > strbuflen) return <API key>; memcpy(strbuf, buf->p, buf->len); strbuf[buf->len] = 0; return 0; } int ICACHE_FLASH_ATTR coap_build(uint8_t *buf, size_t *buflen, const coap_packet_t *pkt) { size_t opts_len = 0; size_t i; uint8_t *p; uint16_t running_delta = 0; // build header if (*buflen < (4U + pkt->hdr.tkl)) return <API key>; buf[0] = (pkt->hdr.ver & 0x03) << 6; buf[0] |= (pkt->hdr.t & 0x03) << 4; buf[0] |= (pkt->hdr.tkl & 0x0F); buf[1] = pkt->hdr.code; buf[2] = pkt->hdr.id[0]; buf[3] = pkt->hdr.id[1]; // inject token p = buf + 4; if ((pkt->hdr.tkl > 0) && (pkt->hdr.tkl != pkt->tok.len)) return <API key>; if (pkt->hdr.tkl > 0) memcpy(p, pkt->tok.p, pkt->hdr.tkl); // // http://tools.ietf.org/html/rfc7252#section-3.1 // inject options p += pkt->hdr.tkl; for (i=0;i<pkt->numopts;i++) { uint32_t optDelta; uint8_t len, delta = 0; if (((size_t)(p-buf)) > *buflen) return <API key>; optDelta = pkt->opts[i].num - running_delta; coap_option_nibble(optDelta, &delta); coap_option_nibble((uint32_t)pkt->opts[i].buf.len, &len); *p++ = (0xFF & (delta << 4 | len)); if (delta == 13) { *p++ = (optDelta - 13); } else if (delta == 14) { *p++ = ((optDelta-269) >> 8); *p++ = (0xFF & (optDelta-269)); } if (len == 13) { *p++ = (pkt->opts[i].buf.len - 13); } else if (len == 14) { *p++ = (pkt->opts[i].buf.len >> 8); *p++ = (0xFF & (pkt->opts[i].buf.len-269)); } memcpy(p, pkt->opts[i].buf.p, pkt->opts[i].buf.len); p += pkt->opts[i].buf.len; running_delta = pkt->opts[i].num; } opts_len = (p - buf) - 4; // number of bytes used by options if (pkt->payload.len > 0) { if (*buflen < 4 + 1 + pkt->payload.len + opts_len) return <API key>; buf[4 + opts_len] = 0xFF; // payload marker memcpy(buf+5 + opts_len, pkt->payload.p, pkt->payload.len); *buflen = opts_len + 5 + pkt->payload.len; } else *buflen = opts_len + 4; return 0; } void ICACHE_FLASH_ATTR coap_option_nibble(uint32_t value, uint8_t *nibble) { if (value<13) { *nibble = (0xFF & value); } else if (value<=0xFF+13) { *nibble = 13; } else if (value<=0xFFFF+269) { *nibble = 14; } } int ICACHE_FLASH_ATTR coap_make_response(coap_rw_buffer_t *scratch, coap_packet_t *pkt, const uint8_t *content, size_t content_len, uint8_t msgid_hi, uint8_t msgid_lo, const coap_buffer_t* tok, coap_responsecode_t rspcode, coap_content_type_t content_type) { pkt->hdr.ver = 0x01; pkt->hdr.t = COAP_TYPE_ACK; pkt->hdr.tkl = 0; pkt->hdr.code = rspcode; pkt->hdr.id[0] = msgid_hi; pkt->hdr.id[1] = msgid_lo; pkt->numopts = 1; // need token in response if (tok) { pkt->hdr.tkl = tok->len; pkt->tok = *tok; } // safe because 1 < MAXOPT pkt->opts[0].num = <API key>; pkt->opts[0].buf.p = scratch->p; if (scratch->len < 2) return <API key>; scratch->p[0] = ((uint16_t)content_type & 0xFF00) >> 8; scratch->p[1] = ((uint16_t)content_type & 0x00FF); pkt->opts[0].buf.len = 2; pkt->payload.p = content; pkt->payload.len = content_len; return 0; } // FIXME, if this looked in the table at the path before the method then // it could more easily return 405 errors int ICACHE_FLASH_ATTR coap_handle_req(coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt) { const coap_option_t *opt; uint8_t count; int i; const coap_endpoint_t *ep = endpoints; while(NULL != ep->handler) { if (ep->method != inpkt->hdr.code) goto next; if (NULL != (opt = coap_findOptions(inpkt, <API key>, &count))) { if (count != ep->path->count) goto next; for (i=0;i<count;i++) { if (opt[i].buf.len != strlen(ep->path->elems[i])) goto next; if (0 != memcmp(ep->path->elems[i], opt[i].buf.p, opt[i].buf.len)) goto next; } // match! return ep->handler(scratch, inpkt, outpkt, inpkt->hdr.id[0], inpkt->hdr.id[1]); } next: ep++; } coap_make_response(scratch, outpkt, NULL, 0, inpkt->hdr.id[0], inpkt->hdr.id[1], &inpkt->tok, <API key>, <API key>); return 0; } void coap_setup(void) { }
<aside class="main-sidebar"> <section class="sidebar"> <div class="user-panel"> <div class="pull-left image"> <img src="<?php echo base_url() ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <div class="pull-left info"> <p>Alexander Pierce</p> <i class="fa fa-circle text-success"></i> Online </div> </div> <!-- sidebar menu: : style can be found in sidebar.less --> <ul class="sidebar-menu"> <li class="treeview"> <a href=" <i class="fa fa-users"></i> <span>Funcionarios</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="<?php echo base_url()?>funcionarios/Index/<API key>"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="<?php echo base_url()?>funcionarios/Index/listadoFuncionarios"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href=" <i class="fa fa-cogs"></i> <span>Cuentas de Usuarios</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href=" <i class="fa fa-graduation-cap" aria-hidden="true"></i> <span>Matrícula de Párvulos</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href=" <i class="fa fa-cubes" aria-hidden="true"></i> <span>Niveles Jardín</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="<?php echo base_url() ?>niveles/Index/crearNivel"><i class="fa fa-circle-o text-aqua"></i> Registrar Niveles Jardín</a></li> <li><a href="<?php echo base_url() ?>niveles/Index/crearNivelAnual"><i class="fa fa-circle-o text-aqua"></i> Crear Niveles Anuales</a></li> <li><a href="<?php echo base_url() ?>niveles/Index/armarNivelAnual"><i class="fa fa-circle-o text-aqua"></i> Armar Niveles</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Niveles</a></li> </ul> </li> <li class="treeview"> <a href=" <i class="fa fa-book" aria-hidden="true"></i> <span>Unidades de Contenido</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href=" <i class="fa fa-laptop" aria-hidden="true"></i> <span>Planific. Educadora</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href=" <i class="fa fa-bar-chart" aria-hidden="true"></i> <span>Reportes</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> <li class="treeview"> <a href=" <i class="fa fa-question-circle" aria-hidden="true"></i> <span>Ayuda</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Registro Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Listado Funcionarios</a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> Reporte Funcionarios</a></li> </ul> </li> </ul> </section> </aside>
<!DOCTYPE html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="keywords" content=" "> <title>Prerequisites | LivePerson Technical Documentation</title> <link rel="stylesheet" href="css/syntax.css"> <link rel="stylesheet" type="text/css" href="css/font-awesome-4.7.0/css/font-awesome.min.css"> <!--<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">--> <link rel="stylesheet" href="css/modern-business.css"> <link rel="stylesheet" href="css/lavish-bootstrap.css"> <link rel="stylesheet" href="css/customstyles.css"> <link rel="stylesheet" href="css/theme-blue.css"> <!-- <script src="assets/js/jsoneditor.js"></script> --> <script src="assets/js/jquery-3.1.0.min.js"></script> <!-- <link rel='stylesheet' id='theme_stylesheet' href='//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css'> --> <!-- <link rel='stylesheet' id='theme_stylesheet' href='//netdna.bootstrapcdn.com/<TwitterConsumerkey>/2.3.2/css/bootstrap-combined.min.css'> <script src="assets/js/jquery.cookie-1.4.1.min.js"></script> <script src="js/jquery.navgoco.min.js"></script> <script src="assets/js/bootstrap-3.3.4.min.js"></script> <script src="assets/js/anchor-2.0.0.min.js"></script> <script src="js/toc.js"></script> <script src="js/customscripts.js"></script> <link rel="shortcut icon" href="images/favicon.ico"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif] <link rel="alternate" type="application/rss+xml" title="" href="http://0.0.0.0:4005feed.xml"> <script> $(document).ready(function() { // Initialize navgoco with default options $("#mysidebar").navgoco({ caretHtml: '', accordion: true, openClass: 'active', // open save: false, // leave false or nav highlighting doesn't work right cookie: { name: 'navgoco', expires: false, path: '/' }, slide: { duration: 400, easing: 'swing' } }); $("#collapseAll").click(function(e) { e.preventDefault(); $("#mysidebar").navgoco('toggle', false); }); $("#expandAll").click(function(e) { e.preventDefault(); $("#mysidebar").navgoco('toggle', true); }); }); </script> <script> $(function () { $('[data-toggle="tooltip"]').tooltip() }) </script> </head> <body> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container topnavlinks"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#<API key>"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="fa fa-home fa-lg navbar-brand" href="index.html">&nbsp;<span class="projectTitle"> LivePerson Technical Documentation</span></a> </div> <div class="collapse navbar-collapse" id="<API key>"> <ul class="nav navbar-nav navbar-right"> <!-- entries without drop-downs appear here --> <!-- entries with drop-downs appear here --> <!-- conditional logic to control which topnav appears for the audience defined in the configuration file.--> <li><a class="email" title="Submit feedback" href="https://github.com/LivePersonInc/dev-hub/issues" ><i class="fa fa-github"></i> Issues</a><li> <!--comment out this block if you want to hide search <li> <!--start search <div id="<API key>"> <input type="text" id="search-input" placeholder="search..."> <ul id="results-container"></ul> </div> <script src="js/jekyll-search.js" type="text/javascript"></script> <script type="text/javascript"> SimpleJekyllSearch.init({ searchInput: document.getElementById('search-input'), resultsContainer: document.getElementById('results-container'), dataSource: 'search.json', <API key>: '<li><a href="{url}" title="Prerequisites">{title}</a></li>', noResultsText: 'No results found.', limit: 10, fuzzy: true, }) </script> <!--end search </li> </ul> </div> </div> <!-- /.container --> </nav> <!-- Page Content --> <div class="container"> <div class="col-lg-12">&nbsp;</div> <!-- Content Row --> <div class="row"> <!-- Sidebar Column --> <div class="col-md-3"> <ul id="mysidebar" class="nav"> <li class="sidebarTitle"> </li> <li> <a href="#">Common Guidelines</a> <ul> <li class="subfolders"> <a href="#">Introduction</a> <ul> <li class="thirdlevel"><a href="index.html">Home</a></li> <li class="thirdlevel"><a href="getting-started.html">Getting Started with LiveEngage APIs</a></li> </ul> </li> <li class="subfolders"> <a href="#">Guides</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Customized Chat Windows</a></li> </ul> </li> </ul> <li> <a href="#">Account Configuration</a> <ul> <li class="subfolders"> <a href="#">Predefined Content API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Get Predefined Content Items</a></li> <li class="thirdlevel"><a href="<API key>.html">Get Predefined Content by ID</a></li> <li class="thirdlevel"><a href="<API key>.html">Predefined Content Query Delta</a></li> <li class="thirdlevel"><a href="<API key>.html">Create Predefined Content</a></li> <li class="thirdlevel"><a href="<API key>.html">Update Predefined Content</a></li> <li class="thirdlevel"><a href="<API key>.html">Update Predefined Content Items</a></li> <li class="thirdlevel"><a href="<API key>.html">Delete Predefined Content</a></li> <li class="thirdlevel"><a href="<API key>.html">Delete Predefined Content Items</a></li> <li class="thirdlevel"><a href="<API key>.html">Get Default Predefined Content Items</a></li> <li class="thirdlevel"><a href="<API key>.html">Get Default Predefined Content by ID</a></li> <li class="thirdlevel"><a href="<API key>.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Automatic Messages API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Get Automatic Messages</a></li> <li class="thirdlevel"><a href="<API key>.html">Get Automatic Message by ID</a></li> <li class="thirdlevel"><a href="<API key>.html">Update an Automatic Message</a></li> <li class="thirdlevel"><a href="<API key>.html">Appendix</a></li> </ul> </li> </ul> <li> <a href="#">Administration</a> <ul> <li class="subfolders"> <a href="#">Users API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Get all users</a></li> <li class="thirdlevel"><a href="<API key>.html">Get user by ID</a></li> <li class="thirdlevel"><a href="<API key>.html">Create users</a></li> <li class="thirdlevel"><a href="<API key>.html">Update users</a></li> <li class="thirdlevel"><a href="<API key>.html">Update user</a></li> <li class="thirdlevel"><a href="<API key>.html">Delete users</a></li> <li class="thirdlevel"><a href="<API key>.html">Delete user</a></li> <li class="thirdlevel"><a href="<API key>.html">Change user's password</a></li> <li class="thirdlevel"><a href="<API key>.html">Reset user's password</a></li> <li class="thirdlevel"><a href="<API key>.html">User query delta</a></li> <li class="thirdlevel"><a href="<API key>.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Skills API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Get all skills</a></li> <li class="thirdlevel"><a href="<API key>.html">Get skill by ID</a></li> <li class="thirdlevel"><a href="<API key>.html">Create skills</a></li> <li class="thirdlevel"><a href="administration.update-skills.html">Update skills</a></li> <li class="thirdlevel"><a href="<API key>.html">Update skill</a></li> <li class="thirdlevel"><a href="<API key>.html">Delete skills</a></li> <li class="thirdlevel"><a href="<API key>.html">Delete skill</a></li> <li class="thirdlevel"><a href="<API key>.html">Skills Query Delta</a></li> <li class="thirdlevel"><a href="<API key>.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Agent Groups API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Get all agent groups</a></li> <li class="thirdlevel"><a href="<API key>.html">Get agent group by ID</a></li> <li class="thirdlevel"><a href="<API key>.html">Create agent groups</a></li> <li class="thirdlevel"><a href="<API key>.html">Update agent groups</a></li> <li class="thirdlevel"><a href="<API key>.html">Update agent group</a></li> <li class="thirdlevel"><a href="<API key>.html">Delete agent groups</a></li> <li class="thirdlevel"><a href="<API key>.html">Delete agent group</a></li> <li class="thirdlevel"><a href="<API key>.html">Get subgroups and members of an agent group</a></li> <li class="thirdlevel"><a href="<API key>.html">Agent Groups Query Delta</a></li> </ul> </li> </ul> <li> <a href="#">Consumer Experience</a> <ul> <li class="subfolders"> <a href="#">JavaScript Chat SDK</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Getting Started</a></li> <li class="thirdlevel"><a href="<API key>.html">Chat States</a></li> <li class="thirdlevel"><a href="<API key>.html">Surveys</a></li> <li class="thirdlevel"><a href="<API key>.html">Creating an Instance</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html"><API key></a></li> <li class="thirdlevel"><a href="<API key>.html">getPreChatSurvey</a></li> <li class="thirdlevel"><a href="<API key>.html">getEngagement</a></li> <li class="thirdlevel"><a href="<API key>.html">requestChat</a></li> <li class="thirdlevel"><a href="<API key>.html">addLine</a></li> <li class="thirdlevel"><a href="<API key>.html">setVisitorTyping</a></li> <li class="thirdlevel"><a href="<API key>.html">setVisitorName</a></li> <li class="thirdlevel"><a href="<API key>.html">endChat</a></li> <li class="thirdlevel"><a href="<API key>.html">requestTranscript</a></li> <li class="thirdlevel"><a href="<API key>.html">getExitSurvey</a></li> <li class="thirdlevel"><a href="<API key>.html">submitExitSurvey</a></li> <li class="thirdlevel"><a href="<API key>.html">getOfflineSurvey</a></li> <li class="thirdlevel"><a href="<API key>.html">submitOfflineSurvey</a></li> <li class="thirdlevel"><a href="<API key>.html">getState</a></li> <li class="thirdlevel"><a href="<API key>.html">getAgentLoginName</a></li> <li class="thirdlevel"><a href="<API key>.html">getVisitorName</a></li> <li class="thirdlevel"><a href="<API key>.html">getAgentId</a></li> <li class="thirdlevel"><a href="<API key>.html">getRtSessionId</a></li> <li class="thirdlevel"><a href="<API key>.html">getSessionKey</a></li> <li class="thirdlevel"><a href="<API key>.html">getAgentTyping</a></li> <li class="thirdlevel"><a href="<API key>.html">Events</a></li> <li class="thirdlevel"><a href="<API key>.html">onLoad</a></li> <li class="thirdlevel"><a href="<API key>.html">onInit</a></li> <li class="thirdlevel"><a href="<API key>.html">onEstimatedWaitTime</a></li> <li class="thirdlevel"><a href="<API key>.html">onEngagement</a></li> <li class="thirdlevel"><a href="<API key>.html">onPreChatSurvey</a></li> <li class="thirdlevel"><a href="<API key>.html">onStart</a></li> <li class="thirdlevel"><a href="<API key>.html">onStop</a></li> <li class="thirdlevel"><a href="<API key>.html">onRequestChat</a></li> <li class="thirdlevel"><a href="<API key>.html">onTranscript</a></li> <li class="thirdlevel"><a href="<API key>.html">onLine</a></li> <li class="thirdlevel"><a href="<API key>.html">onState</a></li> <li class="thirdlevel"><a href="<API key>.html">onInfo</a></li> <li class="thirdlevel"><a href="<API key>.html">onAgentTyping</a></li> <li class="thirdlevel"><a href="<API key>.html">onExitSurvey</a></li> <li class="thirdlevel"><a href="<API key>.html"><API key></a></li> <li class="thirdlevel"><a href="<API key>.html">Engagement Attributes Body Example</a></li> <li class="thirdlevel"><a href="<API key>.html">Demo App</a></li> </ul> </li> <li class="subfolders"> <a href="#">Server Chat API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Getting Started</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Availability</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Available Slots</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Estimated Wait Time</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve an Offline Survey</a></li> <li class="thirdlevel"><a href="<API key>.html">Start a Chat</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Chat Resources, Events and Information</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Chat Events</a></li> <li class="thirdlevel"><a href="<API key>.html">Add Lines / End Chat</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Chat Information</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve the Visitor's Name</a></li> <li class="thirdlevel"><a href="<API key>.html">Set the Visitor's Name</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve the Agent's Typing Status</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve the Visitor's Typing Status</a></li> <li class="thirdlevel"><a href="<API key>.html">Set the Visitor's Typing Status</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Exit Survey Structure</a></li> <li class="thirdlevel"><a href="<API key>.html">Submit Survey Data</a></li> <li class="thirdlevel"><a href="<API key>.html">Send a Transcript</a></li> <li class="thirdlevel"><a href="<API key>.html">Sample Postman Collection</a></li> </ul> </li> <li class="subfolders"> <a href="#">Push Service API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>">TLS Authentication</a></li> <li class="thirdlevel"><a href="<API key>">HTTP Response Codes</a></li> <li class="thirdlevel"><a href="<API key>">Configuration of Push Proxy</a></li> </ul> </li> <li class="subfolders"> <a href="#">In-App Messaging SDK iOS (2.0)</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Quick Start</a></li> <li class="thirdlevel"><a href="<API key>.html">Advanced Configurations</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">initialize</a></li> <li class="thirdlevel"><a href="<API key>.html">showConversation</a></li> <li class="thirdlevel"><a href="<API key>.html">removeConversation</a></li> <li class="thirdlevel"><a href="<API key>.html">reconnect</a></li> <li class="thirdlevel"><a href="<API key>.html">toggleChatActions</a></li> <li class="thirdlevel"><a href="<API key>.html"><API key></a></li> <li class="thirdlevel"><a href="<API key>.html">markAsUrgent</a></li> <li class="thirdlevel"><a href="<API key>.html">isUrgent</a></li> <li class="thirdlevel"><a href="<API key>.html">dismissUrgent</a></li> <li class="thirdlevel"><a href="<API key>.html">resolveConversation</a></li> <li class="thirdlevel"><a href="<API key>.html">clearHistory</a></li> <li class="thirdlevel"><a href="<API key>.html">logout</a></li> <li class="thirdlevel"><a href="<API key>.html">destruct</a></li> <li class="thirdlevel"><a href="<API key>.html">handlePush</a></li> <li class="thirdlevel"><a href="<API key>.html"><API key></a></li> <li class="thirdlevel"><a href="<API key>.html">setUserProfile</a></li> <li class="thirdlevel"><a href="<API key>.html">getAssignedAgent</a></li> <li class="thirdlevel"><a href="<API key>.html">subscribeLogEvents</a></li> <li class="thirdlevel"><a href="<API key>.html">getSDKVersion</a></li> <li class="thirdlevel"><a href="<API key>.html"><API key></a></li> <li class="thirdlevel"><a href="<API key>.html"><API key></a></li> <li class="thirdlevel"><a href="<API key>.html"><API key></a></li> <li class="thirdlevel"><a href="<API key>.html">Interface and Class Definitions</a></li> <li class="thirdlevel"><a href="<API key>.html">Callbacks index</a></li> <li class="thirdlevel"><a href="<API key>.html">Configuring the SDK</a></li> <li class="thirdlevel"><a href="<API key>.html">Attributes</a></li> <li class="thirdlevel"><a href="<API key>.html">Deprecated Attributes</a></li> <li class="thirdlevel"><a href="<API key>.html">String localization in SDK</a></li> <li class="thirdlevel"><a href="<API key>.html">Localization Keys</a></li> <li class="thirdlevel"><a href="<API key>.html">Timestamps Formatting</a></li> <li class="thirdlevel"><a href="<API key>.html">OS Certificate Creation</a></li> <li class="thirdlevel"><a href="<API key>.html">CSAT UI Content</a></li> <li class="thirdlevel"><a href="<API key>.html">Photo Sharing (Beta)</a></li> <li class="thirdlevel"><a href="<API key>.html">Configuring Push Notifications</a></li> <li class="thirdlevel"><a href="<API key>.html">Open Source List</a></li> <li class="thirdlevel"><a href="<API key>.html">Security</a></li> </ul> </li> <li class="subfolders"> <a href="#">In-App Messaging SDK Android (2.0)</a> <ul> <li class="thirdlevel"><a href="android-overview.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Prerequisites</a></li> <li class="thirdlevel"><a href="<API key>.html">Step 1: Download and Unzip the SDK</a></li> <li class="thirdlevel"><a href="<API key>.html">Step 2: Configure project settings to connect LiveEngage SDK</a></li> <li class="thirdlevel"><a href="<API key>.html">Step 3: Code integration for basic deployment</a></li> <li class="thirdlevel"><a href="<API key>.html">SDK Initialization and Lifecycle</a></li> <li class="thirdlevel"><a href="<API key>.html">Authentication</a></li> <li class="thirdlevel"><a href="<API key>.html">Conversations Lifecycle</a></li> <li class="thirdlevel"><a href="<API key>.html">LivePerson Callbacks Interface</a></li> <li class="thirdlevel"><a href="<API key>.html">Notifications</a></li> <li class="thirdlevel"><a href="android-user-data.html">User Data</a></li> <li class="thirdlevel"><a href="android-logs.html">Logs and Info</a></li> <li class="thirdlevel"><a href="android-methods.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">initialize (Deprecated)</a></li> <li class="thirdlevel"><a href="<API key>.html">initialize (with SDK properties object)</a></li> <li class="thirdlevel"><a href="<API key>.html">showConversation</a></li> <li class="thirdlevel"><a href="<API key>.html">showConversation (with authentication support)</a></li> <li class="thirdlevel"><a href="<API key>.html">hideConversation</a></li> <li class="thirdlevel"><a href="<API key>.html"><API key></a></li> <li class="thirdlevel"><a href="<API key>.html"><API key> with authentication support</a></li> <li class="thirdlevel"><a href="android-reconnect.html">reconnect</a></li> <li class="thirdlevel"><a href="<API key>.html">setUserProfile</a></li> <li class="thirdlevel"><a href="<API key>.html">setUserProfile (Deprecated)</a></li> <li class="thirdlevel"><a href="<API key>.html">registerLPPusher</a></li> <li class="thirdlevel"><a href="<API key>.html">unregisterLPPusher</a></li> <li class="thirdlevel"><a href="android-handlepush.html">handlePush</a></li> <li class="thirdlevel"><a href="<API key>.html">getSDKVersion</a></li> <li class="thirdlevel"><a href="android-setcallback.html">setCallback</a></li> <li class="thirdlevel"><a href="<API key>.html">removeCallBack</a></li> <li class="thirdlevel"><a href="<API key>.html"><API key></a></li> <li class="thirdlevel"><a href="<API key>.html">checkAgentID</a></li> <li class="thirdlevel"><a href="android-markurgent.html"><API key></a></li> <li class="thirdlevel"><a href="android-marknormal.html"><API key></a></li> <li class="thirdlevel"><a href="android-checkurgent.html"><API key></a></li> <li class="thirdlevel"><a href="<API key>.html">resolveConversation</a></li> <li class="thirdlevel"><a href="android-shutdown.html">shutDown</a></li> <li class="thirdlevel"><a href="<API key>.html">shutDown (Deprecated)</a></li> <li class="thirdlevel"><a href="<API key>.html">clearHistory</a></li> <li class="thirdlevel"><a href="android-logout.html">logOut</a></li> <li class="thirdlevel"><a href="<API key>.html">Callbacks Index</a></li> <li class="thirdlevel"><a href="<API key>.html">Configuring the SDK</a></li> <li class="thirdlevel"><a href="android-attributes.html">Attributes</a></li> <li class="thirdlevel"><a href="<API key>.html">Configuring the message’s EditText</a></li> <li class="thirdlevel"><a href="android-proguard.html">Proguard Configuration</a></li> <li class="thirdlevel"><a href="<API key>.html">Modifying Strings</a></li> <li class="thirdlevel"><a href="<API key>.html">Modifying Resources</a></li> <li class="thirdlevel"><a href="<API key>.html">Plural String Resource Example</a></li> <li class="thirdlevel"><a href="android-timestamps.html">Timestamps Formatting</a></li> <li class="thirdlevel"><a href="android-off-hours.html">Date and Time</a></li> <li class="thirdlevel"><a href="android-bubble.html">Bubble Timestamp</a></li> <li class="thirdlevel"><a href="android-separator.html">Separator Timestamp</a></li> <li class="thirdlevel"><a href="android-resolve.html">Resolve Message</a></li> <li class="thirdlevel"><a href="android-csat.html">CSAT Behavior</a></li> <li class="thirdlevel"><a href="<API key>.html">Photo Sharing - Beta</a></li> <li class="thirdlevel"><a href="<API key>.html">Enable Push Notifications</a></li> <li class="thirdlevel"><a href="android-appendix.html">Appendix</a></li> </ul> </li> </ul> <li> <a href="#">Real-time Interactions</a> <ul> <li class="subfolders"> <a href="#">Visit Information API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Visit Information</a></li> </ul> </li> <li class="subfolders"> <a href="#">App Engagement API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Create Session</a></li> <li class="thirdlevel"><a href="<API key>.html">Update Session</a></li> </ul> </li> <li class="subfolders"> <a href="#">Engagement Attributes</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Engagement Attributes</a></li> </ul> </li> <li class="subfolders"> <a href="#">IVR Engagement API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key> engagement.html">External Engagement</a></li> </ul> </li> <li class="subfolders"> <a href="#">Validate Engagement</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Validate Engagement API</a></li> </ul> </li> <li class="subfolders"> <a href="#">Engagement Trigger API</a> <ul> <li class="thirdlevel"><a href="trigger-overview.html">Overview</a></li> <li class="thirdlevel"><a href="trigger-methods.html">Methods</a></li> <li class="thirdlevel"><a href="trigger-click.html">Click</a></li> <li class="thirdlevel"><a href="trigger-getinfo.html">getEngagementInfo</a></li> <li class="thirdlevel"><a href="trigger-getstate.html">getEngagementState</a></li> </ul> </li> <li class="subfolders"> <a href="#">Engagement Window Widget SDK</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Getting Started</a></li> <li class="thirdlevel"><a href="<API key>.html">Limitations</a></li> <li class="thirdlevel"><a href="<API key>.html">Configuration</a></li> <li class="thirdlevel"><a href="<API key>.html">How to use the SDK</a></li> <li class="thirdlevel"><a href="<API key>.html">Code Examples</a></li> <li class="thirdlevel"><a href="<API key>.html">Event Structure</a></li> </ul> </li> </ul> <li> <a href="#">Agent</a> <ul> <li class="subfolders"> <a href="#">Agent Workspace Widget SDK</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Getting Started</a></li> <li class="thirdlevel"><a href="<API key>.html">Limitations</a></li> <li class="thirdlevel"><a href="<API key>.html">How to use the SDK</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Public Model Structure</a></li> <li class="thirdlevel"><a href="<API key>.html">Public Properties</a></li> <li class="thirdlevel"><a href="<API key>.html">Code Examples</a></li> </ul> </li> <li class="subfolders"> <a href="#">LivePerson Domain API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Domain API</a></li> </ul> </li> <li class="subfolders"> <a href="#">Login Service API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Getting Started</a></li> <li class="thirdlevel"><a href="agent-login-methods.html">Methods</a></li> <li class="thirdlevel"><a href="agent-login.html">Login</a></li> <li class="thirdlevel"><a href="agent-refresh.html">Refresh</a></li> <li class="thirdlevel"><a href="agent-refresh.html">Logout</a></li> </ul> </li> <li class="subfolders"> <a href="#">Chat Agent API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Getting Started</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Start Agent Session</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Current Availability</a></li> <li class="thirdlevel"><a href="<API key>.html">Set Agent Availability</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Available Agents</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Available Slots</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Agent Information</a></li> <li class="thirdlevel"><a href="<API key>.html">Determine Incoming Chat Requests</a></li> <li class="thirdlevel"><a href="agent-accept-chat.html">Accept a Chat</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Chat Sessions</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Chat Resources, Events and Information</a></li> <li class="thirdlevel"><a href="agent-retrieve-data.html">Retrieve Data for Multiple Chats</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Chat Events</a></li> <li class="thirdlevel"><a href="agent-add-lines.html">Add Lines</a></li> <li class="thirdlevel"><a href="agent-end-chat.html">End Chat</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Chat Information</a></li> <li class="thirdlevel"><a href="">Retrieve Visitor’s Name</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Agent's Typing Status</a></li> <li class="thirdlevel"><a href="<API key>.html">Set Agent’s Typing Status</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Visitor's Typing Status</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Available Skills</a></li> <li class="thirdlevel"><a href="agent-transfer-chat.html">Transfer a Chat</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Agent Survey Structure</a></li> </ul> </li> <li class="subfolders"> <a href="#">Messaging Agent SDK</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> </ul> </li> </ul> <li> <a href="#">Data</a> <ul> <li class="subfolders"> <a href="#">Data Access API (Beta)</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Architecture</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Base Resource</a></li> <li class="thirdlevel"><a href="<API key>.html">Agent Activity</a></li> <li class="thirdlevel"><a href="<API key>.html">Web Session</a></li> <li class="thirdlevel"><a href="<API key>.html">Engagement</a></li> <li class="thirdlevel"><a href="<API key>.html">Survey</a></li> <li class="thirdlevel"><a href="<API key>.html">Schema</a></li> <li class="thirdlevel"><a href="<API key>.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Messaging Operations API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Messaging Conversation</a></li> <li class="thirdlevel"><a href="<API key>.html">Messaging CSAT Distribution</a></li> <li class="thirdlevel"><a href="<API key>.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Messaging Interactions API (Beta)</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Conversations</a></li> <li class="thirdlevel"><a href="<API key>.html">Get conversation by conversation ID</a></li> <li class="thirdlevel"><a href="<API key>.html">Get Conversations by Consumer ID</a></li> <li class="thirdlevel"><a href="<API key>.html">Sample Code</a></li> <li class="thirdlevel"><a href="<API key>.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Engagement History API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Retrieve Engagement List by Criteria</a></li> <li class="thirdlevel"><a href="<API key>.html">Sample Code</a></li> <li class="thirdlevel"><a href="<API key>.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Operational Real-time API</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Methods</a></li> <li class="thirdlevel"><a href="<API key>.html">Queue Health</a></li> <li class="thirdlevel"><a href="<API key>.html">Engagement Activity</a></li> <li class="thirdlevel"><a href="<API key>.html">Agent Activity</a></li> <li class="thirdlevel"><a href="<API key>.html">Current Queue State</a></li> <li class="thirdlevel"><a href="<API key>.html">SLA Histogram</a></li> <li class="thirdlevel"><a href="<API key>.html">Sample Code</a></li> </ul> </li> </ul> <li> <a href="#">LiveEngage Tag</a> <ul> <li class="subfolders"> <a href="#">LE Tag Events</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">How to use these Events</a></li> <li class="thirdlevel"><a href="<API key>.html">Events</a></li> <li class="thirdlevel"><a href="lp-tag-visitor-flow.html">Visitor Flow Events</a></li> <li class="thirdlevel"><a href="lp-tag-engagement.html">Engagement Events</a></li> <li class="thirdlevel"><a href="<API key>.html">Engagement Window Events</a></li> </ul> </li> </ul> <li> <a href="#">Messaging Window API</a> <ul> <li class="subfolders"> <a href="#">Introduction</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Home</a></li> <li class="thirdlevel"><a href="<API key>.html">Protocol Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Getting Started</a></li> </ul> </li> <li class="subfolders"> <a href="#">Tutorials</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Get Messages</a></li> <li class="thirdlevel"><a href="<API key>.html">Conversation Metadata</a></li> <li class="thirdlevel"><a href="<API key>.html">Read/Accept events</a></li> <li class="thirdlevel"><a href="<API key>.html">Authentication</a></li> <li class="thirdlevel"><a href="<API key>.html">Agent Profile</a></li> <li class="thirdlevel"><a href="<API key>.html">Post Conversation Survey</a></li> <li class="thirdlevel"><a href="<API key>.html">Client Properties</a></li> <li class="thirdlevel"><a href="<API key>.html">Avoid Webqasocket Headers</a></li> </ul> </li> <li class="subfolders"> <a href="#">Samples</a> <ul> <li class="thirdlevel"><a href="<API key>.html">JavaScript Messenger</a></li> </ul> </li> <li class="subfolders"> <a href="#">API Reference</a> <ul> <li class="thirdlevel"><a href="<API key>.html">Overview</a></li> <li class="thirdlevel"><a href="<API key>.html">Request Builder</a></li> <li class="thirdlevel"><a href="<API key>.html">Response Builder</a></li> <li class="thirdlevel"><a href="<API key>.html">Notification Builder</a></li> <li class="thirdlevel"><a href="<API key>.html">New Conversation</a></li> <li class="thirdlevel"><a href="<API key>.html">Close Conversation</a></li> <li class="thirdlevel"><a href="<API key>.html">Urgent Conversation</a></li> <li class="thirdlevel"><a href="<API key>.html">Update CSAT</a></li> <li class="thirdlevel"><a href="<API key>.html">Subscribe Conversations Metadata</a></li> <li class="thirdlevel"><a href="<API key>.html">Unsubscribe Conversations Metadata</a></li> <li class="thirdlevel"><a href="<API key>.html">Publish Content</a></li> <li class="thirdlevel"><a href="<API key>.html">Subscribe Conversation Content</a></li> <li class="thirdlevel"><a href="<API key>.html">Browser Init Connection</a></li> </ul> </li> </ul> <!-- if you aren't using the accordion, uncomment this block: <p class="external"> <a href="#" id="collapseAll">Collapse All</a> | <a href="#" id="expandAll">Expand All</a> </p> </li> </ul> </div> <!-- this highlights the active parent class in the navgoco sidebar. this is critical so that the parent expands when you're viewing a page. This must appear below the sidebar code above. Otherwise, if placed inside customscripts.js, the script runs before the sidebar code runs and the class never gets inserted.--> <script>$("li.active").parents('li').toggleClass("active");</script> <!-- Content Column --> <div class="col-md-9"> <div class="post-header"> <h1 class="post-title-main">Prerequisites</h1> </div> <div class="post-content"> <p>The following prerequisites are required:</p> <ul> <li>LiveEngage account</li> <li>Dedicated user for the bot created in LiveEngage</li> </ul> <div class="tags"> </div> </div> <hr class="shaded"/> <footer> <div class="row"> <div class="col-lg-12 footer"> &copy;2017 LivePerson. All rights reserved.<br />This documentation is subject to change without notice.<br /> Site last generated: Mar 13, 2017 <br /> <p><img src="img/company_logo.png" alt="Company logo"/></p> </div> </div> </footer> </div> <!-- /.row --> </div> <!-- /.container --> </div> </body> </html>
package com.agileEAP.workflow.definition; public enum ActivityType { //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("")] StartActivity(1), //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("")] ManualActivity(2), //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("")] RouterActivity(3), //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("")] SubflowActivity(4), //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("")] AutoActivity(5), //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("")] EndActivity(6), //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes: //[Remark("")] ProcessActivity(7); private int intValue; private static java.util.HashMap<Integer, ActivityType> mappings; private synchronized static java.util.HashMap<Integer, ActivityType> getMappings() { if (mappings == null) { mappings = new java.util.HashMap<Integer, ActivityType>(); } return mappings; } private ActivityType(int value) { intValue = value; ActivityType.getMappings().put(value, this); } public int getValue() { return intValue; } public static ActivityType forValue(int value) { return getMappings().get(value); } }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="uk" version="2.0"> <defaumlcodec>UTF-8</defaumlcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Menlocoin</source> <translation>Про Menlocoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Menlocoin&lt;/b&gt; version</source> <translation>Версія &lt;b&gt;Menlocoin&apos;a&lt;b&gt;</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http: This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http: <translation> Це програмне забезпечення є експериментальним. Поширюється за ліцензією MIT/X11, додаткова інформація міститься у файлі COPYING, а також за адресою http: Цей продукт включає в себе програмне забезпечення, розроблене в рамках проекту OpenSSL (http: </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Авторське право</translation> </message> <message> <location line="+0"/> <source>The Menlocoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Адресна книга</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Двічі клікніть на адресу чи назву для їх зміни</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Створити нову адресу</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Копіювати виділену адресу в буфер обміну</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Створити адресу</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Menlocoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Це ваші адреси для отримання платежів. Ви можете давати різні адреси різним людям, таким чином маючи можливість відслідкувати хто конкретно і скільки вам заплатив.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Скопіювати адресу</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Показати QR-&amp;Код</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Menlocoin address</source> <translation>Підпишіть повідомлення щоб довести, що ви є власником цієї адреси</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Вилучити вибрані адреси з переліку</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Експортувати дані з поточної вкладки в файл</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Menlocoin address</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Menlocoin-адресою</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Видалити</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Menlocoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Скопіювати &amp;мітку</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Редагувати</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Експортувати адресну книгу</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Файли відділені комами (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Помилка при експортуванні</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Неможливо записати у файл %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Назва</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(немає назви)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Діалог введення паролю</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Введіть пароль</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Новий пароль</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Повторіть пароль</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Введіть новий пароль для гаманця.&lt;br/&gt;Будь ласка, використовуйте паролі що містять &lt;b&gt;як мінімум 10 випадкових символів&lt;/b&gt;, або &lt;b&gt;як мінімум 8 слів&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Зашифрувати гаманець</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ця операція потребує пароль для розблокування гаманця.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Розблокувати гаманець</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ця операція потребує пароль для дешифрування гаманця.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Дешифрувати гаманець</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Змінити пароль</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Ввести старий та новий паролі для гаманця.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Підтвердити шифрування гаманця</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>УВАГА: Якщо ви зашифруєте гаманець і забудете пароль, ви &lt;b&gt;ВТРАТИТЕ ВСІ СВОЇ БІТКОІНИ&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Ви дійсно хочете зашифрувати свій гаманець?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Увага: Ввімкнено Caps Lock!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Гаманець зашифровано</translation> </message> <message> <location line="-56"/> <source>Menlocoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your menlocoins from being stolen by malware infecting your computer.</source> <translation>Біткоін-клієнт буде закрито для завершення процесу шифрування. Пам&apos;ятайте, що шифрування гаманця не може повністю захистити ваші біткоіни від крадіжки, у випадку якщо ваш комп&apos;ютер буде інфіковано шкідливими програмами.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Не вдалося зашифрувати гаманець</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Виникла помилка під час шифрування гаманця. Ваш гаманець не було зашифровано.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Введені паролі не співпадають.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Не вдалося розблокувати гаманець</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Введений пароль є невірним.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Не вдалося розшифрувати гаманець</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Пароль було успішно змінено.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Підписати повідомлення...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Синхронізація з мережею...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Огляд</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Показати загальний огляд гаманця</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>Транзакції</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Переглянути історію транзакцій</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Редагувати список збережених адрес та міток</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Показати список адрес для отримання платежів</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Вихід</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Вийти</translation> </message> <message> <location line="+4"/> <source>Show information about Menlocoin</source> <translation>Показати інформацію про Menlocoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>&amp;Про Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Показати інформацію про Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Параметри...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Шифрування гаманця...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Резервне копіювання гаманця...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Змінити парол&amp;ь...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Імпорт блоків з диску...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Menlocoin address</source> <translation>Відправити монети на вказану адресу</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Menlocoin</source> <translation>Редагувати параметри</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Резервне копіювання гаманця в інше місце</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Змінити пароль, який використовується для шифрування гаманця</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Вікно зневадження</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Відкрити консоль зневадження і діагностики</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>Перевірити повідомлення...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Menlocoin</source> <translation>Menlocoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Гаманець</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Menlocoin</source> <translation>&amp;Про Menlocoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Показати / Приховати</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Показує або приховує головне вікно</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Menlocoin addresses to prove you own them</source> <translation>Підтвердіть, що Ви є власником повідомлення підписавши його Вашою Menlocoin-адресою </translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Menlocoin addresses</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Menlocoin-адресою</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Файл</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Налаштування</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Довідка</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Панель вкладок</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[тестова мережа]</translation> </message> <message> <location line="+47"/> <source>Menlocoin client</source> <translation>Menlocoin-клієнт</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Menlocoin network</source> <translation><numerusform>%n активне з&apos;єднання з мережею</numerusform><numerusform>%n активні з&apos;єднання з мережею</numerusform><numerusform>%n активних з&apos;єднань з мережею</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Оброблено %1 блоків історії транзакцій.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Помилка</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Увага</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Інформація</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Синхронізовано</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Синхронізується...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Підтвердити комісію</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Надіслані транзакції</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Отримані перекази</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Дата: %1 Кількість: %2 Тип: %3 Адреса: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Обробка URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Menlocoin address or malformed URI parameters.</source> <translation>Неможливо обробити URI! Це може бути викликано неправильною Menlocoin-адресою, чи невірними параметрами URI.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>&lt;b&gt;Зашифрований&lt;/b&gt; гаманець &lt;b&gt;розблоковано&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>&lt;b&gt;Зашифрований&lt;/b&gt; гаманець &lt;b&gt;заблоковано&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Menlocoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Сповіщення мережі</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Редагувати адресу</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Мітка</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Мітка, пов&apos;язана з цим записом адресної книги</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Адреса</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Адреса, пов&apos;язана з цим записом адресної книги. Може бути змінено тільки для адреси відправника.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Нова адреса для отримання</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Нова адреса для відправлення</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Редагувати адресу для отримання</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Редагувати адресу для відправлення</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Введена адреса «%1» вже присутня в адресній книзі.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Menlocoin address.</source> <translation>Введена адреса «%1» не є коректною адресою в мережі Menlocoin.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Неможливо розблокувати гаманець.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Не вдалося згенерувати нові ключі.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Menlocoin-Qt</source> <translation>Menlocoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>версія</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Використання:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>параметри командного рядка</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Параметри інтерфейсу</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Встановлення мови, наприклад &quot;de_DE&quot; (типово: системна)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Запускати згорнутим</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Показувати заставку під час запуску (типово: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Параметри</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Головні</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Заплатити комісі&amp;ю</translation> </message> <message> <location line="+31"/> <source>Automatically start Menlocoin after logging in to the system.</source> <translation>Автоматично запускати гаманець при вході до системи.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Menlocoin on system login</source> <translation>&amp;Запускати гаманець при вході в систему</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Скинути всі параметри клієнта на типові.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>Скинути параметри</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Мережа</translation> </message> <message> <location line="+6"/> <source>Automatically open the Menlocoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Автоматично відкривати порт для клієнту біткоін на роутері. Працює лише якщо ваш роутер підтримує UPnP і ця функція увімкнена.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Відображення порту через &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Menlocoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Підключатись до мережі Menlocoin через SOCKS-проксі (наприклад при використанні Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>Підключатись через &amp;SOCKS-проксі:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP проксі:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-адреса проксі-сервера (наприклад 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Порт:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Порт проксі-сервера (наприклад 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS версії:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Версія SOCKS-проксі (наприклад 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Вікно</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Показувати лише іконку в треї після згортання вікна.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>Мінімізувати &amp;у трей</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Згортати замість закриття. Якщо ця опція включена, програма закриється лише після вибору відповідного пункту в меню.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Згортати замість закритт&amp;я</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Відображення</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Мова інтерфейсу користувача:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Menlocoin.</source> <translation>Встановлює мову інтерфейсу. Зміни набудуть чинності після перезапуску Menlocoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>В&amp;имірювати монети в:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Виберіть одиницю вимірювання монет, яка буде відображатись в гаманці та при відправленні.</translation> </message> <message> <location line="+9"/> <source>Whether to show Menlocoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Відображати адресу в списку транзакцій</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Гаразд</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Скасувати</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Застосувати</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>типово</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Підтвердження скидання параметрів</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Деякі параметри потребують перезапуск клієнта для набуття чинності.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Продовжувати?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Увага</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Menlocoin.</source> <translation>Цей параметр набуде чинності після перезапуску Menlocoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Невірно вказано адресу проксі.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Menlocoin network after a connection is established, but this process has not completed yet.</source> <translation>Показана інформація вже може бути застарілою. Ваш гаманець буде автоматично синхронізовано з мережею Menlocoin після встановлення підключення, але цей процес ще не завершено.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Баланс:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Непідтверджені:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Гаманець</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Недавні транзакції&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Ваш поточний баланс</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Загальна сума всіх транзакцій, які ще не підтверджені, та до цих пір не враховуються в загальному балансі</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>не синхронізовано</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start menlocoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Діалог QR-коду</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Запросити Платіж</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Кількість:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Мітка:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Повідомлення:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Зберегти як...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Помилка при кодуванні URI в QR-код.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Невірно введено кількість, будь ласка, перевірте.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Кінцевий URI занадто довгий, спробуйте зменшити текст для мітки / повідомлення.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Зберегти QR-код</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG-зображення (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Назва клієнту</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>Н/Д</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Версія клієнту</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Інформація</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Використовується OpenSSL версії</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation>Мережа</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Кількість підключень</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>В тестовій мережі</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Поточне число блоків</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>Відкрити</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Параметри командного рядка</translation> </message> <message> <location line="+7"/> <source>Show the Menlocoin-Qt help message to get a list with possible Menlocoin command-line options.</source> <translation>Показати довідку Menlocoin-Qt для отримання переліку можливих параметрів командного рядка.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>Показати</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>Консоль</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Дата збирання</translation> </message> <message> <location line="-104"/> <source>Menlocoin - Debug window</source> <translation>Menlocoin - Вікно зневадження</translation> </message> <message> <location line="+25"/> <source>Menlocoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Файл звіту зневадження</translation> </message> <message> <location line="+7"/> <source>Open the Menlocoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Очистити консоль</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Menlocoin RPC console.</source> <translation>Вітаємо у консолі Menlocoin RPC.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Використовуйте стрілки вгору вниз для навігації по історії, і &lt;b&gt;Ctrl-L&lt;/b&gt; для очищення екрана.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Наберіть &lt;b&gt;help&lt;/b&gt; для перегляду доступних команд.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Відправити</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Відправити на декілька адрес</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Дод&amp;ати одержувача</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Видалити всі поля транзакції</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Очистити &amp;все</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Баланс:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Підтвердити відправлення</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Відправити</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; адресату %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Підтвердіть відправлення</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Ви впевнені що хочете відправити %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> і </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Адреса отримувача невірна, будь ласка перепровірте.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Кількість монет для відправлення повинна бути більшою 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Кількість монет для відправлення перевищує ваш баланс.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Сума перевищить ваш баланс, якщо комісія %1 буде додана до вашої транзакції.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Знайдено адресу що дублюється. Відправлення на кожну адресу дозволяється лише один раз на кожну операцію переказу.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Помилка: Не вдалося створити транзакцію!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Помилка: транзакцію було відхилено. Це може статись, якщо декілька монет з вашого гаманця вже використані, наприклад, якщо ви використовуєте одну копію гаманця (wallet.dat), а монети були використані з іншої копії, але не позначені як використані в цій.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Кількість:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Отримувач:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. <API key>)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Введіть мітку для цієї адреси для додавання її в адресну книгу</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Мітка:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Вибрати адресу з адресної книги</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Вставити адресу</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Видалити цього отримувача</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Menlocoin address (e.g. <API key>)</source> <translation>Введіть адресу Menlocoin (наприклад <API key>)</translation> </message> </context> <context> <name><API key></name> <message> <location filename="../forms/<API key>.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Підписи - Підпис / Перевірка повідомлення</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. <API key>)</source> <translation>Введіть адресу Menlocoin (наприклад <API key>)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Вибрати адресу з адресної книги</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Вставити адресу</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Введіть повідомлення, яке ви хочете підписати тут</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Підпис</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Копіювати поточну сигнатуру до системного буферу обміну</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Menlocoin address</source> <translation>Підпишіть повідомлення щоб довести, що ви є власником цієї адреси</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Підписати повідомлення</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Скинути всі поля підпису повідомлення</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Очистити &amp;все</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. <API key>)</source> <translation>Введіть адресу Menlocoin (наприклад <API key>)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Menlocoin address</source> <translation>Перевірте повідомлення для впевненості, що воно підписано вказаною Menlocoin-адресою</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Перевірити повідомлення</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Скинути всі поля перевірки повідомлення</translation> </message> <message> <location filename="../<API key>.cpp" line="+27"/> <location line="+3"/> <source>Enter a Menlocoin address (e.g. <API key>)</source> <translation>Введіть адресу Menlocoin (наприклад <API key>)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Натисніть кнопку «Підписати повідомлення», для отримання підпису</translation> </message> <message> <location line="+3"/> <source>Enter Menlocoin signature</source> <translation>Введіть сигнатуру Menlocoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Введена нечинна адреса.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Будь ласка, перевірте адресу та спробуйте ще.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Не вдалося підписати повідомлення.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Повідомлення підписано.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Підпис не можливо декодувати.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Будь ласка, перевірте підпис та спробуйте ще.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Не вдалося перевірити повідомлення.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Повідомлення перевірено.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Menlocoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[тестова мережа]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Відкрити до %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/поза інтернетом</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/не підтверджено</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 підтверджень</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Статус</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Згенеровано</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Відправник</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Отримувач</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>Мітка</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Кредит</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>не прийнято</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Дебет</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Комісія за транзакцію</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Загальна сума</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Повідомлення</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Коментар</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID транзакції</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Після генерації монет, потрібно зачекати 120 блоків, перш ніж їх можна буде використати. Коли ви згенерували цей блок, його було відправлено в мережу для того, щоб він був доданий до ланцюжка блоків. Якщо ця процедура не вдасться, статус буде змінено на «не підтверджено» і ви не зможете потратити згенеровані монету. Таке може статись, якщо хтось інший згенерував блок на декілька секунд раніше.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Транзакція</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Кількість</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>true</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>false</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ще не було успішно розіслано</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>невідомий</translation> </message> </context> <context> <name><API key></name> <message> <location filename="../forms/<API key>.ui" line="+14"/> <source>Transaction details</source> <translation>Деталі транзакції</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Даний діалог показує детальну статистику по вибраній транзакції</translation> </message> </context> <context> <name><API key></name> <message> <location filename="../<API key>.cpp" line="+225"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Кількість</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Відкрити до %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Поза інтернетом (%1 підтверджень)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Непідтверджено (%1 із %2 підтверджень)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Підтверджено (%1 підтверджень)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Цей блок не був отриманий жодними іншими вузлами і, ймовірно, не буде прийнятий!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Згенеровано, але не підтверджено</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Отримано</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Отримано від</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Відправлено</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Відправлено собі</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Добуто</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(недоступно)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Статус транзакції. Наведіть вказівник на це поле, щоб показати кількість підтверджень.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Дата і час, коли транзакцію було отримано.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Тип транзакції.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Адреса отримувача транзакції.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Сума, додана чи знята з балансу.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Всі</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Сьогодні</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>На цьому тижні</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>На цьому місяці</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Минулого місяця</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Цього року</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Проміжок...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Отримані на</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Відправлені на</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Відправлені собі</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Добуті</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Інше</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Введіть адресу чи мітку для пошуку</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Мінімальна сума</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Скопіювати адресу</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Скопіювати мітку</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Копіювати кількість</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Редагувати мітку</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Показати деталі транзакції</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Експортувати дані транзакцій</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Файли, розділені комою (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Підтверджені</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Мітка</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Кількість</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>Ідентифікатор</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Помилка експорту</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Неможливо записати у файл %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Діапазон від:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>до</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Відправити</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Експортувати дані з поточної вкладки в файл</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Виникла помилка при спробі зберегти гаманець в новому місці.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Успішне створення резервної копії</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Данні гаманця успішно збережено в новому місці призначення.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Menlocoin version</source> <translation>Версія</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Використання:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or menlocoind</source> <translation>Відправити команду серверу -server чи демону</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Список команд</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Отримати довідку по команді</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Параметри:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: menlocoin.conf)</source> <translation>Вкажіть файл конфігурації (типово: menlocoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: menlocoind.pid)</source> <translation>Вкажіть pid-файл (типово: menlocoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Вкажіть робочий каталог</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Встановити розмір кешу бази даних в мегабайтах (типово: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Чекати на з&apos;єднання на &lt;port&gt; (типово: 9333 або тестова мережа: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Підтримувати не більше &lt;n&gt; зв&apos;язків з колегами (типово: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Поріг відключення неправильно під&apos;єднаних пірів (типово: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Максимальній розмір вхідного буферу на одне з&apos;єднання (типово: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Прослуховувати &lt;port&gt; для JSON-RPC-з&apos;єднань (типово: 9332 або тестова мережа: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Приймати команди із командного рядка та команди JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Запустити в фоновому режимі (як демон) та приймати команди</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Використовувати тестову мережу</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=menlocoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Menlocoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Menlocoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Помилка: транзакцію було відхилено. Це може статись, якщо декілька монет з вашого гаманця вже використані, наприклад, якщо ви використовуєте одну копію гаманця (wallet.dat), а монети були використані з іншої копії, але не позначені як використані в цій.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Увага: встановлено занадто велику комісію (-paytxfee). Комісія зніматиметься кожен раз коли ви проводитимете транзакції.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Menlocoin will not work properly.</source> <translation>Увага: будь ласка, перевірте дату і час на своєму комп&apos;ютері. Якщо ваш годинник йде неправильно, Menlocoin може працювати некоректно.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Увага: помилка читання wallet.dat! Всі ключі прочитано коректно, але дані транзакцій чи записи адресної книги можуть бути пропущені, або пошкоджені.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Увага: файл wallet.dat пошкоджено, дані врятовано! Оригінальний wallet.dat збережено як wallet.{timestamp}.bak до %s; якщо Ваш баланс чи транзакції неправильні, Ви можете відновити їх з резервної копії. </translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Спроба відновити закриті ключі з пошкодженого wallet.dat</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Підключитись лише до вказаного вузла</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Помилка ініціалізації бази даних блоків</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Помилка завантаження бази даних блоків</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Помилка: Мало вільного місця на диску!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Помилка: Гаманець заблокований, неможливо створити транзакцію!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Помилка: системна помилка: </translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Скільки блоків перевіряти під час запуску (типово: 288, 0 = всі)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Імпорт блоків з зовнішнього файлу blk000??.dat</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>Інформація</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Помилка в адресі -tor: «%s»</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Максимальний буфер, &lt;n&gt;*1000 байт (типово: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Максимальній розмір вихідного буферу на одне з&apos;єднання, &lt;n&gt;*1000 байт (типово: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Виводити більше налагоджувальної інформації. Мається на увазі всі шнші -debug* параметри</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Доповнювати налагоджувальний вивід відміткою часу</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Menlocoin Wiki for SSL setup instructions)</source> <translation>Параметри SSL: (див. Menlocoin Wiki для налаштування SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Вибір версії socks-проксі для використання (4-5, типово: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Відсилати налагоджувальну інформацію на консоль, а не у файл debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Відсилати налагоджувальну інформацію до налагоджувача</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Встановити максимальний розмір блоку у байтах (типово: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Встановити мінімальний розмір блоку у байтах (типово: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Стискати файл debug.log під час старту клієнта (типово: 1 коли відсутутній параметр -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Вказати тайм-аут підключення у мілісекундах (типово: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Системна помилка: </translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Намагатись використовувати UPnP для відображення порту, що прослуховується на роутері (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Намагатись використовувати UPnP для відображення порту, що прослуховується на роутері (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Ім&apos;я користувача для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Попередження</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Увага: Поточна версія застаріла, необхідне оновлення!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat пошкоджено, відновлення не вдалося</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Пароль для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Дозволити JSON-RPC-з&apos;єднання з вказаної IP-адреси</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Відправляти команди на вузол, запущений на &lt;ip&gt; (типово: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Модернізувати гаманець до останнього формату</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Встановити розмір пулу ключів &lt;n&gt; (типово: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Пересканувати ланцюжок блоків, в пошуку втрачених транзакцій</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Використовувати OpenSSL (https) для JSON-RPC-з&apos;єднань</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Файл сертифіката сервера (типово: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Закритий ключ сервера (типово: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Допустимі шифри (типово: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Дана довідка</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Неможливо прив&apos;язати до порту %s на цьому комп&apos;ютері (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Підключитись через SOCKS-проксі</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Дозволити пошук в DNS для команд -addnode, -seednode та -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Завантаження адрес...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Помилка при завантаженні wallet.dat: Гаманець пошкоджено</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Menlocoin</source> <translation>Помилка при завантаженні wallet.dat: Гаманець потребує новішої версії Біткоін-клієнта</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Menlocoin to complete</source> <translation>Потрібно перезаписати гаманець: перезапустіть Біткоін-клієнт для завершення</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Помилка при завантаженні wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Помилка в адресі проксі-сервера: «%s»</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Невідома мережа вказана в -onlynet: «%s»</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Помилка у величині комісії -paytxfee=&lt;amount&gt;: «%s»</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Некоректна кількість</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Недостатньо коштів</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Завантаження індексу блоків...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Додати вузол до підключення і лишити його відкритим</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Menlocoin is probably already running.</source> <translation>Неможливо прив&apos;язати до порту %s на цьому комп&apos;ютері. Можливо гаманець вже запущено.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Комісія за КБ</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Завантаження гаманця...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Неможливо записати типову адресу</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Сканування...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Завантаження завершене</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>Помилка</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Ви мусите встановити rpcpassword=&lt;password&gt; в файлі конфігурації: %s Якщо файл не існує, створіть його із правами тільки для читання власником (owner-readable-only).</translation> </message> </context> </TS>
package com.asayama.rps.simulator; public enum Hand { ROCK, PAPER, SCISSORS; }
package foodtruck.linxup; import java.util.List; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.joda.time.DateTime; import foodtruck.model.Location; /** * @author aviolette * @since 11/1/16 */ public class Trip { private Location start; private Location end; private DateTime startTime; private DateTime endTime; private List<Position> positions; private Trip(Builder builder) { this.start = builder.start; this.end = builder.end; this.startTime = builder.startTime; this.endTime = builder.endTime; this.positions = ImmutableList.copyOf(builder.positions); } public static Builder builder() { return new Builder(); } public static Builder builder(Trip instance) { return new Builder(instance); } public String getName() { return start.getShortenedName() + " to " + end.getShortenedName(); } public Location getStart() { return start; } public Location getEnd() { return end; } public DateTime getStartTime() { return startTime; } public DateTime getEndTime() { return endTime; } public List<Position> getPositions() { return positions; } @Override public String toString() { return MoreObjects.toStringHelper(this) // .add("start", start) // .add("end", end) .add("startTime", startTime) .add("endTime", endTime) .toString(); } public static class Builder { private Location start; private Location end; private DateTime startTime; private DateTime endTime; private List<Position> positions = Lists.newLinkedList(); public Builder() { } public Builder(Trip instance) { this.start = instance.start; this.end = instance.end; this.startTime = instance.startTime; this.endTime = instance.endTime; this.positions = instance.positions; } public Builder start(Location start) { this.start = start; return this; } public Builder end(Location end) { this.end = end; return this; } public Builder startTime(DateTime startTime) { this.startTime = startTime; return this; } public Builder endTime(DateTime endTime) { this.endTime = endTime; return this; } public Trip build() { return new Trip(this); } public DateTime getStartTime() { return startTime; } public DateTime getEndTime() { return endTime; } public Builder addPosition(Position position) { positions.add(position); return this; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("start", start.getShortenedName()) .add("end", end.getShortenedName()) // .add("start", start) // .add("end", end) .add("startTime", startTime) .add("endTime", endTime) .toString(); } } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_77) on Sun Aug 13 19:07:39 PKT 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class com.hikmat30ce.workday.integrator.hr.generated.<API key> (<API key> 1.0.0 API)</title> <meta name="date" content="2017-08-13"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.hikmat30ce.workday.integrator.hr.generated.<API key> (<API key> 1.0.0 API)"; } } catch(err) { } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/hikmat30ce/workday/integrator/hr/generated/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <h2 title="Uses of Class com.hikmat30ce.workday.integrator.hr.generated.<API key>" class="title">Uses of Class<br>com.hikmat30ce.workday.integrator.hr.generated.<API key></h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html" title="class in com.hikmat30ce.workday.integrator.hr.generated"><API key></a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.hikmat30ce.workday.integrator.hr.generated">com.hikmat30ce.workday.integrator.hr.generated</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.hikmat30ce.workday.integrator.hr.generated"> </a> <h3>Uses of <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html" title="class in com.hikmat30ce.workday.integrator.hr.generated"><API key></a> in <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/package-summary.html">com.hikmat30ce.workday.integrator.hr.generated</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/package-summary.html">com.hikmat30ce.workday.integrator.hr.generated</a> declared as <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html" title="class in com.hikmat30ce.workday.integrator.hr.generated"><API key></a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html" title="class in com.hikmat30ce.workday.integrator.hr.generated"><API key></a></code></td> <td class="colLast"><span class="typeNameLabel"><API key>.</span><code><span class="memberNameLink"><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html#<API key>"><API key></a></span></code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/package-summary.html">com.hikmat30ce.workday.integrator.hr.generated</a> that return <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html" title="class in com.hikmat30ce.workday.integrator.hr.generated"><API key></a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html" title="class in com.hikmat30ce.workday.integrator.hr.generated"><API key></a></code></td> <td class="colLast"><span class="typeNameLabel">ObjectFactory.</span><code><span class="memberNameLink"><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/ObjectFactory.html#<API key>--"><API key></a></span>()</code> <div class="block">Create an instance of <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html" title="class in com.hikmat30ce.workday.integrator.hr.generated"><code><API key></code></a></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html" title="class in com.hikmat30ce.workday.integrator.hr.generated"><API key></a></code></td> <td class="colLast"><span class="typeNameLabel"><API key>.</span><code><span class="memberNameLink"><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html#<API key>--"><API key></a></span>()</code> <div class="block">Gets the value of the <API key> property.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/package-summary.html">com.hikmat30ce.workday.integrator.hr.generated</a> with parameters of type <a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html" title="class in com.hikmat30ce.workday.integrator.hr.generated"><API key></a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel"><API key>.</span><code><span class="memberNameLink"><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html#<API key>.hikmat30ce.workday.integrator.hr.generated.<API key>-"><API key></a></span>(<a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html" title="class in com.hikmat30ce.workday.integrator.hr.generated"><API key></a>&nbsp;value)</code> <div class="block">Sets the value of the <API key> property.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../com/hikmat30ce/workday/integrator/hr/generated/<API key>.html" title="class in com.hikmat30ce.workday.integrator.hr.generated">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/hikmat30ce/workday/integrator/hr/generated/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.bottom"> </a></div> <p class="legalCopy"><small>Copyright & </body> </html>
Tessellator.TextureDummy = function (ready){ this.super(null); if (ready){ this.setReady(); }; }; Tessellator.extend(Tessellator.TextureDummy, Tessellator.Texture); Tessellator.TextureDummy.prototype.configure = Tessellator.EMPTY_FUNC; Tessellator.TextureDummy.prototype.bind = Tessellator.EMPTY_FUNC;