text
stringlengths
3
1.04M
using BookStore.Client.Utils; using BookStore.Data; using System.Collections.Generic; using System.Data.Entity.Validation; namespace BookStore.Client.Commands { public class OfferReadCommand : BaseCommand, ICommand { public OfferReadCommand(IBookStoreContext context) : base(context) { } //syntax offerread:1 public override string Execute(IList<string> parameters) { parameters.ValidateParameters(1); var result = ErrorMessage.NoID; var offer = this.Context.Offers.Find(int.Parse(parameters[0])); if (offer != null) { try { var title = offer.Book.Title; result = offer.Print(title); } catch (DbEntityValidationException ex) { result = "Entity framework X like u" + ex; } } return result; } } }
MilesTek provides same day shipmet for a wide array of AV cables, including HDMI, Component, S-video, 3.5 mm stereo, XLR, and audio & video assemblies. MilesTek provides same-day shipment for flexible coaxial and twinax cable assemblies. These assemblies are configured with multiple connector combination. Click on the Cable Assembly Wizard to find the cable you need, and create a custom-length. MilesTek maintains a large inventory of network patch cords, SVGA cables, Displayport, and USB cables is wide array of colors and configurations. This inventory is complemented by MilesTek's custom assembly capability whcih allows for quick turns for custom lengths.
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Modal from 'Components/Modal/Modal'; import FileBrowserModalContentConnector from './FileBrowserModalContentConnector'; import styles from './FileBrowserModal.css'; class FileBrowserModal extends Component { // // Render render() { const { isOpen, onModalClose, ...otherProps } = this.props; return ( <Modal className={styles.modal} isOpen={isOpen} onModalClose={onModalClose} > <FileBrowserModalContentConnector {...otherProps} onModalClose={onModalClose} /> </Modal> ); } } FileBrowserModal.propTypes = { isOpen: PropTypes.bool.isRequired, onModalClose: PropTypes.func.isRequired }; export default FileBrowserModal;
Curious human, making universal connections through music. Safari Trio with John Gunther, Victor Mestas, Gonzalo Teppa & special guest Peter Szendofi. @ Five Points Jazz Festival, Saturday May 16, 2pm at "Cervantes' Other Side" John Gunther is a composer and multi-instrumentalist playing Saxophones, Clarinet, and Flute. With a restless musical spirit, he explores all forms of jazz from traditional to avant-garde as well as classical music, world music and experimental electronic music performing on stages throughout the U.S., South America and Europe. He has performed or recorded with many jazz luminaries such as Jimmy Heath, Ron Miles, Dave Douglas, Dewey Redman, Christian McBride, Bill Frisell, Dizzy Gillespie All-Star Big Band, Woody Herman Orchestra, & Maria Schneider Orchestra as well as soloist with Sinfonietta Paris Chamber Orchestra, Carpe Diem String Quartet and Banda Nacional de Cartago in Costa Rica. As part of New York city's "downtown" music scene for many years, he produced five recordings for Creative Improvised Music Projects (CIMP) and is co-founder of the contemporary jazz ensembles, "Spooky Actions" & "Convergence." John is an Associate Professor and Director of the Thompson Jazz Studies Program at the University of Colorado Boulder. In 2007 he founded the Boulder Laptop Orchestra [BLOrk] to explore the intersection of music, performance, art, and technology. John Gunther 2013 All rights reserved. Simple theme. Powered by Blogger.
RE: Email tracking, once the purview of salespeople, is going mainstream. At this point, we're all pretty comfortable with the idea of read receipts on Facebook Messenger, iMessage, WhatsApp, and other messaging services. You send someone a text, and almost immediately can see whether or not it's been delivered or read. Well, an email tracker is like a read receipt for your email. Trackers will let you know if someone read your email or not. (Or at least, a tracker will tell you if someone opened it.) They're becoming increasingly popular. But unlike read receipts in messaging, it's not something you can toggle on or off. The sender turns it on, and the recipient? Well, the recipient probably has no idea whatsoever that the tracker exists. In fact, there are probably a bunch in your mail right now that you aren't aware of. Most email trackers use an "invisible" web beacon — usually a small white pixel — to track email. When you open an email with a beacon in it, your computer accesses the image file, which is then reported to whoever is tracking you. Most of these services can tell you a lot more than just whether or not an email has been opened. They can tell you when and where it was opened, and how many times. They can tell you if multiple people — or at least multiple IP addresses — opened the message. Some, like Mixmax for example, can tell you if the files you sent have been downloaded, or the links you included have been clicked, too. Email tracking was for most of its history pretty much confined to the world of marketing. The majority of the email trackers out there — some of which have been around for over a decade — were initially built for salespeople. customer relationship management (CRM) is a software industry worth billions of dollars, and the ability to measure the impact and engagement (industry terms for attention spent, basically) of the emails you send is a big part of it. Boomerang is an email scheduling app that also offers optional read receipts, a feature that is growing in popularity, with usage up 14% in the last year. But, the company says, only 6% of the people using it are in sales. Conrado Lamas, head of communications at MailTrack, says the number of people who track their emails is exploding. The MailTrack Chrome extension claims over 421,000 active users, and is adding 60,000 new ones very month, according to Lamas. The company, which was founded in Barcelona in 2013, recently ~celebrated~ its 1 billionth tracked email and is nearing 1 million installations. Bananatag, which claims to have more than 250,000 users, says its technology has been used to track around 25 million emails. Lamas estimates that since 2013, the number of people using apps with email trackers has increased by 284%, to nearly 3 million. No doubt most of those millions are tracking emails to their clients, bosses, sources, HR representatives, and assistants, but many are also tracking messages to their spouses, parents, exes, dog walkers, and babysitters. Lamas says half of the people using MailTrack are doing so on their personal email accounts, and other executives in the space agree. "We've seen an increase, especially in personal trackers," Chad Woodford of Trackbuster told BuzzFeed News. Trackbuster, for which Woodford runs product, strips trackers from emails; Woodford also runs product for Senders, an email enhancement app that shows email recipients info from the sender's social media accounts by embedding it into the message. Woodford said Trackbuster was started precisely because the use of invisible email trackers in personal email was on the rise. "Email clients like Outlook used to have a read receipt feature baked into the header of the email. The recipient could decide not to honor that. What bothered us was, the way it works now, they put a hidden pixel or code in the email," Woodford told BuzzFeed News. "It's a little more nefarious in a way." Woodford says, based on the more than 50 million messages processed by Trackbuster and Senders, around 60% of all emails — which includes marketing emails, newsletters, etc. — contain a tracker, while about 11% of personal emails do. Where in the 🌎 are people opening your 📧? So why use an email tracker? They're helpful anytime you're trying to gather intelligence about how someone remotely is interacting with your email. For example, when you're job searching. I emailed Corey's stripper-biting lawyer to ask about 1996. I use email tracking software. He's opened it 17 times! Not everyone is ready for email tracking to go mainstream. A lot of the people BuzzFeed News spoke to said it seems like too much information. Some find it creepy. Others think it's a power play. As you'd expect, there are services out there, like UglyMail, Trackbuster, and PixelBlock, that can warn unsuspecting readers that messages contain trackers, or even remove the email trackers altogether. The CEO of Mixmax said those kinds of tools work sporadically in disabling his product. But what's clear is that, while many people want to know if their sent emails are being opened and read, there's another group who are just as adamant about that information remaining hidden. Email tracking and untracking wars are fascinating.
Professionally Cleaned! Delightful open floor plan w/vaulted ceiling in great room, frplce & Brazilian cherry hardwood flrs. Main floor features 2 bedrooms, study/office & laundry. Kitchen w/SS appliances, granite counters, pantry & large kitchen island. Lovely master ste w/ shower/garden tub, two sinks & spacious walk-in closet. Glass french doors to study/office. Unfinished partial basement w/crawl space for future expansion or great storage. Privacy fenced yard. First American Home Warranty!
<?php namespace SPHERE\Common\Documentation; use SPHERE\Common\Documentation\Designer\Book; /** * Class Designer * * @package SPHERE\Common\Documentation */ class Designer { /** @var Book[] $BookList */ private $BookList = array(); /** * @return string */ public function __toString() { return (string)$this->getContent(); } /** * @return string */ public function getContent() { return implode('', $this->BookList); } /** * @param string $Title * * @return Book */ public function createBook($Title) { $Book = new Book($Title); array_push($this->BookList, $Book); return $Book; } }
thepete.com: That's not light at the end of the tunnel--it's more #snow! #NYC ain't out of the #winter woods yet! (via @NY1weather) That #CooCoo #ClimateChange! That's not light at the end of the tunnel--it's more #snow! #NYC ain't out of the #winter woods yet! (via @NY1weather) That #CooCoo #ClimateChange!
package spatutorial.client.services import diode.ActionResult._ import diode.RootModelRW import diode.data._ import spatutorial.shared._ import utest._ object SPACircuitTests extends TestSuite { def tests = TestSuite { 'TodoHandler - { val model = Ready(Todos(Seq( TodoItem("1", 0, "Test1", TodoLow, completed = false), TodoItem("2", 0, "Test2", TodoLow, completed = false), TodoItem("3", 0, "Test3", TodoHigh, completed = true) ))) val newTodos = Seq( TodoItem("3", 0, "Test3", TodoHigh, completed = true) ) def build = new TodoHandler(new RootModelRW(model)) 'RefreshTodos - { val h = build val result = h.handle(RefreshTodos) result match { case EffectOnly(effects) => assert(effects.size == 1) case _ => assert(false) } } 'UpdateAllTodos - { val h = build val result = h.handle(UpdateAllTodos(newTodos)) assert(result == ModelUpdate(Ready(Todos(newTodos)))) } 'UpdateTodoAdd - { val h = build val result = h.handle(UpdateTodo(TodoItem("4", 0, "Test4", TodoNormal, completed = false))) result match { case ModelUpdateEffect(newValue, effects) => assert(newValue.get.items.size == 4) assert(newValue.get.items(3).id == "4") assert(effects.size == 1) case _ => assert(false) } } 'UpdateTodo - { val h = build val result = h.handle(UpdateTodo(TodoItem("1", 0, "Test111", TodoNormal, completed = false))) result match { case ModelUpdateEffect(newValue, effects) => assert(newValue.get.items.size == 3) assert(newValue.get.items.head.content == "Test111") assert(effects.size == 1) case _ => assert(false) } } 'DeleteTodo - { val h = build val result = h.handle(DeleteTodo(model.get.items.head)) result match { case ModelUpdateEffect(newValue, effects) => assert(newValue.get.items.size == 2) assert(newValue.get.items.head.content == "Test2") assert(effects.size == 1) case _ => assert(false) } } } 'MotdHandler - { val model: Pot[String] = Ready("Message of the Day!") def build = new MotdHandler(new RootModelRW(model)) 'UpdateMotd - { val h = build var result = h.handle(UpdateMotd()) result match { case ModelUpdateEffect(newValue, effects) => assert(newValue.isPending) assert(effects.size == 1) case _ => assert(false) } result = h.handle(UpdateMotd(Ready("New message"))) result match { case ModelUpdate(newValue) => assert(newValue.isReady) assert(newValue.get == "New message") case _ => assert(false) } } } } }
# Micromphale brevipes (Berk. & Ravenel) Singer SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Kew Bull. 8(1): 42 (1953) #### Original name Marasmius brevipes Berk. & Ravenel ### Remarks null
# The largest heading (an <h1> tag) ## The second largest heading (an <h2> tag) … ###### The 6th largest heading (an <h6> tag) In the words of Abraham Lincoln: > Pardon my french *This text will be italic* **This text will be bold** **Everyone _must_ attend the meeting at 5 o'clock today.** ```lua local ffi = require('ffi') local hd = require('hoedown') local bundle = require('luvi').bundle local flags = hd.HOEDOWN_HTML_ESCAPE local renderer = hd.hoedown_html_renderer_new(flags, 0) local extensions = bit.bor( hd.HOEDOWN_EXT_BLOCK, hd.HOEDOWN_EXT_SPAN ) local document = hd.hoedown_document_new(renderer, extensions, 16); local html = hd.hoedown_buffer_new(16) local markdown = bundle.readfile("sample.md") hd.hoedown_document_render(document, html, markdown, #markdown); local string = ffi.string(html.data, html.size) ``` $$ \begin{align*} & \phi(x,y) = \phi \left(\sum_{i=1}^n x_ie_i, \sum_{j=1}^n y_je_j \right) = \sum_{i=1}^n \sum_{j=1}^n x_i y_j \phi(e_i, e_j) = \\ & (x_1, \ldots, x_n) \left( \begin{array}{ccc} \phi(e_1, e_1) & \cdots & \phi(e_1, e_n) \\ \vdots & \ddots & \vdots \\ \phi(e_n, e_1) & \cdots & \phi(e_n, e_n) \end{array} \right) \left( \begin{array}{c} y_1 \\ \vdots \\ y_n \end{array} \right) \end{align*} $$ Does it work with "smart quotes?" Isn't it nice? First Header | Second Header ------------- | ------------- Content Cell | Content Cell Content Cell | Content Cell
//>>built define("dojo/_base/kernel dojo/_base/lang dojo/_base/Color dojo/_base/sniff dojo/_base/window dojo/_base/array dojo/dom dojo/dom-construct dojo/dom-geometry".split(" "),function(t,g,n,k,h,p,u,q,v){var d=g.getObject("dojox.gfx",!0),f=d._base={};d._hasClass=function(a,c){return(a=a.getAttribute("className"))&&0<=(" "+a+" ").indexOf(" "+c+" ")};d._addClass=function(a,c){var b=a.getAttribute("className")||"";(!b||0>(" "+b+" ").indexOf(" "+c+" "))&&a.setAttribute("className",b+(b?" ":"")+c)};d._removeClass= function(a,c){var b=a.getAttribute("className");b&&a.setAttribute("className",b.replace(new RegExp("(^|\\s+)"+c+"(\\s+|$)"),"$1$2"))};f._getFontMeasurements=function(){var a={"1em":0,"1ex":0,"100%":0,"12pt":0,"16px":0,"xx-small":0,"x-small":0,small:0,medium:0,large:0,"x-large":0,"xx-large":0},c,b;k("ie")&&(b=h.doc.documentElement.style.fontSize||"",b||(h.doc.documentElement.style.fontSize="100%"));var e=q.create("div",{style:{position:"absolute",left:"0",top:"-100px",width:"30px",height:"1000em", borderWidth:"0",margin:"0",padding:"0",outline:"none",lineHeight:"1",overflow:"hidden"}},h.body());for(c in a)e.style.fontSize=c,a[c]=16*Math.round(12*e.offsetHeight/16)/12/1E3;k("ie")&&(h.doc.documentElement.style.fontSize=b);h.body().removeChild(e);return a};var l=null;f._getCachedFontMeasurements=function(a){if(a||!l)l=f._getFontMeasurements();return l};var m=null,w={};f._getTextBox=function(a,c,b){var e,d,f=arguments.length,g;m||(m=q.create("div",{style:{position:"absolute",top:"-10000px",left:"0", visibility:"hidden"}},h.body()));e=m;e.className="";d=e.style;d.borderWidth="0";d.margin="0";d.padding="0";d.outline="0";if(1<f&&c)for(g in c)g in w||(d[g]=c[g]);2<f&&b&&(e.className=b);e.innerHTML=a;e.getBoundingClientRect?(d=e.getBoundingClientRect(),d={l:d.left,t:d.top,w:d.width||d.right-d.left,h:d.height||d.bottom-d.top}):d=v.getMarginBox(e);e.innerHTML="";return d};f._computeTextLocation=function(a,c,b,d){var e={};switch(a.align){case "end":e.x=a.x-c;break;case "middle":e.x=a.x-c/2;break;default:e.x= a.x}e.y=a.y-b*(d?.75:1);return e};f._computeTextBoundingBox=function(a){if(!d._base._isRendered(a))return{x:0,y:0,width:0,height:0};var c;c=a.getShape();var b=a.getFont()||d.defaultFont;a=a.getTextWidth();b=d.normalizedLength(b.size);c=f._computeTextLocation(c,a,b,!0);return{x:c.x,y:c.y,width:a,height:b}};f._isRendered=function(a){for(a=a.parent;a&&a.getParent;)a=a.parent;return null!==a};var x=0;f._getUniqueId=function(){var a;do a=t._scopeName+"xUnique"+ ++x;while(u.byId(a));return a};var r=k("pointer-events")? "touchAction":null;f._fixMsTouchAction=r?function(a){a.rawNode.style[r]="none"}:function(){};g.mixin(d,{defaultPath:{type:"path",path:""},defaultPolyline:{type:"polyline",points:[]},defaultRect:{type:"rect",x:0,y:0,width:100,height:100,r:0},defaultEllipse:{type:"ellipse",cx:0,cy:0,rx:200,ry:100},defaultCircle:{type:"circle",cx:0,cy:0,r:100},defaultLine:{type:"line",x1:0,y1:0,x2:100,y2:100},defaultImage:{type:"image",x:0,y:0,width:0,height:0,src:""},defaultText:{type:"text",x:0,y:0,text:"",align:"start", decoration:"none",rotated:!1,kerning:!0},defaultTextPath:{type:"textpath",text:"",align:"start",decoration:"none",rotated:!1,kerning:!0},defaultStroke:{type:"stroke",color:"black",style:"solid",width:1,cap:"butt",join:4},defaultLinearGradient:{type:"linear",x1:0,y1:0,x2:100,y2:100,colors:[{offset:0,color:"black"},{offset:1,color:"white"}]},defaultRadialGradient:{type:"radial",cx:0,cy:0,r:100,colors:[{offset:0,color:"black"},{offset:1,color:"white"}]},defaultPattern:{type:"pattern",x:0,y:0,width:0, height:0,src:""},defaultFont:{type:"font",style:"normal",variant:"normal",weight:"normal",size:"10pt",family:"serif"},getDefault:function(){var a={};return function(c){var b=a[c];if(b)return new b;b=a[c]=new Function;b.prototype=d["default"+c];return new b}}(),normalizeColor:function(a){return a instanceof n?a:new n(a)},normalizeParameters:function(a,c){var b;if(c){var d={};for(b in a)b in c&&!(b in d)&&(a[b]=c[b])}return a},makeParameters:function(a,c){var b=null;if(!c)return g.delegate(a);var d= {};for(b in a)b in d||(d[b]=g.clone(b in c?c[b]:a[b]));return d},formatNumber:function(a,c){var b=a.toString();if(0<=b.indexOf("e"))b=a.toFixed(4);else{var d=b.indexOf(".");0<=d&&5<b.length-d&&(b=a.toFixed(4))}return 0>a?b:c?" "+b:b},makeFontString:function(a){return a.style+" "+a.variant+" "+a.weight+" "+a.size+" "+a.family},splitFontString:function(a){var c=d.getDefault("Font");a=a.split(/\s+/);if(!(5>a.length)){c.style=a[0];c.variant=a[1];c.weight=a[2];var b=a[3].indexOf("/");c.size=0>b?a[3]:a[3].substring(0, b);var e=4;0>b&&("/"==a[4]?e=6:"/"==a[4].charAt(0)&&(e=5));e<a.length&&(c.family=a.slice(e).join(" "))}return c},cm_in_pt:72/2.54,mm_in_pt:7.2/2.54,px_in_pt:function(){return d._base._getCachedFontMeasurements()["12pt"]/12},pt2px:function(a){return a*d.px_in_pt()},px2pt:function(a){return a/d.px_in_pt()},normalizedLength:function(a){if(0===a.length)return 0;if(2<a.length){var c=d.px_in_pt(),b=parseFloat(a);switch(a.slice(-2)){case "px":return b;case "pt":return b*c;case "in":return 72*b*c;case "pc":return 12* b*c;case "mm":return b*d.mm_in_pt*c;case "cm":return b*d.cm_in_pt*c}}return parseFloat(a)},pathVmlRegExp:/([A-Za-z]+)|(\d+(\.\d+)?)|(\.\d+)|(-\d+(\.\d+)?)|(-\.\d+)/g,pathSvgRegExp:/([A-DF-Za-df-z])|([-+]?\d*[.]?\d+(?:[eE][-+]?\d+)?)/g,equalSources:function(a,c){return a&&c&&a===c},switchTo:function(a){var c="string"==typeof a?d[a]:a;c&&(p.forEach("Group Rect Ellipse Circle Line Polyline Image Text Path TextPath EsriPath Surface createSurface fixTarget".split(" "),function(a){d[a]=c[a]}),"string"== typeof a?d.renderer=a:p.some(["svg","vml","canvas","canvasWithEvents","silverlight"],function(a){return d.renderer=d[a]&&d[a].Surface===d.Surface?a:null}))}});return d});
Staff training is essential in the healthcare industry, and training your employees is part of your legislative responsibilities if you work in the healthcare industry. We speak with Lin Pronger Business Manager of Unity Training Solutions to find out more. Unity Training Solutions Ltd was born in 2013 as an innovative training organisation. Sister company to Unity Care Solutions, who have branched out into the Training world! Initially delivering mandatory training for the Care Sector, they have now launched more specialised training courses. Lin started her Unity career as Branch Manager of Unity Care Solutions in January 2009 managing an experienced team of trained nurses and care support workers helping people in their own homes, nursing homes and private businesses. Unity has been established since 2006 and employ over 150 staff in the South East. In this 2:58 second snippet we find out more about NHS Personal Health Budgets. Will the NHS Personal Health Budgets be a blessing or will they add to your already heavy load? This weeks Knowing Your Business show was presented by Ian Gentles and guest presenter Lesley Nell.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Generated by indoc on 23 Oct 2016 --> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="indoc_WI.css" rel="stylesheet" type="text/css" /> <title>26.2. How a novel is published</title> <script type="text/javascript"> function showExtra(id, imid) { if (document.getElementById(id).style.display == 'block') { document.getElementById(id).style.display = 'none'; document.getElementById(imid).src = 'inform:/doc_images/extra.png'; } else { document.getElementById(id).style.display = 'block'; document.getElementById(imid).src = 'inform:/doc_images/extraclose.png'; } } function onLoaded() { if (window.location.hash) { var hash = window.location.hash.substring(2); if (hash.search("_") >= 0) { var res = hash.split("_"); showExample("example"+res[1]); } else { showExample("example"+hash); } } } window.onload=onLoaded; function showExample(id) { if (document.getElementById(id).style.display == 'block') { document.getElementById(id).style.display = 'none'; } else { document.getElementById(id).style.display = 'block'; } } function openExtra(id, imid) { document.getElementById(id).style.display = 'block'; document.getElementById(imid).src = 'inform:/doc_images/extraclose.png'; } function closeExtra(id, imid) { document.getElementById(id).style.display = 'none'; document.getElementById(imid).src = 'inform:/doc_images/extra.png'; } </script> </head> <body class="paper papertint"><script language="JavaScript"> function pasteCode(code) { var myProject = window.Project; myProject.selectView('source'); myProject.pasteCode(code); } </script> <script language="JavaScript"> function createNewProject(code, title) { var myProject = window.Project; myProject.createNewProject(title, code); } </script> <!-- SEARCH TITLE "How a novel is published" --> <!-- SEARCH SECTION "26.2" --> <!-- SEARCH SORT "000-026-002-000" --> <!-- START IGNORE 420 --> <div class="bookheader"> <table class="fullwidth midnightblack"><tr><td class="midnightbannerleftcell"><a href="doc420.html" class="standardlink"><img alt="Hookleft.png" src="inform:/doc_images/Hookleft.png" id="hookleft" /></a></td><td class="midnightbannercentrecell"><a href="index.html" class="standardlink"><span class="midnightbannertext">Chapter 26: Publishing</span></a></td><td class="midnightbannerrightcell"><a href="index.html" class="standardlink"><img alt="Hookup.png" src="inform:/doc_images/Hookup.png" id="hookup" /></a><a href="doc422.html" class="standardlink"><img alt="Hookright.png" src="inform:/doc_images/Hookright.png" id="hookright" /></a></td></tr></table></div> <!-- END IGNORE --> <p class="sectionheading">§26.2. How a novel is published</p> <p>Suppose that a (traditional) novel has been delivered to a publisher: the author has handed it over as a pile of twenty chapters of prose, and feels that it is finished. In fact there is much still to do:</p> <p>(a) Editing. An editor works through the book, looking for problems in the plot, uneven passages, difficulties of tone and a hundred other nuanced points. The author generally then revises the book and submits again.</p> <p>(b) Copy-editing. A copy-editor fixes punctuation errors, awkwardly worded sentences and other low-level problems.</p> <p>(c) Bibliographic data is added.</p> <p>(d) Printing. The text is given a clean, readable rendition, and no longer looks like a home-made typescript.</p> <p>(e) Cover art is added. Even unillustrated novels have pictorial covers, and these images are often used to set the tone for the book - they set the reader's frame of mind, so something more is happening than mere marketing.</p> <p>(f) A back cover blurb is added. This will also find its way into catalogues, onto book trade databases, appear on Amazon.com and so forth. Both a description and a lure, it gives a flavour of the work without actually being any part of it.</p> <p>(g) Binding. Not only are the inside pages printed, but maps, plates of illustrations, free CDs, fold-out charts, etc., may be tipped in to the binding.</p> <p>(h) Legal deposit. Copies are lodged with libraries of record, such as the British Library or the Library of Congress, to ensure that the work cannot be lost from cultural history. (In most countries, this is a legal obligation for publishers.)</p> <p>(i) Shipping. Copies are sent out to bookshops.</p> <p>(j) Publicity. The author and publisher combine to put out the word, circulate leaflets, put up posters and so forth.</p> <p>(k) Reviews and awards. Reviews are published, usually stirring up interest in the book. These having been stellar, a few months later the author bashfully accepts a Pulitzer Prize, the Booker or some similar token of cultural esteem.</p> <hr /> <!-- START IGNORE --> <div class="bookfooter"> <table class="fullwidth"><tr><td class="footerprevious"><a href="doc420.html" class="footerlink">Previous</a></td><td class="footercontents"><a href="index.html" class="footerlink">Contents</a></td><td class="footernext"><a href="doc422.html" class="footerlink">Next</a></td></tr></table> </div> <!-- END IGNORE --> </body> </html>
A Few of this Encore's key features include: **KEYLESS ENTRY**, **FOG LIGHTS**, **POWER WINDOWS**, **HEATED LEATHER SEATS**, **SATELLITE RADIO**, a **BACK-UP CAMERA**, **ALL WHEEL DRIVE**, **TINTED GLASS**, an **AUXILIARY AUDIO INPUT**, **STEERING WHEEL AUDIO CONTROLS**, a **TURBOCHARGED ENGINE**, **REMOTE START**, a Turbocharged Engine, Multi-zone Climate Control, Heated Mirrors, All Wheel Drive, a Back-Up Camera, Satellite Radio, Remote Engine Start, Automatic Climate Control, Steering Wheel Audio Controls, Power Windows, Fog Lights, Electronic Stability Control, an Auxiliary Audio Input, an Onboard Hands-Free Communications System, Heated Seats, **AUTOMATIC CLIMATE CONTROL**l, Heated Steering Wheel, Keyless Entry, and Aluminum Wheels. This 2016 Buick Encore AWD Leather, Stock# 16B123 features a coastal blue metallic exterior with a ebony cloth interior. Factory equipped with an impressive ecotec 1.4l i4 smpi dohc turbocharged vvt engine, and a 6-speed automatic electronic with overdrive with all wheel drive, drivetrain, all-wheel drive (awd.
CBSE counseling is commencing for Class X, XII Board Exams -2019. CBSE is providing physiological counseling to overcome the stress related to board exams 2019 for the students and the parents. 1. 1800118004 is the toll free number which will be operated 24x7 to offer best solutions regarding the board exams. These services are available both in India and abroad. a.Pre Exam-February to April and b.Post Result- May to June and will be over on 4 April 2019 and the timings of the session will be 8am to 10 pm for all the 7 days. 3. The tele counseling is offered by the principals and trained counselors who belongs from the CBSE affiliated private and government schools across the globe. 4. 2019 is the year which will be marked for introducing the Interactive Voice Response system through the toll free number through which the students, parents or even the stakeholders can know all the details about the board exams and can also know the tips to score better in their exams. All these information is pre- recorded as well and will be complimented with live tele counseling services. 5. ’Knowing Children Better’ is an audio-visual presentation which is uploaded on the website of CBSE.
package net.tapi.handynotes; public class HandyNotes11 extends HandyNotes { }
HTMLWidgets.widget({ name: "treeNetwork", type: "output", initialize: function(el, width, height) { var diameter = Math.min(parseInt(width),parseInt(height)); d3.select(el).append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")" + " scale("+diameter/800+","+diameter/800+")"); return d3.layout.tree(); }, resize: function(el, width, height, tree) { var diameter = Math.min(parseInt(width),parseInt(height)); var s = d3.select(el).selectAll("svg"); s.attr("width", width).attr("height", height); tree.size([360, diameter/2 - parseInt(s.attr("margin"))]); var svg = d3.select(el).selectAll("svg").select("g"); svg.attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")" + " scale("+diameter/800+","+diameter/800+")"); }, renderValue: function(el, x, tree) { // x is a list with two elements, options and root; root must already be a // JSON array with the d3Tree root data var s = d3.select(el).selectAll("svg"); var diameter = Math.min(parseInt(s.attr("width")),parseInt(s.attr("height"))); s.attr("margin", x.options.margin); tree.size([360, diameter/2 - parseInt(s.attr("margin"))]) .separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; }); // select the svg group element and remove existing children s.attr("pointer-events", "all").selectAll("*").remove(); s.append("g") .attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")" + " scale("+diameter/800+","+diameter/800+")"); var svg = d3.select(el).selectAll("g"); var root = JSON.parse(x.root); var nodes = tree.nodes(root), links = tree.links(nodes); var diagonal = d3.svg.diagonal.radial() .projection(function(d) { return [d.y, d.x / 180 * Math.PI]; }); // draw links var link = svg.selectAll(".link") .data(links) .enter().append("path") .style("fill", "none") .style("stroke", "#ccc") .style("opacity", "0.55") .style("stroke-width", "1.5px") .attr("d", diagonal); // draw nodes var node = svg.selectAll(".node") .data(nodes) .enter().append("g") .attr("class", "node") .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; }) .on("mouseover", mouseover) .on("mouseout", mouseout); // node circles node.append("circle") .attr("r", 4.5) .style("fill", x.options.nodeColour) .style("opacity", x.options.opacity) .style("stroke", x.options.nodeStroke) .style("stroke-width", "1.5px"); // node text node.append("text") .attr("dy", ".31em") .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; }) .attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; }) .style("font", x.options.fontSize + "px serif") .style("opacity", x.options.opacity) .style("fill", x.options.textColour) .text(function(d) { return d.name; }); // mouseover event handler function mouseover() { d3.select(this).select("circle").transition() .duration(750) .attr("r", 9) d3.select(this).select("text").transition() .duration(750) .attr("dy", ".31em") .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; }) .attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; }) .style("stroke-width", ".5px") .style("font", "25px serif") .style("opacity", 1); } // mouseout event handler function mouseout() { d3.select(this).select("circle").transition() .duration(750) .attr("r", 4.5) d3.select(this).select("text").transition() .duration(750) .attr("dy", ".31em") .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; }) .attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; }) .style("font", x.options.fontSize + "px serif") .style("opacity", x.options.opacity); } }, });
Commercial Remodel, Greensboro, NC | KC's Improvement & Construction Co., Inc. Commercial Remodel, Greensboro, NC | KC's Improvement & Construction Co., Inc. We can help your Greensboro business thrive with a skilled and professional commercial remodel. As your business grows and changes, you might find that what once worked for your space simply doesn’t work anymore. Whether you’ve outgrown your space or are in desperate need of a different and more functional layout, our team at KC’s Improvement & Construction Co., Inc. is here for you and your Greensboro, North Carolina business. The way a place of business is designed and constructed can have a big impact on the way the business is run, managed, and perceived by clients– even the productivity of your employees is affected. In order for your business to keep up with the times, it needs to be functional, as well as energizing and pleasing to the eye. No matter what your business is, our team can help you find the right design to maximize your commercial remodel. At KC’s Improvement & Construction Co., Inc., we have been working in the construction and remodeling business since 1984. That means we have over three decades of experience with businesses big and small, just like yours. We promise we will use this experience to ensure that your commercial remodel is done in a time efficient manner and with a carefully laid-out plan of action. Because any commercial remodel can make your business temporarily lose income, we will work with you to find the best options for your business. Sometimes that means remaining open during construction, and sometimes that means closing your doors temporarily. We will discuss all your viable options during your commercial remodel, so you and your business will be ready when the time comes. If you have any questions about commercial remodeling, we would love to hear from you!
var mainCalendar="Tunniplaan"; var eventsCalendar="Events"; var homeworkCalendar="Homeworks"; var colour="#FAEBD7"; var monday = new Date(); var fullMonthFromToday=new Date(); var dayNumber= monday.getDay(); if(dayNumber==0){dayNumber=7;}//Stupid americans monday.setTime(monday.getTime() - (1000*3600*24*(dayNumber-1))); var sunday = new Date(); sunday.setTime(sunday.getTime() + (1000*3600*24*(7-dayNumber))); fullMonthFromToday.setTime(monday.getTime() + (1000*3600*24*31)); var clientId = '267206477795-nmicslqg1i7kvt6tanp8d8208nnke05p.apps.googleusercontent.com'; var apiKey = 'AIzaSyDXoUmbATnAIXsOWk9qqWZZYHizxD_k60s'; var scopes = 'https://www.googleapis.com/auth/calendar'; var sendToCalendarID = ''; function handleClientLoad() { gapi.client.setApiKey(apiKey); //window.setTimeout(checkAuth,2); checkAuth(); } function checkAuth() { gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult); } function handleAuthResult(authResult) { var authorizeButton = document.getElementById('authorize-button'); if (authResult) { authorizeButton.style.visibility = 'hidden'; listCalendars(); }else { authorizeButton.style.visibility = ''; authorizeButton.onclick = handleAuthClick; } } function handleAuthClick(event) { gapi.auth.authorize( {client_id: clientId, scope: scopes, immediate: false}, handleAuthResult); return false; } function makeApiCall(calId) { gapi.client.load('calendar', 'v3', function() { var request = gapi.client.calendar.events.list({ 'calendarId': calId, 'timeMin': monday, 'timeMax': sunday }); request.execute(function(resp) { var calendarEntries= new Array(); var calendarTimes= new Array(); var calendarEndTimes= new Array(); try{ for (var i = 0; i < resp.items.length; i++) { try{ if(resp.items[i].summary!=null){ calendarEntries.push(resp.items[i].summary); calendarTimes.push(new Date(resp.items[i].start.dateTime)); calendarEndTimes.push(new Date(resp.items[i].end.dateTime)); } }catch(e){} } }catch(e){} putResultToTable(calendarEntries, calendarTimes, calendarEndTimes); }); }); }; function putResultToTable(calendarEntries, calendarTimes, calendarEndTimes){ for(var i = 0; i < calendarEntries.length; i++){ getHoursNumber(calendarTimes[i], calendarEntries[i], calendarEndTimes[i]); } colour="#F0F8FF"; } function getHoursNumber(datetime, calendarEntry , endTime){ var endHours=endTime.getHours(); var hours = datetime.getHours(); var day= datetime.getDay(); console.log(colour); document.getElementById(day+'h'+hours).style.backgroundColor = colour; if(document.getElementById(day+'h'+hours).value!=""){ document.getElementById(day+'h'+hours).innerHTML=calendarEntry; while(hours<endHours){ hours+=1; document.getElementById(day+'h'+hours).style.backgroundColor = colour; } } } function listCalendars () { gapi.client.load('calendar', 'v3', function() { var request = gapi.client.calendar.calendarList.list(); var listContent = '<form id="calendarForm">'; request.execute(function(resp) { console.log(resp.items.length); for (var i = 0, length = resp.items.length; i < length; i++){ if(resp.items[i].summary==mainCalendar || resp.items[i].summary==homeworkCalendar ) { createCalendar(resp.items[i].id, resp.items[i].colorId); } if(resp.items[i].summary==eventsCalendar) { createEventCalendar(resp.items[i].id); } } }); }); } function createEventCalendar(calId){ gapi.client.load('calendar', 'v3', function() { var request = gapi.client.calendar.events.list({ 'calendarId': calId, 'timeMin': monday, 'timeMax': fullMonthFromToday }); request.execute(function(resp) { var calendarEntry=""; var calendarTimes= new Array(); var calendarEndTimes= new Array(); var dateToday=""; try{ for (var i = 0; i < resp.items.length; i++) { if(resp.items[i].summary!=null){ var eventTime=new Date(resp.items[i].start.dateTime); eventStartHour=eventTime.getHours(); dateToday=$.datepicker.formatDate('DD dd MM yy ', new Date(resp.items[i].start.dateTime)); calendarEntry+='<strong>'+resp.items[i].summary+'</strong> - '+dateToday+' '+ eventStartHour+'.00 </br>'; } } }catch(e){} document.getElementById('news-box').innerHTML=calendarEntry; }); }); } function createCalendar(eventId, colourId){ var color=parseInt(colour); switch(color) { case 0: colour="brown"; break; case 1: colour="brown"; break; case 2: colour="red"; break; case 3: colour="red"; break; case 4: colour="red"; break; case 5: colour="red"; break; case 6: colour="orange"; break; case 7: colour="light-green"; break; case 8: colour="light-green"; break; case 9: colour="light-green"; break; case 10: colour="light-green"; break; case 11: colour="yellow"; break; case 12: colour="orange"; break; case 13: colour="cyan"; break; case 14: colour="light-blue"; break; case 15: colour="blue"; break; case 16: colour="blue"; break; case 17: colour="lilac"; break; case 18: colour="lilac"; break; case 19: colour="grey"; break; case 20: colour="grey"; break; case 21: colour="grey"; break; case 22: colour="pink"; break; case 23: colour="lilac"; break; case 24: colour="blue"; break; } makeApiCall(eventId); } function chooseCalendar(){ var radios = document.getElementsByName('calendarId'); for (var i = 0, length = radios.length; i < length; i++) { if (radios[i].checked) { console.log(radios[i].id); sendToCalendarID = radios[i].value; console.log("kalendri id kuhu salvestatakse: "+ sendToCalendarID); makeApiCall(radios[i].value); } } document.getElementById('calendarForm').innerHTML = ''; } function Search(){ title=document.getElementById('name').value; console.log(title); submitForm(title) } function createInstance(){ var req = null; if(window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("XHR not created"); } } } return req; }; createInstance();
The volunteers from Zilverlijn phone elderly people in need of a good conversation. For a chat, or for a laugh. That is badly needed: The Netherlands has about 200,000 extremely lonely old people. The Zilverlijn is an initiative of the KPN Mooiste Contact Fonds and the National Fund for the Elderly. Many elderly people have a need for personal contact: a chat, being able to laugh together with someone. The Netherlands has about 200,000 extremely lonely old people. These are people who have social contact no more than once every 4 weeks. Together with the National Fund for the Elderly, the KPN Mooiste Contact Fonds wants to do something about this major social issue. That’s why we launched the Zilverlijn in 2015. This involves approximately 1,000 volunteers making weekly telephone calls to elderly people in need of contact. Video report about ‘De Zilverlijn’. KPN volunteer Simon Hoogvliet and Brenda Emmen-Hassell, a staff member at the Elderly Fund, demonstrate what the initiative looks like in practice. It’s simple. Elderly people who appreciate a call are telephoned by a KPN volunteer from a specially designed mobile center: the Zilverlijn bus. The Zilverlijn bus regularly parks at different KPN offices. This means it’s possible to keep the call center staffed with a revolving group of KPN volunteers. The volunteers check that everything is ok with the elderly person that they have on the phone. The project is designed so that people don’t have to initiate the contact themselves. Signing up for a conversation with a volunteer is sufficient. In this way, the KPN Mooiste Contact Fonds wants to make it as easy as possible to register for the Zilverlijn. Go to the National Fund for more information and registration.
"Glutathione: Your Body Premier Antioxidant and Detoxifier" For those who have chronic Fatigue, Heart disease, Cancer, Chronic Infections, Autoimmune disease, diabetes, Alzheimer’s, Parkinson's, Arthritis, Asthma, Kidney problems, Liver diseases, you name it. If you are very sick, you most likely have a Glutathione Deficiency. The combination of our modern nutrient-depleted diet, a lack of exercise, high levels of obesity and low levels of a vital enzyme known as glutathione have combined to create a toxic environment perfect for the development of the many lifestyle diseases plaguing humanity today. Over 125 million Americans have at least one chronic condition like heart disease, diabetes or autoimmune illness, with nearly half of us having two or more of these conditions. Glutathione is a simple molecule absolutely essential to the prevention of chronic and age-related diseases. It is produced naturally by the body and is made up of a combination of three protein or amino acid building blocks: cysteine, glycine, and glutamine. (And by the way, LIPOSOMAL GLUTATHIONE from lookingvibrant.com is produced exclusively in Japan through a fermentation process to help increase absorption. It is capable of regenerating itself in the liver and fights the accumulation of free radicals in the body. Free radicals are the result of toxic overload in combination with normal cellular metabolic oxidation and are directly associated with inflammation and disease, particularly autoimmune and other chronic diseases. Glutathione neutralizes toxins and free radicals, boosts immunity, reduces inflammation, repairs DNA, transports amino acids to and from cells, and performs a host of other vital functions. Although glutathione is found in every cell in the body, it is particularly concentrated in the liver – where it works overtime to neutralize the carcinogens, pollutants, and toxins to which we are exposed on a daily basis. The number of people fighting autoimmune diseases has increased dramatically in the past few years, and researchers now believe that these conditions are closely related to a leaky gut syndrome, which allows bacteria, toxins, and antigens to enter the bloodstream, triggering immune reactions and chronic inflammation. The mineral selenium helps to covert reduced glutathione to the oxidized variety, while (NAC) N-acetyl cysteine can raise the levels of glutathione found in older cells. Vitamin C helps to convert oxidized glutathione to the active reduced form, while B-complex vitamins assist with glutathione production.
package com.xthena.hr.manager; import com.xthena.hr.domain.HrShZhaop; import com.xthena.core.hibernate.HibernateEntityDao; import org.springframework.stereotype.Service; @Service public class HrShZhaopManager extends HibernateEntityDao<HrShZhaop> { }
/*! * Pusher JavaScript Library v6.0.1 * https://pusher.com/ * * Copyright 2017, Pusher * Released under the MIT licence. */ var Pusher = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Copyright (C) 2016 Dmitry Chestnykh // MIT License. See LICENSE file for details. var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); /** * Package base64 implements Base64 encoding and decoding. */ // Invalid character used in decoding to indicate // that the character to decode is out of range of // alphabet and cannot be decoded. var INVALID_BYTE = 256; /** * Implements standard Base64 encoding. * * Operates in constant time. */ var Coder = /** @class */ (function () { // TODO(dchest): methods to encode chunk-by-chunk. function Coder(_paddingCharacter) { if (_paddingCharacter === void 0) { _paddingCharacter = "="; } this._paddingCharacter = _paddingCharacter; } Coder.prototype.encodedLength = function (length) { if (!this._paddingCharacter) { return (length * 8 + 5) / 6 | 0; } return (length + 2) / 3 * 4 | 0; }; Coder.prototype.encode = function (data) { var out = ""; var i = 0; for (; i < data.length - 2; i += 3) { var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]); out += this._encodeByte((c >>> 3 * 6) & 63); out += this._encodeByte((c >>> 2 * 6) & 63); out += this._encodeByte((c >>> 1 * 6) & 63); out += this._encodeByte((c >>> 0 * 6) & 63); } var left = data.length - i; if (left > 0) { var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0); out += this._encodeByte((c >>> 3 * 6) & 63); out += this._encodeByte((c >>> 2 * 6) & 63); if (left === 2) { out += this._encodeByte((c >>> 1 * 6) & 63); } else { out += this._paddingCharacter || ""; } out += this._paddingCharacter || ""; } return out; }; Coder.prototype.maxDecodedLength = function (length) { if (!this._paddingCharacter) { return (length * 6 + 7) / 8 | 0; } return length / 4 * 3 | 0; }; Coder.prototype.decodedLength = function (s) { return this.maxDecodedLength(s.length - this._getPaddingLength(s)); }; Coder.prototype.decode = function (s) { if (s.length === 0) { return new Uint8Array(0); } var paddingLength = this._getPaddingLength(s); var length = s.length - paddingLength; var out = new Uint8Array(this.maxDecodedLength(length)); var op = 0; var i = 0; var haveBad = 0; var v0 = 0, v1 = 0, v2 = 0, v3 = 0; for (; i < length - 4; i += 4) { v0 = this._decodeChar(s.charCodeAt(i + 0)); v1 = this._decodeChar(s.charCodeAt(i + 1)); v2 = this._decodeChar(s.charCodeAt(i + 2)); v3 = this._decodeChar(s.charCodeAt(i + 3)); out[op++] = (v0 << 2) | (v1 >>> 4); out[op++] = (v1 << 4) | (v2 >>> 2); out[op++] = (v2 << 6) | v3; haveBad |= v0 & INVALID_BYTE; haveBad |= v1 & INVALID_BYTE; haveBad |= v2 & INVALID_BYTE; haveBad |= v3 & INVALID_BYTE; } if (i < length - 1) { v0 = this._decodeChar(s.charCodeAt(i)); v1 = this._decodeChar(s.charCodeAt(i + 1)); out[op++] = (v0 << 2) | (v1 >>> 4); haveBad |= v0 & INVALID_BYTE; haveBad |= v1 & INVALID_BYTE; } if (i < length - 2) { v2 = this._decodeChar(s.charCodeAt(i + 2)); out[op++] = (v1 << 4) | (v2 >>> 2); haveBad |= v2 & INVALID_BYTE; } if (i < length - 3) { v3 = this._decodeChar(s.charCodeAt(i + 3)); out[op++] = (v2 << 6) | v3; haveBad |= v3 & INVALID_BYTE; } if (haveBad !== 0) { throw new Error("Base64Coder: incorrect characters for decoding"); } return out; }; // Standard encoding have the following encoded/decoded ranges, // which we need to convert between. // // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + / // Index: 0 - 25 26 - 51 52 - 61 62 63 // ASCII: 65 - 90 97 - 122 48 - 57 43 47 // // Encode 6 bits in b into a new character. Coder.prototype._encodeByte = function (b) { // Encoding uses constant time operations as follows: // // 1. Define comparison of A with B using (A - B) >>> 8: // if A > B, then result is positive integer // if A <= B, then result is 0 // // 2. Define selection of C or 0 using bitwise AND: X & C: // if X == 0, then result is 0 // if X != 0, then result is C // // 3. Start with the smallest comparison (b >= 0), which is always // true, so set the result to the starting ASCII value (65). // // 4. Continue comparing b to higher ASCII values, and selecting // zero if comparison isn't true, otherwise selecting a value // to add to result, which: // // a) undoes the previous addition // b) provides new value to add // var result = b; // b >= 0 result += 65; // b > 25 result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97); // b > 51 result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48); // b > 61 result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43); // b > 62 result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47); return String.fromCharCode(result); }; // Decode a character code into a byte. // Must return 256 if character is out of alphabet range. Coder.prototype._decodeChar = function (c) { // Decoding works similar to encoding: using the same comparison // function, but now it works on ranges: result is always incremented // by value, but this value becomes zero if the range is not // satisfied. // // Decoding starts with invalid value, 256, which is then // subtracted when the range is satisfied. If none of the ranges // apply, the function returns 256, which is then checked by // the caller to throw error. var result = INVALID_BYTE; // start with invalid character // c == 43 (c > 42 and c < 44) result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62); // c == 47 (c > 46 and c < 48) result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63); // c > 47 and c < 58 result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52); // c > 64 and c < 91 result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0); // c > 96 and c < 123 result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26); return result; }; Coder.prototype._getPaddingLength = function (s) { var paddingLength = 0; if (this._paddingCharacter) { for (var i = s.length - 1; i >= 0; i--) { if (s[i] !== this._paddingCharacter) { break; } paddingLength++; } if (s.length < 4 || paddingLength > 2) { throw new Error("Base64Coder: incorrect padding"); } } return paddingLength; }; return Coder; }()); exports.Coder = Coder; var stdCoder = new Coder(); function encode(data) { return stdCoder.encode(data); } exports.encode = encode; function decode(s) { return stdCoder.decode(s); } exports.decode = decode; /** * Implements URL-safe Base64 encoding. * (Same as Base64, but '+' is replaced with '-', and '/' with '_'). * * Operates in constant time. */ var URLSafeCoder = /** @class */ (function (_super) { __extends(URLSafeCoder, _super); function URLSafeCoder() { return _super !== null && _super.apply(this, arguments) || this; } // URL-safe encoding have the following encoded/decoded ranges: // // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _ // Index: 0 - 25 26 - 51 52 - 61 62 63 // ASCII: 65 - 90 97 - 122 48 - 57 45 95 // URLSafeCoder.prototype._encodeByte = function (b) { var result = b; // b >= 0 result += 65; // b > 25 result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97); // b > 51 result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48); // b > 61 result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45); // b > 62 result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95); return String.fromCharCode(result); }; URLSafeCoder.prototype._decodeChar = function (c) { var result = INVALID_BYTE; // c == 45 (c > 44 and c < 46) result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62); // c == 95 (c > 94 and c < 96) result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63); // c > 47 and c < 58 result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52); // c > 64 and c < 91 result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0); // c > 96 and c < 123 result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26); return result; }; return URLSafeCoder; }(Coder)); exports.URLSafeCoder = URLSafeCoder; var urlSafeCoder = new URLSafeCoder(); function encodeURLSafe(data) { return urlSafeCoder.encode(data); } exports.encodeURLSafe = encodeURLSafe; function decodeURLSafe(s) { return urlSafeCoder.decode(s); } exports.decodeURLSafe = decodeURLSafe; exports.encodedLength = function (length) { return stdCoder.encodedLength(length); }; exports.maxDecodedLength = function (length) { return stdCoder.maxDecodedLength(length); }; exports.decodedLength = function (s) { return stdCoder.decodedLength(s); }; //# sourceMappingURL=base64.js.map /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Copyright (C) 2016 Dmitry Chestnykh // MIT License. See LICENSE file for details. Object.defineProperty(exports, "__esModule", { value: true }); /** * Package utf8 implements UTF-8 encoding and decoding. */ var INVALID_UTF16 = "utf8: invalid string"; var INVALID_UTF8 = "utf8: invalid source encoding"; /** * Encodes the given string into UTF-8 byte array. * Throws if the source string has invalid UTF-16 encoding. */ function encode(s) { // Calculate result length and allocate output array. // encodedLength() also validates string and throws errors, // so we don't need repeat validation here. var arr = new Uint8Array(encodedLength(s)); var pos = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { arr[pos++] = c; } else if (c < 0x800) { arr[pos++] = 0xc0 | c >> 6; arr[pos++] = 0x80 | c & 0x3f; } else if (c < 0xd800) { arr[pos++] = 0xe0 | c >> 12; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } else { i++; // get one more character c = (c & 0x3ff) << 10; c |= s.charCodeAt(i) & 0x3ff; c += 0x10000; arr[pos++] = 0xf0 | c >> 18; arr[pos++] = 0x80 | (c >> 12) & 0x3f; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } } return arr; } exports.encode = encode; /** * Returns the number of bytes required to encode the given string into UTF-8. * Throws if the source string has invalid UTF-16 encoding. */ function encodedLength(s) { var result = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { result += 1; } else if (c < 0x800) { result += 2; } else if (c < 0xd800) { result += 3; } else if (c <= 0xdfff) { if (i >= s.length - 1) { throw new Error(INVALID_UTF16); } i++; // "eat" next character result += 4; } else { throw new Error(INVALID_UTF16); } } return result; } exports.encodedLength = encodedLength; /** * Decodes the given byte array from UTF-8 into a string. * Throws if encoding is invalid. */ function decode(arr) { var chars = []; for (var i = 0; i < arr.length; i++) { var b = arr[i]; if (b & 0x80) { var min = void 0; if (b < 0xe0) { // Need 1 more byte. if (i >= arr.length) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; if ((n1 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x1f) << 6 | (n1 & 0x3f); min = 0x80; } else if (b < 0xf0) { // Need 2 more bytes. if (i >= arr.length - 1) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 12 | (n1 & 0x3f) << 6 | (n2 & 0x3f); min = 0x800; } else if (b < 0xf8) { // Need 3 more bytes. if (i >= arr.length - 2) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; var n3 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80 || (n3 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 18 | (n1 & 0x3f) << 12 | (n2 & 0x3f) << 6 | (n3 & 0x3f); min = 0x10000; } else { throw new Error(INVALID_UTF8); } if (b < min || (b >= 0xd800 && b <= 0xdfff)) { throw new Error(INVALID_UTF8); } if (b >= 0x10000) { // Surrogate pair. if (b > 0x10ffff) { throw new Error(INVALID_UTF8); } b -= 0x10000; chars.push(String.fromCharCode(0xd800 | (b >> 10))); b = 0xdc00 | (b & 0x3ff); } } chars.push(String.fromCharCode(b)); } return chars.join(""); } exports.decode = decode; //# sourceMappingURL=utf8.js.map /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { // required so we don't have to do require('pusher').default etc. module.exports = __webpack_require__(3).default; /***/ }), /* 3 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // CONCATENATED MODULE: ./src/core/base64.ts function encode(s) { return btoa(utob(s)); } var fromCharCode = String.fromCharCode; var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var b64tab = {}; for (var base64_i = 0, l = b64chars.length; base64_i < l; base64_i++) { b64tab[b64chars.charAt(base64_i)] = base64_i; } var cb_utob = function (c) { var cc = c.charCodeAt(0); return cc < 0x80 ? c : cc < 0x800 ? fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f)) : fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + fromCharCode(0x80 | (cc & 0x3f)); }; var utob = function (u) { return u.replace(/[^\x00-\x7F]/g, cb_utob); }; var cb_encode = function (ccc) { var padlen = [0, 2, 1][ccc.length % 3]; var ord = (ccc.charCodeAt(0) << 16) | ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8) | (ccc.length > 2 ? ccc.charCodeAt(2) : 0); var chars = [ b64chars.charAt(ord >>> 18), b64chars.charAt((ord >>> 12) & 63), padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63), padlen >= 1 ? '=' : b64chars.charAt(ord & 63) ]; return chars.join(''); }; var btoa = self.btoa || function (b) { return b.replace(/[\s\S]{1,3}/g, cb_encode); }; // CONCATENATED MODULE: ./src/core/utils/timers/abstract_timer.ts var Timer = (function () { function Timer(set, clear, delay, callback) { var _this = this; this.clear = clear; this.timer = set(function () { if (_this.timer) { _this.timer = callback(_this.timer); } }, delay); } Timer.prototype.isRunning = function () { return this.timer !== null; }; Timer.prototype.ensureAborted = function () { if (this.timer) { this.clear(this.timer); this.timer = null; } }; return Timer; }()); /* harmony default export */ var abstract_timer = (Timer); // CONCATENATED MODULE: ./src/core/utils/timers/index.ts var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); function timers_clearTimeout(timer) { self.clearTimeout(timer); } function timers_clearInterval(timer) { self.clearInterval(timer); } var OneOffTimer = (function (_super) { __extends(OneOffTimer, _super); function OneOffTimer(delay, callback) { return _super.call(this, setTimeout, timers_clearTimeout, delay, function (timer) { callback(); return null; }) || this; } return OneOffTimer; }(abstract_timer)); var PeriodicTimer = (function (_super) { __extends(PeriodicTimer, _super); function PeriodicTimer(delay, callback) { return _super.call(this, setInterval, timers_clearInterval, delay, function (timer) { callback(); return timer; }) || this; } return PeriodicTimer; }(abstract_timer)); // CONCATENATED MODULE: ./src/core/util.ts var Util = { now: function () { if (Date.now) { return Date.now(); } else { return new Date().valueOf(); } }, defer: function (callback) { return new OneOffTimer(0, callback); }, method: function (name) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var boundArguments = Array.prototype.slice.call(arguments, 1); return function (object) { return object[name].apply(object, boundArguments.concat(arguments)); }; } }; /* harmony default export */ var util = (Util); // CONCATENATED MODULE: ./src/core/utils/collections.ts function extend(target) { var sources = []; for (var _i = 1; _i < arguments.length; _i++) { sources[_i - 1] = arguments[_i]; } for (var i = 0; i < sources.length; i++) { var extensions = sources[i]; for (var property in extensions) { if (extensions[property] && extensions[property].constructor && extensions[property].constructor === Object) { target[property] = extend(target[property] || {}, extensions[property]); } else { target[property] = extensions[property]; } } } return target; } function stringify() { var m = ['Pusher']; for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] === 'string') { m.push(arguments[i]); } else { m.push(safeJSONStringify(arguments[i])); } } return m.join(' : '); } function arrayIndexOf(array, item) { var nativeIndexOf = Array.prototype.indexOf; if (array === null) { return -1; } if (nativeIndexOf && array.indexOf === nativeIndexOf) { return array.indexOf(item); } for (var i = 0, l = array.length; i < l; i++) { if (array[i] === item) { return i; } } return -1; } function objectApply(object, f) { for (var key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { f(object[key], key, object); } } } function keys(object) { var keys = []; objectApply(object, function (_, key) { keys.push(key); }); return keys; } function values(object) { var values = []; objectApply(object, function (value) { values.push(value); }); return values; } function apply(array, f, context) { for (var i = 0; i < array.length; i++) { f.call(context || self, array[i], i, array); } } function map(array, f) { var result = []; for (var i = 0; i < array.length; i++) { result.push(f(array[i], i, array, result)); } return result; } function mapObject(object, f) { var result = {}; objectApply(object, function (value, key) { result[key] = f(value); }); return result; } function filter(array, test) { test = test || function (value) { return !!value; }; var result = []; for (var i = 0; i < array.length; i++) { if (test(array[i], i, array, result)) { result.push(array[i]); } } return result; } function filterObject(object, test) { var result = {}; objectApply(object, function (value, key) { if ((test && test(value, key, object, result)) || Boolean(value)) { result[key] = value; } }); return result; } function flatten(object) { var result = []; objectApply(object, function (value, key) { result.push([key, value]); }); return result; } function any(array, test) { for (var i = 0; i < array.length; i++) { if (test(array[i], i, array)) { return true; } } return false; } function collections_all(array, test) { for (var i = 0; i < array.length; i++) { if (!test(array[i], i, array)) { return false; } } return true; } function encodeParamsObject(data) { return mapObject(data, function (value) { if (typeof value === 'object') { value = safeJSONStringify(value); } return encodeURIComponent(encode(value.toString())); }); } function buildQueryString(data) { var params = filterObject(data, function (value) { return value !== undefined; }); var query = map(flatten(encodeParamsObject(params)), util.method('join', '=')).join('&'); return query; } function decycleObject(object) { var objects = [], paths = []; return (function derez(value, path) { var i, name, nu; switch (typeof value) { case 'object': if (!value) { return null; } for (i = 0; i < objects.length; i += 1) { if (objects[i] === value) { return { $ref: paths[i] }; } } objects.push(value); paths.push(path); if (Object.prototype.toString.apply(value) === '[object Array]') { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = derez(value[i], path + '[' + i + ']'); } } else { nu = {}; for (name in value) { if (Object.prototype.hasOwnProperty.call(value, name)) { nu[name] = derez(value[name], path + '[' + JSON.stringify(name) + ']'); } } } return nu; case 'number': case 'string': case 'boolean': return value; } })(object, '$'); } function safeJSONStringify(source) { try { return JSON.stringify(source); } catch (e) { return JSON.stringify(decycleObject(source)); } } // CONCATENATED MODULE: ./src/core/defaults.ts var Defaults = { VERSION: "6.0.1", PROTOCOL: 7, wsPort: 80, wssPort: 443, wsPath: '', httpHost: 'sockjs.pusher.com', httpPort: 80, httpsPort: 443, httpPath: '/pusher', stats_host: 'stats.pusher.com', authEndpoint: '/pusher/auth', authTransport: 'ajax', activityTimeout: 120000, pongTimeout: 30000, unavailableTimeout: 10000, cluster: 'mt1', cdn_http: "http://js.pusher.com", cdn_https: "https://js.pusher.com", dependency_suffix: "" }; /* harmony default export */ var defaults = (Defaults); // CONCATENATED MODULE: ./src/core/transports/url_schemes.ts function getGenericURL(baseScheme, params, path) { var scheme = baseScheme + (params.useTLS ? 's' : ''); var host = params.useTLS ? params.hostTLS : params.hostNonTLS; return scheme + '://' + host + path; } function getGenericPath(key, queryString) { var path = '/app/' + key; var query = '?protocol=' + defaults.PROTOCOL + '&client=js' + '&version=' + defaults.VERSION + (queryString ? '&' + queryString : ''); return path + query; } var ws = { getInitial: function (key, params) { var path = (params.httpPath || '') + getGenericPath(key, 'flash=false'); return getGenericURL('ws', params, path); } }; var http = { getInitial: function (key, params) { var path = (params.httpPath || '/pusher') + getGenericPath(key); return getGenericURL('http', params, path); } }; var sockjs = { getInitial: function (key, params) { return getGenericURL('http', params, params.httpPath || '/pusher'); }, getPath: function (key, params) { return getGenericPath(key); } }; // CONCATENATED MODULE: ./src/core/events/callback_registry.ts var callback_registry_CallbackRegistry = (function () { function CallbackRegistry() { this._callbacks = {}; } CallbackRegistry.prototype.get = function (name) { return this._callbacks[prefix(name)]; }; CallbackRegistry.prototype.add = function (name, callback, context) { var prefixedEventName = prefix(name); this._callbacks[prefixedEventName] = this._callbacks[prefixedEventName] || []; this._callbacks[prefixedEventName].push({ fn: callback, context: context }); }; CallbackRegistry.prototype.remove = function (name, callback, context) { if (!name && !callback && !context) { this._callbacks = {}; return; } var names = name ? [prefix(name)] : keys(this._callbacks); if (callback || context) { this.removeCallback(names, callback, context); } else { this.removeAllCallbacks(names); } }; CallbackRegistry.prototype.removeCallback = function (names, callback, context) { apply(names, function (name) { this._callbacks[name] = filter(this._callbacks[name] || [], function (binding) { return ((callback && callback !== binding.fn) || (context && context !== binding.context)); }); if (this._callbacks[name].length === 0) { delete this._callbacks[name]; } }, this); }; CallbackRegistry.prototype.removeAllCallbacks = function (names) { apply(names, function (name) { delete this._callbacks[name]; }, this); }; return CallbackRegistry; }()); /* harmony default export */ var callback_registry = (callback_registry_CallbackRegistry); function prefix(name) { return '_' + name; } // CONCATENATED MODULE: ./src/core/events/dispatcher.ts var dispatcher_Dispatcher = (function () { function Dispatcher(failThrough) { this.callbacks = new callback_registry(); this.global_callbacks = []; this.failThrough = failThrough; } Dispatcher.prototype.bind = function (eventName, callback, context) { this.callbacks.add(eventName, callback, context); return this; }; Dispatcher.prototype.bind_global = function (callback) { this.global_callbacks.push(callback); return this; }; Dispatcher.prototype.unbind = function (eventName, callback, context) { this.callbacks.remove(eventName, callback, context); return this; }; Dispatcher.prototype.unbind_global = function (callback) { if (!callback) { this.global_callbacks = []; return this; } this.global_callbacks = filter(this.global_callbacks || [], function (c) { return c !== callback; }); return this; }; Dispatcher.prototype.unbind_all = function () { this.unbind(); this.unbind_global(); return this; }; Dispatcher.prototype.emit = function (eventName, data, metadata) { for (var i = 0; i < this.global_callbacks.length; i++) { this.global_callbacks[i](eventName, data); } var callbacks = this.callbacks.get(eventName); var args = []; if (metadata) { args.push(data, metadata); } else if (data) { args.push(data); } if (callbacks && callbacks.length > 0) { for (var i = 0; i < callbacks.length; i++) { callbacks[i].fn.apply(callbacks[i].context || self, args); } } else if (this.failThrough) { this.failThrough(eventName, data); } return this; }; return Dispatcher; }()); /* harmony default export */ var dispatcher = (dispatcher_Dispatcher); // CONCATENATED MODULE: ./src/core/logger.ts var logger_Logger = (function () { function Logger() { this.globalLog = function (message) { if (self.console && self.console.log) { self.console.log(message); } }; } Logger.prototype.debug = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this.log(this.globalLog, args); }; Logger.prototype.warn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this.log(this.globalLogWarn, args); }; Logger.prototype.error = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this.log(this.globalLogError, args); }; Logger.prototype.globalLogWarn = function (message) { if (self.console && self.console.warn) { self.console.warn(message); } else { this.globalLog(message); } }; Logger.prototype.globalLogError = function (message) { if (self.console && self.console.error) { self.console.error(message); } else { this.globalLogWarn(message); } }; Logger.prototype.log = function (defaultLoggingFunction) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var message = stringify.apply(this, arguments); if (core_pusher.log) { core_pusher.log(message); } else if (core_pusher.logToConsole) { var log = defaultLoggingFunction.bind(this); log(message); } }; return Logger; }()); /* harmony default export */ var logger = (new logger_Logger()); // CONCATENATED MODULE: ./src/core/transports/transport_connection.ts var transport_connection_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var transport_connection_TransportConnection = (function (_super) { transport_connection_extends(TransportConnection, _super); function TransportConnection(hooks, name, priority, key, options) { var _this = _super.call(this) || this; _this.initialize = worker_runtime.transportConnectionInitializer; _this.hooks = hooks; _this.name = name; _this.priority = priority; _this.key = key; _this.options = options; _this.state = 'new'; _this.timeline = options.timeline; _this.activityTimeout = options.activityTimeout; _this.id = _this.timeline.generateUniqueID(); return _this; } TransportConnection.prototype.handlesActivityChecks = function () { return Boolean(this.hooks.handlesActivityChecks); }; TransportConnection.prototype.supportsPing = function () { return Boolean(this.hooks.supportsPing); }; TransportConnection.prototype.connect = function () { var _this = this; if (this.socket || this.state !== 'initialized') { return false; } var url = this.hooks.urls.getInitial(this.key, this.options); try { this.socket = this.hooks.getSocket(url, this.options); } catch (e) { util.defer(function () { _this.onError(e); _this.changeState('closed'); }); return false; } this.bindListeners(); logger.debug('Connecting', { transport: this.name, url: url }); this.changeState('connecting'); return true; }; TransportConnection.prototype.close = function () { if (this.socket) { this.socket.close(); return true; } else { return false; } }; TransportConnection.prototype.send = function (data) { var _this = this; if (this.state === 'open') { util.defer(function () { if (_this.socket) { _this.socket.send(data); } }); return true; } else { return false; } }; TransportConnection.prototype.ping = function () { if (this.state === 'open' && this.supportsPing()) { this.socket.ping(); } }; TransportConnection.prototype.onOpen = function () { if (this.hooks.beforeOpen) { this.hooks.beforeOpen(this.socket, this.hooks.urls.getPath(this.key, this.options)); } this.changeState('open'); this.socket.onopen = undefined; }; TransportConnection.prototype.onError = function (error) { this.emit('error', { type: 'WebSocketError', error: error }); this.timeline.error(this.buildTimelineMessage({ error: error.toString() })); }; TransportConnection.prototype.onClose = function (closeEvent) { if (closeEvent) { this.changeState('closed', { code: closeEvent.code, reason: closeEvent.reason, wasClean: closeEvent.wasClean }); } else { this.changeState('closed'); } this.unbindListeners(); this.socket = undefined; }; TransportConnection.prototype.onMessage = function (message) { this.emit('message', message); }; TransportConnection.prototype.onActivity = function () { this.emit('activity'); }; TransportConnection.prototype.bindListeners = function () { var _this = this; this.socket.onopen = function () { _this.onOpen(); }; this.socket.onerror = function (error) { _this.onError(error); }; this.socket.onclose = function (closeEvent) { _this.onClose(closeEvent); }; this.socket.onmessage = function (message) { _this.onMessage(message); }; if (this.supportsPing()) { this.socket.onactivity = function () { _this.onActivity(); }; } }; TransportConnection.prototype.unbindListeners = function () { if (this.socket) { this.socket.onopen = undefined; this.socket.onerror = undefined; this.socket.onclose = undefined; this.socket.onmessage = undefined; if (this.supportsPing()) { this.socket.onactivity = undefined; } } }; TransportConnection.prototype.changeState = function (state, params) { this.state = state; this.timeline.info(this.buildTimelineMessage({ state: state, params: params })); this.emit(state, params); }; TransportConnection.prototype.buildTimelineMessage = function (message) { return extend({ cid: this.id }, message); }; return TransportConnection; }(dispatcher)); /* harmony default export */ var transport_connection = (transport_connection_TransportConnection); // CONCATENATED MODULE: ./src/core/transports/transport.ts var transport_Transport = (function () { function Transport(hooks) { this.hooks = hooks; } Transport.prototype.isSupported = function (environment) { return this.hooks.isSupported(environment); }; Transport.prototype.createConnection = function (name, priority, key, options) { return new transport_connection(this.hooks, name, priority, key, options); }; return Transport; }()); /* harmony default export */ var transports_transport = (transport_Transport); // CONCATENATED MODULE: ./src/runtimes/isomorphic/transports/transports.ts var WSTransport = new transports_transport({ urls: ws, handlesActivityChecks: false, supportsPing: false, isInitialized: function () { return Boolean(worker_runtime.getWebSocketAPI()); }, isSupported: function () { return Boolean(worker_runtime.getWebSocketAPI()); }, getSocket: function (url) { return worker_runtime.createWebSocket(url); } }); var httpConfiguration = { urls: http, handlesActivityChecks: false, supportsPing: true, isInitialized: function () { return true; } }; var streamingConfiguration = extend({ getSocket: function (url) { return worker_runtime.HTTPFactory.createStreamingSocket(url); } }, httpConfiguration); var pollingConfiguration = extend({ getSocket: function (url) { return worker_runtime.HTTPFactory.createPollingSocket(url); } }, httpConfiguration); var xhrConfiguration = { isSupported: function () { return worker_runtime.isXHRSupported(); } }; var XHRStreamingTransport = new transports_transport((extend({}, streamingConfiguration, xhrConfiguration))); var XHRPollingTransport = new transports_transport(extend({}, pollingConfiguration, xhrConfiguration)); var Transports = { ws: WSTransport, xhr_streaming: XHRStreamingTransport, xhr_polling: XHRPollingTransport }; /* harmony default export */ var transports = (Transports); // CONCATENATED MODULE: ./src/core/transports/assistant_to_the_transport_manager.ts var assistant_to_the_transport_manager_AssistantToTheTransportManager = (function () { function AssistantToTheTransportManager(manager, transport, options) { this.manager = manager; this.transport = transport; this.minPingDelay = options.minPingDelay; this.maxPingDelay = options.maxPingDelay; this.pingDelay = undefined; } AssistantToTheTransportManager.prototype.createConnection = function (name, priority, key, options) { var _this = this; options = extend({}, options, { activityTimeout: this.pingDelay }); var connection = this.transport.createConnection(name, priority, key, options); var openTimestamp = null; var onOpen = function () { connection.unbind('open', onOpen); connection.bind('closed', onClosed); openTimestamp = util.now(); }; var onClosed = function (closeEvent) { connection.unbind('closed', onClosed); if (closeEvent.code === 1002 || closeEvent.code === 1003) { _this.manager.reportDeath(); } else if (!closeEvent.wasClean && openTimestamp) { var lifespan = util.now() - openTimestamp; if (lifespan < 2 * _this.maxPingDelay) { _this.manager.reportDeath(); _this.pingDelay = Math.max(lifespan / 2, _this.minPingDelay); } } }; connection.bind('open', onOpen); return connection; }; AssistantToTheTransportManager.prototype.isSupported = function (environment) { return this.manager.isAlive() && this.transport.isSupported(environment); }; return AssistantToTheTransportManager; }()); /* harmony default export */ var assistant_to_the_transport_manager = (assistant_to_the_transport_manager_AssistantToTheTransportManager); // CONCATENATED MODULE: ./src/core/connection/protocol/protocol.ts var Protocol = { decodeMessage: function (messageEvent) { try { var messageData = JSON.parse(messageEvent.data); var pusherEventData = messageData.data; if (typeof pusherEventData === 'string') { try { pusherEventData = JSON.parse(messageData.data); } catch (e) { } } var pusherEvent = { event: messageData.event, channel: messageData.channel, data: pusherEventData }; if (messageData.user_id) { pusherEvent.user_id = messageData.user_id; } return pusherEvent; } catch (e) { throw { type: 'MessageParseError', error: e, data: messageEvent.data }; } }, encodeMessage: function (event) { return JSON.stringify(event); }, processHandshake: function (messageEvent) { var message = Protocol.decodeMessage(messageEvent); if (message.event === 'pusher:connection_established') { if (!message.data.activity_timeout) { throw 'No activity timeout specified in handshake'; } return { action: 'connected', id: message.data.socket_id, activityTimeout: message.data.activity_timeout * 1000 }; } else if (message.event === 'pusher:error') { return { action: this.getCloseAction(message.data), error: this.getCloseError(message.data) }; } else { throw 'Invalid handshake'; } }, getCloseAction: function (closeEvent) { if (closeEvent.code < 4000) { if (closeEvent.code >= 1002 && closeEvent.code <= 1004) { return 'backoff'; } else { return null; } } else if (closeEvent.code === 4000) { return 'tls_only'; } else if (closeEvent.code < 4100) { return 'refused'; } else if (closeEvent.code < 4200) { return 'backoff'; } else if (closeEvent.code < 4300) { return 'retry'; } else { return 'refused'; } }, getCloseError: function (closeEvent) { if (closeEvent.code !== 1000 && closeEvent.code !== 1001) { return { type: 'PusherError', data: { code: closeEvent.code, message: closeEvent.reason || closeEvent.message } }; } else { return null; } } }; /* harmony default export */ var protocol = (Protocol); // CONCATENATED MODULE: ./src/core/connection/connection.ts var connection_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var connection_Connection = (function (_super) { connection_extends(Connection, _super); function Connection(id, transport) { var _this = _super.call(this) || this; _this.id = id; _this.transport = transport; _this.activityTimeout = transport.activityTimeout; _this.bindListeners(); return _this; } Connection.prototype.handlesActivityChecks = function () { return this.transport.handlesActivityChecks(); }; Connection.prototype.send = function (data) { return this.transport.send(data); }; Connection.prototype.send_event = function (name, data, channel) { var event = { event: name, data: data }; if (channel) { event.channel = channel; } logger.debug('Event sent', event); return this.send(protocol.encodeMessage(event)); }; Connection.prototype.ping = function () { if (this.transport.supportsPing()) { this.transport.ping(); } else { this.send_event('pusher:ping', {}); } }; Connection.prototype.close = function () { this.transport.close(); }; Connection.prototype.bindListeners = function () { var _this = this; var listeners = { message: function (messageEvent) { var pusherEvent; try { pusherEvent = protocol.decodeMessage(messageEvent); } catch (e) { _this.emit('error', { type: 'MessageParseError', error: e, data: messageEvent.data }); } if (pusherEvent !== undefined) { logger.debug('Event recd', pusherEvent); switch (pusherEvent.event) { case 'pusher:error': _this.emit('error', { type: 'PusherError', data: pusherEvent.data }); break; case 'pusher:ping': _this.emit('ping'); break; case 'pusher:pong': _this.emit('pong'); break; } _this.emit('message', pusherEvent); } }, activity: function () { _this.emit('activity'); }, error: function (error) { _this.emit('error', { type: 'WebSocketError', error: error }); }, closed: function (closeEvent) { unbindListeners(); if (closeEvent && closeEvent.code) { _this.handleCloseEvent(closeEvent); } _this.transport = null; _this.emit('closed'); } }; var unbindListeners = function () { objectApply(listeners, function (listener, event) { _this.transport.unbind(event, listener); }); }; objectApply(listeners, function (listener, event) { _this.transport.bind(event, listener); }); }; Connection.prototype.handleCloseEvent = function (closeEvent) { var action = protocol.getCloseAction(closeEvent); var error = protocol.getCloseError(closeEvent); if (error) { this.emit('error', error); } if (action) { this.emit(action, { action: action, error: error }); } }; return Connection; }(dispatcher)); /* harmony default export */ var connection_connection = (connection_Connection); // CONCATENATED MODULE: ./src/core/connection/handshake/index.ts var handshake_Handshake = (function () { function Handshake(transport, callback) { this.transport = transport; this.callback = callback; this.bindListeners(); } Handshake.prototype.close = function () { this.unbindListeners(); this.transport.close(); }; Handshake.prototype.bindListeners = function () { var _this = this; this.onMessage = function (m) { _this.unbindListeners(); var result; try { result = protocol.processHandshake(m); } catch (e) { _this.finish('error', { error: e }); _this.transport.close(); return; } if (result.action === 'connected') { _this.finish('connected', { connection: new connection_connection(result.id, _this.transport), activityTimeout: result.activityTimeout }); } else { _this.finish(result.action, { error: result.error }); _this.transport.close(); } }; this.onClosed = function (closeEvent) { _this.unbindListeners(); var action = protocol.getCloseAction(closeEvent) || 'backoff'; var error = protocol.getCloseError(closeEvent); _this.finish(action, { error: error }); }; this.transport.bind('message', this.onMessage); this.transport.bind('closed', this.onClosed); }; Handshake.prototype.unbindListeners = function () { this.transport.unbind('message', this.onMessage); this.transport.unbind('closed', this.onClosed); }; Handshake.prototype.finish = function (action, params) { this.callback(extend({ transport: this.transport, action: action }, params)); }; return Handshake; }()); /* harmony default export */ var connection_handshake = (handshake_Handshake); // CONCATENATED MODULE: ./src/core/auth/pusher_authorizer.ts var pusher_authorizer_PusherAuthorizer = (function () { function PusherAuthorizer(channel, options) { this.channel = channel; var authTransport = options.authTransport; if (typeof worker_runtime.getAuthorizers()[authTransport] === 'undefined') { throw "'" + authTransport + "' is not a recognized auth transport"; } this.type = authTransport; this.options = options; this.authOptions = options.auth || {}; } PusherAuthorizer.prototype.composeQuery = function (socketId) { var query = 'socket_id=' + encodeURIComponent(socketId) + '&channel_name=' + encodeURIComponent(this.channel.name); for (var i in this.authOptions.params) { query += '&' + encodeURIComponent(i) + '=' + encodeURIComponent(this.authOptions.params[i]); } return query; }; PusherAuthorizer.prototype.authorize = function (socketId, callback) { PusherAuthorizer.authorizers = PusherAuthorizer.authorizers || worker_runtime.getAuthorizers(); PusherAuthorizer.authorizers[this.type].call(this, worker_runtime, socketId, callback); }; return PusherAuthorizer; }()); /* harmony default export */ var pusher_authorizer = (pusher_authorizer_PusherAuthorizer); // CONCATENATED MODULE: ./src/core/timeline/timeline_sender.ts var timeline_sender_TimelineSender = (function () { function TimelineSender(timeline, options) { this.timeline = timeline; this.options = options || {}; } TimelineSender.prototype.send = function (useTLS, callback) { if (this.timeline.isEmpty()) { return; } this.timeline.send(worker_runtime.TimelineTransport.getAgent(this, useTLS), callback); }; return TimelineSender; }()); /* harmony default export */ var timeline_sender = (timeline_sender_TimelineSender); // CONCATENATED MODULE: ./src/core/errors.ts var errors_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var BadEventName = (function (_super) { errors_extends(BadEventName, _super); function BadEventName(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return BadEventName; }(Error)); var RequestTimedOut = (function (_super) { errors_extends(RequestTimedOut, _super); function RequestTimedOut(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return RequestTimedOut; }(Error)); var TransportPriorityTooLow = (function (_super) { errors_extends(TransportPriorityTooLow, _super); function TransportPriorityTooLow(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return TransportPriorityTooLow; }(Error)); var TransportClosed = (function (_super) { errors_extends(TransportClosed, _super); function TransportClosed(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return TransportClosed; }(Error)); var UnsupportedFeature = (function (_super) { errors_extends(UnsupportedFeature, _super); function UnsupportedFeature(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return UnsupportedFeature; }(Error)); var UnsupportedTransport = (function (_super) { errors_extends(UnsupportedTransport, _super); function UnsupportedTransport(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return UnsupportedTransport; }(Error)); var UnsupportedStrategy = (function (_super) { errors_extends(UnsupportedStrategy, _super); function UnsupportedStrategy(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return UnsupportedStrategy; }(Error)); // CONCATENATED MODULE: ./src/core/utils/url_store.ts var urlStore = { baseUrl: 'https://pusher.com', urls: { authenticationEndpoint: { path: '/docs/authenticating_users' }, javascriptQuickStart: { path: '/docs/javascript_quick_start' }, triggeringClientEvents: { path: '/docs/client_api_guide/client_events#trigger-events' }, encryptedChannelSupport: { fullUrl: 'https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support' } } }; var buildLogSuffix = function (key) { var urlPrefix = 'See:'; var urlObj = urlStore.urls[key]; if (!urlObj) return ''; var url; if (urlObj.fullUrl) { url = urlObj.fullUrl; } else if (urlObj.path) { url = urlStore.baseUrl + urlObj.path; } if (!url) return ''; return urlPrefix + " " + url; }; /* harmony default export */ var url_store = ({ buildLogSuffix: buildLogSuffix }); // CONCATENATED MODULE: ./src/core/channels/channel.ts var channel_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var channel_Channel = (function (_super) { channel_extends(Channel, _super); function Channel(name, pusher) { var _this = _super.call(this, function (event, data) { logger.debug('No callbacks on ' + name + ' for ' + event); }) || this; _this.name = name; _this.pusher = pusher; _this.subscribed = false; _this.subscriptionPending = false; _this.subscriptionCancelled = false; return _this; } Channel.prototype.authorize = function (socketId, callback) { return callback(false, { auth: '' }); }; Channel.prototype.trigger = function (event, data) { if (event.indexOf('client-') !== 0) { throw new BadEventName("Event '" + event + "' does not start with 'client-'"); } if (!this.subscribed) { var suffix = url_store.buildLogSuffix('triggeringClientEvents'); logger.warn("Client event triggered before channel 'subscription_succeeded' event . " + suffix); } return this.pusher.send_event(event, data, this.name); }; Channel.prototype.disconnect = function () { this.subscribed = false; this.subscriptionPending = false; }; Channel.prototype.handleEvent = function (event) { var eventName = event.event; var data = event.data; if (eventName === 'pusher_internal:subscription_succeeded') { this.handleSubscriptionSucceededEvent(event); } else if (eventName.indexOf('pusher_internal:') !== 0) { var metadata = {}; this.emit(eventName, data, metadata); } }; Channel.prototype.handleSubscriptionSucceededEvent = function (event) { this.subscriptionPending = false; this.subscribed = true; if (this.subscriptionCancelled) { this.pusher.unsubscribe(this.name); } else { this.emit('pusher:subscription_succeeded', event.data); } }; Channel.prototype.subscribe = function () { var _this = this; if (this.subscribed) { return; } this.subscriptionPending = true; this.subscriptionCancelled = false; this.authorize(this.pusher.connection.socket_id, function (error, data) { if (error) { logger.error(data); _this.emit('pusher:subscription_error', data); } else { data = data; _this.pusher.send_event('pusher:subscribe', { auth: data.auth, channel_data: data.channel_data, channel: _this.name }); } }); }; Channel.prototype.unsubscribe = function () { this.subscribed = false; this.pusher.send_event('pusher:unsubscribe', { channel: this.name }); }; Channel.prototype.cancelSubscription = function () { this.subscriptionCancelled = true; }; Channel.prototype.reinstateSubscription = function () { this.subscriptionCancelled = false; }; return Channel; }(dispatcher)); /* harmony default export */ var channels_channel = (channel_Channel); // CONCATENATED MODULE: ./src/core/channels/private_channel.ts var private_channel_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var private_channel_PrivateChannel = (function (_super) { private_channel_extends(PrivateChannel, _super); function PrivateChannel() { return _super !== null && _super.apply(this, arguments) || this; } PrivateChannel.prototype.authorize = function (socketId, callback) { var authorizer = factory.createAuthorizer(this, this.pusher.config); return authorizer.authorize(socketId, callback); }; return PrivateChannel; }(channels_channel)); /* harmony default export */ var private_channel = (private_channel_PrivateChannel); // CONCATENATED MODULE: ./src/core/channels/members.ts var members_Members = (function () { function Members() { this.reset(); } Members.prototype.get = function (id) { if (Object.prototype.hasOwnProperty.call(this.members, id)) { return { id: id, info: this.members[id] }; } else { return null; } }; Members.prototype.each = function (callback) { var _this = this; objectApply(this.members, function (member, id) { callback(_this.get(id)); }); }; Members.prototype.setMyID = function (id) { this.myID = id; }; Members.prototype.onSubscription = function (subscriptionData) { this.members = subscriptionData.presence.hash; this.count = subscriptionData.presence.count; this.me = this.get(this.myID); }; Members.prototype.addMember = function (memberData) { if (this.get(memberData.user_id) === null) { this.count++; } this.members[memberData.user_id] = memberData.user_info; return this.get(memberData.user_id); }; Members.prototype.removeMember = function (memberData) { var member = this.get(memberData.user_id); if (member) { delete this.members[memberData.user_id]; this.count--; } return member; }; Members.prototype.reset = function () { this.members = {}; this.count = 0; this.myID = null; this.me = null; }; return Members; }()); /* harmony default export */ var members = (members_Members); // CONCATENATED MODULE: ./src/core/channels/presence_channel.ts var presence_channel_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var presence_channel_PresenceChannel = (function (_super) { presence_channel_extends(PresenceChannel, _super); function PresenceChannel(name, pusher) { var _this = _super.call(this, name, pusher) || this; _this.members = new members(); return _this; } PresenceChannel.prototype.authorize = function (socketId, callback) { var _this = this; _super.prototype.authorize.call(this, socketId, function (error, authData) { if (!error) { authData = authData; if (authData.channel_data === undefined) { var suffix = url_store.buildLogSuffix('authenticationEndpoint'); logger.error("Invalid auth response for channel '" + _this.name + "'," + ("expected 'channel_data' field. " + suffix)); callback('Invalid auth response'); return; } var channelData = JSON.parse(authData.channel_data); _this.members.setMyID(channelData.user_id); } callback(error, authData); }); }; PresenceChannel.prototype.handleEvent = function (event) { var eventName = event.event; if (eventName.indexOf('pusher_internal:') === 0) { this.handleInternalEvent(event); } else { var data = event.data; var metadata = {}; if (event.user_id) { metadata.user_id = event.user_id; } this.emit(eventName, data, metadata); } }; PresenceChannel.prototype.handleInternalEvent = function (event) { var eventName = event.event; var data = event.data; switch (eventName) { case 'pusher_internal:subscription_succeeded': this.handleSubscriptionSucceededEvent(event); break; case 'pusher_internal:member_added': var addedMember = this.members.addMember(data); this.emit('pusher:member_added', addedMember); break; case 'pusher_internal:member_removed': var removedMember = this.members.removeMember(data); if (removedMember) { this.emit('pusher:member_removed', removedMember); } break; } }; PresenceChannel.prototype.handleSubscriptionSucceededEvent = function (event) { this.subscriptionPending = false; this.subscribed = true; if (this.subscriptionCancelled) { this.pusher.unsubscribe(this.name); } else { this.members.onSubscription(event.data); this.emit('pusher:subscription_succeeded', this.members); } }; PresenceChannel.prototype.disconnect = function () { this.members.reset(); _super.prototype.disconnect.call(this); }; return PresenceChannel; }(private_channel)); /* harmony default export */ var presence_channel = (presence_channel_PresenceChannel); // EXTERNAL MODULE: ./node_modules/@stablelib/utf8/lib/utf8.js var utf8 = __webpack_require__(1); // EXTERNAL MODULE: ./node_modules/@stablelib/base64/lib/base64.js var base64 = __webpack_require__(0); // CONCATENATED MODULE: ./src/core/channels/encrypted_channel.ts var encrypted_channel_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var encrypted_channel_EncryptedChannel = (function (_super) { encrypted_channel_extends(EncryptedChannel, _super); function EncryptedChannel(name, pusher, nacl) { var _this = _super.call(this, name, pusher) || this; _this.key = null; _this.nacl = nacl; return _this; } EncryptedChannel.prototype.authorize = function (socketId, callback) { var _this = this; _super.prototype.authorize.call(this, socketId, function (error, authData) { if (error) { callback(true, authData); return; } var sharedSecret = authData['shared_secret']; if (!sharedSecret) { var errorMsg = "No shared_secret key in auth payload for encrypted channel: " + _this.name; callback(true, errorMsg); return; } _this.key = Object(base64["decode"])(sharedSecret); delete authData['shared_secret']; callback(false, authData); }); }; EncryptedChannel.prototype.trigger = function (event, data) { throw new UnsupportedFeature('Client events are not currently supported for encrypted channels'); }; EncryptedChannel.prototype.handleEvent = function (event) { var eventName = event.event; var data = event.data; if (eventName.indexOf('pusher_internal:') === 0 || eventName.indexOf('pusher:') === 0) { _super.prototype.handleEvent.call(this, event); return; } this.handleEncryptedEvent(eventName, data); }; EncryptedChannel.prototype.handleEncryptedEvent = function (event, data) { var _this = this; if (!this.key) { logger.debug('Received encrypted event before key has been retrieved from the authEndpoint'); return; } if (!data.ciphertext || !data.nonce) { logger.error('Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: ' + data); return; } var cipherText = Object(base64["decode"])(data.ciphertext); if (cipherText.length < this.nacl.secretbox.overheadLength) { logger.error("Expected encrypted event ciphertext length to be " + this.nacl.secretbox.overheadLength + ", got: " + cipherText.length); return; } var nonce = Object(base64["decode"])(data.nonce); if (nonce.length < this.nacl.secretbox.nonceLength) { logger.error("Expected encrypted event nonce length to be " + this.nacl.secretbox.nonceLength + ", got: " + nonce.length); return; } var bytes = this.nacl.secretbox.open(cipherText, nonce, this.key); if (bytes === null) { logger.debug('Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint...'); this.authorize(this.pusher.connection.socket_id, function (error, authData) { if (error) { logger.error("Failed to make a request to the authEndpoint: " + authData + ". Unable to fetch new key, so dropping encrypted event"); return; } bytes = _this.nacl.secretbox.open(cipherText, nonce, _this.key); if (bytes === null) { logger.error("Failed to decrypt event with new key. Dropping encrypted event"); return; } _this.emitJSON(event, Object(utf8["decode"])(bytes)); return; }); return; } this.emitJSON(event, Object(utf8["decode"])(bytes)); }; EncryptedChannel.prototype.emitJSON = function (eventName, data) { try { this.emit(eventName, JSON.parse(data)); } catch (e) { this.emit(eventName, data); } return this; }; return EncryptedChannel; }(private_channel)); /* harmony default export */ var encrypted_channel = (encrypted_channel_EncryptedChannel); // CONCATENATED MODULE: ./src/core/connection/connection_manager.ts var connection_manager_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var connection_manager_ConnectionManager = (function (_super) { connection_manager_extends(ConnectionManager, _super); function ConnectionManager(key, options) { var _this = _super.call(this) || this; _this.state = 'initialized'; _this.connection = null; _this.key = key; _this.options = options; _this.timeline = _this.options.timeline; _this.usingTLS = _this.options.useTLS; _this.errorCallbacks = _this.buildErrorCallbacks(); _this.connectionCallbacks = _this.buildConnectionCallbacks(_this.errorCallbacks); _this.handshakeCallbacks = _this.buildHandshakeCallbacks(_this.errorCallbacks); var Network = worker_runtime.getNetwork(); Network.bind('online', function () { _this.timeline.info({ netinfo: 'online' }); if (_this.state === 'connecting' || _this.state === 'unavailable') { _this.retryIn(0); } }); Network.bind('offline', function () { _this.timeline.info({ netinfo: 'offline' }); if (_this.connection) { _this.sendActivityCheck(); } }); _this.updateStrategy(); return _this; } ConnectionManager.prototype.connect = function () { if (this.connection || this.runner) { return; } if (!this.strategy.isSupported()) { this.updateState('failed'); return; } this.updateState('connecting'); this.startConnecting(); this.setUnavailableTimer(); }; ConnectionManager.prototype.send = function (data) { if (this.connection) { return this.connection.send(data); } else { return false; } }; ConnectionManager.prototype.send_event = function (name, data, channel) { if (this.connection) { return this.connection.send_event(name, data, channel); } else { return false; } }; ConnectionManager.prototype.disconnect = function () { this.disconnectInternally(); this.updateState('disconnected'); }; ConnectionManager.prototype.isUsingTLS = function () { return this.usingTLS; }; ConnectionManager.prototype.startConnecting = function () { var _this = this; var callback = function (error, handshake) { if (error) { _this.runner = _this.strategy.connect(0, callback); } else { if (handshake.action === 'error') { _this.emit('error', { type: 'HandshakeError', error: handshake.error }); _this.timeline.error({ handshakeError: handshake.error }); } else { _this.abortConnecting(); _this.handshakeCallbacks[handshake.action](handshake); } } }; this.runner = this.strategy.connect(0, callback); }; ConnectionManager.prototype.abortConnecting = function () { if (this.runner) { this.runner.abort(); this.runner = null; } }; ConnectionManager.prototype.disconnectInternally = function () { this.abortConnecting(); this.clearRetryTimer(); this.clearUnavailableTimer(); if (this.connection) { var connection = this.abandonConnection(); connection.close(); } }; ConnectionManager.prototype.updateStrategy = function () { this.strategy = this.options.getStrategy({ key: this.key, timeline: this.timeline, useTLS: this.usingTLS }); }; ConnectionManager.prototype.retryIn = function (delay) { var _this = this; this.timeline.info({ action: 'retry', delay: delay }); if (delay > 0) { this.emit('connecting_in', Math.round(delay / 1000)); } this.retryTimer = new OneOffTimer(delay || 0, function () { _this.disconnectInternally(); _this.connect(); }); }; ConnectionManager.prototype.clearRetryTimer = function () { if (this.retryTimer) { this.retryTimer.ensureAborted(); this.retryTimer = null; } }; ConnectionManager.prototype.setUnavailableTimer = function () { var _this = this; this.unavailableTimer = new OneOffTimer(this.options.unavailableTimeout, function () { _this.updateState('unavailable'); }); }; ConnectionManager.prototype.clearUnavailableTimer = function () { if (this.unavailableTimer) { this.unavailableTimer.ensureAborted(); } }; ConnectionManager.prototype.sendActivityCheck = function () { var _this = this; this.stopActivityCheck(); this.connection.ping(); this.activityTimer = new OneOffTimer(this.options.pongTimeout, function () { _this.timeline.error({ pong_timed_out: _this.options.pongTimeout }); _this.retryIn(0); }); }; ConnectionManager.prototype.resetActivityCheck = function () { var _this = this; this.stopActivityCheck(); if (this.connection && !this.connection.handlesActivityChecks()) { this.activityTimer = new OneOffTimer(this.activityTimeout, function () { _this.sendActivityCheck(); }); } }; ConnectionManager.prototype.stopActivityCheck = function () { if (this.activityTimer) { this.activityTimer.ensureAborted(); } }; ConnectionManager.prototype.buildConnectionCallbacks = function (errorCallbacks) { var _this = this; return extend({}, errorCallbacks, { message: function (message) { _this.resetActivityCheck(); _this.emit('message', message); }, ping: function () { _this.send_event('pusher:pong', {}); }, activity: function () { _this.resetActivityCheck(); }, error: function (error) { _this.emit('error', { type: 'WebSocketError', error: error }); }, closed: function () { _this.abandonConnection(); if (_this.shouldRetry()) { _this.retryIn(1000); } } }); }; ConnectionManager.prototype.buildHandshakeCallbacks = function (errorCallbacks) { var _this = this; return extend({}, errorCallbacks, { connected: function (handshake) { _this.activityTimeout = Math.min(_this.options.activityTimeout, handshake.activityTimeout, handshake.connection.activityTimeout || Infinity); _this.clearUnavailableTimer(); _this.setConnection(handshake.connection); _this.socket_id = _this.connection.id; _this.updateState('connected', { socket_id: _this.socket_id }); } }); }; ConnectionManager.prototype.buildErrorCallbacks = function () { var _this = this; var withErrorEmitted = function (callback) { return function (result) { if (result.error) { _this.emit('error', { type: 'WebSocketError', error: result.error }); } callback(result); }; }; return { tls_only: withErrorEmitted(function () { _this.usingTLS = true; _this.updateStrategy(); _this.retryIn(0); }), refused: withErrorEmitted(function () { _this.disconnect(); }), backoff: withErrorEmitted(function () { _this.retryIn(1000); }), retry: withErrorEmitted(function () { _this.retryIn(0); }) }; }; ConnectionManager.prototype.setConnection = function (connection) { this.connection = connection; for (var event in this.connectionCallbacks) { this.connection.bind(event, this.connectionCallbacks[event]); } this.resetActivityCheck(); }; ConnectionManager.prototype.abandonConnection = function () { if (!this.connection) { return; } this.stopActivityCheck(); for (var event in this.connectionCallbacks) { this.connection.unbind(event, this.connectionCallbacks[event]); } var connection = this.connection; this.connection = null; return connection; }; ConnectionManager.prototype.updateState = function (newState, data) { var previousState = this.state; this.state = newState; if (previousState !== newState) { var newStateDescription = newState; if (newStateDescription === 'connected') { newStateDescription += ' with new socket ID ' + data.socket_id; } logger.debug('State changed', previousState + ' -> ' + newStateDescription); this.timeline.info({ state: newState, params: data }); this.emit('state_change', { previous: previousState, current: newState }); this.emit(newState, data); } }; ConnectionManager.prototype.shouldRetry = function () { return this.state === 'connecting' || this.state === 'connected'; }; return ConnectionManager; }(dispatcher)); /* harmony default export */ var connection_manager = (connection_manager_ConnectionManager); // CONCATENATED MODULE: ./src/core/channels/channels.ts var channels_Channels = (function () { function Channels() { this.channels = {}; } Channels.prototype.add = function (name, pusher) { if (!this.channels[name]) { this.channels[name] = createChannel(name, pusher); } return this.channels[name]; }; Channels.prototype.all = function () { return values(this.channels); }; Channels.prototype.find = function (name) { return this.channels[name]; }; Channels.prototype.remove = function (name) { var channel = this.channels[name]; delete this.channels[name]; return channel; }; Channels.prototype.disconnect = function () { objectApply(this.channels, function (channel) { channel.disconnect(); }); }; return Channels; }()); /* harmony default export */ var channels = (channels_Channels); function createChannel(name, pusher) { if (name.indexOf('private-encrypted-') === 0) { if (pusher.config.nacl) { return factory.createEncryptedChannel(name, pusher, pusher.config.nacl); } var errMsg = 'Tried to subscribe to a private-encrypted- channel but no nacl implementation available'; var suffix = url_store.buildLogSuffix('encryptedChannelSupport'); throw new UnsupportedFeature(errMsg + ". " + suffix); } else if (name.indexOf('private-') === 0) { return factory.createPrivateChannel(name, pusher); } else if (name.indexOf('presence-') === 0) { return factory.createPresenceChannel(name, pusher); } else { return factory.createChannel(name, pusher); } } // CONCATENATED MODULE: ./src/core/utils/factory.ts var Factory = { createChannels: function () { return new channels(); }, createConnectionManager: function (key, options) { return new connection_manager(key, options); }, createChannel: function (name, pusher) { return new channels_channel(name, pusher); }, createPrivateChannel: function (name, pusher) { return new private_channel(name, pusher); }, createPresenceChannel: function (name, pusher) { return new presence_channel(name, pusher); }, createEncryptedChannel: function (name, pusher, nacl) { return new encrypted_channel(name, pusher, nacl); }, createTimelineSender: function (timeline, options) { return new timeline_sender(timeline, options); }, createAuthorizer: function (channel, options) { if (options.authorizer) { return options.authorizer(channel, options); } return new pusher_authorizer(channel, options); }, createHandshake: function (transport, callback) { return new connection_handshake(transport, callback); }, createAssistantToTheTransportManager: function (manager, transport, options) { return new assistant_to_the_transport_manager(manager, transport, options); } }; /* harmony default export */ var factory = (Factory); // CONCATENATED MODULE: ./src/core/transports/transport_manager.ts var transport_manager_TransportManager = (function () { function TransportManager(options) { this.options = options || {}; this.livesLeft = this.options.lives || Infinity; } TransportManager.prototype.getAssistant = function (transport) { return factory.createAssistantToTheTransportManager(this, transport, { minPingDelay: this.options.minPingDelay, maxPingDelay: this.options.maxPingDelay }); }; TransportManager.prototype.isAlive = function () { return this.livesLeft > 0; }; TransportManager.prototype.reportDeath = function () { this.livesLeft -= 1; }; return TransportManager; }()); /* harmony default export */ var transport_manager = (transport_manager_TransportManager); // CONCATENATED MODULE: ./src/core/strategies/sequential_strategy.ts var sequential_strategy_SequentialStrategy = (function () { function SequentialStrategy(strategies, options) { this.strategies = strategies; this.loop = Boolean(options.loop); this.failFast = Boolean(options.failFast); this.timeout = options.timeout; this.timeoutLimit = options.timeoutLimit; } SequentialStrategy.prototype.isSupported = function () { return any(this.strategies, util.method('isSupported')); }; SequentialStrategy.prototype.connect = function (minPriority, callback) { var _this = this; var strategies = this.strategies; var current = 0; var timeout = this.timeout; var runner = null; var tryNextStrategy = function (error, handshake) { if (handshake) { callback(null, handshake); } else { current = current + 1; if (_this.loop) { current = current % strategies.length; } if (current < strategies.length) { if (timeout) { timeout = timeout * 2; if (_this.timeoutLimit) { timeout = Math.min(timeout, _this.timeoutLimit); } } runner = _this.tryStrategy(strategies[current], minPriority, { timeout: timeout, failFast: _this.failFast }, tryNextStrategy); } else { callback(true); } } }; runner = this.tryStrategy(strategies[current], minPriority, { timeout: timeout, failFast: this.failFast }, tryNextStrategy); return { abort: function () { runner.abort(); }, forceMinPriority: function (p) { minPriority = p; if (runner) { runner.forceMinPriority(p); } } }; }; SequentialStrategy.prototype.tryStrategy = function (strategy, minPriority, options, callback) { var timer = null; var runner = null; if (options.timeout > 0) { timer = new OneOffTimer(options.timeout, function () { runner.abort(); callback(true); }); } runner = strategy.connect(minPriority, function (error, handshake) { if (error && timer && timer.isRunning() && !options.failFast) { return; } if (timer) { timer.ensureAborted(); } callback(error, handshake); }); return { abort: function () { if (timer) { timer.ensureAborted(); } runner.abort(); }, forceMinPriority: function (p) { runner.forceMinPriority(p); } }; }; return SequentialStrategy; }()); /* harmony default export */ var sequential_strategy = (sequential_strategy_SequentialStrategy); // CONCATENATED MODULE: ./src/core/strategies/best_connected_ever_strategy.ts var best_connected_ever_strategy_BestConnectedEverStrategy = (function () { function BestConnectedEverStrategy(strategies) { this.strategies = strategies; } BestConnectedEverStrategy.prototype.isSupported = function () { return any(this.strategies, util.method('isSupported')); }; BestConnectedEverStrategy.prototype.connect = function (minPriority, callback) { return connect(this.strategies, minPriority, function (i, runners) { return function (error, handshake) { runners[i].error = error; if (error) { if (allRunnersFailed(runners)) { callback(true); } return; } apply(runners, function (runner) { runner.forceMinPriority(handshake.transport.priority); }); callback(null, handshake); }; }); }; return BestConnectedEverStrategy; }()); /* harmony default export */ var best_connected_ever_strategy = (best_connected_ever_strategy_BestConnectedEverStrategy); function connect(strategies, minPriority, callbackBuilder) { var runners = map(strategies, function (strategy, i, _, rs) { return strategy.connect(minPriority, callbackBuilder(i, rs)); }); return { abort: function () { apply(runners, abortRunner); }, forceMinPriority: function (p) { apply(runners, function (runner) { runner.forceMinPriority(p); }); } }; } function allRunnersFailed(runners) { return collections_all(runners, function (runner) { return Boolean(runner.error); }); } function abortRunner(runner) { if (!runner.error && !runner.aborted) { runner.abort(); runner.aborted = true; } } // CONCATENATED MODULE: ./src/core/strategies/cached_strategy.ts var cached_strategy_CachedStrategy = (function () { function CachedStrategy(strategy, transports, options) { this.strategy = strategy; this.transports = transports; this.ttl = options.ttl || 1800 * 1000; this.usingTLS = options.useTLS; this.timeline = options.timeline; } CachedStrategy.prototype.isSupported = function () { return this.strategy.isSupported(); }; CachedStrategy.prototype.connect = function (minPriority, callback) { var usingTLS = this.usingTLS; var info = fetchTransportCache(usingTLS); var strategies = [this.strategy]; if (info && info.timestamp + this.ttl >= util.now()) { var transport = this.transports[info.transport]; if (transport) { this.timeline.info({ cached: true, transport: info.transport, latency: info.latency }); strategies.push(new sequential_strategy([transport], { timeout: info.latency * 2 + 1000, failFast: true })); } } var startTimestamp = util.now(); var runner = strategies .pop() .connect(minPriority, function cb(error, handshake) { if (error) { flushTransportCache(usingTLS); if (strategies.length > 0) { startTimestamp = util.now(); runner = strategies.pop().connect(minPriority, cb); } else { callback(error); } } else { storeTransportCache(usingTLS, handshake.transport.name, util.now() - startTimestamp); callback(null, handshake); } }); return { abort: function () { runner.abort(); }, forceMinPriority: function (p) { minPriority = p; if (runner) { runner.forceMinPriority(p); } } }; }; return CachedStrategy; }()); /* harmony default export */ var cached_strategy = (cached_strategy_CachedStrategy); function getTransportCacheKey(usingTLS) { return 'pusherTransport' + (usingTLS ? 'TLS' : 'NonTLS'); } function fetchTransportCache(usingTLS) { var storage = worker_runtime.getLocalStorage(); if (storage) { try { var serializedCache = storage[getTransportCacheKey(usingTLS)]; if (serializedCache) { return JSON.parse(serializedCache); } } catch (e) { flushTransportCache(usingTLS); } } return null; } function storeTransportCache(usingTLS, transport, latency) { var storage = worker_runtime.getLocalStorage(); if (storage) { try { storage[getTransportCacheKey(usingTLS)] = safeJSONStringify({ timestamp: util.now(), transport: transport, latency: latency }); } catch (e) { } } } function flushTransportCache(usingTLS) { var storage = worker_runtime.getLocalStorage(); if (storage) { try { delete storage[getTransportCacheKey(usingTLS)]; } catch (e) { } } } // CONCATENATED MODULE: ./src/core/strategies/delayed_strategy.ts var delayed_strategy_DelayedStrategy = (function () { function DelayedStrategy(strategy, _a) { var number = _a.delay; this.strategy = strategy; this.options = { delay: number }; } DelayedStrategy.prototype.isSupported = function () { return this.strategy.isSupported(); }; DelayedStrategy.prototype.connect = function (minPriority, callback) { var strategy = this.strategy; var runner; var timer = new OneOffTimer(this.options.delay, function () { runner = strategy.connect(minPriority, callback); }); return { abort: function () { timer.ensureAborted(); if (runner) { runner.abort(); } }, forceMinPriority: function (p) { minPriority = p; if (runner) { runner.forceMinPriority(p); } } }; }; return DelayedStrategy; }()); /* harmony default export */ var delayed_strategy = (delayed_strategy_DelayedStrategy); // CONCATENATED MODULE: ./src/core/strategies/if_strategy.ts var IfStrategy = (function () { function IfStrategy(test, trueBranch, falseBranch) { this.test = test; this.trueBranch = trueBranch; this.falseBranch = falseBranch; } IfStrategy.prototype.isSupported = function () { var branch = this.test() ? this.trueBranch : this.falseBranch; return branch.isSupported(); }; IfStrategy.prototype.connect = function (minPriority, callback) { var branch = this.test() ? this.trueBranch : this.falseBranch; return branch.connect(minPriority, callback); }; return IfStrategy; }()); /* harmony default export */ var if_strategy = (IfStrategy); // CONCATENATED MODULE: ./src/core/strategies/first_connected_strategy.ts var FirstConnectedStrategy = (function () { function FirstConnectedStrategy(strategy) { this.strategy = strategy; } FirstConnectedStrategy.prototype.isSupported = function () { return this.strategy.isSupported(); }; FirstConnectedStrategy.prototype.connect = function (minPriority, callback) { var runner = this.strategy.connect(minPriority, function (error, handshake) { if (handshake) { runner.abort(); } callback(error, handshake); }); return runner; }; return FirstConnectedStrategy; }()); /* harmony default export */ var first_connected_strategy = (FirstConnectedStrategy); // CONCATENATED MODULE: ./src/runtimes/isomorphic/default_strategy.ts function testSupportsStrategy(strategy) { return function () { return strategy.isSupported(); }; } var getDefaultStrategy = function (config, baseOptions, defineTransport) { var definedTransports = {}; function defineTransportStrategy(name, type, priority, options, manager) { var transport = defineTransport(config, name, type, priority, options, manager); definedTransports[name] = transport; return transport; } var ws_options = Object.assign({}, baseOptions, { hostNonTLS: config.wsHost + ':' + config.wsPort, hostTLS: config.wsHost + ':' + config.wssPort, httpPath: config.wsPath }); var wss_options = extend({}, ws_options, { useTLS: true }); var http_options = Object.assign({}, baseOptions, { hostNonTLS: config.httpHost + ':' + config.httpPort, hostTLS: config.httpHost + ':' + config.httpsPort, httpPath: config.httpPath }); var timeouts = { loop: true, timeout: 15000, timeoutLimit: 60000 }; var ws_manager = new transport_manager({ lives: 2, minPingDelay: 10000, maxPingDelay: config.activityTimeout }); var streaming_manager = new transport_manager({ lives: 2, minPingDelay: 10000, maxPingDelay: config.activityTimeout }); var ws_transport = defineTransportStrategy('ws', 'ws', 3, ws_options, ws_manager); var wss_transport = defineTransportStrategy('wss', 'ws', 3, wss_options, ws_manager); var xhr_streaming_transport = defineTransportStrategy('xhr_streaming', 'xhr_streaming', 1, http_options, streaming_manager); var xhr_polling_transport = defineTransportStrategy('xhr_polling', 'xhr_polling', 1, http_options); var ws_loop = new sequential_strategy([ws_transport], timeouts); var wss_loop = new sequential_strategy([wss_transport], timeouts); var streaming_loop = new sequential_strategy([xhr_streaming_transport], timeouts); var polling_loop = new sequential_strategy([xhr_polling_transport], timeouts); var http_loop = new sequential_strategy([ new if_strategy(testSupportsStrategy(streaming_loop), new best_connected_ever_strategy([ streaming_loop, new delayed_strategy(polling_loop, { delay: 4000 }) ]), polling_loop) ], timeouts); var wsStrategy; if (baseOptions.useTLS) { wsStrategy = new best_connected_ever_strategy([ ws_loop, new delayed_strategy(http_loop, { delay: 2000 }) ]); } else { wsStrategy = new best_connected_ever_strategy([ ws_loop, new delayed_strategy(wss_loop, { delay: 2000 }), new delayed_strategy(http_loop, { delay: 5000 }) ]); } return new cached_strategy(new first_connected_strategy(new if_strategy(testSupportsStrategy(ws_transport), wsStrategy, http_loop)), definedTransports, { ttl: 1800000, timeline: baseOptions.timeline, useTLS: baseOptions.useTLS }); }; /* harmony default export */ var default_strategy = (getDefaultStrategy); // CONCATENATED MODULE: ./src/runtimes/isomorphic/transports/transport_connection_initializer.ts /* harmony default export */ var transport_connection_initializer = (function () { var self = this; self.timeline.info(self.buildTimelineMessage({ transport: self.name + (self.options.useTLS ? 's' : '') })); if (self.hooks.isInitialized()) { self.changeState('initialized'); } else { self.onClose(); } }); // CONCATENATED MODULE: ./src/core/http/http_request.ts var http_request_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var MAX_BUFFER_LENGTH = 256 * 1024; var http_request_HTTPRequest = (function (_super) { http_request_extends(HTTPRequest, _super); function HTTPRequest(hooks, method, url) { var _this = _super.call(this) || this; _this.hooks = hooks; _this.method = method; _this.url = url; return _this; } HTTPRequest.prototype.start = function (payload) { var _this = this; this.position = 0; this.xhr = this.hooks.getRequest(this); this.unloader = function () { _this.close(); }; worker_runtime.addUnloadListener(this.unloader); this.xhr.open(this.method, this.url, true); if (this.xhr.setRequestHeader) { this.xhr.setRequestHeader('Content-Type', 'application/json'); } this.xhr.send(payload); }; HTTPRequest.prototype.close = function () { if (this.unloader) { worker_runtime.removeUnloadListener(this.unloader); this.unloader = null; } if (this.xhr) { this.hooks.abortRequest(this.xhr); this.xhr = null; } }; HTTPRequest.prototype.onChunk = function (status, data) { while (true) { var chunk = this.advanceBuffer(data); if (chunk) { this.emit('chunk', { status: status, data: chunk }); } else { break; } } if (this.isBufferTooLong(data)) { this.emit('buffer_too_long'); } }; HTTPRequest.prototype.advanceBuffer = function (buffer) { var unreadData = buffer.slice(this.position); var endOfLinePosition = unreadData.indexOf('\n'); if (endOfLinePosition !== -1) { this.position += endOfLinePosition + 1; return unreadData.slice(0, endOfLinePosition); } else { return null; } }; HTTPRequest.prototype.isBufferTooLong = function (buffer) { return this.position === buffer.length && buffer.length > MAX_BUFFER_LENGTH; }; return HTTPRequest; }(dispatcher)); /* harmony default export */ var http_request = (http_request_HTTPRequest); // CONCATENATED MODULE: ./src/core/http/state.ts var State; (function (State) { State[State["CONNECTING"] = 0] = "CONNECTING"; State[State["OPEN"] = 1] = "OPEN"; State[State["CLOSED"] = 3] = "CLOSED"; })(State || (State = {})); /* harmony default export */ var state = (State); // CONCATENATED MODULE: ./src/core/http/http_socket.ts var autoIncrement = 1; var http_socket_HTTPSocket = (function () { function HTTPSocket(hooks, url) { this.hooks = hooks; this.session = randomNumber(1000) + '/' + randomString(8); this.location = getLocation(url); this.readyState = state.CONNECTING; this.openStream(); } HTTPSocket.prototype.send = function (payload) { return this.sendRaw(JSON.stringify([payload])); }; HTTPSocket.prototype.ping = function () { this.hooks.sendHeartbeat(this); }; HTTPSocket.prototype.close = function (code, reason) { this.onClose(code, reason, true); }; HTTPSocket.prototype.sendRaw = function (payload) { if (this.readyState === state.OPEN) { try { worker_runtime.createSocketRequest('POST', getUniqueURL(getSendURL(this.location, this.session))).start(payload); return true; } catch (e) { return false; } } else { return false; } }; HTTPSocket.prototype.reconnect = function () { this.closeStream(); this.openStream(); }; HTTPSocket.prototype.onClose = function (code, reason, wasClean) { this.closeStream(); this.readyState = state.CLOSED; if (this.onclose) { this.onclose({ code: code, reason: reason, wasClean: wasClean }); } }; HTTPSocket.prototype.onChunk = function (chunk) { if (chunk.status !== 200) { return; } if (this.readyState === state.OPEN) { this.onActivity(); } var payload; var type = chunk.data.slice(0, 1); switch (type) { case 'o': payload = JSON.parse(chunk.data.slice(1) || '{}'); this.onOpen(payload); break; case 'a': payload = JSON.parse(chunk.data.slice(1) || '[]'); for (var i = 0; i < payload.length; i++) { this.onEvent(payload[i]); } break; case 'm': payload = JSON.parse(chunk.data.slice(1) || 'null'); this.onEvent(payload); break; case 'h': this.hooks.onHeartbeat(this); break; case 'c': payload = JSON.parse(chunk.data.slice(1) || '[]'); this.onClose(payload[0], payload[1], true); break; } }; HTTPSocket.prototype.onOpen = function (options) { if (this.readyState === state.CONNECTING) { if (options && options.hostname) { this.location.base = replaceHost(this.location.base, options.hostname); } this.readyState = state.OPEN; if (this.onopen) { this.onopen(); } } else { this.onClose(1006, 'Server lost session', true); } }; HTTPSocket.prototype.onEvent = function (event) { if (this.readyState === state.OPEN && this.onmessage) { this.onmessage({ data: event }); } }; HTTPSocket.prototype.onActivity = function () { if (this.onactivity) { this.onactivity(); } }; HTTPSocket.prototype.onError = function (error) { if (this.onerror) { this.onerror(error); } }; HTTPSocket.prototype.openStream = function () { var _this = this; this.stream = worker_runtime.createSocketRequest('POST', getUniqueURL(this.hooks.getReceiveURL(this.location, this.session))); this.stream.bind('chunk', function (chunk) { _this.onChunk(chunk); }); this.stream.bind('finished', function (status) { _this.hooks.onFinished(_this, status); }); this.stream.bind('buffer_too_long', function () { _this.reconnect(); }); try { this.stream.start(); } catch (error) { util.defer(function () { _this.onError(error); _this.onClose(1006, 'Could not start streaming', false); }); } }; HTTPSocket.prototype.closeStream = function () { if (this.stream) { this.stream.unbind_all(); this.stream.close(); this.stream = null; } }; return HTTPSocket; }()); function getLocation(url) { var parts = /([^\?]*)\/*(\??.*)/.exec(url); return { base: parts[1], queryString: parts[2] }; } function getSendURL(url, session) { return url.base + '/' + session + '/xhr_send'; } function getUniqueURL(url) { var separator = url.indexOf('?') === -1 ? '?' : '&'; return url + separator + 't=' + +new Date() + '&n=' + autoIncrement++; } function replaceHost(url, hostname) { var urlParts = /(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(url); return urlParts[1] + hostname + urlParts[3]; } function randomNumber(max) { return Math.floor(Math.random() * max); } function randomString(length) { var result = []; for (var i = 0; i < length; i++) { result.push(randomNumber(32).toString(32)); } return result.join(''); } /* harmony default export */ var http_socket = (http_socket_HTTPSocket); // CONCATENATED MODULE: ./src/core/http/http_streaming_socket.ts var http_streaming_socket_hooks = { getReceiveURL: function (url, session) { return url.base + '/' + session + '/xhr_streaming' + url.queryString; }, onHeartbeat: function (socket) { socket.sendRaw('[]'); }, sendHeartbeat: function (socket) { socket.sendRaw('[]'); }, onFinished: function (socket, status) { socket.onClose(1006, 'Connection interrupted (' + status + ')', false); } }; /* harmony default export */ var http_streaming_socket = (http_streaming_socket_hooks); // CONCATENATED MODULE: ./src/core/http/http_polling_socket.ts var http_polling_socket_hooks = { getReceiveURL: function (url, session) { return url.base + '/' + session + '/xhr' + url.queryString; }, onHeartbeat: function () { }, sendHeartbeat: function (socket) { socket.sendRaw('[]'); }, onFinished: function (socket, status) { if (status === 200) { socket.reconnect(); } else { socket.onClose(1006, 'Connection interrupted (' + status + ')', false); } } }; /* harmony default export */ var http_polling_socket = (http_polling_socket_hooks); // CONCATENATED MODULE: ./src/runtimes/isomorphic/http/http_xhr_request.ts var http_xhr_request_hooks = { getRequest: function (socket) { var Constructor = worker_runtime.getXHRAPI(); var xhr = new Constructor(); xhr.onreadystatechange = xhr.onprogress = function () { switch (xhr.readyState) { case 3: if (xhr.responseText && xhr.responseText.length > 0) { socket.onChunk(xhr.status, xhr.responseText); } break; case 4: if (xhr.responseText && xhr.responseText.length > 0) { socket.onChunk(xhr.status, xhr.responseText); } socket.emit('finished', xhr.status); socket.close(); break; } }; return xhr; }, abortRequest: function (xhr) { xhr.onreadystatechange = null; xhr.abort(); } }; /* harmony default export */ var http_xhr_request = (http_xhr_request_hooks); // CONCATENATED MODULE: ./src/runtimes/isomorphic/http/http.ts var HTTP = { createStreamingSocket: function (url) { return this.createSocket(http_streaming_socket, url); }, createPollingSocket: function (url) { return this.createSocket(http_polling_socket, url); }, createSocket: function (hooks, url) { return new http_socket(hooks, url); }, createXHR: function (method, url) { return this.createRequest(http_xhr_request, method, url); }, createRequest: function (hooks, method, url) { return new http_request(hooks, method, url); } }; /* harmony default export */ var http_http = (HTTP); // CONCATENATED MODULE: ./src/runtimes/isomorphic/runtime.ts var Isomorphic = { getDefaultStrategy: default_strategy, Transports: transports, transportConnectionInitializer: transport_connection_initializer, HTTPFactory: http_http, setup: function (PusherClass) { PusherClass.ready(); }, getLocalStorage: function () { return undefined; }, getClientFeatures: function () { return keys(filterObject({ ws: transports.ws }, function (t) { return t.isSupported({}); })); }, getProtocol: function () { return 'http:'; }, isXHRSupported: function () { return true; }, createSocketRequest: function (method, url) { if (this.isXHRSupported()) { return this.HTTPFactory.createXHR(method, url); } else { throw 'Cross-origin HTTP requests are not supported'; } }, createXHR: function () { var Constructor = this.getXHRAPI(); return new Constructor(); }, createWebSocket: function (url) { var Constructor = this.getWebSocketAPI(); return new Constructor(url); }, addUnloadListener: function (listener) { }, removeUnloadListener: function (listener) { } }; /* harmony default export */ var runtime = (Isomorphic); // CONCATENATED MODULE: ./src/runtimes/worker/net_info.ts var net_info_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var NetInfo = (function (_super) { net_info_extends(NetInfo, _super); function NetInfo() { return _super !== null && _super.apply(this, arguments) || this; } NetInfo.prototype.isOnline = function () { return true; }; return NetInfo; }(dispatcher)); var net_info_Network = new NetInfo(); // CONCATENATED MODULE: ./src/runtimes/worker/auth/fetch_auth.ts var fetchAuth = function (context, socketId, callback) { var headers = new Headers(); headers.set('Content-Type', 'application/x-www-form-urlencoded'); for (var headerName in this.authOptions.headers) { headers.set(headerName, this.authOptions.headers[headerName]); } var body = this.composeQuery(socketId); var request = new Request(this.options.authEndpoint, { headers: headers, body: body, credentials: 'same-origin', method: 'POST' }); return fetch(request) .then(function (response) { var status = response.status; if (status === 200) { return response.text(); } else { logger.error("Couldn't get auth info from your auth endpoint", status); throw status; } }) .then(function (data) { try { data = JSON.parse(data); } catch (e) { var message = 'JSON returned from auth endpoint was invalid, yet status code was 200. Data was: ' + data; logger.error(message); throw message; } callback(false, data); })["catch"](function (err) { callback(true, err); }); }; /* harmony default export */ var fetch_auth = (fetchAuth); // CONCATENATED MODULE: ./src/runtimes/worker/timeline/fetch_timeline.ts var getAgent = function (sender, useTLS) { return function (data, callback) { var scheme = 'http' + (useTLS ? 's' : '') + '://'; var url = scheme + (sender.host || sender.options.host) + sender.options.path; var query = buildQueryString(data); url += '/' + 2 + '?' + query; fetch(url) .then(function (response) { if (response.status !== 200) { throw "received " + response.status + " from stats.pusher.com"; } return response.json(); }) .then(function (_a) { var host = _a.host; if (host) { sender.host = host; } })["catch"](function (err) { logger.debug('TimelineSender Error: ', err); }); }; }; var fetchTimeline = { name: 'xhr', getAgent: getAgent }; /* harmony default export */ var fetch_timeline = (fetchTimeline); // CONCATENATED MODULE: ./src/runtimes/worker/runtime.ts var runtime_getDefaultStrategy = runtime.getDefaultStrategy, runtime_Transports = runtime.Transports, setup = runtime.setup, getProtocol = runtime.getProtocol, isXHRSupported = runtime.isXHRSupported, getLocalStorage = runtime.getLocalStorage, createXHR = runtime.createXHR, createWebSocket = runtime.createWebSocket, addUnloadListener = runtime.addUnloadListener, removeUnloadListener = runtime.removeUnloadListener, transportConnectionInitializer = runtime.transportConnectionInitializer, createSocketRequest = runtime.createSocketRequest, HTTPFactory = runtime.HTTPFactory; var Worker = { getDefaultStrategy: runtime_getDefaultStrategy, Transports: runtime_Transports, setup: setup, getProtocol: getProtocol, isXHRSupported: isXHRSupported, getLocalStorage: getLocalStorage, createXHR: createXHR, createWebSocket: createWebSocket, addUnloadListener: addUnloadListener, removeUnloadListener: removeUnloadListener, transportConnectionInitializer: transportConnectionInitializer, createSocketRequest: createSocketRequest, HTTPFactory: HTTPFactory, TimelineTransport: fetch_timeline, getAuthorizers: function () { return { ajax: fetch_auth }; }, getWebSocketAPI: function () { return WebSocket; }, getXHRAPI: function () { return XMLHttpRequest; }, getNetwork: function () { return net_info_Network; } }; /* harmony default export */ var worker_runtime = (Worker); // CONCATENATED MODULE: ./src/core/timeline/level.ts var TimelineLevel; (function (TimelineLevel) { TimelineLevel[TimelineLevel["ERROR"] = 3] = "ERROR"; TimelineLevel[TimelineLevel["INFO"] = 6] = "INFO"; TimelineLevel[TimelineLevel["DEBUG"] = 7] = "DEBUG"; })(TimelineLevel || (TimelineLevel = {})); /* harmony default export */ var timeline_level = (TimelineLevel); // CONCATENATED MODULE: ./src/core/timeline/timeline.ts var timeline_Timeline = (function () { function Timeline(key, session, options) { this.key = key; this.session = session; this.events = []; this.options = options || {}; this.sent = 0; this.uniqueID = 0; } Timeline.prototype.log = function (level, event) { if (level <= this.options.level) { this.events.push(extend({}, event, { timestamp: util.now() })); if (this.options.limit && this.events.length > this.options.limit) { this.events.shift(); } } }; Timeline.prototype.error = function (event) { this.log(timeline_level.ERROR, event); }; Timeline.prototype.info = function (event) { this.log(timeline_level.INFO, event); }; Timeline.prototype.debug = function (event) { this.log(timeline_level.DEBUG, event); }; Timeline.prototype.isEmpty = function () { return this.events.length === 0; }; Timeline.prototype.send = function (sendfn, callback) { var _this = this; var data = extend({ session: this.session, bundle: this.sent + 1, key: this.key, lib: 'js', version: this.options.version, cluster: this.options.cluster, features: this.options.features, timeline: this.events }, this.options.params); this.events = []; sendfn(data, function (error, result) { if (!error) { _this.sent++; } if (callback) { callback(error, result); } }); return true; }; Timeline.prototype.generateUniqueID = function () { this.uniqueID++; return this.uniqueID; }; return Timeline; }()); /* harmony default export */ var timeline_timeline = (timeline_Timeline); // CONCATENATED MODULE: ./src/core/strategies/transport_strategy.ts var transport_strategy_TransportStrategy = (function () { function TransportStrategy(name, priority, transport, options) { this.name = name; this.priority = priority; this.transport = transport; this.options = options || {}; } TransportStrategy.prototype.isSupported = function () { return this.transport.isSupported({ useTLS: this.options.useTLS }); }; TransportStrategy.prototype.connect = function (minPriority, callback) { var _this = this; if (!this.isSupported()) { return failAttempt(new UnsupportedStrategy(), callback); } else if (this.priority < minPriority) { return failAttempt(new TransportPriorityTooLow(), callback); } var connected = false; var transport = this.transport.createConnection(this.name, this.priority, this.options.key, this.options); var handshake = null; var onInitialized = function () { transport.unbind('initialized', onInitialized); transport.connect(); }; var onOpen = function () { handshake = factory.createHandshake(transport, function (result) { connected = true; unbindListeners(); callback(null, result); }); }; var onError = function (error) { unbindListeners(); callback(error); }; var onClosed = function () { unbindListeners(); var serializedTransport; serializedTransport = safeJSONStringify(transport); callback(new TransportClosed(serializedTransport)); }; var unbindListeners = function () { transport.unbind('initialized', onInitialized); transport.unbind('open', onOpen); transport.unbind('error', onError); transport.unbind('closed', onClosed); }; transport.bind('initialized', onInitialized); transport.bind('open', onOpen); transport.bind('error', onError); transport.bind('closed', onClosed); transport.initialize(); return { abort: function () { if (connected) { return; } unbindListeners(); if (handshake) { handshake.close(); } else { transport.close(); } }, forceMinPriority: function (p) { if (connected) { return; } if (_this.priority < p) { if (handshake) { handshake.close(); } else { transport.close(); } } } }; }; return TransportStrategy; }()); /* harmony default export */ var transport_strategy = (transport_strategy_TransportStrategy); function failAttempt(error, callback) { util.defer(function () { callback(error); }); return { abort: function () { }, forceMinPriority: function () { } }; } // CONCATENATED MODULE: ./src/core/strategies/strategy_builder.ts var strategy_builder_Transports = worker_runtime.Transports; var strategy_builder_defineTransport = function (config, name, type, priority, options, manager) { var transportClass = strategy_builder_Transports[type]; if (!transportClass) { throw new UnsupportedTransport(type); } var enabled = (!config.enabledTransports || arrayIndexOf(config.enabledTransports, name) !== -1) && (!config.disabledTransports || arrayIndexOf(config.disabledTransports, name) === -1); var transport; if (enabled) { options = Object.assign({ ignoreNullOrigin: config.ignoreNullOrigin }, options); transport = new transport_strategy(name, priority, manager ? manager.getAssistant(transportClass) : transportClass, options); } else { transport = strategy_builder_UnsupportedStrategy; } return transport; }; var strategy_builder_UnsupportedStrategy = { isSupported: function () { return false; }, connect: function (_, callback) { var deferred = util.defer(function () { callback(new UnsupportedStrategy()); }); return { abort: function () { deferred.ensureAborted(); }, forceMinPriority: function () { } }; } }; // CONCATENATED MODULE: ./src/core/config.ts function getConfig(opts) { var config = { activityTimeout: opts.activityTimeout || defaults.activityTimeout, authEndpoint: opts.authEndpoint || defaults.authEndpoint, authTransport: opts.authTransport || defaults.authTransport, cluster: opts.cluster || defaults.cluster, httpPath: opts.httpPath || defaults.httpPath, httpPort: opts.httpPort || defaults.httpPort, httpsPort: opts.httpsPort || defaults.httpsPort, pongTimeout: opts.pongTimeout || defaults.pongTimeout, statsHost: opts.statsHost || defaults.stats_host, unavailableTimeout: opts.unavailableTimeout || defaults.unavailableTimeout, wsPath: opts.wsPath || defaults.wsPath, wsPort: opts.wsPort || defaults.wsPort, wssPort: opts.wssPort || defaults.wssPort, enableStats: getEnableStatsConfig(opts), httpHost: getHttpHost(opts), useTLS: shouldUseTLS(opts), wsHost: getWebsocketHost(opts) }; if ('auth' in opts) config.auth = opts.auth; if ('authorizer' in opts) config.authorizer = opts.authorizer; if ('disabledTransports' in opts) config.disabledTransports = opts.disabledTransports; if ('enabledTransports' in opts) config.enabledTransports = opts.enabledTransports; if ('ignoreNullOrigin' in opts) config.ignoreNullOrigin = opts.ignoreNullOrigin; if ('timelineParams' in opts) config.timelineParams = opts.timelineParams; if ('nacl' in opts) { config.nacl = opts.nacl; } return config; } function getHttpHost(opts) { if (opts.httpHost) { return opts.httpHost; } if (opts.cluster) { return "sockjs-" + opts.cluster + ".pusher.com"; } return defaults.httpHost; } function getWebsocketHost(opts) { if (opts.wsHost) { return opts.wsHost; } if (opts.cluster) { return getWebsocketHostFromCluster(opts.cluster); } return getWebsocketHostFromCluster(defaults.cluster); } function getWebsocketHostFromCluster(cluster) { return "ws-" + cluster + ".pusher.com"; } function shouldUseTLS(opts) { if (worker_runtime.getProtocol() === 'https:') { return true; } else if (opts.forceTLS === false) { return false; } return true; } function getEnableStatsConfig(opts) { if ('enableStats' in opts) { return opts.enableStats; } if ('disableStats' in opts) { return !opts.disableStats; } return false; } // CONCATENATED MODULE: ./src/core/pusher.ts var pusher_Pusher = (function () { function Pusher(app_key, options) { var _this = this; checkAppKey(app_key); options = options || {}; if (!options.cluster && !(options.wsHost || options.httpHost)) { var suffix = url_store.buildLogSuffix('javascriptQuickStart'); logger.warn("You should always specify a cluster when connecting. " + suffix); } if ('disableStats' in options) { logger.warn('The disableStats option is deprecated in favor of enableStats'); } this.key = app_key; this.config = getConfig(options); this.channels = factory.createChannels(); this.global_emitter = new dispatcher(); this.sessionID = Math.floor(Math.random() * 1000000000); this.timeline = new timeline_timeline(this.key, this.sessionID, { cluster: this.config.cluster, features: Pusher.getClientFeatures(), params: this.config.timelineParams || {}, limit: 50, level: timeline_level.INFO, version: defaults.VERSION }); if (this.config.enableStats) { this.timelineSender = factory.createTimelineSender(this.timeline, { host: this.config.statsHost, path: '/timeline/v2/' + worker_runtime.TimelineTransport.name }); } var getStrategy = function (options) { return worker_runtime.getDefaultStrategy(_this.config, options, strategy_builder_defineTransport); }; this.connection = factory.createConnectionManager(this.key, { getStrategy: getStrategy, timeline: this.timeline, activityTimeout: this.config.activityTimeout, pongTimeout: this.config.pongTimeout, unavailableTimeout: this.config.unavailableTimeout, useTLS: Boolean(this.config.useTLS) }); this.connection.bind('connected', function () { _this.subscribeAll(); if (_this.timelineSender) { _this.timelineSender.send(_this.connection.isUsingTLS()); } }); this.connection.bind('message', function (event) { var eventName = event.event; var internal = eventName.indexOf('pusher_internal:') === 0; if (event.channel) { var channel = _this.channel(event.channel); if (channel) { channel.handleEvent(event); } } if (!internal) { _this.global_emitter.emit(event.event, event.data); } }); this.connection.bind('connecting', function () { _this.channels.disconnect(); }); this.connection.bind('disconnected', function () { _this.channels.disconnect(); }); this.connection.bind('error', function (err) { logger.warn(err); }); Pusher.instances.push(this); this.timeline.info({ instances: Pusher.instances.length }); if (Pusher.isReady) { this.connect(); } } Pusher.ready = function () { Pusher.isReady = true; for (var i = 0, l = Pusher.instances.length; i < l; i++) { Pusher.instances[i].connect(); } }; Pusher.getClientFeatures = function () { return keys(filterObject({ ws: worker_runtime.Transports.ws }, function (t) { return t.isSupported({}); })); }; Pusher.prototype.channel = function (name) { return this.channels.find(name); }; Pusher.prototype.allChannels = function () { return this.channels.all(); }; Pusher.prototype.connect = function () { this.connection.connect(); if (this.timelineSender) { if (!this.timelineSenderTimer) { var usingTLS = this.connection.isUsingTLS(); var timelineSender = this.timelineSender; this.timelineSenderTimer = new PeriodicTimer(60000, function () { timelineSender.send(usingTLS); }); } } }; Pusher.prototype.disconnect = function () { this.connection.disconnect(); if (this.timelineSenderTimer) { this.timelineSenderTimer.ensureAborted(); this.timelineSenderTimer = null; } }; Pusher.prototype.bind = function (event_name, callback, context) { this.global_emitter.bind(event_name, callback, context); return this; }; Pusher.prototype.unbind = function (event_name, callback, context) { this.global_emitter.unbind(event_name, callback, context); return this; }; Pusher.prototype.bind_global = function (callback) { this.global_emitter.bind_global(callback); return this; }; Pusher.prototype.unbind_global = function (callback) { this.global_emitter.unbind_global(callback); return this; }; Pusher.prototype.unbind_all = function (callback) { this.global_emitter.unbind_all(); return this; }; Pusher.prototype.subscribeAll = function () { var channelName; for (channelName in this.channels.channels) { if (this.channels.channels.hasOwnProperty(channelName)) { this.subscribe(channelName); } } }; Pusher.prototype.subscribe = function (channel_name) { var channel = this.channels.add(channel_name, this); if (channel.subscriptionPending && channel.subscriptionCancelled) { channel.reinstateSubscription(); } else if (!channel.subscriptionPending && this.connection.state === 'connected') { channel.subscribe(); } return channel; }; Pusher.prototype.unsubscribe = function (channel_name) { var channel = this.channels.find(channel_name); if (channel && channel.subscriptionPending) { channel.cancelSubscription(); } else { channel = this.channels.remove(channel_name); if (channel && this.connection.state === 'connected') { channel.unsubscribe(); } } }; Pusher.prototype.send_event = function (event_name, data, channel) { return this.connection.send_event(event_name, data, channel); }; Pusher.prototype.shouldUseTLS = function () { return this.config.useTLS; }; Pusher.instances = []; Pusher.isReady = false; Pusher.logToConsole = false; Pusher.Runtime = worker_runtime; Pusher.ScriptReceivers = worker_runtime.ScriptReceivers; Pusher.DependenciesReceivers = worker_runtime.DependenciesReceivers; Pusher.auth_callbacks = worker_runtime.auth_callbacks; return Pusher; }()); /* harmony default export */ var core_pusher = __webpack_exports__["default"] = (pusher_Pusher); function checkAppKey(key) { if (key === null || key === undefined) { throw 'You must pass your app key when you instantiate Pusher.'; } } worker_runtime.setup(pusher_Pusher); /***/ }) /******/ ]);
Saying ‘I love you’ to your significant other for the very first time is a pretty big deal. Some people are bursting at the seams to spit it out while others are packing their dacks at the prospect. But according to research, on average, most people (22%) are dropping the L bomb ‘within three months’. The YouGov survey of 3,947 men and women in the UK, found that ‘within six months’ (14%) came in second place, followed by ‘within a month’ (13%). There’s really no right or wrong time to do it, here are some of our team’s ‘I love you’ moments went down.
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_STARTDOCUMENTCLASSIFICATIONJOBRESPONSE_P_H #define QTAWS_STARTDOCUMENTCLASSIFICATIONJOBRESPONSE_P_H #include "comprehendresponse_p.h" namespace QtAws { namespace Comprehend { class StartDocumentClassificationJobResponse; class StartDocumentClassificationJobResponsePrivate : public ComprehendResponsePrivate { public: explicit StartDocumentClassificationJobResponsePrivate(StartDocumentClassificationJobResponse * const q); void parseStartDocumentClassificationJobResponse(QXmlStreamReader &xml); private: Q_DECLARE_PUBLIC(StartDocumentClassificationJobResponse) Q_DISABLE_COPY(StartDocumentClassificationJobResponsePrivate) }; } // namespace Comprehend } // namespace QtAws #endif
Despite his relentless efforts to curb the Afghan insurgency, Obama never actually got a grip on the situation. Experts say he's leaving behind a huge mess in Afghanistan that won't be easy for his successor to clean up. The outgoing US president, Barack Obama, is leaving behind a mixed legacy in Afghanistan. In 2009, during his first term in office, Obama ordered a drastic increase in the number of US troops in Afghanistan to tackle the Taliban insurgency. After coming to power in 2008, Obama reviewed Washington's war strategy in Afghanistan and concluded that the US troops in the country - around 68,000 at the time - were well below the strength that was needed to quell the Afghan insurgency. Thus, he ordered a surge and deployed an additional 33,000 US troops to Afghanistan in the hope to restrain Taliban militants and train the Afghan security forces. But he later decided to prematurely reduce a significant number of US soldiers from the war-torn nation that led to a spike in terrorist attacks in the country. The two decisions and their consequences have pretty much determined Obama's Afghanistan legacy, say experts. Michael Kugelman, an Afghanistan expert at the Washington-based Woodrow Wilson Center for Scholars, is of the view that by beefing up the presence of US forces in Afghanistan Obama actually took ownership of the war that was being greatly neglected when he took office. "The surge of troops he announced went a long way toward bringing a modicum of stability, at least for a brief period," Kugelman told DW. But then agreeing to the withdrawal of troops in 2014 - all but 8,000 troops - the outgoing president not only endangered the achievements of the surge but also the whole purpose of the US invasion of Afghanistan. The decision had a negative impact on Afghanistan's security because the targets the US and its NATO allies had set for themselves were hugely compromised. The US was nowhere close to winning the war against Islamists, the Afghan security forces were inadequately trained to fight the insurgents on their own, and the Taliban became stronger than ever. "Obama's hasty exit strategy along a set timeline had a negative impact on the dynamics of conflict in Afghanistan," Timor Sharan, a senior analyst at the International Crisis Group, told DW. The drawdown, he added, left the Afghan security forces vulnerable to defending the country against a resurgent enemy and created leadership vacuum where regional powers like Pakistan, Iran and Russia gained leverage in Afghanistan. What contributed to the failure of President Obama's Afghan war policy, according to Sharan, was the occurrence of three simultaneous transitions in Afghanistan. In 2014, when the US was in the process of withdrawing troops from Afghanistan, the country held its controversial presidential elections in which both candidates - incumbent Afghan president Ashraf Ghani and his chief executive Abdullah Abdullah - claimed victory and almost took the country to the brink of another civil war. And then came the economic transition with the withdrawal of most NATO troops from Afghanistan which resulted in a sharp decline in cash flow and employment in the country. "Obama's timeline did not reflect the realities on the ground," Sharan said, adding that the situation allowed the Taliban to exploit these vulnerabilities and expand their presence around the country. The US president believed that persistent drone attacks on militants operating along the Afghanistan-Pakistan border would yield better results in curbing terrorism. But this strategy was widely criticized by human rights organizations due to the high number of civilian casualties it resulted in. It is, however, difficult to determine whether Obama's drone war was a success or a failure because the unmanned planes eliminated many Taliban and al Qaeda leaders in Afghanistan and Pakistan, including the Taliban chief Mullah Akhtar Mohammad Mansour, who was killed in July last year. Drone attacks, as Kugelman puts it, have proved to be effective in targeting the Pakistani Taliban leaders as well as the militants linked to the so-called "Islamic State" (IS) terror group that has made significant gains in Afghanistan in the past two years. "IS does not have a strong profile in Afghanistan, but it does have a modest presence, and taking out key leaders is a great way to demoralize and divide the group," Kugelman underlined. But Obama's increased use of drone attacks and operations against the Taliban were accompanied by civilian casualties in Afghanistan. That turned then Afghan President Hamid Karzai against Washington. Karzai became increasingly critical of the US' Afghanistan policies. He refused to sign a US-Afghan security pact that allowed Washington to keep military bases in Afghanistan beyond 2015. After Karzai's departure in 2015, Obama found a cooperative partner in Afghanistan in President Ashraf Ghani, who eventually approved the security agreement with Washington. Barack Obama and his generals in Afghanistan hoped that the increase in the number of US troops would defeat the Taliban in the battlefield, which would eventually force the Islamist group to come to the negotiating table. But this never happened. The Taliban gained control over more Afghan districts and provinces after the end of the surge. In 2015, the group even succeeded in briefly capturing the city of Kunduz. But many experts don't blame the Obama administration for the failure of the Afghan peace process. They say that Pakistan's unwillingness to cooperate and convince the Taliban to start peace negotiations with Kabul is the main reason behind it. Islamabad continued to provide sanctuaries to the Taliban and did not use its influence on the group to help Kabul and Washington, says Kugelman. "Obama, at the least, tried hard to help spark a reconciliation process," the analyst concluded. Throughout his two terms, Obama urged Pakistani authorities to use their influence on the Taliban to persuade the outfit to lay down arms and enter peace talks. In October 2015, the US president hosted Pakistani Prime Minister Nawaz Sharif at the White House. The two leaders "called on Taliban leaders to enter into direct talks with Kabul and work toward a sustainable peace settlement." Experts say that in the wake of a spike in violence in Afghanistan, Pakistan's role in assisting the Afghan government in reconciliation efforts with the Taliban is vital - a fact that Obama understood and acknowledged. But security analysts also say that Islamabad continued to provide military and logistical support to the jihadists in Afghanistan to destabilize first Hamid Karzai's and later President Ghani's government. They say that the Taliban's recent resurgence across Afghanistan is proof that they are receiving assistance from the Pakistani military establishment. The situation in Afghanistan became so dire that President Obama had to revise his earlier decision of withdrawing all US troops from Afghanistan before 2017. In 2015, he decided that more than 5,000 US soldiers would stay in the conflict-ravaged country to help the Afghan security forces for an indefinite period of time. Arif Jamal, a US-based journalist and author of books on extremism in Pakistan, believes that Obama was naïve to expect that Islamabad would stop the use of jihadists as a way to increase its influence in Afghanistan. He also said that Obama did not pressure Pakistani officials enough to make them rethink and revise their Afghanistan policies. "The carrot alone is not working. The US must use the stick by imposing military and economic sanctions on Pakistan. As long as US aid keeps flowing to Islamabad, there will be no change in policy," he asserted. Pakistan has received more than $20 billion in civilian and military aid from the US over the past 15 years, which includes Obama's eight years in power.
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.waf.model.transform; import java.util.Map; import java.util.List; import com.amazonaws.AmazonClientException; import com.amazonaws.services.waf.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.util.json.*; /** * FieldToMatchMarshaller */ public class FieldToMatchJsonMarshaller { /** * Marshall the given parameter object, and output to a SdkJsonGenerator */ public void marshall(FieldToMatch fieldToMatch, StructuredJsonGenerator jsonGenerator) { if (fieldToMatch == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } try { jsonGenerator.writeStartObject(); if (fieldToMatch.getType() != null) { jsonGenerator.writeFieldName("Type").writeValue( fieldToMatch.getType()); } if (fieldToMatch.getData() != null) { jsonGenerator.writeFieldName("Data").writeValue( fieldToMatch.getData()); } jsonGenerator.writeEndObject(); } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } } private static FieldToMatchJsonMarshaller instance; public static FieldToMatchJsonMarshaller getInstance() { if (instance == null) instance = new FieldToMatchJsonMarshaller(); return instance; } }
I loved it! I going to have to give this a try! These are lovely, Billy Ray. These are lovely, Billy Ray. First attempt?? I’d say you’re a natural. 🙂 Have a great weekend! This is gorgeous, Billy Ray. A perfectly glorious description. Hugs.
Give your bedroom decor modern update with the cool sophistication of the Modello quilt cover set. Bold geometric patterns combine with vibrant hues of orange and blue to create a stylishly modern bedroom. The reverse features a cool contrast of orange diamonds on a grey background for two looks in one. Our artisans created Modello with 100% long staple cotton for the height of natural softness. It creates an extra-soft handle you’ll look forward to bundling up with each night. The Modello quilt cover is also naturally breathable, so it won’t add extra heat to your bed during the warm weather months. Quality and luxury are the driving forces behind Modello. Each time you pull it out of the dryer, it will delight you with the vibrant colors and inviting softness. And, Modello is the height of modern taste, so you are sure to enjoy the style for years to come.
About — Peak Performance Hemp Co. Peak Performance Hemp is owned by a Registered Nurse whose mission is to educate and empower individuals to reach optimal health. Our goal is to bring you a high quality product designed to help you reach optimal health, using plant based products. I started Peak Performance Hemp to do just that! My mission is to create high quality Full Spectrum Hemp extract products full of phytonutrients, cannabinoids, and terpenes to provide an effective and natural alternative for health and wellness. This is your time to reach your optimal health & peak performance! Many medical studies show all the health benefits that cannabis, hemp, CBD, and terpenes can have. People are loving it because it supports health without any mind-altering psychoactive effects. It’s not about getting high, it is about health! Peak Performance Hemp currently has 2 strengths of Full Spectrum Hemp Tinctures full of cannabinoids and a variety of terpenes. I have used them myself to promote optimal health and improve quality of life! And those days that I need a little extra relaxation, a bath using infused bath salts help melt the stress and tension away. Deanna Mautz, RN, BSN, a member of the American Cannabis Nurses Association. Working with their care team to incorporate conventional medication and treatments with alternative and complimentary treatments, including cannabis use. Incorporating nutrition and lifestyle habits to improve quality of life. And it's this unique approach that makes her clients so successful in improving quality of life and reaching optimal health, no matter what their medical condition.
// // AppDelegate.h // FSStarRatingView_Example // // Created by Farzad Sharbafian on 2015-07-20. // Copyright (c) 2015 Farzad Sharbafian. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
There are two main types of parties: the organisation contracted to manage the register, and the landlords joining the register. In most cases this would be the council and the RSLs. The initial term for which the agreement will stand. It is recommended that this be at least three years for the initial contract to provide commitment, stability and sufficient investment of time and resources to establish the CHR. The rules under which parties can resign from the register after the initial three-year period. Each party will be held to contractual obligations under the agreement. These include contributions, policies and complaints processes (including the obligations of the party contracted to manage the register). You must ensure every partner landlord is held accountable for the component parts of the CHR. This includes staffing, compensation claims, failure to deliver targets and standards, liability of any staff employed for the purposes of delivering the CHR, and termination of any party to the agreement. Audit processes and procedures ensure you are able to carry out performance review, resolve disputes, change or terminate the agreement, deal with default and liabilities, ad manage assets. Rules must govern dispute between parties. Contractual obligations relate to the processing of applications and the maintenance of the database. Details of the partners' expectations on quality of service can be written into service level agreements. These include revenue costs, payments, budgets, VAT, arrangements for charging, collection of contributions, setting and managing budgets, and so on. Security is maintained by compliance with data protection legislation. Timescales for responding to verbal and written enquiries. This part of the agreement will set out the details of the service provider, the host of the system, the system specification, and management and administration of the operational system. Often detailed documentation will already exist if the software chosen to run the CHR is an add-on to an existing system. In these cases, the original documents may require only minor amendments in order to meet the partnership's legal needs. Similarly, with a bespoke system, it is possible to adapt existing documentation drawn up in the process of specifying and procuring that system. Once you have agreed a shared application form, it should be attached as a schedule to the legal agreement. This will ensure that all partners have made a legally binding commitment to use the common forms. If for any reason a partner continues to use their own forms without the permission of the partnership, they can be challenged. The use of a single application form is of course one of the essential components of a CHR, and it is therefore critical to ensure that the legal agreement can enforce this if necessary. Rather than develop a policy on delivery of housing advice within the CHR, a service statement setting out standards and any related processes could be included as a schedule attached to the legal agreement. Who can apply to your register? Depending upon the model of CHR you develop and how it is to be administered, you may need to register separately with the Data Protection Office. It is advisable to agree data sharing protocols for the CHR partnership to ensure consistency and accountability. Development requirements in this area will depend on the model of CHR you choose. If you opt for shared administration then it is unlikely you will need new procedures as the partners are likely to have existing procedures to which they will be held accountable. However, if you decide on centrally-based administration you will need to set procedures to which all partners agree. There are complexities around right of redress for the applicant regardless of the method of administration and it is recommended that you consult with the public ombudsman prior to implementing your CHR to ensure that you meet all your statutory obligations. The agreed process for health assessments should be included within the legal agreement, particularly where this involves contracting work. The budget for ongoing revenue costs should be written in as a schedule to the legal agreement. The model of CHR will to a large extent influence what is included in the budget. For example, where there is a central administration unit, it will incur running costs including staffing, recruitment and training, accommodation, and office facilities. Equally, where the CHR is based on shared administration, there will have to be agreement as to how costs will be redistributed if the burden of administration falls unfairly on some organisations. Other costs which all CHRs will need to include in their budget are printing and distribution of application forms. The legal agreement should identify the detail and frequency of all reports to be produced by the CHR, as well as arrangements for provision of ad hoc reports. The partnership will be required to abide by standing orders. You may wish to consider using the standing orders of one of the CHR partner organisations rather than start from scratch on drawing up new orders. It may be sensible to amend "borrowed" standing orders to cover the early days of the operation, and then create a new set that meets the specific needs of the CHR partnership once these have become clearer after implementation.
# This repo has been moved to: https://github.com/Pushwoosh/pushwoosh-phonegap-cordova-sample/ #### If you are using Phonegap Build check out this sample app with Pushwoosh Phonegap Build plugin integrated: https://github.com/Pushwoosh/pushwoosh-phonegap-cordova-sample/tree/master/Phonegap%20Build
More specific subcategories with additional Bridgend entertainers can be found further down the page. Based in David Street, Bridgend Industrial Estate. Based in Pant Bach, Pyle. Based in Heol ty Maen, Bridgend. Based in Ewenny Road, Bridgend. Map showing location of entertainers in Bridgend.
Martin Masse left the MEI in August 2018. Presentation by Martin Masse, Senior Writer and Editor at the MEI, at the Free Market Seminar organized by the Institute for Liberal Studies at McGill University. Interview (in French) with Martin Masse, Senior Writer and Editor at the MEI, about the state of competition in Canada’s telecommunications industry. The CRTC's approach to telecommunications regulation. The criticism most often heard regarding the telecommunications industry in Canada, and especially wireless services, is that Canadians pay a lot more than people in other countries for lower quality services. It is this criticism that was used to justify the federal government’s and the CRTC’s numerous interventions over the past few years aimed at promoting more competition in the wireless sector. But does this criticism stand up under scrutiny? Portrait of the wireless service offering in Canada. The CRTC and wireless competition. Policies aimed at increasing the number of players in the wireless sector. Wireless Services: Should Regulation Favour Resellers? The Canadian government and the CRTC have adopted various policies over the past decade aimed at increasing the number of players in the wireless sector. Although such policies have had several negative consequences, there is today a well-established fourth wireless provider, owning its own infrastructure, in almost all regions of the country. Ottawa now wants to push this interventionist logic even further by favouring resellers (called Mobile Virtual Network Operators, or MVNOs, in telecom jargon). Would such a policy bring more competition to the telecommunications industry and the intended benefits to consumers? How to create more competition in the wireless sector. Ottawa must not hold back the 4th industrial revolution. The advent of the Internet of Things (IoT), which will soon revolutionize every aspect of our economy and our lives, will force Ottawa to reconsider its telecommunications priorities and policies, argues the 2017 edition of The State of Competition in Canada’s Telecommunications Industry, published by the MEI. The state of Canada’s broadband market. Publication of a Research Paper analyzing various aspects of the Canadian telecommunications industry related to competition. Interview (in French) with Martin Masse, Senior Writer and Editor at the MEI, on the Canadian Telecommunications Industry (starting at 02:20). The federal government and the CRTC should not repeat the mistakes of recent years by intervening in the broadband sector as they have in the wireless sector, argues the MEI in the 2016 edition of a Research Paper entitled The State of Competition in Canada’s Telecommunications Industry. The Paper notes that 96% of Canadian households already had access to download speeds of 5 Mbps in 2014, with 77% of households subscribing to such a service, a trend that has shown strong growth in recent years. Interview (in French) with Martin Masse, Senior Writer and Editor at the MEI, on BCE Inc.’s proposed $3.9 billion acquisition of Manitoba Telecom Services Inc. The numerous interventions carried out by the federal government to encourage the establishment of a 4th wireless telephony player across the country will hurt consumers by undermining innovation in this industry. This is all the more worrisome given that important technological revolutions are in the works that will require billions of dollars of investments from the country’s telecommunications companies. This is one of the conclusions of the 2015 edition of The State of Competition in Canada’s Telecommunications Industry. Ottawa's interventions in the telecommunications sector. Portrait of Mario Vargas Llosa. There are several myths going around regarding the state of competition in the Canadian wireless sector. According to critics, the lack of competition compared to other industrialized countries means that Canadians are among those who pay the most for their services ‒ services, moreover, that are of poor quality. The MEI recently delved into this subject in some detail. As a new round of CRTC hearings begins, during which wholesale roaming fees will be debated, we are revisiting the matter briefly in order to contribute to a more balanced debate. The fed’s wireless hangup: Does Canada really need more players in its telecom market? Various aspects of the Canadian telecommunications industry related to competition. To the detriment of consumers across the country, the federal government has been encouraging artificial competition in the telecommunications industry for the past seven years. Fixated on the goal of promoting the emergence of a fourth wireless carrier in each of Canada's regional markets, the government has lost sight of the ultimate goal of promoting the development of a dynamic, efficient industry, according to this Research Paper. Publication of a booklet on the economic and political thought of Milton Friedman. The impact of a recent CRTC decision.
/* * fb-contrib - Auxiliary detectors for Java programs * Copyright (C) 2005-2016 Dave Brosius * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.mebigfatguy.fbcontrib.detect; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.bcel.classfile.Code; import com.mebigfatguy.fbcontrib.collect.ImmutabilityType; import com.mebigfatguy.fbcontrib.collect.MethodInfo; import com.mebigfatguy.fbcontrib.collect.Statistics; import com.mebigfatguy.fbcontrib.utils.BugType; import com.mebigfatguy.fbcontrib.utils.CollectionUtils; import com.mebigfatguy.fbcontrib.utils.QMethod; import com.mebigfatguy.fbcontrib.utils.Values; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.OpcodeStack.CustomUserValue; import edu.umd.cs.findbugs.ba.ClassContext; /** * looks for code that attempts to modify a collection that is or may be defined as immutable. Doing so will cause exceptions at runtime. */ @CustomUserValue public class ModifyingUnmodifiableCollection extends BytecodeScanningDetector { private static final Map<QMethod, Integer> MODIFYING_METHODS; static { Map<QMethod, Integer> mm = new HashMap<QMethod, Integer>(); mm.put(new QMethod("add", "(Ljava/lang/Object;)Z"), Values.ONE); mm.put(new QMethod("remove", "(Ljava/lang/Object;)Z"), Values.ONE); mm.put(new QMethod("addAll", "(Ljava/util/Collection;)Z"), Values.ONE); mm.put(new QMethod("retainAll", "(Ljava/util/Collection;)Z"), Values.ONE); mm.put(new QMethod("removeAll", "(Ljava/util/Collection;)Z"), Values.ONE); mm.put(new QMethod("put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"), Values.TWO); mm.put(new QMethod("remove", "(Ljava/lang/Object;)Ljava/lang/Object;"), Values.ONE); mm.put(new QMethod("putAll", "(Ljava/util/Map;)V;"), Values.ONE); MODIFYING_METHODS = Collections.<QMethod, Integer> unmodifiableMap(mm); } private final BugReporter bugReporter; private OpcodeStack stack; private ImmutabilityType reportedType; /** * constructs a MUC detector given the reporter to report bugs on * * @param reporter * the sync of bug reports */ public ModifyingUnmodifiableCollection(BugReporter reporter) { bugReporter = reporter; } /** * overrides the visitor to setup and tear down the opcode stack * * @param context * the context object of the currently parse java class */ @Override public void visitClassContext(ClassContext context) { try { stack = new OpcodeStack(); super.visitClassContext(context); } finally { stack = null; } } /** * overrides the visitor to reset the opcode stack, and reset the reported immutability of the method * * @param obj * the context object of the currently parse code block */ @Override public void visitCode(Code obj) { stack.resetForMethodEntry(this); reportedType = ImmutabilityType.UNKNOWN; super.visitCode(obj); } /** * overrides the visitor to find method mutations on collections that have previously been determined to have been created as immutable collections * * @param seen * the currently parsed opcode */ @Override public void sawOpcode(int seen) { if (reportedType == ImmutabilityType.IMMUTABLE) { return; } ImmutabilityType imType = null; try { stack.precomputation(this); switch (seen) { case INVOKESTATIC: case INVOKEINTERFACE: case INVOKESPECIAL: case INVOKEVIRTUAL: { String className = getClassConstantOperand(); String methodName = getNameConstantOperand(); String signature = getSigConstantOperand(); MethodInfo mi = Statistics.getStatistics().getMethodStatistics(className, methodName, signature); imType = mi.getImmutabilityType(); if (seen == INVOKEINTERFACE) { Integer collectionOffset = MODIFYING_METHODS.get(new QMethod(methodName, signature)); if ((collectionOffset != null) && CollectionUtils.isListSetMap(className)) { if (stack.getStackDepth() > collectionOffset.intValue()) { OpcodeStack.Item item = stack.getStackItem(collectionOffset.intValue()); ImmutabilityType type = (ImmutabilityType) item.getUserValue(); if ((type == ImmutabilityType.IMMUTABLE) || ((type == ImmutabilityType.POSSIBLY_IMMUTABLE) && (reportedType != ImmutabilityType.POSSIBLY_IMMUTABLE))) { bugReporter.reportBug(new BugInstance(this, BugType.MUC_MODIFYING_UNMODIFIABLE_COLLECTION.name(), (type == ImmutabilityType.IMMUTABLE) ? HIGH_PRIORITY : NORMAL_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this)); reportedType = type; } } } } } break; default: break; } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } finally { stack.sawOpcode(this, seen); if (imType != null) { if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); item.setUserValue(imType); } } } } }
#!/bin/sh -e # Copyright (c) 2017-2021, OARC, Inc. # Copyright (c) 2011-2017, IIS - The Internet Foundation in Sweden # All rights reserved. # # This file is part of PacketQ. # # PacketQ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PacketQ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PacketQ. If not, see <http://www.gnu.org/licenses/>. ../packetq -t -s "select s, dst_addr as Dst_addr, qtype as questiontype, lower(src_addr) as lower_src, if(1 and s < 1 or s <= 1 or s > 1 or s >= 1, 't', 'f'), trim(trim('foofoo' || rsplit(src_addr, 1) || 'foofoo', 'foo'), 'bar'), count(*), len(src_addr), sum(msg_size + -1 - 2 % 4 << 3 >> 2 | 3 & ~4) + 1, min(msg_size), max(msg_size), truncate(1.1) as integer, 1.1 as float, sum(src_port + 1.0 - 2.0 / 1.5 * -2.5) + 1.0, max(src_port + 1.0), min(src_port + 1.0), avg(src_port), stdev(src_port), name('rcode', 0) from dns where src_addr like '%' and (qr or not qr) group by src_addr, s having s >= 0 order by s, lower_src, integer, float" "$srcdir/../../pcap/sample.pcap.gz" > test3.out diff -uw "$srcdir/test3.gold" test3.out
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Orphans () where import Data.Vector (Vector) import qualified Data.Vector as V import Test.SmallCheck.Series as SC import Test.Tasty.QuickCheck as QC instance Serial m a => Serial m (Vector a) where series = fmap V.fromList series instance Arbitrary a => Arbitrary (Vector a) where arbitrary = fmap V.fromList arbitrary shrink = map V.fromList . shrink . V.toList
/* * This report script shows a scatter plot with requests over time */ require([ "HoneyProxy/util/formatSize", "dojox/charting/Chart", "dojox/charting/themes/Claro", "dojox/charting/plot2d/Scatter", "dojox/charting/action2d/Tooltip", "dojox/charting/action2d/Magnify", "dojox/charting/plot2d/Markers", "dojox/charting/axis2d/Default", ], function(formatSize, Chart, theme, Scatter, Tooltip, Magnify, Highlight) { var hosts = {}; // hostname -> y plot value var hostcount = 0; //number of known hosts var data = []; // Iterate over all flows and sum up content lengths traffic.query().forEach(function(flow){ var host = flow.request.host; if(!(host in hosts)) hosts[host] = hostcount++; data.push( { x:flow.request.timestamp_start, y:hosts[host], text: flow.request.path, flow: flow }); }); // Create the chart within it's "holding" node a = document.createElement("div"); a.style.width = "100%"; out.appendChild(a); var chart = new Chart(a,{ title: "Requests over time" }); // Set the theme chart.setTheme(theme); // Add the only/default plot chart.addPlot("default", { type: Scatter, markers: true, }); var labels = []; labels.push({text:"",value:-1}); for(i in hosts){ labels.push({text:i,value:hosts[i]}) } labels.push({text:"",value:hostcount}); a.style.height = (200+labels.length*10)+"px"; //Add axes chart.addAxis("x", { fixUpper: "minor", fixLower: "minor", labelFunc: function(a){ return (new Date(a*1000)).toLocaleTimeString(); } }); chart.addAxis("y", { labels: labels, vertical: true, min: -0.5, max: hostcount-0.5, dropLabels: false, minorTickStep: 1, majorTickStep: 1 }); // Add the series of data chart.addSeries("default",data); chart.connectToPlot( "default", function(evt){ if(!(evt.type === "onclick" && evt.element === "marker")) return; detailView.showDetails(data[evt.index].flow); chart.resize(); }) //Add tooltip var tip = new Tooltip(chart,"default"); var magnify = new Magnify(chart, "default"); // Render the chart! chart.render(); chart.resize(); });
<?php namespace JMS\Payment\CoreBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; /* * Copyright 2010 Johannes M. Schmitt <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ class Configuration { public function getConfigTree() { $tb = new TreeBuilder(); return $tb ->root('jms_payment_core', 'array') ->children() ->scalarNode('secret')->isRequired()->cannotBeEmpty()->end() ->end() ->end() ->buildTree(); } }
Watford and Wolves lock horns at Wembley on Sunday afternoon with both sides looking to give their fans the ultimate day out in the Final in May. VAR incidents will be shown to fans inside Wembley this weekend, so will it cause controversy or will we see an entertaining game won by a bit of brilliance? It’s been win, lose, win, lose, win lose of late for Watford. They’ve not drawn any of their last nine but they head into Sunday’s match on the back of a 4-1 hammering of Fulham. Their path to this stage of the FA Cup has been a win at Woking, a win at Newcastle, a win at QPR, and, most recently, a home win against Crystal Palace. The Hornets last met Wolves in the FA Cup back in 2008. They lost 4-1 that day. Wolves have won on their last six trips to Wembley. Omen? Some would say so. Regardless of this little fact, they’re in decent form and have beaten Manchester United twice in the space of two weeks. Their journey to this stage has been a little bumpier than Watford’s, but they’ve had some tough matches. It started with a home win against Liverpool. They were taken to a replay against League One Shrewsbury but came through that test to win away at Bristol City in the following round. Manchester United tried and failed in the previous round. Roberto Pereyra and Isaac Success are in a race against time to make this one. They will both have fitness tests to see if they can play this weekend. Tom Cleverley will certainly miss out with a calf issue. It’s a clean bill of health as far as Wolves are concerned. The only definite bit of team news is that John Ruddy will keep his place in goal ahead of Rui Patricio. Ruddy has played every game so far in the competition, so it’d be a bit unfair if he lost his place now. Watford Predicted XI: Foster, Femenia, Mariappa, Cathcart, Holebas, Doucoure, Capoue, Pereyra, Deulofeu, Hughes, Deeney. Wolves Predicted XI: Ruddy, Bennett, Coady, Boly, Doherty, Dendoncker, Neves, Jonny, Moutinho, Jota, Jimenez. It’s no surprise to see Wolves installed as favourites by the bookies to win this one. They’re priced at 6/4. Watford are the outsiders at a generous 2/1, with the draw available at odds of 11/5. 1-2. Watford won at Molineux back in October but Wolves are a much-improved team since then. They’re in great form and I think they’ll carry that form over to this FA Cup game. Deeney and co will give it a good go for the Hornets, there’s no doubt about that, but I think Wolves will edge it. Both sides won their respective league matches last time out, but it’s worth noting here that Watford have lost their last three away from Vicarage Road. Wolves are a good enough price for me. We could look into total goals, scorers and both teams to score, but I think Nuno Santo’s side are a decent enough price to simply back them in the Match Odds market. They’re 6/4. Join me on the Wolves hype train. Wolves have won on their last six visits to Wembley Stadium. Wolves have lost just two of their last 14 matches in all competitions. Watford have lost their last three matches away from home. Watford have lost the last four matches played at Wembley. The Hornet's biggest FA Cup defeat was a 10-0 loss against Wolves in January 1912. Watford have won just one of the seven FA Cup meetings between the two sides – 3-0 in the fifth round in 1980.
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using RestSharp; using Xunit; using Org.OpenAPITools.Client; using Org.OpenAPITools.Apis; // uncomment below to import models //using Org.OpenAPITools.Models; namespace Org.OpenAPITools.Test.Api { /// <summary> /// Class for testing BlueOceanApi /// </summary> /// <remarks> /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). /// Please update the test case below to test the API endpoint. /// </remarks> public class BlueOceanApiTests : IDisposable { private BlueOceanApi instance; public BlueOceanApiTests() { instance = new BlueOceanApi(); } public void Dispose() { // Cleanup when everything is done. } /// <summary> /// Test an instance of BlueOceanApi /// </summary> [Fact] public void InstanceTest() { // TODO uncomment below to test 'IsType' BlueOceanApi //Assert.IsType<BlueOceanApi>(instance); } /// <summary> /// Test DeletePipelineQueueItem /// </summary> [Fact] public void DeletePipelineQueueItemTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string queue = null; //instance.DeletePipelineQueueItem(organization, pipeline, queue); } /// <summary> /// Test GetAuthenticatedUser /// </summary> [Fact] public void GetAuthenticatedUserTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //var response = instance.GetAuthenticatedUser(organization); //Assert.IsType<User>(response); } /// <summary> /// Test GetClasses /// </summary> [Fact] public void GetClassesTest() { // TODO uncomment below to test the method and replace null with proper value //string _class = null; //var response = instance.GetClasses(_class); //Assert.IsType<string>(response); } /// <summary> /// Test GetJsonWebKey /// </summary> [Fact] public void GetJsonWebKeyTest() { // TODO uncomment below to test the method and replace null with proper value //int key = null; //var response = instance.GetJsonWebKey(key); //Assert.IsType<string>(response); } /// <summary> /// Test GetJsonWebToken /// </summary> [Fact] public void GetJsonWebTokenTest() { // TODO uncomment below to test the method and replace null with proper value //int? expiryTimeInMins = null; //int? maxExpiryTimeInMins = null; //var response = instance.GetJsonWebToken(expiryTimeInMins, maxExpiryTimeInMins); //Assert.IsType<string>(response); } /// <summary> /// Test GetOrganisation /// </summary> [Fact] public void GetOrganisationTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //var response = instance.GetOrganisation(organization); //Assert.IsType<Organisation>(response); } /// <summary> /// Test GetOrganisations /// </summary> [Fact] public void GetOrganisationsTest() { // TODO uncomment below to test the method and replace null with proper value //var response = instance.GetOrganisations(); //Assert.IsType<List<Organisation>>(response); } /// <summary> /// Test GetPipeline /// </summary> [Fact] public void GetPipelineTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //var response = instance.GetPipeline(organization, pipeline); //Assert.IsType<Pipeline>(response); } /// <summary> /// Test GetPipelineActivities /// </summary> [Fact] public void GetPipelineActivitiesTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //var response = instance.GetPipelineActivities(organization, pipeline); //Assert.IsType<List<PipelineActivity>>(response); } /// <summary> /// Test GetPipelineBranch /// </summary> [Fact] public void GetPipelineBranchTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string branch = null; //var response = instance.GetPipelineBranch(organization, pipeline, branch); //Assert.IsType<BranchImpl>(response); } /// <summary> /// Test GetPipelineBranchRun /// </summary> [Fact] public void GetPipelineBranchRunTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string branch = null; //string run = null; //var response = instance.GetPipelineBranchRun(organization, pipeline, branch, run); //Assert.IsType<PipelineRun>(response); } /// <summary> /// Test GetPipelineBranches /// </summary> [Fact] public void GetPipelineBranchesTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //var response = instance.GetPipelineBranches(organization, pipeline); //Assert.IsType<MultibranchPipeline>(response); } /// <summary> /// Test GetPipelineFolder /// </summary> [Fact] public void GetPipelineFolderTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string folder = null; //var response = instance.GetPipelineFolder(organization, folder); //Assert.IsType<PipelineFolderImpl>(response); } /// <summary> /// Test GetPipelineFolderPipeline /// </summary> [Fact] public void GetPipelineFolderPipelineTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string folder = null; //var response = instance.GetPipelineFolderPipeline(organization, pipeline, folder); //Assert.IsType<PipelineImpl>(response); } /// <summary> /// Test GetPipelineQueue /// </summary> [Fact] public void GetPipelineQueueTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //var response = instance.GetPipelineQueue(organization, pipeline); //Assert.IsType<List<QueueItemImpl>>(response); } /// <summary> /// Test GetPipelineRun /// </summary> [Fact] public void GetPipelineRunTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //var response = instance.GetPipelineRun(organization, pipeline, run); //Assert.IsType<PipelineRun>(response); } /// <summary> /// Test GetPipelineRunLog /// </summary> [Fact] public void GetPipelineRunLogTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //int? start = null; //bool? download = null; //var response = instance.GetPipelineRunLog(organization, pipeline, run, start, download); //Assert.IsType<string>(response); } /// <summary> /// Test GetPipelineRunNode /// </summary> [Fact] public void GetPipelineRunNodeTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //string node = null; //var response = instance.GetPipelineRunNode(organization, pipeline, run, node); //Assert.IsType<PipelineRunNode>(response); } /// <summary> /// Test GetPipelineRunNodeStep /// </summary> [Fact] public void GetPipelineRunNodeStepTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //string node = null; //string step = null; //var response = instance.GetPipelineRunNodeStep(organization, pipeline, run, node, step); //Assert.IsType<PipelineStepImpl>(response); } /// <summary> /// Test GetPipelineRunNodeStepLog /// </summary> [Fact] public void GetPipelineRunNodeStepLogTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //string node = null; //string step = null; //var response = instance.GetPipelineRunNodeStepLog(organization, pipeline, run, node, step); //Assert.IsType<string>(response); } /// <summary> /// Test GetPipelineRunNodeSteps /// </summary> [Fact] public void GetPipelineRunNodeStepsTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //string node = null; //var response = instance.GetPipelineRunNodeSteps(organization, pipeline, run, node); //Assert.IsType<List<PipelineStepImpl>>(response); } /// <summary> /// Test GetPipelineRunNodes /// </summary> [Fact] public void GetPipelineRunNodesTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //var response = instance.GetPipelineRunNodes(organization, pipeline, run); //Assert.IsType<List<PipelineRunNode>>(response); } /// <summary> /// Test GetPipelineRuns /// </summary> [Fact] public void GetPipelineRunsTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //var response = instance.GetPipelineRuns(organization, pipeline); //Assert.IsType<List<PipelineRun>>(response); } /// <summary> /// Test GetPipelines /// </summary> [Fact] public void GetPipelinesTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //var response = instance.GetPipelines(organization); //Assert.IsType<List<Pipeline>>(response); } /// <summary> /// Test GetSCM /// </summary> [Fact] public void GetSCMTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string scm = null; //var response = instance.GetSCM(organization, scm); //Assert.IsType<GithubScm>(response); } /// <summary> /// Test GetSCMOrganisationRepositories /// </summary> [Fact] public void GetSCMOrganisationRepositoriesTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string scm = null; //string scmOrganisation = null; //string credentialId = null; //int? pageSize = null; //int? pageNumber = null; //var response = instance.GetSCMOrganisationRepositories(organization, scm, scmOrganisation, credentialId, pageSize, pageNumber); //Assert.IsType<List<GithubOrganization>>(response); } /// <summary> /// Test GetSCMOrganisationRepository /// </summary> [Fact] public void GetSCMOrganisationRepositoryTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string scm = null; //string scmOrganisation = null; //string repository = null; //string credentialId = null; //var response = instance.GetSCMOrganisationRepository(organization, scm, scmOrganisation, repository, credentialId); //Assert.IsType<List<GithubOrganization>>(response); } /// <summary> /// Test GetSCMOrganisations /// </summary> [Fact] public void GetSCMOrganisationsTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string scm = null; //string credentialId = null; //var response = instance.GetSCMOrganisations(organization, scm, credentialId); //Assert.IsType<List<GithubOrganization>>(response); } /// <summary> /// Test GetUser /// </summary> [Fact] public void GetUserTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string user = null; //var response = instance.GetUser(organization, user); //Assert.IsType<User>(response); } /// <summary> /// Test GetUserFavorites /// </summary> [Fact] public void GetUserFavoritesTest() { // TODO uncomment below to test the method and replace null with proper value //string user = null; //var response = instance.GetUserFavorites(user); //Assert.IsType<List<FavoriteImpl>>(response); } /// <summary> /// Test GetUsers /// </summary> [Fact] public void GetUsersTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //var response = instance.GetUsers(organization); //Assert.IsType<User>(response); } /// <summary> /// Test PostPipelineRun /// </summary> [Fact] public void PostPipelineRunTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //var response = instance.PostPipelineRun(organization, pipeline, run); //Assert.IsType<QueueItemImpl>(response); } /// <summary> /// Test PostPipelineRuns /// </summary> [Fact] public void PostPipelineRunsTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //var response = instance.PostPipelineRuns(organization, pipeline); //Assert.IsType<QueueItemImpl>(response); } /// <summary> /// Test PutPipelineFavorite /// </summary> [Fact] public void PutPipelineFavoriteTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //bool body = null; //var response = instance.PutPipelineFavorite(organization, pipeline, body); //Assert.IsType<FavoriteImpl>(response); } /// <summary> /// Test PutPipelineRun /// </summary> [Fact] public void PutPipelineRunTest() { // TODO uncomment below to test the method and replace null with proper value //string organization = null; //string pipeline = null; //string run = null; //string blocking = null; //int? timeOutInSecs = null; //var response = instance.PutPipelineRun(organization, pipeline, run, blocking, timeOutInSecs); //Assert.IsType<PipelineRun>(response); } /// <summary> /// Test Search /// </summary> [Fact] public void SearchTest() { // TODO uncomment below to test the method and replace null with proper value //string q = null; //var response = instance.Search(q); //Assert.IsType<string>(response); } /// <summary> /// Test SearchClasses /// </summary> [Fact] public void SearchClassesTest() { // TODO uncomment below to test the method and replace null with proper value //string q = null; //var response = instance.SearchClasses(q); //Assert.IsType<string>(response); } } }
'use strict'; import User from './user.model'; import passport from 'passport'; import config from '../../config/environment'; import jwt from 'jsonwebtoken'; function validationError(res, statusCode) { statusCode = statusCode || 422; return function (err) { res.status(statusCode).json(err); } } function handleError(res, statusCode) { statusCode = statusCode || 500; return function (err) { res.status(statusCode).send(err); }; } /** * Get list of users * restriction: 'admin' */ export function index(req, res) { User.findAsync({}, '-salt -password') .then(users => { res.status(200).json(users); }) .catch(handleError(res)); } /** * Creates a new user */ export function create(req, res, next) { var newUser = new User(req.body); newUser.provider = 'local'; newUser.role = 'user'; newUser.saveAsync() .spread(function (user) { var token = jwt.sign({ _id: user._id }, config.secrets.session, { expiresIn: 60 * 60 * 5 }); res.json({ token }); }) .catch(validationError(res)); } /** * Get a single user */ export function show(req, res, next) { var userId = req.params.id; User.findByIdAsync(userId) .then(user => { if (!user) { return res.status(404).end(); } res.json(user.profile); }) .catch(err => next(err)); } /** * Deletes a user * restriction: 'admin' */ export function destroy(req, res) { User.findByIdAndRemoveAsync(req.params.id) .then(function () { res.status(204).end(); }) .catch(handleError(res)); } /** * Change a users password */ export function changePassword(req, res, next) { var userId = req.user._id; var oldPass = String(req.body.oldPassword); var newPass = String(req.body.newPassword); User.findByIdAsync(userId) .then(user => { if (user.authenticate(oldPass)) { user.password = newPass; return user.saveAsync() .then(() => { res.status(204).end(); }) .catch(validationError(res)); } else { return res.status(403).end(); } }); } export function updateOrder(req, res) { var userId = req.params.id; User.findByIdAndUpdate(userId, { $push: { 'order': req.body.order } }, { safe: true, upsert: true, new: true }, function (err, user) { console.log(err); }); } function handleEntityNotFound(res) { return function (entity) { if (!entity) { res.status(404).end(); return null; } return entity; }; } function respondWithResult(res, statusCode) { statusCode = statusCode || 200; return function (entity) { if (entity) { res.status(statusCode).json(entity); } }; } function saveUpdates(updates) { return function (entity) { var updated = _.merge(entity, updates); return updated.saveAsync() .spread(updated => { return updated; }); }; } /** * Get my info */ export function me(req, res, next) { var userId = req.user._id; User.findOneAsync({ _id: userId }, '-salt -password') .then(user => { // don't ever give out the password or salt if (!user) { return res.status(401).end(); } res.json(user); }) .catch(err => next(err)); } /** * Authentication callback */ export function authCallback(req, res, next) { res.redirect('/'); }
Vladan Stanković, PhD, is the Research Associate of the Institute for Political Studies, member of the Editorial Board of the journal Politička revija (Political Review). As an expert on issues of sociology and politicology of religion, he published numerous papers, the book “Pravoslavno društvo – ustanove, kultura, razvoj” (Orthodox Society – Institutions, Culture, Development) (Institute for Political Studies, 2014) and is an on-call lecturer at the Faculty of Orthodox Theology, Faculty of Political Sciences and the Faculty of Law of the University in Belgrade. Member of the Serbian Society of Sociology. The national identity of the Serbs and Montenegrism are two parallel and exclusive phenomena. Th e representatives of the Montenegrin national identity deny their Serbian ethnic origin, with the help of the „Civil concept of the Montenegrin nation“ assimilate national Serbs in Montenegro. Th ese assimilation processes of Serbs permanently destabilize montenegrin society and undermine stability in the Western Balkans region. Th e exit strategy would represent, for the beginning: a consociational model for the organization of Montenegro, as a society of multiethnic and inter-religious communities, based on equal principles that would take place in parallel with the processes of regional integration in the Western Balkans region.
// Copyright (C) 2015 André Bargull. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-method-definitions-static-semantics-early-errors description: > A SyntaxError is thrown if a setter method contains a non-simple parameter list and a UseStrict directive. info: | Static Semantics: Early Errors It is a Syntax Error if ContainsUseStrict of FunctionBody is true and IsSimpleParameterList of PropertySetParameterList is false. negative: phase: parse type: SyntaxError ---*/ throw "Test262: This statement should not be evaluated."; var o = { set m(a = 0) { "use strict"; } };
--- layout: post title: "2014年十月周中聚会" date: 2014-10-21 19:00:00 categories: monthly callup --- ####时间:2014年10月21日(周二) 晚上7点到9点 ####地点:浦东新区世纪大道8号上海国金中心D座B1楼LG1-37室 COSTA COFFEE(国金中心店) ####交通:*位置在浦东陆家嘴的Apple Store旁边*,提早到达的同学请负责占座 ####网址:[点评网址](http://www.dianping.com/shop/4600640) ####主题: Rails 4.2已释出 [beta2](http://weblog.rubyonrails.org/2014/9/29/Rails-4-2-0-beta2-has-been-released/),我们不妨来讨论下新版本中好用又好玩的新增特性。
I haven't been able to post much this week since we've been in Colorado, but were able to snap a few pictures today. We have been camping the majority of the time, so my wardrobe here hasn't been that exciting haha... Finally got to wear some normal clothes today! This top from target is so so soft! It is a bit oversized (I am wearing a small) and flowy. It is just a nice casual tee to have.
module Decorum module Examples class MilkDecorator < Decorum::Decorator share :milk_level, :calories attr_accessor :animal, :milk_type # recursive function to allow all MilkDecorators to add # some milk; note the tail call is wrapped in decorated_tail def add_milk self.milk_level = milk_level.to_i + 1 decorated_tail(milk_level) { next_link.add_milk } end # used with non-shared attributes, (e.g., "animal") # decorated tail can also be used to defer a # call to the _first_ decorator in the chain # that responds to the method def first_animal decorated_tail(animal) { next_link.first_animal } end # for goodness' sake what has bob been putting in his coffee def all_animals(animals=[]) animals << animal decorated_tail(animals) { next_link.all_animals(animals) } end end end end
83000 Batu Pahat, Johor, Malaysia. Copyright © 2019 Bbmilkit. All rights reserved.
<?php die('www');
Earlier today, Instagram announced an update that would automatically add alt text and image descriptions to images in the feed, explore, and profile sections of the app so vision impaired users can get information about what is in a picture. Users can also add their own alt text or image descriptions to posts so that they can ensure their vision impaired followers are not left out of the fun. However, with this new update, it's important that users know not only what alt text and image descriptions are, but how to write alt text and image descriptions for Instagram posts. Today, I will be sharing a brief tutorial on how to make Instagram posts accessible for screen readers using alt text and image descriptions. The first part of this post defines common assistive technology terms for those not familiar with them, the second part of the post covers tips for writing alt text and image descriptions for Instagram, and the third part of the post shares how to add alt text and image descriptions to Instagram posts. Alt text tells people what is in an image, such as text or basic essential details. If an image fails to load, alt text will display in its place. Search engines also index alt text information and consider it a factor when determining search engine ratings. This is a very short description, usually only 1-2 sentences. For a photo based app like Instagram, alt text can be written with more detail compared to alt text that is written for an image on a blog. It is strongly recommended that alt text be 125 characters or less to ensure compatibility for popular screen readers. An image description gives more details than alt text and allows someone to learn more about what is in an image that goes beyond alt text. Alt text gives the user the most important information while image descriptions provide further detail. For example, alt text tells someone that there’s a puddle on the floor, and image description tells someone that the puddle on the floor is in the middle of the floor and it’s orange juice. Users may choose to add detailed descriptions as the default alt text, or may add descriptions to the end of a caption so people can get more details if they want. Image descriptions can be longer than traditional alt text, but I recommend keeping them the length of a tweet, or about 280 characters. A screen reader, sometimes referred to as text-to-speech, is a form of assistive technology that allows people with vision impairments such as blindness and low vision to read digital information. Screen readers are built in to almost every smartphone currently on the market so that users can read text messages, make phone calls, interact with apps, and much more. When it comes to mobile users, a majority of blind and low vision users use VoiceOver on their iOS devices- read more about VoiceOver here. Screen readers need a little bit of help in order to be able to read information, so this is where users come in and write out their own alt text and image descriptions so that the screen reader has something to read. Next, we're gonna learn how to write alt text for your Instagram posts so that screen reader users can know what's going on. "Hey Veronica, who's that in the photo with you?" "Oh, that's a fluffy gray dog sitting in my lap. We're sitting on the ground at a therapy dog event." Is there a sign in the photo, or is it a screenshot of an article? Write out any important text that is in the photo that someone would notice or want to read. If there's a billboard in the background of your group photo that a sighted person wouldn't notice, then you don't have to mention it, but if everyone is gathered around the billboard to take a photo, then write out what the billboard says and what it looks like. Don't be afraid to share what colors are in a photo, if color is important. However, don't get caught up trying to explain what color is to someone who can't see it. A photo can be described as being in black-and-white, having warm or cool colors, or being tinted a certain color. Someone wearing clothes that are the main focus of the photo can write that they are wearing a black and white lace dress with yellow earrings. For personal Instagram accounts, I would write out names of people who are in the picture for the first part of the description, then describe the setting of the photo. For example, if I took a selfie with friends, I would write "Veronica and Lakota smiling at the camera while standing on the streets of Washington, DC." For business Instagram accounts that use models or where description matters, I would write out a simple description that includes information such as skin tone, gender, hair color/style, what they are wearing, and any other interesting features or expressions. For example, I might write a description of my friend as "a white female with shoulder length blonde hair wearing a black dress and silver earrings. She is smiling and her blue eyes are looking at something behind the camera." Instagram accounts for topics such as fashion, photography, and interior design are going to have more detailed descriptions than someone's personal account that is followed by a handful of family and friends. Even if it doesn't seem like you'd have any followers with vision impairment, you never know who may develop issues with their eyesight or if someone may be hiding a condition from you, since not all vision impairments are easily noticeable. It only takes about thirty seconds to write out a description, so why not take the time to do so? Right before you publish a new Instagram post, there is an option under "advanced settings" to compose an alt text description. You can type out your alt text here, or copy and paste it from another app. If you want to add a longer image description, add an open bracket at the end of your caption, add the phrase "image description:" and then type out/copy and paste whatever you want to add. Make sure to add a closed bracket at the end! To add alt text to an existing post, click on the three vertical dots at the top of the post, click "edit", and then tap the "alt text" option that is directly on top of the photo, next to the "tag people" option. From there, you can add your own alt text and it will be saved to the photo. To add a longer image description to an existing post, click on the three vertical dots at the top of the post, click "edit", and then edit the caption following the same guidelines from the section "Adding Image Descriptions to a New Post." Make sure to click the check mark afterwards to save your work. I'm so excited that Instagram is taking steps to be more accessible for people with vision impairment. Over 250 million people worldwide have some form of vision loss, and this number is expected to continue to grow with the senior population. By knowing how to write alt text and image descriptions for Instagram posts, people and businesses can ensure that those who have vision impairments aren't excluded from enjoying what they have to share.
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Lucene.Net.Spatial.Utils; namespace Lucene.Net.Spatial.Geometry.Shape { /// <summary> /// 2D Vector /// </summary> public class Vector2D { public Vector2D() { X = 0; Y = 0; } /// <summary> /// Create a vector from the origin of the coordinate system to the given point /// </summary> /// <param name="x">The x.</param> /// <param name="y">The y.</param> public Vector2D(double x, double y) { X = x; Y = y; } /// <summary> /// Create a vector from the origin of the coordinate system to the given point /// </summary> public Vector2D(Point2D p) : this(p.X, p.Y) {} /// <summary> /// Create a vector from one point to another /// </summary> public Vector2D(Point2D from, Point2D to) : this(to.X - from.X, to.Y - from.Y) {} public Vector2D(Vector2D other) { X = other.X; Y = other.Y; } public double X { get; set; } public double Y { get; set; } public void Set(double x, double y) { X = x; Y = y; } public bool Equals(Vector2D other) { return other != null && X == other.X && Y == other.Y; } public double Dot(Vector2D v) { return ((X) * v.X) + (Y * v.Y); } /// <summary> /// Vector length (magnitude) squared /// </summary> public double NormSqr() { // Cast to F to prevent overflows return (X * X) + (Y * Y); } public double Norm() { return Math.Sqrt(NormSqr()); } public Vector2D Mult(double d) { return new Vector2D(X * d, Y * d); } public override int GetHashCode() { const int prime = 31; int result = 1; long temp = Convert.ToInt64(X); result = prime * result + (int)(temp ^ BitwiseHelper.ZeroFillRightShift(temp, 32)); temp = Convert.ToInt64(Y); result = prime * result + (int)(temp ^ BitwiseHelper.ZeroFillRightShift(temp, 32)); return result; } public override bool Equals(object obj) { if (this == obj) return true; if (obj == null) return false; if (GetType() != obj.GetType()) return false; var other = (Vector2D)obj; if (Convert.ToInt64(X) != Convert.ToInt64(other.X)) return false; return Convert.ToInt64(Y) == Convert.ToInt64(other.Y); } } }
Millions of Syrian children were forced by war and violence to leave everything behind and live in refugee camps. They try to build up a temporary existence in neighbouring countries such as Jordan, Lebanon, Turkey and Iraq, in poor conditions. UNICEF helps these children by giving them the support they need. Since 2011, millions of Syrian children have fled their homes because of the war and violence, leaving behind all their belongings. A simple message wasn’t enough. For the target audience the latest symbol of modern communication is the emoji. Combined with well-known photographs of refugee childeren we created the strong emotional impact we needed. To support UNICEF’s work in Syria and neighbouring countries, we created a campaign that turns a wide variety of emoji into emergency aid. By texting an emoji like a drop of water, a sleeping smiley or a campfire, you symbolically give a refugee child the aid it needs – giving a deeper meaning to the three euros you donate by texting. TV-commercials, digital outdoor ads, mobile bannering, print and non-spot advertising are used to create awareness amongst a broad target audience.
The canopy cover is custom-designed to protect the canopy from scratch during storage or transportation. It also helps prevent finger prints or dust on your beautiful canopy clear coat. The canopy covers are carefully handcrafted to perfectly fit the canopy shape. It has 2 small pockets at the canopy tails to custom fit the canopy so it is not easy to slip out. The material is ultra soft and the linings are carefully sewed to ensure the canopy cover does not scratch when putting on the canopy. This could be one of the best investments for your beautiful airbrush canopy.
$('#close').on('click', function() { var toServer = {temp2:user + ' left the chat!!', type:'message', sender:user} websocket.send(JSON.stringify(toServer)); var toServer2 = {temp2:user, type:'close'} websocket.send(JSON.stringify(toServer2)); websocket.close(); location.reload(); });
<?php /** * @file include/attach.php * * @brief File/attach API with the potential for revision control. * * @TODO A filesystem storage abstraction which maintains security (and 'data' * contains a system filename which is inaccessible from the web). This could * get around PHP storage limits and store videos and larger items, using fread * or OS methods or native code to read/write or chunk it through. * @todo Also an 'append' option to the storage function might be a useful addition. */ require_once('include/permissions.php'); require_once('include/security.php'); /** * @brief Guess the mimetype from file ending. * * This function takes a file name and guess the mimetype from the * filename extension. * * @param $filename a string filename * @return string The mimetype according to a file ending. */ function z_mime_content_type($filename) { $mime_types = array( 'txt' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html', 'php' => 'text/html', 'css' => 'text/css', 'js' => 'application/javascript', 'json' => 'application/json', 'xml' => 'application/xml', 'swf' => 'application/x-shockwave-flash', 'flv' => 'video/x-flv', 'epub' => 'application/epub+zip', // images 'png' => 'image/png', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'bmp' => 'image/bmp', 'ico' => 'image/vnd.microsoft.icon', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', // archives 'zip' => 'application/zip', 'rar' => 'application/x-rar-compressed', 'exe' => 'application/x-msdownload', 'msi' => 'application/x-msdownload', 'cab' => 'application/vnd.ms-cab-compressed', // audio/video 'mp3' => 'audio/mpeg', 'wav' => 'audio/wav', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'ogg' => 'audio/ogg', 'ogv' => 'video/ogg', 'ogx' => 'application/ogg', 'flac' => 'audio/flac', 'opus' => 'audio/ogg', 'webm' => 'video/webm', // 'webm' => 'audio/webm', 'mp4' => 'video/mp4', // 'mp4' => 'audio/mp4', // adobe 'pdf' => 'application/pdf', 'psd' => 'image/vnd.adobe.photoshop', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', // ms office 'doc' => 'application/msword', 'rtf' => 'application/rtf', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', // open office 'odt' => 'application/vnd.oasis.opendocument.text', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'odp' => 'application/vnd.oasis.opendocument.presentation', 'odg' => 'application/vnd.oasis.opendocument.graphics', 'odc' => 'application/vnd.oasis.opendocument.chart', 'odf' => 'application/vnd.oasis.opendocument.formula', 'odi' => 'application/vnd.oasis.opendocument.image', 'odm' => 'application/vnd.oasis.opendocument.text-master', 'odb' => 'application/vnd.oasis.opendocument.base', 'odb' => 'application/vnd.oasis.opendocument.database', 'ott' => 'application/vnd.oasis.opendocument.text-template', 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', 'otp' => 'application/vnd.oasis.opendocument.presentation-template', 'otg' => 'application/vnd.oasis.opendocument.graphics-template', 'otc' => 'application/vnd.oasis.opendocument.chart-template', 'otf' => 'application/vnd.oasis.opendocument.formula-template', 'oti' => 'application/vnd.oasis.opendocument.image-template', 'oth' => 'application/vnd.oasis.opendocument.text-web' ); $last_dot = strrpos($filename, '.'); if ($last_dot !== false) { $ext = strtolower(substr($filename, $last_dot + 1)); if (array_key_exists($ext, $mime_types)) { return $mime_types[$ext]; } } return 'application/octet-stream'; } /** * @brief Count files/attachments. * * @param int $channel_id * @param string $observer * @param string $hash (optional) * @param string $filename (optional) * @param string $filetype (optional) * @return associative array with: * * \e boolean \b success * * \e int|boolean \b results amount of found results, or false * * \e string \b message with error messages if any */ function attach_count_files($channel_id, $observer, $hash = '', $filename = '', $filetype = '') { $ret = array('success' => false); if(! perm_is_allowed($channel_id, $observer, 'read_storage')) { $ret['message'] = t('Permission denied.'); return $ret; } require_once('include/security.php'); $sql_extra = permissions_sql($channel_id); if($hash) $sql_extra .= protect_sprintf(" and hash = '" . dbesc($hash) . "' "); if($filename) $sql_extra .= protect_sprintf(" and filename like '@" . dbesc($filename) . "@' "); if($filetype) $sql_extra .= protect_sprintf(" and filetype like '@" . dbesc($filetype) . "@' "); $r = q("select id, uid, folder from attach where uid = %d $sql_extra", intval($channel_id) ); $ret['success'] = ((is_array($r)) ? true : false); $ret['results'] = ((is_array($r)) ? count($r) : false); return $ret; } /** * @brief Returns a list of files/attachments. * * @param $channel_id * @param $observer * @param $hash (optional) * @param $filename (optional) * @param $filetype (optional) * @param $orderby * @param $start * @param $entries * @return associative array with: * * \e boolean \b success * * \e array|boolean \b results array with results, or false * * \e string \b message with error messages if any */ function attach_list_files($channel_id, $observer, $hash = '', $filename = '', $filetype = '', $orderby = 'created desc', $start = 0, $entries = 0) { $ret = array('success' => false); if(! perm_is_allowed($channel_id,$observer, 'view_storage')) { $ret['message'] = t('Permission denied.'); return $ret; } require_once('include/security.php'); $sql_extra = permissions_sql($channel_id); if($hash) $sql_extra .= protect_sprintf(" and hash = '" . dbesc($hash) . "' "); if($filename) $sql_extra .= protect_sprintf(" and filename like '@" . dbesc($filename) . "@' "); if($filetype) $sql_extra .= protect_sprintf(" and filetype like '@" . dbesc($filetype) . "@' "); if($entries) $limit = " limit " . intval($start) . ", " . intval(entries) . " "; // Retrieve all columns except 'data' $r = q("select id, aid, uid, hash, filename, filetype, filesize, revision, folder, os_storage, is_dir, is_photo, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where uid = %d $sql_extra ORDER BY $orderby $limit", intval($channel_id) ); $ret['success'] = ((is_array($r)) ? true : false); $ret['results'] = ((is_array($r)) ? $r : false); return $ret; } /** * @brief Find an attachment by hash and revision. * * Returns the entire attach structure including data. * * This could exhaust memory so most useful only when immediately sending the data. * * @param string $hash * @param int $rev Revision * @return array */ function attach_by_hash($hash, $rev = 0) { $ret = array('success' => false); // Check for existence, which will also provide us the owner uid $sql_extra = ''; if($rev == (-1)) $sql_extra = " order by revision desc "; elseif($rev) $sql_extra = " and revision = " . intval($rev) . " "; $r = q("SELECT uid FROM attach WHERE hash = '%s' $sql_extra LIMIT 1", dbesc($hash) ); if(! $r) { $ret['message'] = t('Item was not found.'); return $ret; } if(! perm_is_allowed($r[0]['uid'], get_observer_hash(), 'view_storage')) { $ret['message'] = t('Permission denied.'); return $ret; } $sql_extra = permissions_sql($r[0]['uid']); // Now we'll see if we can access the attachment $r = q("SELECT * FROM attach WHERE hash = '%s' and uid = %d $sql_extra LIMIT 1", dbesc($hash), intval($r[0]['uid']) ); if(! $r) { $ret['message'] = t('Permission denied.'); return $ret; } if($r[0]['folder']) { $x = attach_can_view_folder($r[0]['uid'],get_observer_hash(),$r[0]['folder']); if(! $x) { $ret['message'] = t('Permission denied.'); return $ret; } } $ret['success'] = true; $ret['data'] = $r[0]; return $ret; } function attach_can_view_folder($uid,$ob_hash,$folder_hash) { $sql_extra = permissions_sql($uid,$ob_hash); $hash = $folder_hash; $result = false; do { $r = q("select folder from attach where hash = '%s' and uid = %d $sql_extra", dbesc($hash), intval($uid) ); if(! $r) return false; $hash = $r[0]['folder']; } while($hash); return true; } /** * @brief Find an attachment by hash and revision. * * Returns the entire attach structure excluding data. * * @see attach_by_hash() * @param $hash * @param $rev revision default 0 * @return associative array with everything except data * * \e boolean \b success boolean true or false * * \e string \b message (optional) only when success is false * * \e array \b data array of attach DB entry without data component */ function attach_by_hash_nodata($hash, $rev = 0) { $ret = array('success' => false); // Check for existence, which will also provide us the owner uid $sql_extra = ''; if($rev == (-1)) $sql_extra = " order by revision desc "; elseif($rev) $sql_extra = " and revision = " . intval($rev) . " "; $r = q("SELECT uid FROM attach WHERE hash = '%s' $sql_extra LIMIT 1", dbesc($hash) ); if(! $r) { $ret['message'] = t('Item was not found.'); return $ret; } if(! perm_is_allowed($r[0]['uid'],get_observer_hash(),'view_storage')) { $ret['message'] = t('Permission denied.'); return $ret; } $sql_extra = permissions_sql($r[0]['uid']); // Now we'll see if we can access the attachment $r = q("select id, aid, uid, hash, creator, filename, filetype, filesize, revision, folder, os_storage, is_photo, is_dir, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where uid = %d and hash = '%s' $sql_extra limit 1", intval($r[0]['uid']), dbesc($hash) ); if(! $r) { $ret['message'] = t('Permission denied.'); return $ret; } if($r[0]['folder']) { $x = attach_can_view_folder($r[0]['uid'],get_observer_hash(),$r[0]['folder']); if(! $x) { $ret['message'] = t('Permission denied.'); return $ret; } } $ret['success'] = true; $ret['data'] = $r[0]; return $ret; } /** * @brief Stores an attachment from a POST file upload. * * This function stores an attachment. It can be a new one, a replacement or a * new revision depending on value set in \e $options. * * @note Requires an input field \e userfile and does not accept multiple files * in one request. * * @param array $channel channel array of owner * @param string $observer_hash hash of current observer * @param string $options (optional) one of update, replace, revision * @param array $arr (optional) associative array */ /** * A lot going on in this function, and some of it is old cruft and some is new cruft * and the entire thing probably needs to be refactored. It started out just storing * files, before we had DAV. It was made extensible to do extra stuff like edit an * existing file or optionally store a separate revision using $options to choose between different * storage models. Along the way we moved from * DB data storage to file system storage. * Then DAV came along and used different upload methods depending on whether the * file was stored as a DAV directory object or updated as a file object. One of these * is essentially an update and the other is basically an upload, but doesn't use the traditional PHP * upload workflow. * Then came hubzilla and we tried to merge photo functionality with the file storage. Most of * that integration occurs within this function. * This required overlap with the old photo_upload stuff and photo albums were * completely different concepts from directories which needed to be reconciled somehow. * The old revision stuff is kind of orphaned currently. There's new revision stuff for photos * which attaches (2) etc. onto the name, but doesn't integrate with the attach table revisioning. * That's where it sits currently. I repeat it needs to be refactored, and this note is here * for future explorers and those who may be doing that work to understand where it came * from and got to be the monstrosity of tangled unrelated code that it currently is. */ function attach_store($channel, $observer_hash, $options = '', $arr = null) { require_once('include/photos.php'); call_hooks('photo_upload_begin',$arr); $ret = array('success' => false); $channel_id = $channel['channel_id']; $sql_options = ''; $source = (($arr) ? $arr['source'] : ''); $album = (($arr) ? $arr['album'] : ''); $newalbum = (($arr) ? $arr['newalbum'] : ''); $hash = (($arr && $arr['hash']) ? $arr['hash'] : null); $upload_path = (($arr && $arr['directory']) ? $arr['directory'] : ''); $visible = (($arr && $arr['visible']) ? $arr['visible'] : ''); $observer = array(); if($observer_hash) { $x = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($observer_hash) ); if($x) $observer = $x[0]; } logger('arr: ' . print_r($arr,true), LOGGER_DATA); if(! perm_is_allowed($channel_id,$observer_hash, 'write_storage')) { $ret['message'] = t('Permission denied.'); return $ret; } $str_group_allow = perms2str($arr['group_allow']); $str_contact_allow = perms2str($arr['contact_allow']); $str_group_deny = perms2str($arr['group_deny']); $str_contact_deny = perms2str($arr['contact_deny']); // The 'update' option sets db values without uploading a new attachment // 'replace' replaces the existing uploaded data // 'revision' creates a new revision with new upload data // Default is to upload a new file // revise or update must provide $arr['hash'] of the thing to revise/update // By default remove $src when finished $remove_when_processed = true; if($options === 'import') { $src = $arr['src']; $filename = $arr['filename']; $filesize = @filesize($src); $hash = $arr['resource_id']; if(array_key_exists('hash',$arr)) $hash = $arr['hash']; if(array_key_exists('type',$arr)) $type = $arr['type']; if($arr['preserve_original']) $remove_when_processed = false; // if importing a directory, just do it now and go home - we're done. if(array_key_exists('is_dir',$arr) && intval($arr['is_dir'])) { $x = attach_mkdir($channel,$observer_hash,$arr); if($x['message']) logger('import_directory: ' . $x['message']); return; } } elseif($options !== 'update') { $f = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => ''); call_hooks('photo_upload_file',$f); call_hooks('attach_upload_file',$f); if (x($f,'src') && x($f,'filesize')) { $src = $f['src']; $filename = $f['filename']; $filesize = $f['filesize']; $type = $f['type']; } else { if(! x($_FILES,'userfile')) { $ret['message'] = t('No source file.'); return $ret; } $src = $_FILES['userfile']['tmp_name']; $filename = basename($_FILES['userfile']['name']); $filesize = intval($_FILES['userfile']['size']); } } $existing_size = 0; if($options === 'replace') { $x = q("select id, hash, filesize from attach where id = %d and uid = %d limit 1", intval($arr['id']), intval($channel_id) ); if(! $x) { $ret['message'] = t('Cannot locate file to replace'); return $ret; } $existing_id = $x[0]['id']; $existing_size = intval($x[0]['filesize']); $hash = $x[0]['hash']; } if($options === 'revise' || $options === 'update') { $sql_options = " order by revision desc "; if($options === 'update' && $arr && array_key_exists('revision',$arr)) $sql_options = " and revision = " . intval($arr['revision']) . " "; $x = q("select id, aid, uid, filename, filetype, filesize, hash, revision, folder, os_storage, is_photo, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where hash = '%s' and uid = %d $sql_options limit 1", dbesc($arr['hash']), intval($channel_id) ); if(! $x) { $ret['message'] = t('Cannot locate file to revise/update'); return $ret; } $hash = $x[0]['hash']; } $def_extension = ''; $is_photo = 0; $gis = @getimagesize($src); logger('getimagesize: ' . print_r($gis,true), LOGGER_DATA); if(($gis) && ($gis[2] === IMAGETYPE_GIF || $gis[2] === IMAGETYPE_JPEG || $gis[2] === IMAGETYPE_PNG)) { $is_photo = 1; if($gis[2] === IMAGETYPE_GIF) $def_extension = '.gif'; if($gis[2] === IMAGETYPE_JPEG) $def_extension = '.jpg'; if($gis[2] === IMAGETYPE_PNG) $def_extension = '.png'; } $pathname = ''; if($is_photo) { if($newalbum) { $pathname = filepath_macro($newalbum); } elseif(array_key_exists('folder',$arr)) { $x = q("select filename from attach where hash = '%s' and uid = %d limit 1", dbesc($arr['folder']), intval($channel['channel_id']) ); if($x) $pathname = $x[0]['filename']; } else { $pathname = filepath_macro($album); } } else { $pathname = filepath_macro($upload_path); } $darr = array('pathname' => $pathname); // if we need to create a directory, use the channel default permissions. $darr['allow_cid'] = $channel['allow_cid']; $darr['allow_gid'] = $channel['allow_gid']; $darr['deny_cid'] = $channel['deny_cid']; $darr['deny_gid'] = $channel['deny_gid']; $direct = null; if($pathname) { $x = attach_mkdirp($channel, $observer_hash, $darr); $folder_hash = (($x['success']) ? $x['data']['hash'] : ''); $direct = (($x['success']) ? $x['data'] : null); if((! $str_contact_allow) && (! $str_group_allow) && (! $str_contact_deny) && (! $str_group_deny)) { $str_contact_allow = $x['data']['allow_cid']; $str_group_allow = $x['data']['allow_gid']; $str_contact_deny = $x['data']['deny_cid']; $str_group_deny = $x['data']['deny_gid']; } } else { $folder_hash = ((($arr) && array_key_exists('folder',$arr)) ? $arr['folder'] : ''); } if((! $options) || ($options === 'import')) { // A freshly uploaded file. Check for duplicate and resolve with the channel's overwrite settings. $r = q("select filename, id, hash, filesize from attach where filename = '%s' and folder = '%s' ", dbesc($filename), dbesc($folder_hash) ); if($r) { $overwrite = get_pconfig($channel_id,'system','overwrite_dup_files'); if($overwrite) { $options = 'replace'; $existing_id = $x[0]['id']; $existing_size = intval($x[0]['filesize']); $hash = $x[0]['hash']; } else { if(strpos($filename,'.') !== false) { $basename = substr($filename,0,strrpos($filename,'.')); $ext = substr($filename,strrpos($filename,'.')); } else { $basename = $filename; $ext = $def_extension; } $r = q("select filename from attach where ( filename = '%s' OR filename like '%s' ) and folder = '%s' ", dbesc($basename . $ext), dbesc($basename . '(%)' . $ext), dbesc($folder_hash) ); if($r) { $x = 1; do { $found = false; foreach($r as $rr) { if($rr['filename'] === $basename . '(' . $x . ')' . $ext) { $found = true; break; } } if($found) $x++; } while($found); $filename = $basename . '(' . $x . ')' . $ext; } else $filename = $basename . $ext; } } } if(! $hash) $hash = random_string(); // Check storage limits if($options !== 'update') { $maxfilesize = get_config('system','maxfilesize'); if(($maxfilesize) && ($filesize > $maxfilesize)) { $ret['message'] = sprintf( t('File exceeds size limit of %d'), $maxfilesize); if($remove_when_processed) @unlink($src); call_hooks('photo_upload_end',$ret); return $ret; } $limit = service_class_fetch($channel_id, 'attach_upload_limit'); if($limit !== false) { $r = q("select sum(filesize) as total from attach where aid = %d ", intval($channel['channel_account_id']) ); if(($r) && (($r[0]['total'] + $filesize) > ($limit - $existing_size))) { $ret['message'] = upgrade_message(true) . sprintf(t("You have reached your limit of %1$.0f Mbytes attachment storage."), $limit / 1024000); if($remove_when_processed) @unlink($src); call_hooks('photo_upload_end',$ret); return $ret; } } $mimetype = ((isset($type) && $type) ? $type : z_mime_content_type($filename)); } $os_basepath = 'store/' . $channel['channel_address'] . '/' ; $os_relpath = ''; if($folder_hash) { $curr = find_folder_hash_by_attach_hash($channel_id,$folder_hash,true); if($curr) $os_relpath .= $curr . '/'; $os_relpath .= $folder_hash . '/'; } $os_relpath .= $hash; if($src) @file_put_contents($os_basepath . $os_relpath,@file_get_contents($src)); if(array_key_exists('created', $arr)) $created = $arr['created']; else $created = datetime_convert(); if(array_key_exists('edited', $arr)) $edited = $arr['edited']; else $edited = $created; if($options === 'replace') { $r = q("update attach set filename = '%s', filetype = '%s', folder = '%s', filesize = %d, os_storage = %d, is_photo = %d, data = '%s', edited = '%s' where id = %d and uid = %d", dbesc($filename), dbesc($mimetype), dbesc($folder_hash), intval($filesize), intval(1), intval($is_photo), dbesc($os_basepath . $os_relpath), dbesc($created), intval($existing_id), intval($channel_id) ); } elseif($options === 'revise') { $r = q("insert into attach ( aid, uid, hash, creator, filename, filetype, folder, filesize, revision, os_storage, is_photo, data, created, edited, allow_cid, allow_gid, deny_cid, deny_gid ) VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ", intval($x[0]['aid']), intval($channel_id), dbesc($x[0]['hash']), dbesc($observer_hash), dbesc($filename), dbesc($mimetype), dbesc($folder_hash), intval($filesize), intval($x[0]['revision'] + 1), intval(1), intval($is_photo), dbesc($os_basepath . $os_relpath), dbesc($created), dbesc($created), dbesc($x[0]['allow_cid']), dbesc($x[0]['allow_gid']), dbesc($x[0]['deny_cid']), dbesc($x[0]['deny_gid']) ); } elseif($options === 'update') { $r = q("update attach set filename = '%s', filetype = '%s', folder = '%s', edited = '%s', os_storage = %d, is_photo = %d, allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s' where id = %d and uid = %d", dbesc((array_key_exists('filename',$arr)) ? $arr['filename'] : $x[0]['filename']), dbesc((array_key_exists('filetype',$arr)) ? $arr['filetype'] : $x[0]['filetype']), dbesc(($folder_hash) ? $folder_hash : $x[0]['folder']), dbesc($created), dbesc((array_key_exists('os_storage',$arr)) ? $arr['os_storage'] : $x[0]['os_storage']), dbesc((array_key_exists('is_photo',$arr)) ? $arr['is_photo'] : $x[0]['is_photo']), dbesc((array_key_exists('allow_cid',$arr)) ? $arr['allow_cid'] : $x[0]['allow_cid']), dbesc((array_key_exists('allow_gid',$arr)) ? $arr['allow_gid'] : $x[0]['allow_gid']), dbesc((array_key_exists('deny_cid',$arr)) ? $arr['deny_cid'] : $x[0]['deny_cid']), dbesc((array_key_exists('deny_gid',$arr)) ? $arr['deny_gid'] : $x[0]['deny_gid']), intval($x[0]['id']), intval($x[0]['uid']) ); } else { $r = q("INSERT INTO attach ( aid, uid, hash, creator, filename, filetype, folder, filesize, revision, os_storage, is_photo, data, created, edited, allow_cid, allow_gid,deny_cid, deny_gid ) VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ", intval($channel['channel_account_id']), intval($channel_id), dbesc($hash), dbesc(get_observer_hash()), dbesc($filename), dbesc($mimetype), dbesc($folder_hash), intval($filesize), intval(0), intval(1), intval($is_photo), dbesc($os_basepath . $os_relpath), dbesc($created), dbesc($created), dbesc(($arr && array_key_exists('allow_cid',$arr)) ? $arr['allow_cid'] : $str_contact_allow), dbesc(($arr && array_key_exists('allow_gid',$arr)) ? $arr['allow_gid'] : $str_group_allow), dbesc(($arr && array_key_exists('deny_cid',$arr)) ? $arr['deny_cid'] : $str_contact_deny), dbesc(($arr && array_key_exists('deny_gid',$arr)) ? $arr['deny_gid'] : $str_group_deny) ); } if($is_photo) { $args = array( 'source' => $source, 'visible' => $visible, 'resource_id' => $hash, 'album' => basename($pathname), 'os_path' => $os_basepath . $os_relpath, 'filename' => $filename, 'getimagesize' => $gis, 'directory' => $direct); if($arr['contact_allow']) $args['contact_allow'] = $arr['contact_allow']; if($arr['group_allow']) $args['group_allow'] = $arr['group_allow']; if($arr['contact_deny']) $args['contact_deny'] = $arr['contact_deny']; if($arr['group_deny']) $args['group_deny'] = $arr['group_deny']; if(array_key_exists('allow_cid',$arr)) $args['allow_cid'] = $arr['allow_cid']; if(array_key_exists('allow_gid',$arr)) $args['allow_gid'] = $arr['allow_gid']; if(array_key_exists('deny_cid',$arr)) $args['deny_cid'] = $arr['deny_cid']; if(array_key_exists('deny_gid',$arr)) $args['deny_gid'] = $arr['deny_gid']; $args['created'] = $created; $args['edited'] = $edited; if($arr['item']) $args['item'] = $arr['item']; if($arr['body']) $args['body'] = $arr['body']; if($arr['description']) $args['description'] = $arr['description']; $p = photo_upload($channel,$observer,$args); if($p['success']) { $ret['body'] = $p['body']; } } if(($options !== 'update') && ($remove_when_processed)) @unlink($src); if(! $r) { $ret['message'] = t('File upload failed. Possible system limit or action terminated.'); call_hooks('photo_upload_end',$ret); return $ret; } // Caution: This re-uses $sql_options set further above $r = q("select id, aid, uid, hash, creator, filename, filetype, filesize, revision, folder, os_storage, is_photo, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where uid = %d and hash = '%s' $sql_options limit 1", intval($channel_id), dbesc($hash) ); if(! $r) { $ret['message'] = t('Stored file could not be verified. Upload failed.'); call_hooks('photo_upload_end',$ret); return $ret; } $ret['success'] = true; $ret['data'] = $r[0]; if(! $is_photo) { // This would've been called already with a success result in photos_upload() if it was a photo. call_hooks('photo_upload_end',$ret); } return $ret; } /** * @brief Read a virtual directory and return contents. * * Also checking permissions of all parent components. * * @param integer $channel_id * @param string $observer_hash hash of current observer * @param string $pathname * @param string $parent_hash (optional) * * @return array $ret * * \e boolean \b success boolean true or false * * \e string \b message error message if success is false * * \e array \b data array of attach DB entries without data component */ function z_readdir($channel_id, $observer_hash, $pathname, $parent_hash = '') { $ret = array('success' => false); if(! perm_is_allowed($channel_id, get_observer_hash(), 'view_storage')) { $ret['message'] = t('Permission denied.'); return $ret; } if(strpos($pathname, '/')) { $paths = explode('/', $pathname); if(count($paths) > 1) { $curpath = array_shift($paths); $r = q("select hash, id, is_dir from attach where uid = %d and filename = '%s' and is_dir != 0 " . permissions_sql($channel_id) . " limit 1", intval($channel_id), dbesc($curpath) ); if(! $r) { $ret['message'] = t('Path not available.'); return $ret; } return z_readdir($channel_id, $observer_hash, implode('/', $paths), $r[0]['hash']); } } else $paths = array($pathname); $r = q("select id, aid, uid, hash, creator, filename, filetype, filesize, revision, folder, is_photo, is_dir, os_storage, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where id = %d and folder = '%s' and filename = '%s' and is_dir != 0 " . permissions_sql($channel_id), intval($channel_id), dbesc($parent_hash), dbesc($paths[0]) ); if(! $r) { $ret['message'] = t('Path not available.'); return $ret; } $ret['success'] = true; $ret['data'] = $r; return $ret; } /** * @brief Create directory. * * @param array $channel channel array of owner * @param string $observer_hash hash of current observer * @param array $arr parameter array to fulfil request * - Required: * * \e string \b filename * * \e string \b folder hash of parent directory, empty string for root directory * - Optional: * * \e string \b hash precomputed hash for this node * * \e tring \b allow_cid * * \e string \b allow_gid * * \e string \b deny_cid * * \e string \b deny_gid * @return array */ function attach_mkdir($channel, $observer_hash, $arr = null) { $ret = array('success' => false); $channel_id = $channel['channel_id']; $sql_options = ''; $basepath = 'store/' . $channel['channel_address']; logger('attach_mkdir: basepath: ' . $basepath); if(! is_dir($basepath)) os_mkdir($basepath,STORAGE_DEFAULT_PERMISSIONS, true); if(! perm_is_allowed($channel_id, $observer_hash, 'write_storage')) { $ret['message'] = t('Permission denied.'); return $ret; } if(! $arr['filename']) { $ret['message'] = t('Empty pathname'); return $ret; } $arr['hash'] = (($arr['hash']) ? $arr['hash'] : random_string()); // Check for duplicate name. // Check both the filename and the hash as we will be making use of both. $r = q("select id, hash, is_dir, flags from attach where ( filename = '%s' or hash = '%s' ) and folder = '%s' and uid = %d limit 1", dbesc($arr['filename']), dbesc($arr['hash']), dbesc($arr['folder']), intval($channel['channel_id']) ); if($r) { if(array_key_exists('force',$arr) && intval($arr['force']) && (intval($r[0]['is_dir']))) { $ret['success'] = true; $r = q("select * from attach where id = %d limit 1", intval($r[0]['id']) ); if($r) $ret['data'] = $r[0]; return $ret; } $ret['message'] = t('duplicate filename or path'); return $ret; } if($arr['folder']) { // Walk the directory tree from parent back to root to make sure the parent is valid and name is unique and we // have permission to see this path. This implies the root directory itself is public since we won't have permissions // set on the psuedo-directory. We can however set permissions for anything and everything contained within it. $lpath = ''; $lfile = $arr['folder']; $sql_options = permissions_sql($channel['channel_id']); do { $r = q("select filename, hash, flags, is_dir, folder from attach where uid = %d and hash = '%s' and is_dir != 0 $sql_options limit 1", intval($channel['channel_id']), dbesc($lfile) ); if(! $r) { logger('attach_mkdir: hash ' . $lfile . ' not found in ' . $lpath); $ret['message'] = t('Path not found.'); return $ret; } if($lfile) $lpath = $r[0]['hash'] . '/' . $lpath; $lfile = $r[0]['folder']; } while ( ($r[0]['folder']) && intval($r[0]['is_dir'])) ; $path = $basepath . '/' . $lpath; } else $path = $basepath . '/'; $path .= $arr['hash']; $created = datetime_convert(); $r = q("INSERT INTO attach ( aid, uid, hash, creator, filename, filetype, filesize, revision, folder, os_storage, is_dir, data, created, edited, allow_cid, allow_gid, deny_cid, deny_gid ) VALUES ( %d, %d, '%s', '%s', '%s', '%s', %d, %d, '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ", intval($channel['channel_account_id']), intval($channel_id), dbesc($arr['hash']), dbesc(get_observer_hash()), dbesc($arr['filename']), dbesc('multipart/mixed'), intval(0), intval(0), dbesc($arr['folder']), intval(1), intval(1), dbesc($path), dbesc($created), dbesc($created), dbesc(($arr && array_key_exists('allow_cid',$arr)) ? $arr['allow_cid'] : $channel['channel_allow_cid']), dbesc(($arr && array_key_exists('allow_gid',$arr)) ? $arr['allow_gid'] : $channel['channel_allow_gid']), dbesc(($arr && array_key_exists('deny_cid',$arr)) ? $arr['deny_cid'] : $channel['channel_deny_cid']), dbesc(($arr && array_key_exists('deny_gid',$arr)) ? $arr['deny_gid'] : $channel['channel_deny_gid']) ); if($r) { if(os_mkdir($path, STORAGE_DEFAULT_PERMISSIONS, true)) { $ret['success'] = true; // update the parent folder's lastmodified timestamp $e = q("UPDATE attach SET edited = '%s' WHERE hash = '%s' AND uid = %d", dbesc($created), dbesc($arr['folder']), intval($channel_id) ); $z = q("select * from attach where hash = '%s' and uid = %d and is_dir = 1 limit 1", dbesc($arr['hash']), intval($channel_id) ); if($z) $ret['data'] = $z[0]; } else { logger('attach_mkdir: ' . mkdir . ' ' . $path . ' failed.'); $ret['message'] = t('mkdir failed.'); } } else { $ret['message'] = t('database storage failed.'); } return $ret; } /** * @brief Create directory (recursive). * * @param array $channel channel array of owner * @param string $observer_hash hash of current observer * @param array $arr parameter array to fulfil request * - Required: * * \e string \b pathname * * \e string \b folder hash of parent directory, empty string for root directory * - Optional: * * \e string \b allow_cid * * \e string \b allow_gid * * \e string \b deny_cid * * \e string \b deny_gid * @return array */ function attach_mkdirp($channel, $observer_hash, $arr = null) { $ret = array('success' => false); $channel_id = $channel['channel_id']; $sql_options = ''; $basepath = 'store/' . $channel['channel_address']; logger('attach_mkdirp: basepath: ' . $basepath); if(! is_dir($basepath)) os_mkdir($basepath,STORAGE_DEFAULT_PERMISSIONS, true); if(! perm_is_allowed($channel_id, $observer_hash, 'write_storage')) { $ret['message'] = t('Permission denied.'); return $ret; } if(! $arr['pathname']) { $ret['message'] = t('Empty pathname'); return $ret; } $paths = explode('/',$arr['pathname']); if(! $paths) { $ret['message'] = t('Empty path'); return $ret; } $current_parent = ''; foreach($paths as $p) { if(! $p) continue; $arx = array( 'filename' => $p, 'folder' => $current_parent, 'force' => 1 ); if(array_key_exists('allow_cid',$arr)) $arx['allow_cid'] = $arr['allow_cid']; if(array_key_exists('deny_cid',$arr)) $arx['deny_cid'] = $arr['deny_cid']; if(array_key_exists('allow_gid',$arr)) $arx['allow_gid'] = $arr['allow_gid']; if(array_key_exists('deny_gid',$arr)) $arx['deny_gid'] = $arr['deny_gid']; $x = attach_mkdir($channel, $observer_hash, $arx); if($x['success']) { $current_parent = $x['data']['hash']; } else { $ret['message'] = $x['message']; return $ret; } } if(isset($x)) { $ret['success'] = true; $ret['data'] = $x['data']; } return $ret; } /** * @brief Changes permissions of a file. * * @param int $channel_id * @param array $resource * @param string $allow_cid * @param string $allow_gid * @param string $deny_cid * @param string $deny_gid * @param boolean $recurse (optional) default false */ function attach_change_permissions($channel_id, $resource, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $recurse = false) { $r = q("select hash, flags, is_dir, is_photo from attach where hash = '%s' and uid = %d limit 1", dbesc($resource), intval($channel_id) ); if(! $r) return; if(intval($r[0]['is_dir'])) { if($recurse) { $r = q("select hash, flags, is_dir from attach where folder = '%s' and uid = %d", dbesc($resource), intval($channel_id) ); if($r) { foreach($r as $rr) { attach_change_permissions($channel_id, $rr['hash'], $allow_cid, $allow_gid, $deny_cid, $deny_gid, $recurse); } } } } $x = q("update attach set allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s' where hash = '%s' and uid = %d", dbesc($allow_cid), dbesc($allow_gid), dbesc($deny_cid), dbesc($deny_gid), dbesc($resource), intval($channel_id) ); if($r[0]['is_photo']) { $x = q("update photo set allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s' where resource_id = '%s' and uid = %d", dbesc($allow_cid), dbesc($allow_gid), dbesc($deny_cid), dbesc($deny_gid), dbesc($resource), intval($channel_id) ); } } /** * @brief Delete a file/directory from a channel. * * If the provided resource hash is from a directory it will delete everything * recursively under this directory. * * @param int $channel_id * The id of the channel * @param string $resource * The hash to delete * @return void */ function attach_delete($channel_id, $resource, $is_photo = 0) { $c = q("SELECT channel_address FROM channel WHERE channel_id = %d LIMIT 1", intval($channel_id) ); $channel_address = (($c) ? $c[0]['channel_address'] : 'notfound'); $photo_sql = (($is_photo) ? " and is_photo = 1 " : ''); $r = q("SELECT hash, flags, is_dir, is_photo, folder FROM attach WHERE hash = '%s' AND uid = %d $photo_sql limit 1", dbesc($resource), intval($channel_id) ); if(! $r) return; $cloudpath = get_parent_cloudpath($channel_id, $channel_address, $resource); $object = get_file_activity_object($channel_id, $resource, $cloudpath); // If resource is a directory delete everything in the directory recursive if(intval($r[0]['is_dir'])) { $x = q("SELECT hash, os_storage, is_dir, flags FROM attach WHERE folder = '%s' AND uid = %d", dbesc($resource), intval($channel_id) ); if($x) { foreach($x as $xx) { attach_delete($channel_id, $xx['hash']); } } } // delete a file from filesystem if(intval($r[0]['os_storage'])) { $y = q("SELECT data FROM attach WHERE hash = '%s' AND uid = %d LIMIT 1", dbesc($resource), intval($channel_id) ); if($y) { if(strpos($y[0]['data'],'store') === false) $f = 'store/' . $channel_address . '/' . $y[0]['data']; else $f = $y[0]['data']; if(is_dir($f)) @rmdir($f); elseif(file_exists($f)) unlink($f); } } // delete from database $z = q("DELETE FROM attach WHERE hash = '%s' AND uid = %d", dbesc($resource), intval($channel_id) ); if($r[0]['is_photo']) { $x = q("select id, item_hidden from item where resource_id = '%s' and resource_type = 'photo' and uid = %d", dbesc($resource), intval($channel_id) ); if($x) { drop_item($x[0]['id'],false,(($x[0]['item_hidden']) ? DROPITEM_NORMAL : DROPITEM_PHASE1),true); } q("DELETE FROM photo WHERE uid = %d AND resource_id = '%s'", intval($channel_id), dbesc($resource) ); } // update the parent folder's lastmodified timestamp $e = q("UPDATE attach SET edited = '%s' WHERE hash = '%s' AND uid = %d", dbesc(datetime_convert()), dbesc($r[0]['folder']), intval($channel_id) ); file_activity($channel_id, $object, $object['allow_cid'], $object['allow_gid'], $object['deny_cid'], $object['deny_gid'], 'update', $notify=0); } /** * @brief Returns path to file in cloud/. * * @warning This function cannot be used with mod/dav as it always returns a * path valid under mod/cloud. * * @param array $arr associative array with: * * \e int \b uid the channel's uid * * \e string \b folder * * \e string \b filename * @return string * path to the file in cloud/ */ function get_cloudpath($arr) { $basepath = 'cloud/'; if($arr['uid']) { $r = q("select channel_address from channel where channel_id = %d limit 1", intval($arr['uid']) ); if($r) $basepath .= $r[0]['channel_address'] . '/'; } $path = $basepath; if($arr['folder']) { $lpath = ''; $lfile = $arr['folder']; do { $r = q("select filename, hash, flags, is_dir, folder from attach where uid = %d and hash = '%s' and is_dir != 0 limit 1", intval($arr['uid']), dbesc($lfile) ); if(! $r) break; if($lfile) $lpath = $r[0]['filename'] . '/' . $lpath; $lfile = $r[0]['folder']; } while ( ($r[0]['folder']) && intval($r[0]['is_dir'])); $path .= $lpath; } $path .= $arr['filename']; return $path; } /** * @brief Returns path to parent folder in cloud/. * This function cannot be used with mod/dav as it always returns a path valid under mod/cloud * * @param int $channel_id * The id of the channel * @param string $channel_name * The name of the channel * @param string $attachHash * @return string with the full folder path */ function get_parent_cloudpath($channel_id, $channel_name, $attachHash) { $parentFullPath = ''; // build directory tree $parentHash = $attachHash; do { $parentHash = find_folder_hash_by_attach_hash($channel_id, $parentHash); if ($parentHash) { $parentName = find_filename_by_hash($channel_id, $parentHash); $parentFullPath = $parentName . '/' . $parentFullPath; } } while ($parentHash); $parentFullPath = z_root() . '/cloud/' . $channel_name . '/' . $parentFullPath; return $parentFullPath; } /** * @brief Return the hash of an attachment's folder. * * @param int $channel_id * The id of the channel * @param string $attachHash * The hash of the attachment * @return string */ function find_folder_hash_by_attach_hash($channel_id, $attachHash, $recurse = false) { logger('attach_hash: ' . $attachHash); $r = q("SELECT folder FROM attach WHERE uid = %d AND hash = '%s' LIMIT 1", intval($channel_id), dbesc($attachHash) ); $hash = ''; if($r && $r[0]['folder']) { if($recurse) $hash = find_folder_hash_by_attach_hash($channel_id,$r[0]['folder'],true) . '/' . $r[0]['folder']; else $hash = $r[0]['folder']; } return $hash; } /** * @brief Returns the filename of an attachment in a given channel. * * @param int $channel_id * The id of the channel * @param string $attachHash * The hash of the attachment * @return string * The filename of the attachment */ function find_filename_by_hash($channel_id, $attachHash) { $r = q("SELECT filename FROM attach WHERE uid = %d AND hash = '%s' LIMIT 1", intval($channel_id), dbesc($attachHash) ); $filename = ''; if ($r) { $filename = $r[0]['filename']; } return $filename; } /** * * @param $in * @param $out */ function pipe_streams($in, $out) { $size = 0; while (!feof($in)) $size += fwrite($out, fread($in, 8192)); return $size; } /** * @brief Activity for files. * * @param int $channel_id * @param array $object * @param string $allow_cid * @param string $allow_gid * @param string $deny_cid * @param string $deny_gid * @param string $verb * @param boolean $no_activity */ function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $verb, $notify) { require_once('include/items.php'); $poster = get_app()->get_observer(); //if we got no object something went wrong if(!$object) return; //turn strings into arrays $arr_allow_cid = expand_acl($allow_cid); $arr_allow_gid = expand_acl($allow_gid); $arr_deny_cid = expand_acl($deny_cid); $arr_deny_gid = expand_acl($deny_gid); //filter out receivers which do not have permission to view filestorage $arr_allow_cid = check_list_permissions($channel_id, $arr_allow_cid, 'view_storage'); $is_dir = (intval($object['is_dir']) ? true : false); //do not send activity for folders for now if($is_dir) return; //check for recursive perms if we are in a folder if($object['folder']) { $folder_hash = $object['folder']; $r_perms = recursive_activity_recipients($arr_allow_cid, $arr_allow_gid, $arr_deny_cid, $arr_deny_gid, $folder_hash); //split up returned perms $arr_allow_cid = $r_perms['allow_cid']; $arr_allow_gid = $r_perms['allow_gid']; $arr_deny_cid = $r_perms['deny_cid']; $arr_deny_gid = $r_perms['deny_gid']; //filter out receivers which do not have permission to view filestorage $arr_allow_cid = check_list_permissions($channel_id, $arr_allow_cid, 'view_storage'); } $mid = item_message_id(); $arr = array(); $arr['item_wall'] = 1; $arr['item_origin'] = 1; $arr['item_unseen'] = 1; $objtype = ACTIVITY_OBJ_FILE; $private = (($arr_allow_cid[0] || $arr_allow_gid[0] || $arr_deny_cid[0] || $arr_deny_gid[0]) ? 1 : 0); $jsonobject = json_encode($object); //check if item for this object exists $y = q("SELECT mid FROM item WHERE verb = '%s' AND obj_type = '%s' AND resource_id = '%s' AND uid = %d LIMIT 1", dbesc(ACTIVITY_POST), dbesc($objtype), dbesc($object['hash']), intval(local_channel()) ); if($y) { $update = true; $object['d_mid'] = $y[0]['mid']; //attach mid of the old object $u_jsonobject = json_encode($object); //we have got the relevant info - delete the old item before we create the new one $z = q("DELETE FROM item WHERE obj_type = '%s' AND verb = '%s' AND mid = '%s'", dbesc(ACTIVITY_OBJ_FILE), dbesc(ACTIVITY_POST), dbesc($y[0]['mid']) ); } if($update && $verb == 'post' ) { //send update activity and create a new one //updates should be sent to everybody with recursive perms and all eventual former allowed members ($object['allow_cid'] etc.). $u_arr_allow_cid = array_unique(array_merge($arr_allow_cid, expand_acl($object['allow_cid']))); $u_arr_allow_gid = array_unique(array_merge($arr_allow_gid, expand_acl($object['allow_gid']))); $u_arr_deny_cid = array_unique(array_merge($arr_deny_cid, expand_acl($object['deny_cid']))); $u_arr_deny_gid = array_unique(array_merge($arr_deny_gid, expand_acl($object['deny_gid']))); $u_mid = item_message_id(); $arr['aid'] = get_account_id(); $arr['uid'] = $channel_id; $arr['mid'] = $u_mid; $arr['parent_mid'] = $u_mid; $arr['author_xchan'] = $poster['xchan_hash']; $arr['owner_xchan'] = $poster['xchan_hash']; $arr['title'] = ''; //updates should be visible to everybody -> perms may have changed $arr['allow_cid'] = ''; $arr['allow_gid'] = ''; $arr['deny_cid'] = ''; $arr['deny_gid'] = ''; $arr['item_hidden'] = 1; $arr['item_private'] = 0; $arr['verb'] = ACTIVITY_UPDATE; $arr['obj_type'] = $objtype; $arr['object'] = $u_jsonobject; $arr['resource_id'] = $object['hash']; $arr['resource_type'] = 'attach'; $arr['body'] = ''; $post = item_store($arr); $item_id = $post['item_id']; if($item_id) { proc_run('php',"include/notifier.php","activity",$item_id); } call_hooks('post_local_end', $arr); $update = false; //notice( t('File activity updated') . EOL); } if(! $notify) { return; } $arr = array(); $arr['aid'] = get_account_id(); $arr['uid'] = $channel_id; $arr['mid'] = $mid; $arr['parent_mid'] = $mid; $arr['item_wall'] = 1; $arr['item_origin'] = 1; $arr['item_unseen'] = 1; $arr['author_xchan'] = $poster['xchan_hash']; $arr['owner_xchan'] = $poster['xchan_hash']; $arr['title'] = ''; $arr['allow_cid'] = perms2str($arr_allow_cid); $arr['allow_gid'] = perms2str($arr_allow_gid); $arr['deny_cid'] = perms2str($arr_deny_cid); $arr['deny_gid'] = perms2str($arr_deny_gid); $arr['item_hidden'] = 1; $arr['item_private'] = $private; $arr['verb'] = (($update) ? ACTIVITY_UPDATE : ACTIVITY_POST); $arr['obj_type'] = $objtype; $arr['resource_id'] = $object['hash']; $arr['resource_type'] = 'attach'; $arr['object'] = (($update) ? $u_jsonobject : $jsonobject); $arr['body'] = ''; $post = item_store($arr); $item_id = $post['item_id']; if($item_id) { proc_run('php',"include/notifier.php","activity",$item_id); } call_hooks('post_local_end', $arr); //(($verb === 'post') ? notice( t('File activity posted') . EOL) : notice( t('File activity dropped') . EOL)); return; } /** * @brief Create file activity object * * @param int $channel_id * @param string $hash * @param string $cloudpath */ function get_file_activity_object($channel_id, $hash, $cloudpath) { $x = q("SELECT creator, filename, filetype, filesize, revision, folder, os_storage, is_photo, is_dir, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid FROM attach WHERE uid = %d AND hash = '%s' LIMIT 1", intval($channel_id), dbesc($hash) ); $url = rawurlencode($cloudpath . $x[0]['filename']); $links = array(); $links[] = array( 'rel' => 'alternate', 'type' => 'text/html', 'href' => $url ); $object = array( 'type' => ACTIVITY_OBJ_FILE, 'title' => $x[0]['filename'], 'id' => $url, 'link' => $links, 'hash' => $hash, 'creator' => $x[0]['creator'], 'filename' => $x[0]['filename'], 'filetype' => $x[0]['filetype'], 'filesize' => $x[0]['filesize'], 'revision' => $x[0]['revision'], 'folder' => $x[0]['folder'], 'flags' => $x[0]['flags'], 'os_storage' => $x[0]['os_storage'], 'is_photo' => $x[0]['is_photo'], 'is_dir' => $x[0]['is_dir'], 'created' => $x[0]['created'], 'edited' => $x[0]['edited'], 'allow_cid' => $x[0]['allow_cid'], 'allow_gid' => $x[0]['allow_gid'], 'deny_cid' => $x[0]['deny_cid'], 'deny_gid' => $x[0]['deny_gid'] ); return $object; } /** * @brief Returns array of channels which have recursive permission for a file * * @param $arr_allow_cid * @param $arr_allow_gid * @param $arr_deny_cid * @param $arr_deny_gid * @param $folder_hash */ function recursive_activity_recipients($arr_allow_cid, $arr_allow_gid, $arr_deny_cid, $arr_deny_gid, $folder_hash) { $ret = array(); $parent_arr = array(); $count_values = array(); $poster = get_app()->get_observer(); //turn allow_gid into allow_cid's foreach($arr_allow_gid as $gid) { $in_group = in_group($gid); $arr_allow_cid = array_unique(array_merge($arr_allow_cid, $in_group)); } $count = 0; while($folder_hash) { $x = q("SELECT allow_cid, allow_gid, deny_cid, deny_gid, folder FROM attach WHERE hash = '%s' LIMIT 1", dbesc($folder_hash) ); //only process private folders if($x[0]['allow_cid'] || $x[0]['allow_gid'] || $x[0]['deny_cid'] || $x[0]['deny_gid']) { $parent_arr['allow_cid'][] = expand_acl($x[0]['allow_cid']); $parent_arr['allow_gid'][] = expand_acl($x[0]['allow_gid']); /** * @TODO should find a much better solution for the allow_cid <-> allow_gid problem. * Do not use allow_gid for now. Instead lookup the members of the group directly and add them to allow_cid. * */ if($parent_arr['allow_gid']) { foreach($parent_arr['allow_gid'][$count] as $gid) { $in_group = in_group($gid); $parent_arr['allow_cid'][$count] = array_unique(array_merge($parent_arr['allow_cid'][$count], $in_group)); } } $parent_arr['deny_cid'][] = expand_acl($x[0]['deny_cid']); $parent_arr['deny_gid'][] = expand_acl($x[0]['deny_gid']); $count++; } $folder_hash = $x[0]['folder']; } //if none of the parent folders is private just return file perms if(!$parent_arr['allow_cid'] && !$parent_arr['allow_gid'] && !$parent_arr['deny_cid'] && !$parent_arr['deny_gid']) { $ret['allow_gid'] = $arr_allow_gid; $ret['allow_cid'] = $arr_allow_cid; $ret['deny_gid'] = $arr_deny_gid; $ret['deny_cid'] = $arr_deny_cid; return $ret; } //if there are no perms on the file we get them from the first parent folder if(!$arr_allow_cid && !$arr_allow_gid && !$arr_deny_cid && !$arr_deny_gid) { $arr_allow_cid = $parent_arr['allow_cid'][0]; $arr_allow_gid = $parent_arr['allow_gid'][0]; $arr_deny_cid = $parent_arr['deny_cid'][0]; $arr_deny_gid = $parent_arr['deny_gid'][0]; } //allow_cid $r_arr_allow_cid = false; foreach ($parent_arr['allow_cid'] as $folder_arr_allow_cid) { foreach ($folder_arr_allow_cid as $ac_hash) { $count_values[$ac_hash]++; } } foreach ($arr_allow_cid as $fac_hash) { if($count_values[$fac_hash] == $count) $r_arr_allow_cid[] = $fac_hash; } //allow_gid $r_arr_allow_gid = false; foreach ($parent_arr['allow_gid'] as $folder_arr_allow_gid) { foreach ($folder_arr_allow_gid as $ag_hash) { $count_values[$ag_hash]++; } } foreach ($arr_allow_gid as $fag_hash) { if($count_values[$fag_hash] == $count) $r_arr_allow_gid[] = $fag_hash; } //deny_gid foreach($parent_arr['deny_gid'] as $folder_arr_deny_gid) { $r_arr_deny_gid = array_merge($arr_deny_gid, $folder_arr_deny_gid); } $r_arr_deny_gid = array_unique($r_arr_deny_gid); //deny_cid foreach($parent_arr['deny_cid'] as $folder_arr_deny_cid) { $r_arr_deny_cid = array_merge($arr_deny_cid, $folder_arr_deny_cid); } $r_arr_deny_cid = array_unique($r_arr_deny_cid); //if none is allowed restrict to self if(($r_arr_allow_gid === false) && ($r_arr_allow_cid === false)) { $ret['allow_cid'] = $poster['xchan_hash']; } else { $ret['allow_gid'] = $r_arr_allow_gid; $ret['allow_cid'] = $r_arr_allow_cid; $ret['deny_gid'] = $r_arr_deny_gid; $ret['deny_cid'] = $r_arr_deny_cid; } return $ret; } /** * @brief Returns members of a group. * * @param int $group_id id of the group to look up */ function in_group($group_id) { $group_members = array(); /** @TODO make these two queries one with a join. */ $x = q("SELECT id FROM groups WHERE hash = '%s'", dbesc($group_id) ); $r = q("SELECT xchan FROM group_member WHERE gid = %d", intval($x[0]['id']) ); foreach($r as $ig) { $group_members[] = $ig['xchan']; } return $group_members; } function filepath_macro($s) { return str_replace( array( '%Y', '%m', '%d' ), array( datetime_convert('UTC',date_default_timezone_get(),'now', 'Y'), datetime_convert('UTC',date_default_timezone_get(),'now', 'm'), datetime_convert('UTC',date_default_timezone_get(),'now', 'd') ), $s); }
We think that we need to deeply learn about consumers first in order to help them achieve beauty and health as well as create their beautiful lifestyles. In order to do so, we have been not only conducting questionnaire surveys to collect opinions/requests, which is the conventional method, but also conducting observation and measurement by jumping into the consumers’ actual daily lives. We have implemented researches repeatedly by investigating even how consumers act subconsciously before they themselves recognize. We develop products for our consumers around the world. In order to do so, we need to learn about the consumers in the world. We explore the consumers’ “needs” and “wants” by examining skin conditions, beauty awareness, beauty behaviors and life environments in each region not only from the dermatological viewpoint but also from the anthropological viewpoint. The following diagram was plotted with the questionnaire results regarding past UV ray measures and average values of actual wrinkle areas at the corners of the eyes. The target is women in their 50’s from 14 countries. As a result, it was confirmed that women who have taken UV ray related measures since they were young, have less wrinkle areas at the corners of the eyes. We hope that consumers purchase our products and enjoy using them. And we also hope that they like them and continue to use them. Everything is up to the consumers. Therefore, we have been conducting research on counter services, which are for establishing the ties with consumers, including “how we can make consumers interested in our products, feel comfortable, feel excited, etc.”, by using various cutting-edge psychophysiological measurement. We examined how the consumers’ brains react when they touch the products at the counters, etc. with the near-infrared spectroscopy (NIRS) which investigates brain activity based on the changes in brain blood flow. This method is non-invasive and places no burden on consumers. At the same time, we investigated the changes in the feelings that they had at the time via a questionnaire survey. Based on the relationship between brain blood flow and changes in feelings, we can see what kind of feeling the consumer has at the time of product introduction, in the form of his or her brain reaction. As can be seen in the following diagram, there are various introduction activities related to five senses from 1. to 5. among product introduction activities at the counters. As a result of our detailed investigation, we found out that the blood flow significantly increases in the wider area of brain when the consumers take active actions for the cosmetics involving tactile sense and sense of touch and smell, including “3. Touch the contents”, “4. Smell the scent” and “5. Touch the container”, as compared to when they obtain information in a slightly passive manner with their senses of hearing and vision, including “1. Oral product explanation” and “2. Receive explanation while seeing the written tools.” Furthermore, this time, the correlation with not only the attractive points of the product but also comfort and satisfaction level for the product was also seen. In other words, it can be predicted that the brain activity of consumers becomes active when they take active actions such as touching/smelling cosmetics, creating positive feelings. We may be able to cultivate the exciting feelings of consumers if we provide opportunities to promote their proactive actions, which make them feel like experiencing on their own, at the counters as well as when they use the cosmetics. The research paper is published in Chapter 4 of Infrared Spectroscopy – Life and Biomedical Sciences. Illusion refers to “the perception that is different from the target’s original nature”. Cases when our eyes look bigger than actual size and face shapes look different due to makeup can be regarded as one of the illusions. Therefore, Shiseido implemented a quantitative verification with regard to makeup effect which had been frequently expressed in a subjective manner, by utilizing a method used in illusion (perceptual psychological) researches jointly with Morikawa Laboratory, School of Human Sciences, Osaka University. We quantified the illusion effect of eye makeup using the psychophysical measurement method used in perceptual psychological researches. As the first step, we took 2 photos of the same model’s face (one with no makeup and one with eye makeup), adjusted them using image processing so that they can be identical except for the eye areas, and specified this as the standard stimulus (measurement target). Next, as the comparison stimulus (ruler for eye size), we enlarged/reduced the eye size of the same model’s bare skin and created these images. We presented one each of the standard stimulus and comparison stimulus on the right and left of the display respectively and asked the subjects to select the one in which the eyes looked bigger. By repeating this process many times, the point of perceptual equality for the eye size with makeup can be measured. In other words, we can measure about what percentage the eye size with the makeup looked bigger as compared to the eye size without the makeup. The following is one example of the results. It was found that in case of the face with makeup by eyeliner and false eyelashes shown in the middle, the eyes looked 6.4% horizontally and vertically bigger than the actual size (113% in terms of area). Moreover, as a result of the series of researches, we found out that eye size with eye shadow also looks bigger than the one without makeup. As can be seen, we are working on the research for approaching the depth of makeup as well as communicating such depth to consumers by verifying the perceptual effects of makeup in a scientific manner.
<h1>MVC Architecture</h1> <p> As modern browsers become more powerful with rich features, building full-blown web applications in JavaScript is not only feasible, but increasingly popular. Based on <a href="http://httparchive.org/trends.php?s=intersection&minlabel=Jan+20+2011&maxlabel=Jan+15+2012">trends</a> on <a href="http://httparchive.org/">HTTP Archive</a>, deployed JavaScript code size has grown 45% over the course of the year. </p> <img src="{{static}}/images/jstransferrequests.png" width="568" height="292" alt="JS transfer size and JS requests"> <p> With JavaScript's popularity climbing, our client-side applications are much more complex than before. Application development requires collaboration from multiple developers. Writing <strong>maintainable</strong> and <strong>reusable</strong> code is crucial in the new web app era. The Chrome App, with its rich client-side features, is no exception. </p> <p> Design patterns are important to write maintainable and reusable code. A pattern is a reusable solution that can be applied to commonly occurring problems in software design &mdash; in our case &mdash; writing Chrome Apps. We recommend that developers decouple the app into a series of independent components following the MVC pattern. </p> <p> In the last few years, a series of JavaScript MVC frameworks have been developed, such as <a href="http://backbonejs.org/">backbone.js</a>, <a href="http://emberjs.com/">ember.js</a>, <a href="http://angularjs.org/">AngularJS</a>, <a href="http://sencha.com/">Sencha</a>, <a href="http://www.kendoui.com/">Kendo UI</a>, and more. While they all have their unique advantages, each one of them follows some form of MVC pattern with the goal of encouraging developers to write more structured JavaScript code. </p> <h2 id="mvc">MVC pattern overview</h2> <p> MVC offers architectural benefits over standard JavaScript &mdash; it helps you write better organized, and therefore more maintainable code. This pattern has been used and extensively tested over multiple languages and generations of programmers. </p> <p> MVC is composed of three components: </p> <img src="{{static}}/images/mvc.png" width="466" height="303" alt="model-view-controller"> <h3 id="model">Model</h3> <p> Model is where the application’s data objects are stored. The model doesn’t know anything about views and controllers. When a model changes, typically it will notify its observers that a change has occurred. </p> <p> To understand this further, let’s use the Todo list app, a simple, one page web app that tracks your task list. </p> <br> <img src="{{static}}/images/todos.png" width="444" height="366" alt="model-view-controller"> <p> The model here represents attributes associated with each todo item such as description and status. When a new todo item is created, it is stored in an instance of the model. </p> <h3 id="view">View</h3> <p> View is what's presented to the users and how users interact with the app. The view is made with HTML, CSS, JavaScript and often templates. This part of your Chrome App has access to the DOM. </p> <p> For example, in the above todo list web app, you can create a view that nicely presents the list of todo items to your users. Users can also enter a new todo item through some input format; however, the view doesn’t know how to update the model because that’s the controller’s job. </p> <h3 id="controller">Controller</h3> <p> The controller is the decision maker and the glue between the model and view. The controller updates the view when the model changes. It also adds event listeners to the view and updates the model when the user manipulates the view. </p> <p> In the todo list web app, when the user checks an item as completed, the click is forwarded to the controller. The controller modifies the model to mark item as completed. If the data needs to be persistent, it also makes an async save to the server. In rich client-side web app development such as Chrome Apps, keeping the data persistent in local storage is also crucial. In this case, the controller also handles saving the data to the client-side storage such as <a href="app_storage">FileSystem API</a>. </p> <p> There are a few variations of the MVC design pattern such as MVP (Model&ndash;View&ndash;Presenter) and MVVP(Model&ndash;View&ndash;ViewModel). Even with the so called MVC design pattern itself, there is some variation between the traditional MVC pattern vs the modern interpretation in various programming languages. For example, some MVC&ndash;based frameworks will have the view observe the changes in the models while others will let the controller handle the view update. This article is not focused on the comparison of various implementations but rather on the separation&ndash;of&ndash;concerns and it's importance in writing modern web apps. </p> <p> If you are interested in learning more, we recommend <a href="https://plus.google.com/u/0/115133653231679625609/posts">Addy Osmani's</a> online book: <a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/">Learning JavaScript Design Patterns</a>. </p> <p> To summarize, the MVC pattern brings modularity to application developers and it enables: </p> <ul> <li>Reusable and extendable code.</li> <li>Separation of view logic from business logic.</li> <li>Allow simultaneous work between developers who are responsible for different components (such as UI layer and core logic).</li> <li>Easier to maintain.</li> </ul> <h2 id="mvcpersistence">MVC persistence patterns</h2> <p> There are many different ways of implementing persistence with an MVC framework, each with different trade&ndash;offs. When writing Chrome Apps, choose the frameworks with MVC and persistence patterns that feel natural to you and fit you application needs. </p> <h3 id="model_persistence">Model does its own persistence - ActiveRecord pattern</h3> <p> Popular in both server&ndash;side frameworks like Ruby on Rails, and client-side frameworks like <a href="http://backbonejs.org">Backbone.js</a> and <a href="http://emberjs.com/">ember.js</a>, the ActiveRecord pattern places the responsibility for persistence on the model itself and is typically implemented via JSON API. </p> <p> A slightly different take from having a model handle the persistence is to introduce a separate concept of Store and Adapter API. Store, Model and Adapter (in some frameworks it is called Proxy) work hand by hand. Store is the repository that holds the loaded models, and it also provides functions such as creating, querying and filtering the model instances contained within it. </p> <p> An adapter, or a proxy, receives the requests from a store and translates them into appropriate actions to take against your persistent data layer (such as JSON API). This is interesting in the modern web app design because you often interact with more than one persistent data layer such as a remote server and browser’s local storage. Chrome Apps provides both <a href="storage">Chrome Storage API</a> and <a href="fileSystem">HTML 5 fileSystem API</a> for client side storage. </p> <p>Pros:</p> <ul> <li>Simple to use and understand.</li> </ul> <p> Cons: </p> <ul> <li>Hard to test since the persistence layer is ‘baked’ into the object hierarchy.</li> <li>Having different objects use different persistent stores is difficult (for example, FileSystem APIs vs indexedDB vs server&ndash;side).</li> <li>Reusing Model in other applications may create conflicts, such as sharing a single Customer class between two different views, each view wanting to save to different places.</li> </ul> <h3 id="controller_persistence">Controller does persistence</h3> <p> In this pattern, the controller holds a reference to both the model and a datastore and is responsible for keeping the model persisted. The controller responds to lifecycle events like Load, Save, Delete, and issues commands to the datastore to fetch or update the model. </p> <p> Pros: </p> <ul> <li>Easier to test, controller can be passed a mock datastore to write tests against.</li> <li>The same model can be reused with multiple datastores just by constructing controllers with different datastores.</li> </ul> <p> Cons: </p> <ul> <li>Code can be more complex to maintain.</li> </ul> <h3 id="app_controller">AppController does persistence</h3> <p> In some patterns, there is a supervising controller responsible for navigating between one MVC and another. The AppController decides, for example, that a ‘Back’ button moves the client from an editing screen (which contains MVC widgets/formats), to a settings screen. </p> <p> In the AppController pattern, the AppController responds to events and changes the app’s current screen by issuing a call to the datastore to load any models needed and constructing all of the matching views and controllers for that screen. </p> <p> Pros: </p> <ul> <li>Moves persistence layer even higher up the stack where it can be easily changed.</li> <li>Doesn’t pollute lower level controllers like a DatePickerController with the need to know about persistence.</li> </ul> <p> Cons: </p> <ul> <li>Each ‘Page/Screen’ of the app now requires a lot of boilerplate to write or update: Model, View, Controller, AppController.</li> </ul> <h3 id="recommended">Recommended MVC frameworks</h3> <p> MVC is crucial to designing Chrome Apps. We recommend the following <a href="contentSecurityPolicy">CSP&ndash;Compliant</a> MVC frameworks for writing secure and scalable Chrome Apps: </p> <ul> <li><a href="http://angularjs.org/">AngularJS</a> (<a href="https://github.com/GoogleChrome/textdrive-app">Text Drive Reference App</a> and <a href="angular_framework">Build Apps with AngularJS tutorial</a>)</li> <li><a href="http://www.kendoui.com/">Kendo UI</a> (<a href="https://github.com/GoogleChrome/kendo-photo-booth-app">Photo Booth Reference App</a>)</li> <li><a href="http://www.sencha.com/">Sencha</a> (<a href="https://github.com/GoogleChrome/sencha-video-player-app">Video Player Reference App</a> and <a href="sencha_framework">Build Apps with Sencha Ext JS tutorial</a>)</li> </ul> <h2 id="resources">Useful resources</h2> <h3 id="online">Online</h3> <ul> <li><a href="http://www.html5rocks.com/">HTML5Rocks.com</a></li> <li><a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/">Learning JavaScript Design Patterns</a> (by Addy Osmani)</li> <li><a href="http://addyosmani.github.com/todomvc/">TodoMVC</a></li> </ul> <h3 id="books">Books</h3> <ul> <li><a href="http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X">JavaScript Web Applications</a> (By Alex MacCaw)</li> <li><a href="http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752/ref=pd_sim_b_2">JavaScript Patterns</a> (By Stoyan Stefonov)</li> <li><a href="http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680">Maintainable JavaScript</a> (By Nicolas Z. Zakas)</li> </ul> <p class="backtotop"><a href="#top">Back to top</a></p>
Charles Robert “Bob” Johnson, of Gladbrook, passed away Wednesday, March 15, 2017, at Westbrook Acres in Gladbrook. Funeral services were held Monday, March 20, 2017, at 10:30 a.m. at the United Methodist Church of Gladbrook. Inurnment will be held at a later date at Maple Hill Cemetery of Gladbrook. Memorials may be directed to the family. Condolences may be left at www.overtonservice.com. Overton Funeral Home of Traer was entrusted with the care of Bob and his family. Charles Robert “Bob” Johnson was born June 27, 1925 in Garwin, Iowa, son of Harold & Myrtle (Dunn) Johnson. He attended Garwin Schools graduating from Garwin High School with the Class of 1943. Following graduation, Bob was married to Esther Landt. He was drafted into Military Service and served as a cook in the United States Navy with basic training in Faragut, ID and being stationed in Bremerton, WA. Following his service, Bob returned to Iowa farming in Garwin, Beaman, then Gladbrook. He and Esther finally purchased their own farm near Lincoln, Iowa, in 1960. Bob raised hogs and was able to provide most of his own veterinary services through the years. He enjoyed fishing, playing cards (Cribbage with Esther), drinking coffee with his friends in Lincoln, and playing golf. Bob passed away on Wednesday, March 15, 2017, at Westbrook Acres of Gladbrook at the age of 91 years. He was preceded in death by his parents; his beloved Esther; a son, David Johnson; a brother, Lloyd “Gordon” Johnson; and 2 sisters, Mildred Haanel and Helen Rahn. Bob is survived by his son, Gary (Debra) Johnson of Gladbrook; a daughter, Sharry (Larry) Storjohann of Marshalltown; 5 grandchildren; 4 great-grandchildren; and other friends and family.
<?php /** * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * */ namespace Piwik; use Exception; use Piwik\Application\Kernel\GlobalSettingsProvider; use Piwik\Container\StaticContainer; /** * Singleton that provides read & write access to Piwik's INI configuration. * * This class reads and writes to the `config/config.ini.php` file. If config * options are missing from that file, this class will look for their default * values in `config/global.ini.php`. * * ### Examples * * **Getting a value:** * * // read the minimum_memory_limit option under the [General] section * $minValue = Config::getInstance()->General['minimum_memory_limit']; * * **Setting a value:** * * // set the minimum_memory_limit option * Config::getInstance()->General['minimum_memory_limit'] = 256; * Config::getInstance()->forceSave(); * * **Setting an entire section:** * * Config::getInstance()->MySection = array('myoption' => 1); * Config::getInstance()->forceSave(); */ class Config { const DEFAULT_LOCAL_CONFIG_PATH = '/config/config.ini.php'; const DEFAULT_COMMON_CONFIG_PATH = '/config/common.config.ini.php'; const DEFAULT_GLOBAL_CONFIG_PATH = '/config/global.ini.php'; /** * @var boolean */ protected $doNotWriteConfigInTests = false; /** * @var GlobalSettingsProvider */ protected $settings; /** * @return Config */ public static function getInstance() { return StaticContainer::get('Piwik\Config'); } public function __construct(GlobalSettingsProvider $settings) { $this->settings = $settings; } /** * Returns the path to the local config file used by this instance. * * @return string */ public function getLocalPath() { return $this->settings->getPathLocal(); } /** * Returns the path to the global config file used by this instance. * * @return string */ public function getGlobalPath() { return $this->settings->getPathGlobal(); } /** * Returns the path to the common config file used by this instance. * * @return string */ public function getCommonPath() { return $this->settings->getPathCommon(); } /** * Returns absolute path to the global configuration file * * @return string */ public static function getGlobalConfigPath() { return PIWIK_USER_PATH . self::DEFAULT_GLOBAL_CONFIG_PATH; } /** * Returns absolute path to the common configuration file. * * @return string */ public static function getCommonConfigPath() { return PIWIK_USER_PATH . self::DEFAULT_COMMON_CONFIG_PATH; } /** * Returns absolute path to the local configuration file * * @return string */ public static function getLocalConfigPath() { $path = self::getByDomainConfigPath(); if ($path) { return $path; } return PIWIK_USER_PATH . self::DEFAULT_LOCAL_CONFIG_PATH; } private static function getLocalConfigInfoForHostname($hostname) { // Remove any port number to get actual hostname $hostname = Url::getHostSanitized($hostname); $perHostFilename = $hostname . '.config.ini.php'; $pathDomainConfig = PIWIK_USER_PATH . '/config/' . $perHostFilename; return array('file' => $perHostFilename, 'path' => $pathDomainConfig); } public function getConfigHostnameIfSet() { if ($this->getByDomainConfigPath() === false) { return false; } return $this->getHostname(); } public function getClientSideOptions() { $general = $this->General; return array( 'action_url_category_delimiter' => $general['action_url_category_delimiter'], 'autocomplete_min_sites' => $general['autocomplete_min_sites'], 'datatable_export_range_as_day' => $general['datatable_export_range_as_day'], 'datatable_row_limits' => $this->getDatatableRowLimits() ); } /** * @param $general * @return mixed */ private function getDatatableRowLimits() { $limits = $this->General['datatable_row_limits']; $limits = explode(",", $limits); $limits = array_map('trim', $limits); return $limits; } public static function getByDomainConfigPath() { $host = self::getHostname(); $hostConfig = self::getLocalConfigInfoForHostname($host); if (Filesystem::isValidFilename($hostConfig['file']) && file_exists($hostConfig['path']) ) { return $hostConfig['path']; } return false; } /** * Returns the hostname of the current request (without port number) * * @return string */ public static function getHostname() { // Check trusted requires config file which is not ready yet $host = Url::getHost($checkIfTrusted = false); // Remove any port number to get actual hostname $host = Url::getHostSanitized($host); return $host; } /** * If set, Piwik will use the hostname config no matter if it exists or not. Useful for instance if you want to * create a new hostname config: * * $config = Config::getInstance(); * $config->forceUsageOfHostnameConfig('piwik.example.com'); * $config->save(); * * @param string $hostname eg piwik.example.com * @return string * @throws \Exception In case the domain contains not allowed characters * @internal */ public function forceUsageOfLocalHostnameConfig($hostname) { $hostConfig = self::getLocalConfigInfoForHostname($hostname); $filename = $hostConfig['file']; if (!Filesystem::isValidFilename($filename)) { throw new Exception('Piwik domain is not a valid looking hostname (' . $filename . ').'); } $pathLocal = $hostConfig['path']; try { $this->reload($pathLocal); } catch (Exception $ex) { // pass (not required for local file to exist at this point) } return $pathLocal; } /** * Returns `true` if the local configuration file is writable. * * @return bool */ public function isFileWritable() { return is_writable($this->settings->getPathLocal()); } /** * Clear in-memory configuration so it can be reloaded * @deprecated since v2.12.0 */ public function clear() { $this->reload(); } /** * Read configuration from files into memory * * @throws Exception if local config file is not readable; exits for other errors * @deprecated since v2.12.0 */ public function init() { $this->reload(); } /** * Reloads config data from disk. * * @throws \Exception if the global config file is not found and this is a tracker request, or * if the local config file is not found and this is NOT a tracker request. */ protected function reload($pathLocal = null, $pathGlobal = null, $pathCommon = null) { $this->settings->reload($pathGlobal, $pathLocal, $pathCommon); } /** * @deprecated */ public function existsLocalConfig() { return is_readable($this->getLocalPath()); } public function deleteLocalConfig() { $configLocal = $this->getLocalPath(); if(file_exists($configLocal)){ @unlink($configLocal); } } /** * Returns a configuration value or section by name. * * @param string $name The value or section name. * @return string|array The requested value requested. Returned by reference. * @throws Exception If the value requested not found in either `config.ini.php` or * `global.ini.php`. * @api */ public function &__get($name) { $section =& $this->settings->getIniFileChain()->get($name); return $section; } /** * @api */ public function getFromGlobalConfig($name) { return $this->settings->getIniFileChain()->getFrom($this->getGlobalPath(), $name); } /** * @api */ public function getFromCommonConfig($name) { return $this->settings->getIniFileChain()->getFrom($this->getCommonPath(), $name); } /** * @api */ public function getFromLocalConfig($name) { return $this->settings->getIniFileChain()->getFrom($this->getLocalPath(), $name); } /** * Sets a configuration value or section. * * @param string $name This section name or value name to set. * @param mixed $value * @api */ public function __set($name, $value) { $this->settings->getIniFileChain()->set($name, $value); } /** * Dump config * * @return string|null * @throws \Exception */ public function dumpConfig() { $chain = $this->settings->getIniFileChain(); $header = "; <?php exit; ?> DO NOT REMOVE THIS LINE\n"; $header .= "; file automatically generated or modified by Piwik; you can manually override the default values in global.ini.php by redefining them in this file.\n"; return $chain->dumpChanges($header); } /** * Write user configuration file * * @param array $configLocal * @param array $configGlobal * @param array $configCommon * @param array $configCache * @param string $pathLocal * @param bool $clear * * @throws \Exception if config file not writable */ protected function writeConfig($clear = true) { if ($this->doNotWriteConfigInTests) { return; } $output = $this->dumpConfig(); if ($output !== null && $output !== false ) { $success = @file_put_contents($this->getLocalPath(), $output); if ($success === false) { throw $this->getConfigNotWritableException(); } } if ($clear) { $this->reload(); } } /** * Writes the current configuration to the **config.ini.php** file. Only writes options whose * values are different from the default. * * @api */ public function forceSave() { $this->writeConfig(); } /** * @throws \Exception */ public function getConfigNotWritableException() { $path = "config/" . basename($this->getLocalPath()); return new Exception(Piwik::translate('General_ConfigFileIsNotWritable', array("(" . $path . ")", ""))); } }
package br.gov.siscomex.portalunico.rcnt.model; import java.util.List; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DadosAcessoVeculo", propOrder = { "tipoOperacao", "idEvento", "dataHoraOcorrencia", "dataHoraRegistro", "cpfOperadorOcorrencia", "cpfOperadorRegistro", "protocoloEventoRetificadoOuExcluido", "contingencia", "codigoRecinto", "operacao", "direcao", "protocoloAgenda", "dataHoraAgenda", "listaManifestos", "listaDeclaracaoAduaneira", "listaNfe", "listaMalas", "tipoGranel", "listaChassi", "placa", "ufEmplacamento", "ocrPlaca", "oogDimensao", "oogPeso", "listaSemirreboque", "listaConteineresUld", "cnpjTransportador", "nomeTransportador", "motorista", "codigoRecintoDestino", "codigoRecintoOrigem", "dataHoraPartidaOrigem", "modal", "gate", "listaCameras" }) @XmlRootElement(name="DadosAcessoVeculo") public class DadosAcessoVeculo { @XmlType(name="TipoOperacaoEnum") @XmlEnum(String.class) public enum TipoOperacaoEnum { @XmlEnumValue("'I'") @JsonProperty("'I'") I_(String.valueOf("'I'")), @XmlEnumValue("'R'") @JsonProperty("'R'") R_(String.valueOf("'R'")), @XmlEnumValue("'E'") @JsonProperty("'E'") E_(String.valueOf("'E'")); private String value; TipoOperacaoEnum (String v) { value = v; } public String value() { return value; } @Override public String toString() { return String.valueOf(value); } public static TipoOperacaoEnum fromValue(String v) { for (TipoOperacaoEnum b : TipoOperacaoEnum.values()) { if (String.valueOf(b.value).equals(v)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + v + "' to TipoOperacaoEnum"); } } @XmlElement(name="tipoOperacao", required = true) @ApiModelProperty(example = "I", required = true, value = "Indica se o evento transmitido é novo (incluir) ou retifica/exclui evento anterior.<br/>Domínio:<br/>I - Incluir<br/>R - Retificar<br/>E - Excluir") /** * Indica se o evento transmitido é novo (incluir) ou retifica/exclui evento anterior.<br/>Domínio:<br/>I - Incluir<br/>R - Retificar<br/>E - Excluir **/ private TipoOperacaoEnum tipoOperacao = null; @XmlElement(name="idEvento", required = true) @ApiModelProperty(required = true, value = "Identificador único do evento que pode ser utilizado para recuperar as informações do Evento no sistema de origem do Recinto remetente. Ex.: Chave tabela 1 + ... + chave tabela n - tantas chaves quantas forem as tabelas necessárias para montar o registro do evento.<br/>Tamanho: 100") /** * Identificador único do evento que pode ser utilizado para recuperar as informações do Evento no sistema de origem do Recinto remetente. Ex.: Chave tabela 1 + ... + chave tabela n - tantas chaves quantas forem as tabelas necessárias para montar o registro do evento.<br/>Tamanho: 100 **/ private String idEvento = null; @XmlElement(name="dataHoraOcorrencia", required = true) @ApiModelProperty(example = "2020-04-01T10:50:30.150-0300", required = true, value = "Data e hora em que o evento ocorreu ou que se coletou, em formulário papel durante uma contingência, os dados do evento. Deve-se enviar, junto da data, o fuso horário no qual tal data e hora foi gerada.<br/>Formato: 'yyyy-MM-ddTHH:mm:ss.SSSZ'") /** * Data e hora em que o evento ocorreu ou que se coletou, em formulário papel durante uma contingência, os dados do evento. Deve-se enviar, junto da data, o fuso horário no qual tal data e hora foi gerada.<br/>Formato: 'yyyy-MM-ddTHH:mm:ss.SSSZ' **/ private String dataHoraOcorrencia = null; @XmlElement(name="dataHoraRegistro", required = true) @ApiModelProperty(example = "2020-04-01T10:50:30.150-0300", required = true, value = "Data e hora em que se efetuou o lançamento, no sistema informatizado, seja em operações normais, seja das informações coletadas durante uma contingência. Deve-se enviar, junto da data, o fuso horário no qual tal data e hora foi gerada.<br/>Formato: 'yyyy-MM-ddTHH:mm:ss.SSSZ'") /** * Data e hora em que se efetuou o lançamento, no sistema informatizado, seja em operações normais, seja das informações coletadas durante uma contingência. Deve-se enviar, junto da data, o fuso horário no qual tal data e hora foi gerada.<br/>Formato: 'yyyy-MM-ddTHH:mm:ss.SSSZ' **/ private String dataHoraRegistro = null; @XmlElement(name="cpfOperadorOcorrencia") @ApiModelProperty(example = "55555555555", value = "CPF da pessoa que coletou, em formulário papel durante uma contingência, os dados do evento.<br/>Pode ser nulo quando o processo for automatizado, com isso, não há operador de ocorrência e nem de registro.<br/>Tamanho: 11<br/>Formato: 'NNNNNNNNNNN'") /** * CPF da pessoa que coletou, em formulário papel durante uma contingência, os dados do evento.<br/>Pode ser nulo quando o processo for automatizado, com isso, não há operador de ocorrência e nem de registro.<br/>Tamanho: 11<br/>Formato: 'NNNNNNNNNNN' **/ private String cpfOperadorOcorrencia = null; @XmlElement(name="cpfOperadorRegistro") @ApiModelProperty(example = "55555555555", value = "CPF da pessoa que efetuou o lançamento, no sistema informatizado, seja em operações normais, seja das informações coletadas durante uma contingência.<br>Pode ser nulo quando o processo for automatizado, com isso, não há operador de ocorrência e nem de registro.<br/>Tamanho: 11<br/>Formato: 'NNNNNNNNNNN'") /** * CPF da pessoa que efetuou o lançamento, no sistema informatizado, seja em operações normais, seja das informações coletadas durante uma contingência.<br>Pode ser nulo quando o processo for automatizado, com isso, não há operador de ocorrência e nem de registro.<br/>Tamanho: 11<br/>Formato: 'NNNNNNNNNNN' **/ private String cpfOperadorRegistro = null; @XmlElement(name="protocoloEventoRetificadoOuExcluido") @ApiModelProperty(example = "66d24eb1-6ac9-4798-bc93-f4c66eb6fa9b", value = "Observar que no caso de evento retificador ou de exclusão, o protocolo do evento retificado ou excluído deve ser informado para possibilitar a correta vinculação. Usar protocolo recebido após o envio do evento original. O envio de eventos retificadores substitui completamente as informações prestadas no evento retificado.<br/>Tamanho: 36") /** * Observar que no caso de evento retificador ou de exclusão, o protocolo do evento retificado ou excluído deve ser informado para possibilitar a correta vinculação. Usar protocolo recebido após o envio do evento original. O envio de eventos retificadores substitui completamente as informações prestadas no evento retificado.<br/>Tamanho: 36 **/ private String protocoloEventoRetificadoOuExcluido = null; @XmlElement(name="contingencia", required = true) @ApiModelProperty(example = "false", required = true, value = "Indica que este evento ocorreu durante uma contingência. Via de regra deverá haver um evento (Ocorrências de indisponibilidade de equipamentos) para o equipamento envolvido. Transmitir como true sempre que ocorrer falha operacional no sistema do recinto que impeça o registro e/ou envio de informações em seu sistema.<br/>Domínio:<br/>true - Sim<br/>false - Não") /** * Indica que este evento ocorreu durante uma contingência. Via de regra deverá haver um evento (Ocorrências de indisponibilidade de equipamentos) para o equipamento envolvido. Transmitir como true sempre que ocorrer falha operacional no sistema do recinto que impeça o registro e/ou envio de informações em seu sistema.<br/>Domínio:<br/>true - Sim<br/>false - Não **/ private Boolean contingencia = null; @XmlElement(name="codigoRecinto", required = true) @ApiModelProperty(example = "1111111", required = true, value = "Código Siscomex do recinto onde ocorreu o evento a ser transmitido.<br/>Tamanho: 15") /** * Código Siscomex do recinto onde ocorreu o evento a ser transmitido.<br/>Tamanho: 15 **/ private String codigoRecinto = null; @XmlType(name="OperacaoEnum") @XmlEnum(String.class) public enum OperacaoEnum { @XmlEnumValue("G") @JsonProperty("G") G(String.valueOf("G")), @XmlEnumValue("C") @JsonProperty("C") C(String.valueOf("C")); private String value; OperacaoEnum (String v) { value = v; } public String value() { return value; } @Override public String toString() { return String.valueOf(value); } public static OperacaoEnum fromValue(String v) { for (OperacaoEnum b : OperacaoEnum.values()) { if (String.valueOf(b.value).equals(v)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + v + "' to OperacaoEnum"); } } @XmlElement(name="operacao", required = true) @ApiModelProperty(example = "G", required = true, value = "Operação de agendamento de entrada/saída de veículo (agendamento) ou de entrada/saída de veículo (acesso). Pode ser nulo quando o evento for de exclusão.<br/>Domínio:<br/>G - Agendamento<br/>C - Acesso") /** * Operação de agendamento de entrada/saída de veículo (agendamento) ou de entrada/saída de veículo (acesso). Pode ser nulo quando o evento for de exclusão.<br/>Domínio:<br/>G - Agendamento<br/>C - Acesso **/ private OperacaoEnum operacao = null; @XmlType(name="DirecaoEnum") @XmlEnum(String.class) public enum DirecaoEnum { @XmlEnumValue("'E'") @JsonProperty("'E'") E_(String.valueOf("'E'")), @XmlEnumValue("'S'") @JsonProperty("'S'") S_(String.valueOf("'S'")); private String value; DirecaoEnum (String v) { value = v; } public String value() { return value; } @Override public String toString() { return String.valueOf(value); } public static DirecaoEnum fromValue(String v) { for (DirecaoEnum b : DirecaoEnum.values()) { if (String.valueOf(b.value).equals(v)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + v + "' to DirecaoEnum"); } } @XmlElement(name="direcao", required = true) @ApiModelProperty(example = "E", required = true, value = "Direção do veículo. Indica se é um movimento de entrada ou de saída do veículo. Pode ser nulo quando o evento for de exclusão.<br/>Domínio:<br/>E - Entrada<br/>S - Saída") /** * Direção do veículo. Indica se é um movimento de entrada ou de saída do veículo. Pode ser nulo quando o evento for de exclusão.<br/>Domínio:<br/>E - Entrada<br/>S - Saída **/ private DirecaoEnum direcao = null; @XmlElement(name="protocoloAgenda") @ApiModelProperty(value = "Protocolo do Evento de Agendamento que foi recebido quando do envio do evento.<br/>Tamanho: 36") /** * Protocolo do Evento de Agendamento que foi recebido quando do envio do evento.<br/>Tamanho: 36 **/ private String protocoloAgenda = null; @XmlElement(name="dataHoraAgenda") @ApiModelProperty(example = "2020-04-01T10:50:30.150-0300", value = "Data e Hora agendada. Deve-se enviar, junto da data, o fuso horário no qual tal data e hora foi gerada.<br/>Formato: 'yyyy-MM-ddTHH:mm:ss.SSSZ'") /** * Data e Hora agendada. Deve-se enviar, junto da data, o fuso horário no qual tal data e hora foi gerada.<br/>Formato: 'yyyy-MM-ddTHH:mm:ss.SSSZ' **/ private String dataHoraAgenda = null; @XmlElement(name="listaManifestos") @ApiModelProperty(value = "Lista de manifestos.") @Valid /** * Lista de manifestos. **/ private List<DadosDoManisfestoDaCarga> listaManifestos = null; @XmlElement(name="listaDeclaracaoAduaneira") @ApiModelProperty(value = "Lista de declarações aduaneiras associadas à carga.") @Valid /** * Lista de declarações aduaneiras associadas à carga. **/ private List<DocumentoAduaneiro> listaDeclaracaoAduaneira = null; @XmlElement(name="listaNfe") @ApiModelProperty(value = "Lista de chaves das NFE que amparam o transporte.") @Valid /** * Lista de chaves das NFE que amparam o transporte. **/ private List<DadosDaNotaFiscal> listaNfe = null; @XmlElement(name="listaMalas") @ApiModelProperty(value = "Lista com as malas postais. Utilizar apenas para malas postais.") @Valid /** * Lista com as malas postais. Utilizar apenas para malas postais. **/ private List<DadosDaMala> listaMalas = null; @XmlType(name="TipoGranelEnum") @XmlEnum(String.class) public enum TipoGranelEnum { @XmlEnumValue("'01'") @JsonProperty("'01'") _01_(String.valueOf("'01'")), @XmlEnumValue("'02'") @JsonProperty("'02'") _02_(String.valueOf("'02'")), @XmlEnumValue("'03'") @JsonProperty("'03'") _03_(String.valueOf("'03'")), @XmlEnumValue("'04'") @JsonProperty("'04'") _04_(String.valueOf("'04'")), @XmlEnumValue("'05'") @JsonProperty("'05'") _05_(String.valueOf("'05'")), @XmlEnumValue("'06'") @JsonProperty("'06'") _06_(String.valueOf("'06'")), @XmlEnumValue("'07'") @JsonProperty("'07'") _07_(String.valueOf("'07'")), @XmlEnumValue("'99'") @JsonProperty("'99'") _99_(String.valueOf("'99'")); private String value; TipoGranelEnum (String v) { value = v; } public String value() { return value; } @Override public String toString() { return String.valueOf(value); } public static TipoGranelEnum fromValue(String v) { for (TipoGranelEnum b : TipoGranelEnum.values()) { if (String.valueOf(b.value).equals(v)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + v + "' to TipoGranelEnum"); } } @XmlElement(name="tipoGranel") @ApiModelProperty(example = "01", value = "Tipo de granel conforme tabela de domínio.<br/>Domínio:<br/>01 - SÓLIDOS - MINÉRIOS<br/>02 - SÓLIDOS - GRÃOS<br/>03 - SÓLIDOS - FARELOS<br/>04 - SÓLIDOS - OUTROS<br/>05 - LÍQUIDOS - COMBUSTÍVEIS<br/>06 - LÍQUIDOS - OUTROS<br/>07 - GASOSOS<br/>99 - OUTROS<br/>") /** * Tipo de granel conforme tabela de domínio.<br/>Domínio:<br/>01 - SÓLIDOS - MINÉRIOS<br/>02 - SÓLIDOS - GRÃOS<br/>03 - SÓLIDOS - FARELOS<br/>04 - SÓLIDOS - OUTROS<br/>05 - LÍQUIDOS - COMBUSTÍVEIS<br/>06 - LÍQUIDOS - OUTROS<br/>07 - GASOSOS<br/>99 - OUTROS<br/> **/ private TipoGranelEnum tipoGranel = null; @XmlElement(name="listaChassi") @ApiModelProperty(value = "Lista de Chassis. Informar todos os chassis das mercadorias, inclusive o tipo meios próprios (Impo/Expo ônibus, cavalo-trator, semirreboque...)<br/>Tamanho: 50") @Valid /** * Lista de Chassis. Informar todos os chassis das mercadorias, inclusive o tipo meios próprios (Impo/Expo ônibus, cavalo-trator, semirreboque...)<br/>Tamanho: 50 **/ private List<DadosDoChassi> listaChassi = null; @XmlElement(name="placa", required = true) @ApiModelProperty(required = true, value = "Placa do veículo (Cavalo-trator/truck/automóvel/locomotiva). Pode ser nulo quando o evento for de exclusão.<br/>Tamanho: 50") /** * Placa do veículo (Cavalo-trator/truck/automóvel/locomotiva). Pode ser nulo quando o evento for de exclusão.<br/>Tamanho: 50 **/ private String placa = null; @XmlElement(name="ufEmplacamento") @ApiModelProperty(example = "SP", value = "UF Emplacamento.<br/>Informar apenas no caso de trânsito terrestre cuja chegada da carga no país ocorreu via aeroporto<br/>Tamanho: 2") /** * UF Emplacamento.<br/>Informar apenas no caso de trânsito terrestre cuja chegada da carga no país ocorreu via aeroporto<br/>Tamanho: 2 **/ private String ufEmplacamento = null; @XmlElement(name="ocrPlaca") @ApiModelProperty(example = "false", value = "Captura automática da placa. Indica se a placa foi obtida via OCR (Optical Character Recognition).<br/>Domínio:<br/>true - Sim<br/>false - Não") /** * Captura automática da placa. Indica se a placa foi obtida via OCR (Optical Character Recognition).<br/>Domínio:<br/>true - Sim<br/>false - Não **/ private Boolean ocrPlaca = null; @XmlElement(name="oogDimensao") @ApiModelProperty(example = "false", value = "Dimensões que impeçam a entrada/saída OOG (Out of Gauge) pelo gate padrão ou a pesagem ou a passagem pelo scanner.<br/>Domínio:<br/>true - Sim<br/>false - Não") /** * Dimensões que impeçam a entrada/saída OOG (Out of Gauge) pelo gate padrão ou a pesagem ou a passagem pelo scanner.<br/>Domínio:<br/>true - Sim<br/>false - Não **/ private Boolean oogDimensao = null; @XmlElement(name="oogPeso") @ApiModelProperty(example = "false", value = "Peso que impeça a entrada/saída OOG (Out of Gauge) pelo gate padrão, a pesagem ou a passagem pelo scanner.<br/>Domínio:<br/>true - Sim<br/>false - Não") /** * Peso que impeça a entrada/saída OOG (Out of Gauge) pelo gate padrão, a pesagem ou a passagem pelo scanner.<br/>Domínio:<br/>true - Sim<br/>false - Não **/ private Boolean oogPeso = null; @XmlElement(name="listaSemirreboque") @ApiModelProperty(value = "Lista de semirreboques ou vagões. No caso de caminhão truck utilizar essa estrutura repetindo a identificação da placa do veículo.") @Valid /** * Lista de semirreboques ou vagões. No caso de caminhão truck utilizar essa estrutura repetindo a identificação da placa do veículo. **/ private List<DadosSemirreboque> listaSemirreboque = null; @XmlElement(name="listaConteineresUld") @ApiModelProperty(value = "Lista de contêineres ou ULD (Unit Load Device – Aéreo).") @Valid /** * Lista de contêineres ou ULD (Unit Load Device – Aéreo). **/ private List<DadosContinerUldAcessoVeculo> listaConteineresUld = null; @XmlElement(name="cnpjTransportador") @ApiModelProperty(example = "44444444444444", value = "CNPJ da empresa transportadora.<br/>Tamanho: 14<br/>Formato: 'NNNNNNNNNNNNNN'") /** * CNPJ da empresa transportadora.<br/>Tamanho: 14<br/>Formato: 'NNNNNNNNNNNNNN' **/ private String cnpjTransportador = null; @XmlElement(name="nomeTransportador") @ApiModelProperty(value = "Nome da empresa transportadora.<br/>Tamanho: 100") /** * Nome da empresa transportadora.<br/>Tamanho: 100 **/ private String nomeTransportador = null; @XmlElement(name="motorista") @ApiModelProperty(value = "") @Valid private DadosMotorista motorista = null; @XmlElement(name="codigoRecintoDestino") @ApiModelProperty(value = "Código Siscomex do recinto de destino. Informar apenas no caso de saída do recinto em regime de trânsito.<br/>Tamanho: 15") /** * Código Siscomex do recinto de destino. Informar apenas no caso de saída do recinto em regime de trânsito.<br/>Tamanho: 15 **/ private String codigoRecintoDestino = null; @XmlElement(name="codigoRecintoOrigem") @ApiModelProperty(value = "Código Siscomex do recinto de origem. Informar apenas no caso de chegada em recinto em regime de trânsito.<br/>Tamanho: 15") /** * Código Siscomex do recinto de origem. Informar apenas no caso de chegada em recinto em regime de trânsito.<br/>Tamanho: 15 **/ private String codigoRecintoOrigem = null; @XmlElement(name="dataHoraPartidaOrigem") @ApiModelProperty(example = "2020-04-01T10:50:30.150-0300", value = "Informar data e hora de partida do veículo da origem sob regime de trânsito.<br/>Formato: 'yyyy-MM-ddTHH:mm:ss.SSSZ'") /** * Informar data e hora de partida do veículo da origem sob regime de trânsito.<br/>Formato: 'yyyy-MM-ddTHH:mm:ss.SSSZ' **/ private String dataHoraPartidaOrigem = null; @XmlType(name="ModalEnum") @XmlEnum(String.class) public enum ModalEnum { @XmlEnumValue("'R'") @JsonProperty("'R'") R_(String.valueOf("'R'")), @XmlEnumValue("'F'") @JsonProperty("'F'") F_(String.valueOf("'F'")), @XmlEnumValue("'L'") @JsonProperty("'L'") L_(String.valueOf("'L'")); private String value; ModalEnum (String v) { value = v; } public String value() { return value; } @Override public String toString() { return String.valueOf(value); } public static ModalEnum fromValue(String v) { for (ModalEnum b : ModalEnum.values()) { if (String.valueOf(b.value).equals(v)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + v + "' to ModalEnum"); } } @XmlElement(name="modal") @ApiModelProperty(example = "R", value = "Modal. Forma como a carga chegou/saiu do recinto, transporte rodoviário ou transporte ferroviário. Conforme tabela domínio.<br/>Domínio:<br/>R - Rodoviário<br/>F - Ferroviário<br/>L - Fluvial") /** * Modal. Forma como a carga chegou/saiu do recinto, transporte rodoviário ou transporte ferroviário. Conforme tabela domínio.<br/>Domínio:<br/>R - Rodoviário<br/>F - Ferroviário<br/>L - Fluvial **/ private ModalEnum modal = null; @XmlElement(name="gate") @ApiModelProperty(value = "Identificação do Gate.<br/>Usar o protocolo do evento de georreferenciamento relativo ao ponto de acesso utilizado.<br/>Tamanho: 36") /** * Identificação do Gate.<br/>Usar o protocolo do evento de georreferenciamento relativo ao ponto de acesso utilizado.<br/>Tamanho: 36 **/ private String gate = null; @XmlElement(name="listaCameras") @ApiModelProperty(value = "Lista de identificação das câmeras. Usar o protocolo do evento de georreferenciamento para indicar, nesta lista, todas as câmeras que cobrem o Gate por onde o veículo ingressou/saiu.") @Valid /** * Lista de identificação das câmeras. Usar o protocolo do evento de georreferenciamento para indicar, nesta lista, todas as câmeras que cobrem o Gate por onde o veículo ingressou/saiu. **/ private List<DadosDaCmera> listaCameras = null; /** * Indica se o evento transmitido é novo (incluir) ou retifica/exclui evento anterior.&lt;br/&gt;Domínio:&lt;br/&gt;I - Incluir&lt;br/&gt;R - Retificar&lt;br/&gt;E - Excluir * @return tipoOperacao **/ @JsonProperty("tipoOperacao") @NotNull public String getTipoOperacao() { if (tipoOperacao == null) { return null; } return tipoOperacao.value(); } public void setTipoOperacao(TipoOperacaoEnum tipoOperacao) { this.tipoOperacao = tipoOperacao; } public DadosAcessoVeculo tipoOperacao(TipoOperacaoEnum tipoOperacao) { this.tipoOperacao = tipoOperacao; return this; } /** * Identificador único do evento que pode ser utilizado para recuperar as informações do Evento no sistema de origem do Recinto remetente. Ex.: Chave tabela 1 + ... + chave tabela n - tantas chaves quantas forem as tabelas necessárias para montar o registro do evento.&lt;br/&gt;Tamanho: 100 * @return idEvento **/ @JsonProperty("idEvento") @NotNull public String getIdEvento() { return idEvento; } public void setIdEvento(String idEvento) { this.idEvento = idEvento; } public DadosAcessoVeculo idEvento(String idEvento) { this.idEvento = idEvento; return this; } /** * Data e hora em que o evento ocorreu ou que se coletou, em formulário papel durante uma contingência, os dados do evento. Deve-se enviar, junto da data, o fuso horário no qual tal data e hora foi gerada.&lt;br/&gt;Formato: &#39;yyyy-MM-ddTHH:mm:ss.SSSZ&#39; * @return dataHoraOcorrencia **/ @JsonProperty("dataHoraOcorrencia") @NotNull public String getDataHoraOcorrencia() { return dataHoraOcorrencia; } public void setDataHoraOcorrencia(String dataHoraOcorrencia) { this.dataHoraOcorrencia = dataHoraOcorrencia; } public DadosAcessoVeculo dataHoraOcorrencia(String dataHoraOcorrencia) { this.dataHoraOcorrencia = dataHoraOcorrencia; return this; } /** * Data e hora em que se efetuou o lançamento, no sistema informatizado, seja em operações normais, seja das informações coletadas durante uma contingência. Deve-se enviar, junto da data, o fuso horário no qual tal data e hora foi gerada.&lt;br/&gt;Formato: &#39;yyyy-MM-ddTHH:mm:ss.SSSZ&#39; * @return dataHoraRegistro **/ @JsonProperty("dataHoraRegistro") @NotNull public String getDataHoraRegistro() { return dataHoraRegistro; } public void setDataHoraRegistro(String dataHoraRegistro) { this.dataHoraRegistro = dataHoraRegistro; } public DadosAcessoVeculo dataHoraRegistro(String dataHoraRegistro) { this.dataHoraRegistro = dataHoraRegistro; return this; } /** * CPF da pessoa que coletou, em formulário papel durante uma contingência, os dados do evento.&lt;br/&gt;Pode ser nulo quando o processo for automatizado, com isso, não há operador de ocorrência e nem de registro.&lt;br/&gt;Tamanho: 11&lt;br/&gt;Formato: &#39;NNNNNNNNNNN&#39; * @return cpfOperadorOcorrencia **/ @JsonProperty("cpfOperadorOcorrencia") public String getCpfOperadorOcorrencia() { return cpfOperadorOcorrencia; } public void setCpfOperadorOcorrencia(String cpfOperadorOcorrencia) { this.cpfOperadorOcorrencia = cpfOperadorOcorrencia; } public DadosAcessoVeculo cpfOperadorOcorrencia(String cpfOperadorOcorrencia) { this.cpfOperadorOcorrencia = cpfOperadorOcorrencia; return this; } /** * CPF da pessoa que efetuou o lançamento, no sistema informatizado, seja em operações normais, seja das informações coletadas durante uma contingência.&lt;br&gt;Pode ser nulo quando o processo for automatizado, com isso, não há operador de ocorrência e nem de registro.&lt;br/&gt;Tamanho: 11&lt;br/&gt;Formato: &#39;NNNNNNNNNNN&#39; * @return cpfOperadorRegistro **/ @JsonProperty("cpfOperadorRegistro") public String getCpfOperadorRegistro() { return cpfOperadorRegistro; } public void setCpfOperadorRegistro(String cpfOperadorRegistro) { this.cpfOperadorRegistro = cpfOperadorRegistro; } public DadosAcessoVeculo cpfOperadorRegistro(String cpfOperadorRegistro) { this.cpfOperadorRegistro = cpfOperadorRegistro; return this; } /** * Observar que no caso de evento retificador ou de exclusão, o protocolo do evento retificado ou excluído deve ser informado para possibilitar a correta vinculação. Usar protocolo recebido após o envio do evento original. O envio de eventos retificadores substitui completamente as informações prestadas no evento retificado.&lt;br/&gt;Tamanho: 36 * @return protocoloEventoRetificadoOuExcluido **/ @JsonProperty("protocoloEventoRetificadoOuExcluido") public String getProtocoloEventoRetificadoOuExcluido() { return protocoloEventoRetificadoOuExcluido; } public void setProtocoloEventoRetificadoOuExcluido(String protocoloEventoRetificadoOuExcluido) { this.protocoloEventoRetificadoOuExcluido = protocoloEventoRetificadoOuExcluido; } public DadosAcessoVeculo protocoloEventoRetificadoOuExcluido(String protocoloEventoRetificadoOuExcluido) { this.protocoloEventoRetificadoOuExcluido = protocoloEventoRetificadoOuExcluido; return this; } /** * Indica que este evento ocorreu durante uma contingência. Via de regra deverá haver um evento (Ocorrências de indisponibilidade de equipamentos) para o equipamento envolvido. Transmitir como true sempre que ocorrer falha operacional no sistema do recinto que impeça o registro e/ou envio de informações em seu sistema.&lt;br/&gt;Domínio:&lt;br/&gt;true - Sim&lt;br/&gt;false - Não * @return contingencia **/ @JsonProperty("contingencia") @NotNull public Boolean isContingencia() { return contingencia; } public void setContingencia(Boolean contingencia) { this.contingencia = contingencia; } public DadosAcessoVeculo contingencia(Boolean contingencia) { this.contingencia = contingencia; return this; } /** * Código Siscomex do recinto onde ocorreu o evento a ser transmitido.&lt;br/&gt;Tamanho: 15 * @return codigoRecinto **/ @JsonProperty("codigoRecinto") @NotNull public String getCodigoRecinto() { return codigoRecinto; } public void setCodigoRecinto(String codigoRecinto) { this.codigoRecinto = codigoRecinto; } public DadosAcessoVeculo codigoRecinto(String codigoRecinto) { this.codigoRecinto = codigoRecinto; return this; } /** * Operação de agendamento de entrada/saída de veículo (agendamento) ou de entrada/saída de veículo (acesso). Pode ser nulo quando o evento for de exclusão.&lt;br/&gt;Domínio:&lt;br/&gt;G - Agendamento&lt;br/&gt;C - Acesso * @return operacao **/ @JsonProperty("operacao") @NotNull public String getOperacao() { if (operacao == null) { return null; } return operacao.value(); } public void setOperacao(OperacaoEnum operacao) { this.operacao = operacao; } public DadosAcessoVeculo operacao(OperacaoEnum operacao) { this.operacao = operacao; return this; } /** * Direção do veículo. Indica se é um movimento de entrada ou de saída do veículo. Pode ser nulo quando o evento for de exclusão.&lt;br/&gt;Domínio:&lt;br/&gt;E - Entrada&lt;br/&gt;S - Saída * @return direcao **/ @JsonProperty("direcao") @NotNull public String getDirecao() { if (direcao == null) { return null; } return direcao.value(); } public void setDirecao(DirecaoEnum direcao) { this.direcao = direcao; } public DadosAcessoVeculo direcao(DirecaoEnum direcao) { this.direcao = direcao; return this; } /** * Protocolo do Evento de Agendamento que foi recebido quando do envio do evento.&lt;br/&gt;Tamanho: 36 * @return protocoloAgenda **/ @JsonProperty("protocoloAgenda") public String getProtocoloAgenda() { return protocoloAgenda; } public void setProtocoloAgenda(String protocoloAgenda) { this.protocoloAgenda = protocoloAgenda; } public DadosAcessoVeculo protocoloAgenda(String protocoloAgenda) { this.protocoloAgenda = protocoloAgenda; return this; } /** * Data e Hora agendada. Deve-se enviar, junto da data, o fuso horário no qual tal data e hora foi gerada.&lt;br/&gt;Formato: &#39;yyyy-MM-ddTHH:mm:ss.SSSZ&#39; * @return dataHoraAgenda **/ @JsonProperty("dataHoraAgenda") public String getDataHoraAgenda() { return dataHoraAgenda; } public void setDataHoraAgenda(String dataHoraAgenda) { this.dataHoraAgenda = dataHoraAgenda; } public DadosAcessoVeculo dataHoraAgenda(String dataHoraAgenda) { this.dataHoraAgenda = dataHoraAgenda; return this; } /** * Lista de manifestos. * @return listaManifestos **/ @JsonProperty("listaManifestos") public List<DadosDoManisfestoDaCarga> getListaManifestos() { return listaManifestos; } public void setListaManifestos(List<DadosDoManisfestoDaCarga> listaManifestos) { this.listaManifestos = listaManifestos; } public DadosAcessoVeculo listaManifestos(List<DadosDoManisfestoDaCarga> listaManifestos) { this.listaManifestos = listaManifestos; return this; } public DadosAcessoVeculo addListaManifestosItem(DadosDoManisfestoDaCarga listaManifestosItem) { this.listaManifestos.add(listaManifestosItem); return this; } /** * Lista de declarações aduaneiras associadas à carga. * @return listaDeclaracaoAduaneira **/ @JsonProperty("listaDeclaracaoAduaneira") public List<DocumentoAduaneiro> getListaDeclaracaoAduaneira() { return listaDeclaracaoAduaneira; } public void setListaDeclaracaoAduaneira(List<DocumentoAduaneiro> listaDeclaracaoAduaneira) { this.listaDeclaracaoAduaneira = listaDeclaracaoAduaneira; } public DadosAcessoVeculo listaDeclaracaoAduaneira(List<DocumentoAduaneiro> listaDeclaracaoAduaneira) { this.listaDeclaracaoAduaneira = listaDeclaracaoAduaneira; return this; } public DadosAcessoVeculo addListaDeclaracaoAduaneiraItem(DocumentoAduaneiro listaDeclaracaoAduaneiraItem) { this.listaDeclaracaoAduaneira.add(listaDeclaracaoAduaneiraItem); return this; } /** * Lista de chaves das NFE que amparam o transporte. * @return listaNfe **/ @JsonProperty("listaNfe") public List<DadosDaNotaFiscal> getListaNfe() { return listaNfe; } public void setListaNfe(List<DadosDaNotaFiscal> listaNfe) { this.listaNfe = listaNfe; } public DadosAcessoVeculo listaNfe(List<DadosDaNotaFiscal> listaNfe) { this.listaNfe = listaNfe; return this; } public DadosAcessoVeculo addListaNfeItem(DadosDaNotaFiscal listaNfeItem) { this.listaNfe.add(listaNfeItem); return this; } /** * Lista com as malas postais. Utilizar apenas para malas postais. * @return listaMalas **/ @JsonProperty("listaMalas") public List<DadosDaMala> getListaMalas() { return listaMalas; } public void setListaMalas(List<DadosDaMala> listaMalas) { this.listaMalas = listaMalas; } public DadosAcessoVeculo listaMalas(List<DadosDaMala> listaMalas) { this.listaMalas = listaMalas; return this; } public DadosAcessoVeculo addListaMalasItem(DadosDaMala listaMalasItem) { this.listaMalas.add(listaMalasItem); return this; } /** * Tipo de granel conforme tabela de domínio.&lt;br/&gt;Domínio:&lt;br/&gt;01 - SÓLIDOS - MINÉRIOS&lt;br/&gt;02 - SÓLIDOS - GRÃOS&lt;br/&gt;03 - SÓLIDOS - FARELOS&lt;br/&gt;04 - SÓLIDOS - OUTROS&lt;br/&gt;05 - LÍQUIDOS - COMBUSTÍVEIS&lt;br/&gt;06 - LÍQUIDOS - OUTROS&lt;br/&gt;07 - GASOSOS&lt;br/&gt;99 - OUTROS&lt;br/&gt; * @return tipoGranel **/ @JsonProperty("tipoGranel") public String getTipoGranel() { if (tipoGranel == null) { return null; } return tipoGranel.value(); } public void setTipoGranel(TipoGranelEnum tipoGranel) { this.tipoGranel = tipoGranel; } public DadosAcessoVeculo tipoGranel(TipoGranelEnum tipoGranel) { this.tipoGranel = tipoGranel; return this; } /** * Lista de Chassis. Informar todos os chassis das mercadorias, inclusive o tipo meios próprios (Impo/Expo ônibus, cavalo-trator, semirreboque...)&lt;br/&gt;Tamanho: 50 * @return listaChassi **/ @JsonProperty("listaChassi") public List<DadosDoChassi> getListaChassi() { return listaChassi; } public void setListaChassi(List<DadosDoChassi> listaChassi) { this.listaChassi = listaChassi; } public DadosAcessoVeculo listaChassi(List<DadosDoChassi> listaChassi) { this.listaChassi = listaChassi; return this; } public DadosAcessoVeculo addListaChassiItem(DadosDoChassi listaChassiItem) { this.listaChassi.add(listaChassiItem); return this; } /** * Placa do veículo (Cavalo-trator/truck/automóvel/locomotiva). Pode ser nulo quando o evento for de exclusão.&lt;br/&gt;Tamanho: 50 * @return placa **/ @JsonProperty("placa") @NotNull public String getPlaca() { return placa; } public void setPlaca(String placa) { this.placa = placa; } public DadosAcessoVeculo placa(String placa) { this.placa = placa; return this; } /** * UF Emplacamento.&lt;br/&gt;Informar apenas no caso de trânsito terrestre cuja chegada da carga no país ocorreu via aeroporto&lt;br/&gt;Tamanho: 2 * @return ufEmplacamento **/ @JsonProperty("ufEmplacamento") public String getUfEmplacamento() { return ufEmplacamento; } public void setUfEmplacamento(String ufEmplacamento) { this.ufEmplacamento = ufEmplacamento; } public DadosAcessoVeculo ufEmplacamento(String ufEmplacamento) { this.ufEmplacamento = ufEmplacamento; return this; } /** * Captura automática da placa. Indica se a placa foi obtida via OCR (Optical Character Recognition).&lt;br/&gt;Domínio:&lt;br/&gt;true - Sim&lt;br/&gt;false - Não * @return ocrPlaca **/ @JsonProperty("ocrPlaca") public Boolean isOcrPlaca() { return ocrPlaca; } public void setOcrPlaca(Boolean ocrPlaca) { this.ocrPlaca = ocrPlaca; } public DadosAcessoVeculo ocrPlaca(Boolean ocrPlaca) { this.ocrPlaca = ocrPlaca; return this; } /** * Dimensões que impeçam a entrada/saída OOG (Out of Gauge) pelo gate padrão ou a pesagem ou a passagem pelo scanner.&lt;br/&gt;Domínio:&lt;br/&gt;true - Sim&lt;br/&gt;false - Não * @return oogDimensao **/ @JsonProperty("oogDimensao") public Boolean isOogDimensao() { return oogDimensao; } public void setOogDimensao(Boolean oogDimensao) { this.oogDimensao = oogDimensao; } public DadosAcessoVeculo oogDimensao(Boolean oogDimensao) { this.oogDimensao = oogDimensao; return this; } /** * Peso que impeça a entrada/saída OOG (Out of Gauge) pelo gate padrão, a pesagem ou a passagem pelo scanner.&lt;br/&gt;Domínio:&lt;br/&gt;true - Sim&lt;br/&gt;false - Não * @return oogPeso **/ @JsonProperty("oogPeso") public Boolean isOogPeso() { return oogPeso; } public void setOogPeso(Boolean oogPeso) { this.oogPeso = oogPeso; } public DadosAcessoVeculo oogPeso(Boolean oogPeso) { this.oogPeso = oogPeso; return this; } /** * Lista de semirreboques ou vagões. No caso de caminhão truck utilizar essa estrutura repetindo a identificação da placa do veículo. * @return listaSemirreboque **/ @JsonProperty("listaSemirreboque") public List<DadosSemirreboque> getListaSemirreboque() { return listaSemirreboque; } public void setListaSemirreboque(List<DadosSemirreboque> listaSemirreboque) { this.listaSemirreboque = listaSemirreboque; } public DadosAcessoVeculo listaSemirreboque(List<DadosSemirreboque> listaSemirreboque) { this.listaSemirreboque = listaSemirreboque; return this; } public DadosAcessoVeculo addListaSemirreboqueItem(DadosSemirreboque listaSemirreboqueItem) { this.listaSemirreboque.add(listaSemirreboqueItem); return this; } /** * Lista de contêineres ou ULD (Unit Load Device – Aéreo). * @return listaConteineresUld **/ @JsonProperty("listaConteineresUld") public List<DadosContinerUldAcessoVeculo> getListaConteineresUld() { return listaConteineresUld; } public void setListaConteineresUld(List<DadosContinerUldAcessoVeculo> listaConteineresUld) { this.listaConteineresUld = listaConteineresUld; } public DadosAcessoVeculo listaConteineresUld(List<DadosContinerUldAcessoVeculo> listaConteineresUld) { this.listaConteineresUld = listaConteineresUld; return this; } public DadosAcessoVeculo addListaConteineresUldItem(DadosContinerUldAcessoVeculo listaConteineresUldItem) { this.listaConteineresUld.add(listaConteineresUldItem); return this; } /** * CNPJ da empresa transportadora.&lt;br/&gt;Tamanho: 14&lt;br/&gt;Formato: &#39;NNNNNNNNNNNNNN&#39; * @return cnpjTransportador **/ @JsonProperty("cnpjTransportador") public String getCnpjTransportador() { return cnpjTransportador; } public void setCnpjTransportador(String cnpjTransportador) { this.cnpjTransportador = cnpjTransportador; } public DadosAcessoVeculo cnpjTransportador(String cnpjTransportador) { this.cnpjTransportador = cnpjTransportador; return this; } /** * Nome da empresa transportadora.&lt;br/&gt;Tamanho: 100 * @return nomeTransportador **/ @JsonProperty("nomeTransportador") public String getNomeTransportador() { return nomeTransportador; } public void setNomeTransportador(String nomeTransportador) { this.nomeTransportador = nomeTransportador; } public DadosAcessoVeculo nomeTransportador(String nomeTransportador) { this.nomeTransportador = nomeTransportador; return this; } /** * Get motorista * @return motorista **/ @JsonProperty("motorista") public DadosMotorista getMotorista() { return motorista; } public void setMotorista(DadosMotorista motorista) { this.motorista = motorista; } public DadosAcessoVeculo motorista(DadosMotorista motorista) { this.motorista = motorista; return this; } /** * Código Siscomex do recinto de destino. Informar apenas no caso de saída do recinto em regime de trânsito.&lt;br/&gt;Tamanho: 15 * @return codigoRecintoDestino **/ @JsonProperty("codigoRecintoDestino") public String getCodigoRecintoDestino() { return codigoRecintoDestino; } public void setCodigoRecintoDestino(String codigoRecintoDestino) { this.codigoRecintoDestino = codigoRecintoDestino; } public DadosAcessoVeculo codigoRecintoDestino(String codigoRecintoDestino) { this.codigoRecintoDestino = codigoRecintoDestino; return this; } /** * Código Siscomex do recinto de origem. Informar apenas no caso de chegada em recinto em regime de trânsito.&lt;br/&gt;Tamanho: 15 * @return codigoRecintoOrigem **/ @JsonProperty("codigoRecintoOrigem") public String getCodigoRecintoOrigem() { return codigoRecintoOrigem; } public void setCodigoRecintoOrigem(String codigoRecintoOrigem) { this.codigoRecintoOrigem = codigoRecintoOrigem; } public DadosAcessoVeculo codigoRecintoOrigem(String codigoRecintoOrigem) { this.codigoRecintoOrigem = codigoRecintoOrigem; return this; } /** * Informar data e hora de partida do veículo da origem sob regime de trânsito.&lt;br/&gt;Formato: &#39;yyyy-MM-ddTHH:mm:ss.SSSZ&#39; * @return dataHoraPartidaOrigem **/ @JsonProperty("dataHoraPartidaOrigem") public String getDataHoraPartidaOrigem() { return dataHoraPartidaOrigem; } public void setDataHoraPartidaOrigem(String dataHoraPartidaOrigem) { this.dataHoraPartidaOrigem = dataHoraPartidaOrigem; } public DadosAcessoVeculo dataHoraPartidaOrigem(String dataHoraPartidaOrigem) { this.dataHoraPartidaOrigem = dataHoraPartidaOrigem; return this; } /** * Modal. Forma como a carga chegou/saiu do recinto, transporte rodoviário ou transporte ferroviário. Conforme tabela domínio.&lt;br/&gt;Domínio:&lt;br/&gt;R - Rodoviário&lt;br/&gt;F - Ferroviário&lt;br/&gt;L - Fluvial * @return modal **/ @JsonProperty("modal") public String getModal() { if (modal == null) { return null; } return modal.value(); } public void setModal(ModalEnum modal) { this.modal = modal; } public DadosAcessoVeculo modal(ModalEnum modal) { this.modal = modal; return this; } /** * Identificação do Gate.&lt;br/&gt;Usar o protocolo do evento de georreferenciamento relativo ao ponto de acesso utilizado.&lt;br/&gt;Tamanho: 36 * @return gate **/ @JsonProperty("gate") public String getGate() { return gate; } public void setGate(String gate) { this.gate = gate; } public DadosAcessoVeculo gate(String gate) { this.gate = gate; return this; } /** * Lista de identificação das câmeras. Usar o protocolo do evento de georreferenciamento para indicar, nesta lista, todas as câmeras que cobrem o Gate por onde o veículo ingressou/saiu. * @return listaCameras **/ @JsonProperty("listaCameras") public List<DadosDaCmera> getListaCameras() { return listaCameras; } public void setListaCameras(List<DadosDaCmera> listaCameras) { this.listaCameras = listaCameras; } public DadosAcessoVeculo listaCameras(List<DadosDaCmera> listaCameras) { this.listaCameras = listaCameras; return this; } public DadosAcessoVeculo addListaCamerasItem(DadosDaCmera listaCamerasItem) { this.listaCameras.add(listaCamerasItem); return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DadosAcessoVeculo {\n"); sb.append(" tipoOperacao: ").append(toIndentedString(tipoOperacao)).append("\n"); sb.append(" idEvento: ").append(toIndentedString(idEvento)).append("\n"); sb.append(" dataHoraOcorrencia: ").append(toIndentedString(dataHoraOcorrencia)).append("\n"); sb.append(" dataHoraRegistro: ").append(toIndentedString(dataHoraRegistro)).append("\n"); sb.append(" cpfOperadorOcorrencia: ").append(toIndentedString(cpfOperadorOcorrencia)).append("\n"); sb.append(" cpfOperadorRegistro: ").append(toIndentedString(cpfOperadorRegistro)).append("\n"); sb.append(" protocoloEventoRetificadoOuExcluido: ").append(toIndentedString(protocoloEventoRetificadoOuExcluido)).append("\n"); sb.append(" contingencia: ").append(toIndentedString(contingencia)).append("\n"); sb.append(" codigoRecinto: ").append(toIndentedString(codigoRecinto)).append("\n"); sb.append(" operacao: ").append(toIndentedString(operacao)).append("\n"); sb.append(" direcao: ").append(toIndentedString(direcao)).append("\n"); sb.append(" protocoloAgenda: ").append(toIndentedString(protocoloAgenda)).append("\n"); sb.append(" dataHoraAgenda: ").append(toIndentedString(dataHoraAgenda)).append("\n"); sb.append(" listaManifestos: ").append(toIndentedString(listaManifestos)).append("\n"); sb.append(" listaDeclaracaoAduaneira: ").append(toIndentedString(listaDeclaracaoAduaneira)).append("\n"); sb.append(" listaNfe: ").append(toIndentedString(listaNfe)).append("\n"); sb.append(" listaMalas: ").append(toIndentedString(listaMalas)).append("\n"); sb.append(" tipoGranel: ").append(toIndentedString(tipoGranel)).append("\n"); sb.append(" listaChassi: ").append(toIndentedString(listaChassi)).append("\n"); sb.append(" placa: ").append(toIndentedString(placa)).append("\n"); sb.append(" ufEmplacamento: ").append(toIndentedString(ufEmplacamento)).append("\n"); sb.append(" ocrPlaca: ").append(toIndentedString(ocrPlaca)).append("\n"); sb.append(" oogDimensao: ").append(toIndentedString(oogDimensao)).append("\n"); sb.append(" oogPeso: ").append(toIndentedString(oogPeso)).append("\n"); sb.append(" listaSemirreboque: ").append(toIndentedString(listaSemirreboque)).append("\n"); sb.append(" listaConteineresUld: ").append(toIndentedString(listaConteineresUld)).append("\n"); sb.append(" cnpjTransportador: ").append(toIndentedString(cnpjTransportador)).append("\n"); sb.append(" nomeTransportador: ").append(toIndentedString(nomeTransportador)).append("\n"); sb.append(" motorista: ").append(toIndentedString(motorista)).append("\n"); sb.append(" codigoRecintoDestino: ").append(toIndentedString(codigoRecintoDestino)).append("\n"); sb.append(" codigoRecintoOrigem: ").append(toIndentedString(codigoRecintoOrigem)).append("\n"); sb.append(" dataHoraPartidaOrigem: ").append(toIndentedString(dataHoraPartidaOrigem)).append("\n"); sb.append(" modal: ").append(toIndentedString(modal)).append("\n"); sb.append(" gate: ").append(toIndentedString(gate)).append("\n"); sb.append(" listaCameras: ").append(toIndentedString(listaCameras)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private static String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
If you are looking for wedding entertainment ideas in Westminster then look no further. PianoFactor are an Award winning function band bringing an extensive repertoire of songs and complete audience participation together for an unforgettable night of entertainment. The band consists of 2 Piano Entertainers on their baby grand pianos, a Drummer and a Saxophonist performing songs for all ages. This high energy band will have you on your feet all night long. With a superb selection of entertainment packages you not only get a unique wedding reception band in Westminster but great value for money too. With an endless amount of energy and enthusiasm as well as the reliability the musicians at PianoFactor are renowned for, PianoFactor really are a musical force that cannot be compared to other wedding bands. Whatever your budget or needs PianoFactor can accommodate you, all their shows are based on requests from the audience and every event is unique, helping you make those unforgettable memories that people will talk about for years to come. If you are thinking about Hiring wedding entertainment in Westminster - Then you should definitely consider PianoFactor!
#include "EntityComponent.h" namespace Futura { } // namespace Futura
it("should not create a context for typeof require", function() { require("./typeof").should.be.eql("function"); }); it("should answer typeof require correctly", function() { (typeof require).should.be.eql("function"); }); it("should answer typeof define correctly", function() { (typeof define).should.be.eql("function"); }); it("should answer typeof require.amd correctly", function() { (typeof require.amd).should.be.eql("object"); }); it("should answer typeof define.amd correctly", function() { (typeof define.amd).should.be.eql("object"); }); it("should answer typeof module correctly", function() { (typeof module).should.be.eql("object"); }); it("should answer typeof exports correctly", function() { (typeof exports).should.be.eql("object"); }); it("should answer typeof require.include correctly", function() { (typeof require.include).should.be.eql("function"); }); it("should answer typeof require.ensure correctly", function() { (typeof require.ensure).should.be.eql("function"); }); it("should not parse filtered stuff", function() { if(typeof require != "function") require("fail"); if(typeof require !== "function") require("fail"); if(!(typeof require == "function")) require("fail"); if(!(typeof require === "function")) require("fail"); if(typeof require == "undefined") require = require("fail"); if(typeof require === "undefined") require = require("fail"); if(typeof module == "undefined") module = require("fail"); if(typeof module === "undefined") module = require("fail"); if(typeof module != "object") module = require("fail"); if(typeof exports == "undefined") exports = require("fail"); if(typeof require.include !== "function") require.include("fail"); if(typeof require.ensure !== "function") require.ensure(["fail"], function(){}); });
import { CancellationToken, Disposable, DocumentSelector, FormattingOptions, TextDocument, TextEdit } from 'vscode-languageserver-protocol'; import { DocumentFormattingEditProvider } from './index'; import Manager from './manager'; export default class FormatManager extends Manager<DocumentFormattingEditProvider> implements Disposable { register(selector: DocumentSelector, provider: DocumentFormattingEditProvider, priority?: number): Disposable; provideDocumentFormattingEdits(document: TextDocument, options: FormattingOptions, token: CancellationToken): Promise<TextEdit[]>; dispose(): void; }
package program.geometry; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; /** * This is simple model implementation. * @author Tomasz Kapuściński */ public final class Model { private final Vertex[] vertices; /** * Creates new model with given vertices. * @param vertices vertices to use for new model */ public Model(ArrayList<Vertex> vertices) { this.vertices = vertices.toArray(new Vertex[vertices.size()]); } /** * Returns number of vertices in this model. * @return number of vertices in this model */ public int size() { return vertices.length; } /** * Returns vertex under given index. * @param index index * @return vertex under given index */ public Vertex get(int index) { return vertices[index]; } /** * Stores all vertices into {@code ByteBuffer} object * @param buffer {@code ByteBuffer) object where to store vertices */ public void store(ByteBuffer buffer) { for(Vertex vertex : vertices) { vertex.store(buffer); } } /** * Loads model from .obj file * @param file file to read * @return new model read from file */ public static Model load(File file) { try(BufferedReader reader = new BufferedReader(new FileReader(file))) { ArrayList<VertexCoord> vertexcoords = new ArrayList<>(); ArrayList<Normal> normals = new ArrayList<>(); ArrayList<TexCoord> texcoords = new ArrayList<>(); ArrayList<Vertex> vertices = new ArrayList<>(); HashMap<String, Material> materials = new HashMap<>(); Material material = null; while(true) { String line = reader.readLine(); if(line == null) break; String[] parts = line.split(" "); switch(parts[0]) { case "v": float x = Float.parseFloat(parts[1]); float y = Float.parseFloat(parts[2]); float z = Float.parseFloat(parts[3]); vertexcoords.add(new VertexCoord(x, y, z)); break; case "vt": float u = Float.parseFloat(parts[1]); float v = Float.parseFloat(parts[2]); texcoords.add(new TexCoord(u, v)); break; case "vn": float nx = Float.parseFloat(parts[1]); float ny = Float.parseFloat(parts[2]); float nz = Float.parseFloat(parts[3]); normals.add(new Normal(nx, ny, nz)); break; case "mtllib": loadMaterials(materials, new File(parts[1])); break; case "usemtl": material = materials.get(parts[1]); break; case "f": Vertex[] verts = new Vertex[parts.length - 1]; // attribute parsing for(int i=0; i<verts.length; i++) { String[] temp = parts[i+1].split("/"); int vc = Integer.parseInt(temp[0]) - 1; int tc = Integer.parseInt(temp[1]) - 1; int n = Integer.parseInt(temp[2]) - 1; verts[i] = new Vertex(vertexcoords.get(vc), texcoords.get(tc), normals.get(n), material); } // triangulation int count = verts.length - 2; for(int i=0; i<count; i++) { vertices.add(verts[0]); vertices.add(verts[1+i]); vertices.add(verts[2+i]); } break; } } return new Model(vertices); } catch(IOException ex) { throw new RuntimeException(ex); } } private static void loadMaterials(HashMap<String, Material> materials, File file) { try(BufferedReader reader = new BufferedReader(new FileReader(file))) { Material current = null; int id = 0; while(true) { String line = reader.readLine(); if(line == null) break; String[] parts = line.split(" "); switch(parts[0]) { case "newmtl": current = new Material(parts[1], id); materials.put(parts[1], current); id++; break; case "map_Kd": current.setFilename(parts[1]); break; } } } catch(IOException ex) { throw new RuntimeException(ex); } } }
# Lysimachia tsaii C.M.Hu SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
from collections import deque import re class Formula(object): """ Formula allows translation from a prefix-notation expression in a string to a complex number. This is eventually to be replaced with a cython, c++, or openCL implementation as I'm sure the performance of this class is pretty horrible. """ def __init__(self, formulaString='+ ** z 2 c'): self.formulaString = formulaString self.functions = None """ Compile: This method takes in a the prefix statement and evaluates it for given values z and c. """ def compile(self, c, z): form = deque(self.formulaString.split(' ')) return self.parse(form, c, z) def parse(self, queuestring, c, z=0.0): value = queuestring.popleft() if (value == '+'): return self.parse(queuestring, c, z) + self.parse(queuestring, c, z) elif (value == '-'): return self.parse(queuestring, c, z) - self.parse(queuestring, c, z) elif (value == '*'): return self.parse(queuestring, c, z) * self.parse(queuestring, c, z) elif (value == '/'): return self.parse(queuestring, c, z) / self.parse(queuestring, c, z) elif (value == '^' or value == '**'): return self.parse(queuestring, c, z) ** self.parse(queuestring, c, z) elif (value == 'mod' or value == '%'): return self.parse(queuestring, c, z) % self.parse(queuestring, c, z) elif (value == 'rpart'): return complex(self.parse(queuestring, c, z)).real elif (value == 'ipart'): return complex(self.parse(queuestring, c, z)).imag elif (value == 'z'): return z elif (value == 'c'): return c elif (re.compile('^[\d\.]+').match(value)): return float(value) elif (re.compile('^[\d\.]+[\+\-][\d\.]+i$').match(value)): nums = re.split('[\+\-]', value) return complex(float(nums[0], nums[1][:-1])) else: return EOFError
How to Buy an Engagement Ring Over the Phone | Cohen Bros. You’d be amazed at how many engagement rings I’ve sold over the phone to people who’ve never met me face to face. Customers come from all 50 states, but still some customers wonder how you can possibly buy an engagement ring sight unseen. Well, that’s not exactly true – they can see it via their computers, their phones, on the ring finger of a friend who referred them to me, or by a friend who raved about me. So, why do they call Cohen Bros. Jewelry in New York City when they live in Chicago or Dallas or Des Moines, Iowa? Because a brother, a college roommate, a business associate, or a friend told them to call. Almost always, the customer who calls says they know someone who had a good experience with me. What shape diamond would they would like? What’s the ball park budget? Once that’s answered, I can usually point out some pretty good options. I don’t sell low end diamonds so I am NEVER going to let my customer buy something that isn’t nice, but there is always a little trade off between size and quality. Some people want the best possible quality that they can get in their budget. Some people are willing to give up a little quality in order to get a larger diamond. All the options are good, the only piece of advice that I always give the guys is to get his girlfriend whatever shape diamond SHE likes. She is the one that will be wearing it. Guys, if you love a round brilliant cut diamond and you know that she would prefer a cushion-cut diamond, get her the cushion-cut. The rest (size, quality and budget) is up to you. Picking the setting over the phone is easy too. When a guy is about to buy an engagement ring, he usually has some idea of what kind of a setting she would like. At some point during their relationship she managed to impart that piece of information to him. However, sometimes they don’t know and really have no idea. How do we pick a setting then? I always tell the guys that if they have no idea what kind of setting she wants, then the simpler the better. DO NOT BE CREATIVE here or more likely than not I’m going to have to redo it. Sometimes just a plain 6-prong platinum or white gold setting is perfect for a round diamond. If he’d like to see some pictures he can always come back to my website here and look at “engagement rings” or “wedding sets” in the photo gallery to see some rings that we’ve made in the past.
ANNAPOLIS, Md. (AP) — Navy coach Ken Niumatalolo justifiably focused on fixing his team’s defense in the wake a season-opening 59-41 loss to Hawaii. After losing two big-time playmakers, quarterback Riley Ferguson and wide receiver Anthony Miller, the Tigers simply reloaded. Graduate transfer Brady White appears to be a more than ample replacement at quarterback and Damonte Coxie has taken over as the go-to receiver. White completed 22 of 28 passes for 358 yards and five touchdowns to lead Memphis to a 66-14 rout of Mercer in the season opener. White appeared in just three games at Arizona State before suffering a foot injury that caused him to miss the remainder of the 2016 season and all of 2017. He has two years of eligibility remaining with the Tigers after arriving in January. “The level of work that went into his preparation, the way he’s learned the offense, the time he’s spent building the relationships with his teammates. he’s a great young man,” said Memphis coach Mike Norvell, who recruited White at Arizona State while offensive coordinator in Tempe. Navy was befuddled by Hawaii’s run-and-shoot attack on Saturday night in Honolulu, giving up 522 total yards. While the Rainbow Warriors looked sharp, Niumatalolo knows several AAC schools are capable of doing similar damage if the Midshipmen don’t get some things corrected. Memphis amassed 752 yards against Mercer, one yard shy of the school record. Coxie had four catches for 79 yards and a touchdown after performing well in a limited role last year. Tailback Calvin Austin III broke loose for an 83-yard touchdown run, and Darrell Henderson rushed for 76 yards and a score. Memphis has been picked to repeat as West Division champion in the AAC. Now in his third season, Norvell is 19-8 with the Tigers. “You never know how your team is going to respond when the lights come on, so I like what I saw in Game 1,” he said. Navy and Memphis have both been in contention for the West Division title ever since the Midshipmen joined the conference four years ago. The Midshipmen beat the Tigers 45-20 at the Liberty Bowl in 2015 then won by a similar score (42-28) in Annapolis the following season. Memphis forced five turnovers to nip Navy 30-27 last season and won the West with a 7-1 record. Niumatalolo meticulously planned Navy’s road trip to Hawaii in hopes of lessening the impact of the long flights and ensuing jet lag on the players. The 11th-year head coach had a dual purpose in doing so: to ensure the Midshipmen did not tire against Hawaii and were able to bounce back on short rest for Memphis. Navy’s return flight landed Monday morning and the coaching staff had to play catchup the rest of the day to prepare for Memphis. The Midshipmen were back on the practice field on Tuesday in an attempt to maintain a normal game week schedule. “Hopefully, by Saturday we’ll be totally adjusted back to East Coast time,” Niumatalolo said. Memphis coaches and players acknowledged spending time preparing for Navy’s triple-option during spring camp and preseason practice. Defensive coordinator Chris Ball said the Tigers have been gearing up for Navy, off and on, for six months. Last season, the Tigers limited the Midshipmen to 314 rushing yards, almost 100 below their season average. Memphis intercepted two passes and recovered three fumbles. Navy has 20 players from the state of Tennessee on its roster, including several from the greater Memphis area. Senior safety and defensive captain Sean Williams attended Cordova High in Memphis. Starting quarterback Malcolm Perry hails from Clarksville, the fifth-largest city in the state.
<div class="modal fade" id="modal-plan-details" tabindex="-1" role="dialog"> <div class="modal-dialog modal-sm"> <div class="modal-content" v-if="detailingPlan"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title"> @{{ detailingPlan.name }} </h4> </div> <!-- Modal Body --> <div class="modal-body"> <ul class="plan-feature-list p-b-none m-b-none"> <li v-for="feature in detailingPlan.features"> @{{ feature }} </li> </ul> </div> <!-- Modal Actions --> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div>
<?php /** * PureMVC PHP Employee Admin Demo by Sasa Tarbuk <[email protected]> * PureMVC - Copyright(c) 2006-2010 Futurescale, Inc., Some rights reserved. * Your reuse is governed by the Creative Commons Attribution 3.0 Unported License */ class UserListMediator extends Mediator { const NAME = 'UserListMediator'; public $userList; private $userProxy; public function __construct (UserListComponent $userList) { parent::__construct (self::NAME, $userList); $this->userList = $userList; } public function onRegister () { $this->userList->addEventListener (UserListComponent::E_NEW, $this, 'onNew'); $this->userList->addEventListener (UserListComponent::E_DELETE, $this, 'onDelete'); $this->userList->addEventListener (UserListComponent::E_SELECT, $this, 'onSelect'); $this->userProxy = $this->facade->retrieveProxy (UserProxy::NAME); $this->userList->setUsers ($this->userProxy->users); } public function listNotificationInterests () { return array ( AppFacade::CANCEL_SELECTED, AppFacade::USER_ADDED, AppFacade::USER_UPDATED ); } public function handleNotification (INotification $note) { switch ($note->getName ()) { case AppFacade::CANCEL_SELECTED: $this->userList->deSelect (); break; case AppFacade::USER_ADDED: $refID = $this->userProxy->getIndex ($note->getBody ()); $this->userList->addUser ($refID, $note->getBody ()); break; case AppFacade::USER_UPDATED: $refID = $this->userProxy->getIndex ($note->getBody ()); $this->userList->updateUser ($refID, $note->getBody ()); $this->userList->deSelect (); break; } } public function setWindow ($window) { $this->userList->window = $window; } public function onNew () { $this->sendNotification (AppFacade::NEW_USER, new UserVO ()); } public function onDelete () { $this->userList->deleteUser ($this->userList->selectedUserRefID); $user = $this->userProxy->users [$this->userList->selectedUserRefID]; $this->sendNotification (AppFacade::DELETE_USER, $user); } public function onSelect () { $user = $this->userProxy->users [$this->userList->selectedUserRefID]; $this->sendNotification (AppFacade::USER_SELECTED, $user); } }
package com.marcelherd.uebung2.eis.vendor; public class BerlinerKaramelBecher extends Eis { BerlinerKaramelBecher() { setName("Karamel Becher"); setBehaeltnis("Becher"); setArt("Bällchen"); setSorten(new String[] { "Vanille", "Karamel" }); setExtras(new String[] { "Karamelsoße", "Krokant Streußeln", "Sahne" }); setPreis(4.5d); } /** * {@inheritDoc} */ @Override void vorbereiten() { System.out.println(getName() + " wird im " + getBehaeltnis() + " vorbereitet."); } /** * {@inheritDoc} */ @Override void fuellen() { System.out.println(getName() + " wird mit " + getArt() + " der Sorten " + String.join(", ", getSorten()) + " befüllt."); } /** * {@inheritDoc} */ @Override void dekorieren() { System.out.println(getName() + " wird dekoriert mit " + String.join(", ", getExtras())); } }
Ubd Lesson Plan Template Editable ubd lesson plan template editable screenshot of the ubd lesson plan template 4th grade spelling template. ubd lesson plan template editable unit plan and lesson plan templates for backwards planning ideas. ubd lesson plan template editable unit plan and lesson plan templates for backwards planning templates. Ubd Lesson Plan Template Editable ubd lesson plan template editable editable ubd lesson plan template google docs 260511200036 download. ubd lesson plan template editable editable weekly lesson plan template awesome 23 of ubd lesson plan download. ubd lesson plan template editable ubd daily lesson plan template google docs ubd lesson plan template template. Ubd Lesson Plan Template Editable ubd lesson plan template editable ubd lesson plan template word ubd lesson plan template 564d8c7b0c50 download. Ubd Lesson Plan Template Editable ubd lesson plan template editable unit plan and lesson plan templates for backwards planning ideas. ubd lesson plan template editable unit plan and lesson plan templates for backwards planning templates. ubd lesson plan template editable editable ubd lesson plan template google docs 260511200036 download. ubd lesson plan template editable editable weekly lesson plan template awesome 23 of ubd lesson plan download. ubd lesson plan template editable ubd daily lesson plan template google docs ubd lesson plan template template.
The Biology and Personalized Treatment of Lung Cancer: The Yale SPORE in Lung Cancer (YSILC) coalesces translational scientists spanning all aspects of cancer research to converge on the lung cancer problem. The YSILC leverages existing Yale Cancer Center (YCC) strengths including immunobiology, microRNA research, experience with anti-EGFR treatments with acquired resistance, and the behavioral interventions/biological underpinnings of smoking cessation. The goal of the YSILC program is to improve the overall survival rate of lung cancer patients by developing novel therapeutics and personalized prevention strategies based on an understanding of the targetable biochemical and immunological pathways involved in the progression of lung cancer and the acquisition of resistance to therapy. The YSILC translational research team will accomplish this objective through five specific aims: Specific Aim 1: Develop and test novel therapeutics by discovering the mechanisms underlying the response and resistance to anti-PD-1 and anti-B7-H1 (PD-L1) therapies; Specific Aim 2: Evaluate the potential of non-coding microRNAs as targeted therapies; Specific Aim 3: Understand and target the EGFR pathway in mutant/resistant lung cancer; Specific Aim 4: To develop and test the efficacy of a new personalized approach to gain-framed messaging to improve smoking cessation in Americans with asymptomatic lung nodules who continue to smoke; and Specific Aim 5: To develop new research directions and nurture the next generation of translational investigators in lung cancer through a Developmental Research Program and a Career Development Program. Three cores (Administrative; Biostatistics and Bioinformatics; and Biospecimen, Pathology, and Genomics) are proposed to support the projects and their clinical aims, mechanistic studies, and evaluation of biomarkers for clinical application. The highly coordinated YSILC projects, cores, and programs are focused on developing novel lung cancer therapies, with analysis of patient samples, cell-based assays, production of human cell lines and animal models of disease as a guide to design prospective trials that translate these innovative targeted approaches to clinical therapies. The expected translational outcomes of the program include: (1) A highly coordinated and focused development of novel lung cancer therapies; (2) an improved understanding of resistance pathways to PD-1/B7-H1 blockade and EGFR therapies, including prospective studies to overcome/prevent these effects; (3) an understanding of the therapeutic potential of miRNAs in patients; (4) development of effective smoking cessation methods while exploring correlative mechanistic markers; and (5) the development of the next generation of investigators. Recent evidence suggests that tumors may exploit immune inhibitory mechanisms to create a barrier against antitumor immune responses — including endogenous inflammatory immune responses and those induced by immunotherapies. One key mechanism appears to be mediated by the programmed death-1 (PD-1)/B7 homolog 1 (B7-H1) pathway, which restrains antitumor T cell function in the tumor microenvironment (TME). PD-1 is induced on the surface of activated T cells and, after engaging its ligand, down-modulates T cell functions. Our early studies include cloning and identification of B7-H1 (PD-L1, CD274) as an inhibitory ligand for T cell response and characterization of B7-H1 as a major ligand for PD-1 in suppressing tumor immunity in TME. We demonstrated that B7-H1 was upregulated on the cell surface by inflammation (mainly via IFN-gamma), and that high levels of B7-H1 expression were found in many human cancers including non-small cell lung cancer (NSCLC). Blocking the interaction of B7-H1 on tumor cells with PD-1 on tumor-specific T cells can eliminate this barrier in the TME and protect ongoing antitumor immunity, leading to tumor regression in mouse tumor models. Recent clinical trials have demonstrated that anti-PD-1 or anti-B7-H1 monoclonal antibodies (mAb) induced objective clinical responses in a significant fraction of patients with advanced chemo-refractory metastatic NSCLC. Responses were highly durable with manageable toxicity. While these clinical findings are promising, it is now critical to better understand the effects of PD-1/B7-H1 blockade on antitumor immunity and to develop new strategies to overcome resistance. In this project, we will test the hypothesis that NSCLC is immunologically heterogeneous and only a subgroup of NSCLC with membranous B7-H1 (PD-L1) expression on cancer cells and the presence of functional tumor-infiltrating lymphocytes (TILs) will respond to anti-PD-1/B7-H1 therapy, whereas resistance to anti-PD-1/B7-H1 therapy is largely mediated via PD-1/B7-H1-independent suppressive pathways. We will identify subgroups of NSCLC patients who respond to and resist anti-PD-1/B7-H1 therapy by analysis of B7-H1 expression and immune responses in the TME. In addition, we will delineate cellular and molecular mechanisms underlying resistance to anti-PD-1/B7-H1 therapy in each NSCLC subgroup. Finally, we will maximize the therapeutic effect of PD-1/B7-H1 blockade by additionally targeting resistance mechanisms using mouse models with induced lung cancer. The current project integrates basic and clinical sciences, and will use animal models and human specimens in the context of ongoing clinical trials of anti-PD-1 and B7-H1 antibodies to achieve the goals. Taken together, results from our studies will enhance future anti-PD-1/B7-H1 therapy and potentially lead to novel immune-based therapies for lung cancer. Patients with metastatic non-small cell lung cancer (NSCLC) remain incurable with few options. New therapies are critically needed. In this project we propose to translate a fundamental understanding of microRNAs (miRNAs) in NSCLC. The EGFR/RAS and p53 pathways are the most frequently dysregulated pathways in NSCLC and are regulated in part by two miRNAs, miR-34and let-7, tumor suppressors that regulate key lung cancer oncogenes such as KRAS andare lost or poorly expressed in many lung tumors. miR-34 is directly up-regulated by p53 and is one of the most important outputs of p53 signaling. We will test the hypothesis that a novel miRNA-based therapeutic strategy focused on miR-34 reverses NSCLC tumor phenotypes. Preliminary data generated from our lab shows that MRX34, a nanoparticle encapsulated mir34 molecule, provides a benefit in Kras and in Kras;p53 mutant NSCLC mouse models. Our goal is to evaluate MRX34 in patients with metastatic NSCLC while incorporating novel imaging methods to determine drug delivery and effect. In Specific Aim 1 we will investigate miR-34 therapeutics in NSCLC mouse models. We have preliminarily shown that miR-34 administered to KRAS or KRAS;p53 mutant tumor cells blocks proliferation and induces apoptosis, including when delivered systemically as MRX34 to Kras or Kras;p53 mutant mouse models. We propose to investigate efficacy and optimal dosingand scheduling of MRX34 using mouse models; test the effects of MRX34 in combination with drugs known to be active against NSCLC in vitro in KRAS; p53 NSCLC cell lines and in vivo and test if MRX34 treatment shows therapeutic potential in EGFRL858R;p53, and erlotinib-resistant EGFRT790M;p53 mutant mice (in collaboration with Dr. Katie Politi [Project 3]). In Specific Aim 2 we will investigate if MRX34 is delivered to the appropriate tissues and engages its targets. We propose to discover serum and tumor biomarkers in the Kras and Kras;p53 mutant mice treated with MRX34 that will be useful for PK, PD, and efficacy analyses in the clinical trial proposed in Aim 3; to apply 18F-ICMT-11 PET imaging of caspase-3 to measure MRX34-induced apoptosis in lung tumors in Kras;p53 mice. We will radiolabel MRX34 particles with F-18 and if successful, incorporate this as an imaging endpoint to validate magnitude and kinetics of particle delivery to in these models. In Specific Aim 3 we will conduct a clinical trial with MRX34 in patients with NSCLC preselected based on genotype, evaluating response/efficacy and PD endpoints to assess drug delivery and drug:target effects using both novel imaging tools developed in Aim 2 (18F-labelled MRX34 nanoparticle) as well as direct tumor signal transduction effects using 18F-ICMT-11 (caspase) as an exploratory biomarker for drug-induced apoptosis. Patient biopsies will be genotyped for the KRAS, EGFR and p53 status, and tumor and serum miR-34 (and let-7) levels determined. These data will be correlated with outcome and could inform patient selection in these and future trials. Lung adenocarcinomas (LUADs) frequently harbor mutations in genes encoding components of the Epidermal Growth Factor Receptor (EGFR) signaling pathway. Mutations are found in EGFR itself, related receptor tyrosine kinases (RTKs) and in downstream signaling molecules. Emerging evidence from sequencing studies of LUADs by our group and others has also revealed mutations in genes encoding negative regulators of RTKs including the CBL proto-oncogene, an E3 ubiquitin ligase that targets EGFR for degradation. Despite the convergence of these genetic alterations on related and overlapping signaling pathways, each specific mutation determines the sensitivity of the disease to different therapies and defines unique clinical subsets of lung cancer each with its own set of characteristics. For example, mutations in EGFR are the only genetic alteration associated with sensitivity to the tyrosine kinase inhibitors (TKIs) gefitinib and erlotinib. Tumors with these mutations represent a paradigm for the use of targeted therapies in lung cancer. However, responses to EGFR TKIs are not sustained and tumors become resistant on average within a year after drug-treatment is initiated. Acquired resistance to therapies targeting the EGFR is a major impediment to cures or durable responses for these patients. For other subsets of tumors, such as those harboring mutations in CBL, very little is known to date on the biology and drug sensitivity of these tumors. In this project, centered on the EGFR pathway in LUADs, we seek 1) to clarify the mechanisms of acquired resistance to EGFR-directed therapies in EGFR mutant LUADs, 2) to develop rational approaches to overcome resistance to EGFR-directed therapies and, 3) to understand the vulnerabilities of LUADs with mutations in other genes that control EGFR signaling. The use of computed tomography (CT) for medical evaluation for lung cancer screening has resulted in a growing number of patients identified with pulmonary opacities, or lung "nodules". Patients with lung nodules are at heightened risk of lung cancer; for those who currently smoke, cessation is the most important strategy available to reduce lung cancer risk. To date, there has been no research on tobacco cessation in lung nodule patients, who may have unique attributes (e.g., anxiety about having a nodule coupled with tobacco dependence) that warrant research for the development of maximally effective tobacco cessation interventions. We thus have designed and propose to evaluate 2 novel behavioral interventions as adjuncts to pharmacotherapy. Intervention 1 is based on a large body of research on gain-framed messages for promotion of smoking cessation, which in this case will be designed and personalized specifically for patients with lung nodules, to increase rates of quitting. Intervention 2 is based on our findings that tobacco cessation leads to improvements in health biomarkers (skin carotenoids, plasma bilirubin), and this information can be fed back to participants to prevent relapse and promote longer-term cessation. Specifically, we will enroll and randomize patients with lung nodules to Intervention 1, consisting of a personalized video and print intervention, emphasizing the benefits (gain-framed) of quitting smoking, to evaluate the hypothesis that this will improve tobacco quit rates above and beyond standard of care smoking cessation treatment over 8 weeks. Then we will perform a second randomization to Intervention 2, an individual-level, biofeedback intervention to examine the hypothesis that this intervention will reduce smoking at 6 months. In addition, we propose to evaluate the impact of smoking cessation on microRNA profiles in human serum, with particular interest in levels of the let-7 family of microRNAs, to better understand the biological mechanisms by which smoking cessation reduces lung tumor promotion and to explore another potential biomarker of cessation. Blood/DNA will also be banked to support future biomarker-based studies. Overall, this project aims to develop transferable interventions to improve short- and longer-term smoking cessation rates in this understudied high-risk patient population, while also evaluating mechanisms involving tobacco carcinogenesis, with clear translational potential. The goal of the Biostatistics and Bioinformatics Core (Core B) is to address the statistical design and analysis needs of the Yale SPORE in Lung Cancer (YSILC) Projects, the other Cores, the Developmental Research Program (DRP), and the Career Development Program (CDP). To accomplish this goal we have assembled a highly interactive team of cancer biostatisticians and bioinformaticians who will work collaboratively with basic, clinical, translational, and population science researchers to advance the frontiers of cancer medicine. The specific aims of the Biostatistics and Bioinformatics Core are: Aim 1: Provide collaboration and consulting in the design and analysis of basic, translational, population and clinical studies for YSILC; Aim 2: Oversee data management and ensure that data collected on all YSILC studies are of high quality and evaluated with statistical rigor; and Aim 3: Design and monitor the statistical conduct of clinical trials, ensuring data are collected and evaluated with statistical rigor and innovation. For Aim1 the Core will address the analytic and informatics questions arising from the SPORE projects. Services provided by the Core will range from planning activities to consulting on specific analytic questions. More specifically, the Core will schedule regular meetings with the YSILC investigators, and maintain an open door policy for any biostatistical and bioinformatics questions. For Aim 2 the Core will work closely with the investigators to analyze clinical trial data, next generation sequencing data, and bioinformatics data mining. For Aim 3 the Core will design and monitor the statistical aspects of clinical trials for safety, efficacy and futility. Since the observed data can have characteristics different from what was hypothesized, the Core will conduct regular interim analyses, dynamically update the power calculations, develop new statistical and bioinformatics methodology as needed, provide timely suggestions to YSILC investigators, and thus play an important role in the projects in the YSILC. Biostatistics and Bioinformatics is also a key partner in the YSILC with representation on their Senior Leadership Team and participation in all core meetings. The Biospecimen, Pathology and Genomics Core for the Yale Lung Cancer SPORE will serve as the nexus for all human biospecimen acquisition, processing and analysis for all SPORE-sponsored research as well as provide support for all non-human model system specimen molecular analytics not currently offered through Yale shared facilities. Tissue biopsy procurement will be coordinated with all interventionalists and surgeons as this occurs at the bedside or in the operating room with research tissues derived from extra passes of the biopsy needle after the diagnostic specimen has been collected or collection at the surgical pathology bench. The Biospecimen, Pathology and Genomics Core will work closely with Yale Pathology Tissue Services, the research tissue procurement service supported within the Department of Pathology (also directed by David Rimm) to obtain fresh resection specimens. Specifically the Biospecimen, Pathology and Genomics Core will: 1) coordinate the acquisition, processing, aliquoting, storage and distribution for all whole blood samples and their derivatives (e.g., plasma, serum, buffy coat) required for the described research in Projects 1-4 as well as the Developmental and Career Development Award Programs’ approved projects; 2) coordinate the acquisition, handling, storage and distribution for all lung cancer tissue sample collection required for Projects 1-4, Developmental and Career Development Awards; 3) generate conditionally reprogrammed primary lung cancer cell lines from fresh tissue samples for use in Projects 1-3; and 4) conduct molecular pathology experiments including partial support of whole exome sequencing, RNA-Seq and Copy Number Variation analysis (Projects 2 and 3); quantitative microRNA in situ hybridization (Projects 1 and 2) and other molecular pathology support as needed during the term of the SPORE.
Maca root( lepidium meyenii) is very adaptable plant, related to the family of vegetables like cabbage and broccoli,but because of his unique characteristics is considered as one of world’s natural “super food”. Usually is found on high mountains in South America especially at very high altitude mostly in Peru. The root generally is consumed in powder,has specific taste and can be found in drugstores or healthy food stores. Benefits of Maca root include a hormonal balance,Increases energy and makes you stronger,improves the mental well-being. We are not only talking about natural source of “healing” nutrients,but for a safe “super food” that has been used thousands and thousands of years ago from people native to Andes of Peru. Other benefits of Maca root are increased fertility in men and women, stronger immunity, also increases libido and energy which offer a better sexual performance, improves memory and concentration.Helps body to adjust on everyday stress,hard work, diseases etc. Another original characteristic of Maca root is that through the history was considered as very powerful aphrodisiac and fertility secret of the populations that lives in Andes. Consummation of Maca root makes people feeling more live and full of energy, thanks to its ability to balance hormones and to increase ” good” endorphins , leaves a sensation of wellbeing. Another benefit of Maca root is the high amount of nutrients like proteins,fibers, vitamins C and B6, copper ,iron, potassium, manganese,zinc,, phosphorus, selenium, sulphur etc. Contains about 18% proteins,76.5% carbs,5%fats and 8.5%fibers including also more than 20 amino acids and 8 essential amino acids, 20 free fatty acids like lauric, linoleic, palmitic,oleic and stearic acid. According to experts, there is no optimal dose of Maca root powder but many people are starting with one coffee spoon and after few months of consummation, take 2 but not more than 3 coffee spoons. Since increases the strength,many people are using it before doing exercises. Helps in renewing sexual, hormonal and mental health ,despite the fact that is not holding real hormones. Improves PMS syndrome, polycystic ovarian syndrome and menopause , thanks to its control of estrogen in the body. Too low or too high levels of estrogen , makes ovulation and pregnancy difficult and that’s why controling the estrogen and the progesterone as well,is very important for reproduction and fertility,then decreases the symptoms of irregular periods and excess body and facial hair. A study from 2008 of “Menopause” magazine, showed that Maca root lifts woman’s mood during the menopause and suppress depressions and anxiety.The same study talks about increasing of libido in men and women because of high level of serotonin (hormon of happiness). Another study where Maca root was given to female animals, showed that ovarian follicles was growing very well, which is important for reproduction. Its influence on endocrine system is renewing the hormones of these glands especially helps in the health production of thyroid hormones and hormones of the adrenal glands. These two glands have major role in regulation of emotions, starting from stress levels to returning the health appetite.Feeling great meens to have healthy endocrine glands. Clinical studies showed no change of serum level of testosterone by using Maca root, but the consumation of Black Maca has shown increasing of sperm production,much more comparing to Red and Yellow Maca. Red Maca appears as suppressor of prostate hypertrophy, has a positive effect on spermatogenesis and sexual dysfunction. Those who are consuming regularly the powder of Maca root,talks that are more concentrate and full of energy, unlike from coffee, doesn’t feel irritations or the feeling that your body shakes. Even clinical studies proved the positive impact on the people’s mood, energy and strength. How is Maca increasing the energy it’s not known yet, but scientists believes that’s happening through regulation of sugar level in the blood and hormones of adrenal glands. The key moment is the influence of Maca on hypophysis, the conductor of all glands, which shows how important impact has this root on people’s mental health. Maca root works as a natural antioxidant, increase the levels of glutathione and superoxide dismutase,the two biggest disease fighters. Recent studies shows that Maca root has ability to prevent the development of chronic diseases defined with high levels of bad cholesterol, disorders of glucose tolerance etc. This is important for those who have cardiovascular problems,diabetes or metabolic syndrome. Maca root powder can be consumed in the morning instead coffee or it can be added (1 coffe spoon) in milk, yogurt, tee or in your favorite smoothie and oatmeals and it can be found at health food stores,some supermarkets or online. It is available also as 500mg capsules or as a liquid extract.
Unlike the other EAP225 models, which have a Gigabit uplink port, the EAP225-Wall only has a Fast Ethernet uplink port. This is something of a bottleneck as both wireless bands can easily flood that 100 Mbps separately, leave alone together. Include the three Fast Ethernet Downlink Ports and congestion is guaranteed. That Uplink Port should have been a Gigabit Port like in the other EAP225 products. NB: I do have the EAP225-Wall as it is the right physical size for the only practical installation place, most of the rest of the internal network is at Gigabit and the internet connection is also a nice margin above 100 MBps. Thanks for your feedback, your suggestion is important for us, we will keep improving our products.
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <math.h> bool isPrimeNumber(size_t number) { size_t i; size_t max = sqrt(number) + 1; if (number == 1 || number == 2) return true; for (i = 2; i <= max; i++) { if (number % i == 0) return false; } return true; } int main(int argc, char *argv[]) { size_t max, i; if (argc != 2) { fprintf(stderr, "prime_numbers [maximum_value]\n"); return EXIT_FAILURE; } max = atoi(argv[1]); for (i = 1; i <= max; i++) { if (isPrimeNumber(i)) fprintf(stdout, "%zu\n", i); } return EXIT_SUCCESS; }
# use nginx to get anyport of specific url ## set proxy domain `vim /etc/hosts` add record `127.0.0.1 proxy.local` ## add nginx conf `vim /etch/nginx/site-availiable/proxy` add record ```nginx conf server { server_name proxy.local; # server_name "~^(?P<fwd_port>\d+)\.proxy\.local"; location ~ ^/([\d]+)/(?<fwd_path>.*)$ { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. resolver 8.8.8.8; add_header Access-Control-Allow-Origin "*"; proxy_pass http://127.0.0.1:$1/$fwd_path$is_args$args; proxy_redirect off; access_log on; } } ``` ## enable proxy conf ` ln -s /etc/nginx/site-enabled/proxy /etc/nginx/site-enabled/proxy` ## start service ` service nginx start`
As the owner of more than 200 residential buildings and of a number of commercial buildings, the SHDM regularly uses the services of a large number of contractors to perform all kinds of work. Electricians, plumbers, general contractors, installers and repairers of equipment such as elevators are regularly asked to intervene in our different properties. Companies who would like to be on our supplier list may fill out a form to be included. SHDM can then use the information to select potential suppliers based on its needs for calls for tenders or requests for quotes. SHDM will perform due diligence as needed to ensure companies are eligible to receive contracts. SHDM may occasionally email information about public calls for tenders and proposals to companies on the list. Receive our calls for tenders, calls for proposals and requests for quotes. With a real estate portfolio consisting primarily of buildings that were constructed several decades ago, the SHDM must regularly undertake large-scale works, such as roof repairs, replacement of equipment or structural work. Current regulations demand that all contracts over $100,000 be subject to a process of public calls for tenders to be published on the online tendering system of the Québec government at www.seao.ca. Relying on the many professionals and specialists in its team, the SHDM has developed an expertise that benefits its suppliers. We understand the challenges facing our partners and we have an efficient process for the allocation of contracts, the management and verification of work and the payment of bills (30 days or less).
class Admin::ClothingFieldsController < Admin::BaseController before_action :set_clothing_field, only: [:show, :edit, :update, :destroy] # GET /clothing_fields # GET /clothing_fields.json def index @clothing_fields = ClothingField.all end # GET /clothing_fields/1 # GET /clothing_fields/1.json def show end # GET /clothing_fields/new def new @clothing_field = ClothingField.new end # GET /clothing_fields/1/edit def edit end # POST /clothing_fields # POST /clothing_fields.json def create @clothing_field = ClothingField.new(clothing_field_params) respond_to do |format| if @clothing_field.save format.html { redirect_to admin_clothing_field_path(@clothing_field), notice: 'Clothing field was successfully created.' } format.json { render :show, status: :created, location: admin_clothing_field_path(@clothing_field) } else format.html { render :new } format.json { render json: @clothing_field.errors, status: :unprocessable_entity } end end end # PATCH/PUT /clothing_fields/1 # PATCH/PUT /clothing_fields/1.json def update respond_to do |format| if @clothing_field.update(clothing_field_params) format.html { redirect_to admin_clothing_field_path(@clothing_field), notice: 'Clothing field was successfully updated.' } format.json { render :show, status: :ok, location: admin_clothing_field_path(@clothing_field) } else format.html { render :edit } format.json { render json: @clothing_field.errors, status: :unprocessable_entity } end end end # DELETE /clothing_fields/1 # DELETE /clothing_fields/1.json def destroy @clothing_field.destroy respond_to do |format| format.html { redirect_to admin_clothing_fields_path, notice: 'Clothing field was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_clothing_field @clothing_field = ClothingField.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def clothing_field_params params.require(:clothing_field).permit(:name, :type, :func) end end
New Johns Hopkins research showing a more than four-fold increase in the incidence of breast cancer in women with neurofibromatosis-1 (NF1) adds to growing evidence that women with this rare genetic disorder may benefit from early breast cancer screening with mammograms beginning at age 40, and manual breast exams as early as adolescence. In a small study of 126 women with NF1 at the Johns Hopkins Comprehensive Neurofibromatosis Center, the Johns Hopkins scientists identified four cases of breast cancer. The study showed a four-fold increased risk for breast cancer in women with NF1 compared to the general population of women under the age of 50. NF1 is characterized by the uncontrolled growth of mostly non-cancerous tumors along the body’s nerves, often resulting in pain and disfigurement. Beyond their implications for breast cancer screening guidelines for women with NF1, the findings may also shed light on the origins and nature of breast cancer in those without the syndrome, the researchers say, because other recent studies suggest that some women without neurofibromatosis-1 had breast cancers fueled primarily by an NF1 mutation. A recent study, for example, described in the journal Nature, estimated that 3 percent of all breast cancers in the general population are caused by NF1 mutations that arise spontaneously. The major implication of their study, Blakeley says, is the need for medical specialty societies to develop guidelines recognizing NF1 patients under the age of 50 as a group at increased risk for breast cancer. Guidelines developed by medical societies would change clinical practice and, just as importantly, encourage insurance companies to pay for potentially lifesaving screening in younger women with the debilitating disease, the researchers add. Blakeley, director of the Johns Hopkins Comprehensive Neurofibromatosis Center, says she recommends that her NF1 patients get a manual breast exam from a physician annually, beginning in their teens. She recommends mammograms beginning at age 40, 10 years earlier than current National Cancer Institute guidelines for the general population. Research has not yet determined the ideal time for NF1 patients to get their first mammograms; some physicians suggest age 30, the age recommended for women with BRCA mutations. Blakeley says that because radiation exposure can sometimes trigger benign tumors to change to malignant tumors in NF1 patients, she worries about an extra 10 years of radiation exposure due to mammography. The normal Nf1 gene is one of a number of so-called tumor suppressor genes. Roughly one in 3,000 Americans (equal numbers of males and females) has a mutated copy that no longer functions properly and allows tumors to grow unchecked. About half of people with NF1 inherit an Nf1 gene mutation from a parent, and the other half are the first in their family to have an Nf1 gene mutation. In people with NF1, tumors often are on, or just below, the skin and can be disfiguring and painful, depending on where they are located. They can also appear in the brain and large nerves of the body, resulting in neurologic injury. Sometimes the tumors are surgically removed or treated with chemotherapy or radiation. However, these interventions can be risky and do not result in a cure, so many of those affected must live with the tumors and the disfigurement or pain that may accompany them, says Amanda Bergner, M.S., CGC, an assistant professor of genetics and neurology at Johns Hopkins who contributed to the research. The study by Blakeley and Bergner, along with Sara Madanikia and Xiaobu Ye, M.D., all of Johns Hopkins, confirms data in another study published in the same issue of the journal, and two European studies published in recent years. An editorial by D. Gareth Evans of the University of Manchester, accompanying their article, also calls for the development of aggressive screening guidelines for women with NF1. The research was supported by the Johns Hopkins Predoctoral Clinical Research Training Program, grant number 1TL1RR-025007, funded by the National Center for Research Resources, part of the National Institutes of Health.
Students often complain about the excessive amount of homework assignments. You have to write a review on a huge book you have never read before, compose a chemistry lab report and write an essay about the artists of Renaissance. And the worst thing is that you have to do all of these tasks for tomorrow. We understand that the last thing you want is failing the course, so the time has come to ask for some real essay writing help. RealEssay.co.uk is a true essay writing service, because we deliver well-composed, 100% unique papers on time. We are proud of our writing team, because it consists of educated, knowledgeable, hard-working professionals always ready to help a student in need. You are free to contact us at any time of day and night, and we will gladly respond. Our main priority is your needs. Where can you get the best custom writing help in UK? The most reliable and professional UK essay writing help can be easily reached at RealEssay.co.uk. After years of experience, our company became one of the most reliable and trusted in the industry. Read on to learn more about the amazing benefits and services we provide. When you have a number of boring and complicated papers to be done in a short amount of time, our writers can handle it. We deliver a wide range of writing services and, therefore, you can get any kind of paper help right here. We can write term papers, reviews, lab reports, research papers, dissertations, and any other written works that you may need. Even if your paper is urgent, you don’t have to worry about that: our writers can cope with it easily without compromising quality. Our writers have Master’s and Ph.D. degrees in different disciplines, which means that here you will get the best custom writing help in UK. We deliver essay help to students from all over the world. That is why our support team works 24/7, and they are always ready to answer your questions via phone, email, or live chat. We are always by your side! We are called RealEssay.co.uk for a reason. It’s because here you can hire a genuine essay helper to write real essays online for you. We are proud of our writing team, because each of them can write essay of any level of complexity with the highest level of dedication and professionalism. As it has been said earlier, each of them has Master’s or a Ph.D. degree and some of them even have tutoring experience. That is why we can find you a writer regardless of the topic and subject you may have. In addition, our essay writers are native speakers with irreproachable English, so you don’t have to worry about any language, punctuation or grammar mistakes. We do our best to deliver brilliant papers that will ensure your academic success! We want to make sure that you will have a good time dealing with our UK paper writing service. That is why we provide several guarantees to our customers, including confidentiality guarantee, money-back guarantee and satisfaction guarantee. It is difficult to be a student and keep up-to-date with writing work and other duties. If you have too much work to do, you probably need to hire an essay writer (UK) to reduce the load. Luckily, you can buy essay online from RealEssay.co.uk and forget about the nightmare of the endless stream of homework. When you are writing paper and become stuck – our writers will help you to get a quality paper and submit it on time. No more stress, no more sleepless nights, just brilliant custom papers and high results! So if you are ready to order amazing custom essays, get ready to place your order with us. The ordering process is very easy: just visit order page and fill in the order form. Provide all necessary instructions and don’t forget to include all the important details, like topic, discipline, deadline, number of pages, paper type and then your order will be forwarded to a writer. Order a paper now and let our writers amaze you with professional quality!
The use of iridium alloys doped with thorium to encapsulate the 238PuO2 radioactive heat sources used in thermoelectric generators which provide stable electrical power during outer planetary missions has been reported here previously (1, 2). These iridium alloys possess high melting point, good high temperature strength, resistance to oxidation, and are compatible with both the fuel and the surrounding insulation materials. The thorium serves as a grain boundary strengthener, segregating to the grain boundaries and inhibiting intergranular fracture. A container is formed by joining together two hemispherical cups and, because of the application, the equatorial weld is required to be totally reliable. An improved method of welding has been developed for this purpose (3). Iridium alloys may suffer from hot cracking during welding, and experience indicates that even when approved specifications and welding procedures are followed variations in weld quality can occur. Clearly defective welds represent a waste of both materials and fabrication costs. Thus if the weldability of a material can be established prior to or early in the manufacturing process, significant savings will result. Standard tests to determine the hot cracking tendency of metals and alloys do exist, but these are most suitable for sections thicker than 2.5 mm. Now, however, workers at the Oak Ridge National Laboratory have developed a simple modified circular plate test which will successfully determine hot cracking susceptibility (4). Sheet specimens 50 mm in diameter and 0.63 mm thick are held in a test fixture which is designed to restrain them at the centre and the periphery. Using a gas tungsten arc welding procedure under an inert atmosphere, two circular concentric autogenous welds are made, then the disc is removed, turned over, replaced, and the procedure repeated. The first weld is 35 mm in diameter and the other 22.3 mm; after inversion the welds are repeated in the same order. The first welding sequence produces a microstructure which is susceptible to cracking and it also increases the stress in the specimen. If cracking does not occur, the disc is then inverted and the process repeated. After the second sequence, a lack of evidence of cracking in either of the two circular welds is taken to indicate a weldable alloy. If the smaller but not the larger diameter weld shows cracking the material is regarded as being susceptible to cracking, but if both welds are cracked the material is classified as highly susceptible to cracking.
/* pt.c (c) 1998 Grant R. Guenther <[email protected]> Under the terms of the GNU General Public License. This is the high-level driver for parallel port ATAPI tape drives based on chips supported by the paride module. The driver implements both rewinding and non-rewinding devices, filemarks, and the rewind ioctl. It allocates a small internal "bounce buffer" for each open device, but otherwise expects buffering and blocking to be done at the user level. As with most block-structured tapes, short writes are padded to full tape blocks, so reading back a file may return more data than was actually written. By default, the driver will autoprobe for a single parallel port ATAPI tape drive, but if their individual parameters are specified, the driver can handle up to 4 drives. The rewinding devices are named /dev/pt0, /dev/pt1, ... while the non-rewinding devices are /dev/npt0, /dev/npt1, etc. The behaviour of the pt driver can be altered by setting some parameters from the insmod command line. The following parameters are adjustable: drive0 These four arguments can be arrays of drive1 1-6 integers as follows: drive2 drive3 <prt>,<pro>,<uni>,<mod>,<slv>,<dly> Where, <prt> is the base of the parallel port address for the corresponding drive. (required) <pro> is the protocol number for the adapter that supports this drive. These numbers are logged by 'paride' when the protocol modules are initialised. (0 if not given) <uni> for those adapters that support chained devices, this is the unit selector for the chain of devices on the given port. It should be zero for devices that don't support chaining. (0 if not given) <mod> this can be -1 to choose the best mode, or one of the mode numbers supported by the adapter. (-1 if not given) <slv> ATAPI devices can be jumpered to master or slave. Set this to 0 to choose the master drive, 1 to choose the slave, -1 (the default) to choose the first drive found. <dly> some parallel ports require the driver to go more slowly. -1 sets a default value that should work with the chosen protocol. Otherwise, set this to a small integer, the larger it is the slower the port i/o. In some cases, setting this to zero will speed up the device. (default -1) major You may use this parameter to overide the default major number (96) that this driver will use. Be sure to change the device name as well. name This parameter is a character string that contains the name the kernel will use for this device (in /proc output, for instance). (default "pt"). verbose This parameter controls the amount of logging that the driver will do. Set it to 0 for normal operation, 1 to see autoprobe progress messages, or 2 to see additional debugging output. (default 0) If this driver is built into the kernel, you can use the following command line parameters, with the same values as the corresponding module parameters listed above: pt.drive0 pt.drive1 pt.drive2 pt.drive3 In addition, you can use the parameter pt.disable to disable the driver entirely. */ /* */ #define PT_VERSION "1.04" #define PT_MAJOR 96 #define PT_NAME "pt" #define PT_UNITS 4 #include <linux/types.h> /* */ static bool verbose = 0; static int major = PT_MAJOR; static char *name = PT_NAME; static int disable = 0; static int drive0[6] = { 0, 0, 0, -1, -1, -1 }; static int drive1[6] = { 0, 0, 0, -1, -1, -1 }; static int drive2[6] = { 0, 0, 0, -1, -1, -1 }; static int drive3[6] = { 0, 0, 0, -1, -1, -1 }; static int (*drives[4])[6] = {&drive0, &drive1, &drive2, &drive3}; #define D_PRT 0 #define D_PRO 1 #define D_UNI 2 #define D_MOD 3 #define D_SLV 4 #define D_DLY 5 #define DU (*drives[unit]) /* */ #include <linux/module.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/mtio.h> #include <linux/device.h> #include <linux/sched.h> /* */ #include <linux/mutex.h> #include <asm/uaccess.h> module_param(verbose, bool, 0); module_param(major, int, 0); module_param(name, charp, 0); module_param_array(drive0, int, NULL, 0); module_param_array(drive1, int, NULL, 0); module_param_array(drive2, int, NULL, 0); module_param_array(drive3, int, NULL, 0); #include "paride.h" #define PT_MAX_RETRIES 5 #define PT_TMO 3000 /* */ #define PT_SPIN_DEL 50 /* */ #define PT_RESET_TMO 30 /* */ #define PT_READY_TMO 60 /* */ #define PT_REWIND_TMO 1200 /* */ #define PT_SPIN ((1000000/(HZ*PT_SPIN_DEL))*PT_TMO) #define STAT_ERR 0x00001 #define STAT_INDEX 0x00002 #define STAT_ECC 0x00004 #define STAT_DRQ 0x00008 #define STAT_SEEK 0x00010 #define STAT_WRERR 0x00020 #define STAT_READY 0x00040 #define STAT_BUSY 0x00080 #define STAT_SENSE 0x1f000 #define ATAPI_TEST_READY 0x00 #define ATAPI_REWIND 0x01 #define ATAPI_REQ_SENSE 0x03 #define ATAPI_READ_6 0x08 #define ATAPI_WRITE_6 0x0a #define ATAPI_WFM 0x10 #define ATAPI_IDENTIFY 0x12 #define ATAPI_MODE_SENSE 0x1a #define ATAPI_LOG_SENSE 0x4d static DEFINE_MUTEX(pt_mutex); static int pt_open(struct inode *inode, struct file *file); static long pt_ioctl(struct file *file, unsigned int cmd, unsigned long arg); static int pt_release(struct inode *inode, struct file *file); static ssize_t pt_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos); static ssize_t pt_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos); static int pt_detect(void); /* */ #define PT_MEDIA 1 #define PT_WRITE_OK 2 #define PT_REWIND 4 #define PT_WRITING 8 #define PT_READING 16 #define PT_EOF 32 #define PT_NAMELEN 8 #define PT_BUFSIZE 16384 struct pt_unit { struct pi_adapter pia; /* */ struct pi_adapter *pi; int flags; /* */ int last_sense; /* */ int drive; /* */ atomic_t available; /* */ int bs; /* */ int capacity; /* */ int present; /* */ char *bufptr; char name[PT_NAMELEN]; /* */ }; static int pt_identify(struct pt_unit *tape); static struct pt_unit pt[PT_UNITS]; static char pt_scratch[512]; /* */ /* */ static const struct file_operations pt_fops = { .owner = THIS_MODULE, .read = pt_read, .write = pt_write, .unlocked_ioctl = pt_ioctl, .open = pt_open, .release = pt_release, .llseek = noop_llseek, }; /* */ static struct class *pt_class; static inline int status_reg(struct pi_adapter *pi) { return pi_read_regr(pi, 1, 6); } static inline int read_reg(struct pi_adapter *pi, int reg) { return pi_read_regr(pi, 0, reg); } static inline void write_reg(struct pi_adapter *pi, int reg, int val) { pi_write_regr(pi, 0, reg, val); } static inline u8 DRIVE(struct pt_unit *tape) { return 0xa0+0x10*tape->drive; } static int pt_wait(struct pt_unit *tape, int go, int stop, char *fun, char *msg) { int j, r, e, s, p; struct pi_adapter *pi = tape->pi; j = 0; while ((((r = status_reg(pi)) & go) || (stop && (!(r & stop)))) && (j++ < PT_SPIN)) udelay(PT_SPIN_DEL); if ((r & (STAT_ERR & stop)) || (j > PT_SPIN)) { s = read_reg(pi, 7); e = read_reg(pi, 1); p = read_reg(pi, 2); if (j > PT_SPIN) e |= 0x100; if (fun) printk("%s: %s %s: alt=0x%x stat=0x%x err=0x%x" " loop=%d phase=%d\n", tape->name, fun, msg, r, s, e, j, p); return (e << 8) + s; } return 0; } static int pt_command(struct pt_unit *tape, char *cmd, int dlen, char *fun) { struct pi_adapter *pi = tape->pi; pi_connect(pi); write_reg(pi, 6, DRIVE(tape)); if (pt_wait(tape, STAT_BUSY | STAT_DRQ, 0, fun, "before command")) { pi_disconnect(pi); return -1; } write_reg(pi, 4, dlen % 256); write_reg(pi, 5, dlen / 256); write_reg(pi, 7, 0xa0); /* */ if (pt_wait(tape, STAT_BUSY, STAT_DRQ, fun, "command DRQ")) { pi_disconnect(pi); return -1; } if (read_reg(pi, 2) != 1) { printk("%s: %s: command phase error\n", tape->name, fun); pi_disconnect(pi); return -1; } pi_write_block(pi, cmd, 12); return 0; } static int pt_completion(struct pt_unit *tape, char *buf, char *fun) { struct pi_adapter *pi = tape->pi; int r, s, n, p; r = pt_wait(tape, STAT_BUSY, STAT_DRQ | STAT_READY | STAT_ERR, fun, "completion"); if (read_reg(pi, 7) & STAT_DRQ) { n = (((read_reg(pi, 4) + 256 * read_reg(pi, 5)) + 3) & 0xfffc); p = read_reg(pi, 2) & 3; if (p == 0) pi_write_block(pi, buf, n); if (p == 2) pi_read_block(pi, buf, n); } s = pt_wait(tape, STAT_BUSY, STAT_READY | STAT_ERR, fun, "data done"); pi_disconnect(pi); return (r ? r : s); } static void pt_req_sense(struct pt_unit *tape, int quiet) { char rs_cmd[12] = { ATAPI_REQ_SENSE, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0 }; char buf[16]; int r; r = pt_command(tape, rs_cmd, 16, "Request sense"); mdelay(1); if (!r) pt_completion(tape, buf, "Request sense"); tape->last_sense = -1; if (!r) { if (!quiet) printk("%s: Sense key: %x, ASC: %x, ASQ: %x\n", tape->name, buf[2] & 0xf, buf[12], buf[13]); tape->last_sense = (buf[2] & 0xf) | ((buf[12] & 0xff) << 8) | ((buf[13] & 0xff) << 16); } } static int pt_atapi(struct pt_unit *tape, char *cmd, int dlen, char *buf, char *fun) { int r; r = pt_command(tape, cmd, dlen, fun); mdelay(1); if (!r) r = pt_completion(tape, buf, fun); if (r) pt_req_sense(tape, !fun); return r; } static void pt_sleep(int cs) { schedule_timeout_interruptible(cs); } static int pt_poll_dsc(struct pt_unit *tape, int pause, int tmo, char *msg) { struct pi_adapter *pi = tape->pi; int k, e, s; k = 0; e = 0; s = 0; while (k < tmo) { pt_sleep(pause); k++; pi_connect(pi); write_reg(pi, 6, DRIVE(tape)); s = read_reg(pi, 7); e = read_reg(pi, 1); pi_disconnect(pi); if (s & (STAT_ERR | STAT_SEEK)) break; } if ((k >= tmo) || (s & STAT_ERR)) { if (k >= tmo) printk("%s: %s DSC timeout\n", tape->name, msg); else printk("%s: %s stat=0x%x err=0x%x\n", tape->name, msg, s, e); pt_req_sense(tape, 0); return 0; } return 1; } static void pt_media_access_cmd(struct pt_unit *tape, int tmo, char *cmd, char *fun) { if (pt_command(tape, cmd, 0, fun)) { pt_req_sense(tape, 0); return; } pi_disconnect(tape->pi); pt_poll_dsc(tape, HZ, tmo, fun); } static void pt_rewind(struct pt_unit *tape) { char rw_cmd[12] = { ATAPI_REWIND, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; pt_media_access_cmd(tape, PT_REWIND_TMO, rw_cmd, "rewind"); } static void pt_write_fm(struct pt_unit *tape) { char wm_cmd[12] = { ATAPI_WFM, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }; pt_media_access_cmd(tape, PT_TMO, wm_cmd, "write filemark"); } #define DBMSG(msg) ((verbose>1)?(msg):NULL) static int pt_reset(struct pt_unit *tape) { struct pi_adapter *pi = tape->pi; int i, k, flg; int expect[5] = { 1, 1, 1, 0x14, 0xeb }; pi_connect(pi); write_reg(pi, 6, DRIVE(tape)); write_reg(pi, 7, 8); pt_sleep(20 * HZ / 1000); k = 0; while ((k++ < PT_RESET_TMO) && (status_reg(pi) & STAT_BUSY)) pt_sleep(HZ / 10); flg = 1; for (i = 0; i < 5; i++) flg &= (read_reg(pi, i + 1) == expect[i]); if (verbose) { printk("%s: Reset (%d) signature = ", tape->name, k); for (i = 0; i < 5; i++) printk("%3x", read_reg(pi, i + 1)); if (!flg) printk(" (incorrect)"); printk("\n"); } pi_disconnect(pi); return flg - 1; } static int pt_ready_wait(struct pt_unit *tape, int tmo) { char tr_cmd[12] = { ATAPI_TEST_READY, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int k, p; k = 0; while (k < tmo) { tape->last_sense = 0; pt_atapi(tape, tr_cmd, 0, NULL, DBMSG("test unit ready")); p = tape->last_sense; if (!p) return 0; if (!(((p & 0xffff) == 0x0402) || ((p & 0xff) == 6))) return p; k++; pt_sleep(HZ); } return 0x000020; /* */ } static void xs(char *buf, char *targ, int offs, int len) { int j, k, l; j = 0; l = 0; for (k = 0; k < len; k++) if ((buf[k + offs] != 0x20) || (buf[k + offs] != l)) l = targ[j++] = buf[k + offs]; if (l == 0x20) j--; targ[j] = 0; } static int xn(char *buf, int offs, int size) { int v, k; v = 0; for (k = 0; k < size; k++) v = v * 256 + (buf[k + offs] & 0xff); return v; } static int pt_identify(struct pt_unit *tape) { int dt, s; char *ms[2] = { "master", "slave" }; char mf[10], id[18]; char id_cmd[12] = { ATAPI_IDENTIFY, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0 }; char ms_cmd[12] = { ATAPI_MODE_SENSE, 0, 0x2a, 0, 36, 0, 0, 0, 0, 0, 0, 0 }; char ls_cmd[12] = { ATAPI_LOG_SENSE, 0, 0x71, 0, 0, 0, 0, 0, 36, 0, 0, 0 }; char buf[36]; s = pt_atapi(tape, id_cmd, 36, buf, "identify"); if (s) return -1; dt = buf[0] & 0x1f; if (dt != 1) { if (verbose) printk("%s: Drive %d, unsupported type %d\n", tape->name, tape->drive, dt); return -1; } xs(buf, mf, 8, 8); xs(buf, id, 16, 16); tape->flags = 0; tape->capacity = 0; tape->bs = 0; if (!pt_ready_wait(tape, PT_READY_TMO)) tape->flags |= PT_MEDIA; if (!pt_atapi(tape, ms_cmd, 36, buf, "mode sense")) { if (!(buf[2] & 0x80)) tape->flags |= PT_WRITE_OK; tape->bs = xn(buf, 10, 2); } if (!pt_atapi(tape, ls_cmd, 36, buf, "log sense")) tape->capacity = xn(buf, 24, 4); printk("%s: %s %s, %s", tape->name, mf, id, ms[tape->drive]); if (!(tape->flags & PT_MEDIA)) printk(", no media\n"); else { if (!(tape->flags & PT_WRITE_OK)) printk(", RO"); printk(", blocksize %d, %d MB\n", tape->bs, tape->capacity / 1024); } return 0; } /* */ static int pt_probe(struct pt_unit *tape) { if (tape->drive == -1) { for (tape->drive = 0; tape->drive <= 1; tape->drive++) if (!pt_reset(tape)) return pt_identify(tape); } else { if (!pt_reset(tape)) return pt_identify(tape); } return -1; } static int pt_detect(void) { struct pt_unit *tape; int specified = 0, found = 0; int unit; printk("%s: %s version %s, major %d\n", name, name, PT_VERSION, major); specified = 0; for (unit = 0; unit < PT_UNITS; unit++) { struct pt_unit *tape = &pt[unit]; tape->pi = &tape->pia; atomic_set(&tape->available, 1); tape->flags = 0; tape->last_sense = 0; tape->present = 0; tape->bufptr = NULL; tape->drive = DU[D_SLV]; snprintf(tape->name, PT_NAMELEN, "%s%d", name, unit); if (!DU[D_PRT]) continue; specified++; if (pi_init(tape->pi, 0, DU[D_PRT], DU[D_MOD], DU[D_UNI], DU[D_PRO], DU[D_DLY], pt_scratch, PI_PT, verbose, tape->name)) { if (!pt_probe(tape)) { tape->present = 1; found++; } else pi_release(tape->pi); } } if (specified == 0) { tape = pt; if (pi_init(tape->pi, 1, -1, -1, -1, -1, -1, pt_scratch, PI_PT, verbose, tape->name)) { if (!pt_probe(tape)) { tape->present = 1; found++; } else pi_release(tape->pi); } } if (found) return 0; printk("%s: No ATAPI tape drive detected\n", name); return -1; } static int pt_open(struct inode *inode, struct file *file) { int unit = iminor(inode) & 0x7F; struct pt_unit *tape = pt + unit; int err; mutex_lock(&pt_mutex); if (unit >= PT_UNITS || (!tape->present)) { mutex_unlock(&pt_mutex); return -ENODEV; } err = -EBUSY; if (!atomic_dec_and_test(&tape->available)) goto out; pt_identify(tape); err = -ENODEV; if (!(tape->flags & PT_MEDIA)) goto out; err = -EROFS; if ((!(tape->flags & PT_WRITE_OK)) && (file->f_mode & FMODE_WRITE)) goto out; if (!(iminor(inode) & 128)) tape->flags |= PT_REWIND; err = -ENOMEM; tape->bufptr = kmalloc(PT_BUFSIZE, GFP_KERNEL); if (tape->bufptr == NULL) { printk("%s: buffer allocation failed\n", tape->name); goto out; } file->private_data = tape; mutex_unlock(&pt_mutex); return 0; out: atomic_inc(&tape->available); mutex_unlock(&pt_mutex); return err; } static long pt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct pt_unit *tape = file->private_data; struct mtop __user *p = (void __user *)arg; struct mtop mtop; switch (cmd) { case MTIOCTOP: if (copy_from_user(&mtop, p, sizeof(struct mtop))) return -EFAULT; switch (mtop.mt_op) { case MTREW: mutex_lock(&pt_mutex); pt_rewind(tape); mutex_unlock(&pt_mutex); return 0; case MTWEOF: mutex_lock(&pt_mutex); pt_write_fm(tape); mutex_unlock(&pt_mutex); return 0; default: /* */ printk(KERN_DEBUG "%s: Unimplemented mt_op %d\n", tape->name, mtop.mt_op); return -EINVAL; } default: return -ENOTTY; } } static int pt_release(struct inode *inode, struct file *file) { struct pt_unit *tape = file->private_data; if (atomic_read(&tape->available) > 1) return -EINVAL; if (tape->flags & PT_WRITING) pt_write_fm(tape); if (tape->flags & PT_REWIND) pt_rewind(tape); kfree(tape->bufptr); tape->bufptr = NULL; atomic_inc(&tape->available); return 0; } static ssize_t pt_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos) { struct pt_unit *tape = filp->private_data; struct pi_adapter *pi = tape->pi; char rd_cmd[12] = { ATAPI_READ_6, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int k, n, r, p, s, t, b; if (!(tape->flags & (PT_READING | PT_WRITING))) { tape->flags |= PT_READING; if (pt_atapi(tape, rd_cmd, 0, NULL, "start read-ahead")) return -EIO; } else if (tape->flags & PT_WRITING) return -EIO; if (tape->flags & PT_EOF) return 0; t = 0; while (count > 0) { if (!pt_poll_dsc(tape, HZ / 100, PT_TMO, "read")) return -EIO; n = count; if (n > 32768) n = 32768; /* */ b = (n - 1 + tape->bs) / tape->bs; n = b * tape->bs; /* */ rd_cmd[4] = b; r = pt_command(tape, rd_cmd, n, "read"); mdelay(1); if (r) { pt_req_sense(tape, 0); return -EIO; } while (1) { r = pt_wait(tape, STAT_BUSY, STAT_DRQ | STAT_ERR | STAT_READY, DBMSG("read DRQ"), ""); if (r & STAT_SENSE) { pi_disconnect(pi); pt_req_sense(tape, 0); return -EIO; } if (r) tape->flags |= PT_EOF; s = read_reg(pi, 7); if (!(s & STAT_DRQ)) break; n = (read_reg(pi, 4) + 256 * read_reg(pi, 5)); p = (read_reg(pi, 2) & 3); if (p != 2) { pi_disconnect(pi); printk("%s: Phase error on read: %d\n", tape->name, p); return -EIO; } while (n > 0) { k = n; if (k > PT_BUFSIZE) k = PT_BUFSIZE; pi_read_block(pi, tape->bufptr, k); n -= k; b = k; if (b > count) b = count; if (copy_to_user(buf + t, tape->bufptr, b)) { pi_disconnect(pi); return -EFAULT; } t += b; count -= b; } } pi_disconnect(pi); if (tape->flags & PT_EOF) break; } return t; } static ssize_t pt_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos) { struct pt_unit *tape = filp->private_data; struct pi_adapter *pi = tape->pi; char wr_cmd[12] = { ATAPI_WRITE_6, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int k, n, r, p, s, t, b; if (!(tape->flags & PT_WRITE_OK)) return -EROFS; if (!(tape->flags & (PT_READING | PT_WRITING))) { tape->flags |= PT_WRITING; if (pt_atapi (tape, wr_cmd, 0, NULL, "start buffer-available mode")) return -EIO; } else if (tape->flags & PT_READING) return -EIO; if (tape->flags & PT_EOF) return -ENOSPC; t = 0; while (count > 0) { if (!pt_poll_dsc(tape, HZ / 100, PT_TMO, "write")) return -EIO; n = count; if (n > 32768) n = 32768; /* */ b = (n - 1 + tape->bs) / tape->bs; n = b * tape->bs; /* */ wr_cmd[4] = b; r = pt_command(tape, wr_cmd, n, "write"); mdelay(1); if (r) { /* */ pt_req_sense(tape, 0); return -EIO; } while (1) { r = pt_wait(tape, STAT_BUSY, STAT_DRQ | STAT_ERR | STAT_READY, DBMSG("write DRQ"), NULL); if (r & STAT_SENSE) { pi_disconnect(pi); pt_req_sense(tape, 0); return -EIO; } if (r) tape->flags |= PT_EOF; s = read_reg(pi, 7); if (!(s & STAT_DRQ)) break; n = (read_reg(pi, 4) + 256 * read_reg(pi, 5)); p = (read_reg(pi, 2) & 3); if (p != 0) { pi_disconnect(pi); printk("%s: Phase error on write: %d \n", tape->name, p); return -EIO; } while (n > 0) { k = n; if (k > PT_BUFSIZE) k = PT_BUFSIZE; b = k; if (b > count) b = count; if (copy_from_user(tape->bufptr, buf + t, b)) { pi_disconnect(pi); return -EFAULT; } pi_write_block(pi, tape->bufptr, k); t += b; count -= b; n -= k; } } pi_disconnect(pi); if (tape->flags & PT_EOF) break; } return t; } static int __init pt_init(void) { int unit; int err; if (disable) { err = -EINVAL; goto out; } if (pt_detect()) { err = -ENODEV; goto out; } err = register_chrdev(major, name, &pt_fops); if (err < 0) { printk("pt_init: unable to get major number %d\n", major); for (unit = 0; unit < PT_UNITS; unit++) if (pt[unit].present) pi_release(pt[unit].pi); goto out; } major = err; pt_class = class_create(THIS_MODULE, "pt"); if (IS_ERR(pt_class)) { err = PTR_ERR(pt_class); goto out_chrdev; } for (unit = 0; unit < PT_UNITS; unit++) if (pt[unit].present) { device_create(pt_class, NULL, MKDEV(major, unit), NULL, "pt%d", unit); device_create(pt_class, NULL, MKDEV(major, unit + 128), NULL, "pt%dn", unit); } goto out; out_chrdev: unregister_chrdev(major, "pt"); out: return err; } static void __exit pt_exit(void) { int unit; for (unit = 0; unit < PT_UNITS; unit++) if (pt[unit].present) { device_destroy(pt_class, MKDEV(major, unit)); device_destroy(pt_class, MKDEV(major, unit + 128)); } class_destroy(pt_class); unregister_chrdev(major, name); for (unit = 0; unit < PT_UNITS; unit++) if (pt[unit].present) pi_release(pt[unit].pi); } MODULE_LICENSE("GPL"); module_init(pt_init) module_exit(pt_exit)
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Services; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; namespace Umbraco.Tests.Services { /// <summary> /// Tests covering the EntityService /// </summary> [TestFixture] [Apartment(ApartmentState.STA)] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerFixture)] public class EntityServiceTests : TestWithSomeContentBase { private Language _langFr; private Language _langEs; public override void SetUp() { base.SetUp(); if (_langFr == null && _langEs == null) { _langFr = new Language("fr-FR"); _langEs = new Language("es-ES"); ServiceContext.LocalizationService.Save(_langFr); ServiceContext.LocalizationService.Save(_langEs); } } [Test] public void EntityService_Can_Get_Paged_Descendants_Ordering_Path() { var contentType = ServiceContext.ContentTypeService.Get("umbTextpage"); var root = MockedContent.CreateSimpleContent(contentType); ServiceContext.ContentService.Save(root); var rootId = root.Id; var ids = new List<int>(); for (int i = 0; i < 10; i++) { var c1 = MockedContent.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ServiceContext.ContentService.Save(c1); ids.Add(c1.Id); root = c1; // make a hierarchy } var service = ServiceContext.EntityService; long total; var entities = service.GetPagedDescendants(rootId, UmbracoObjectTypes.Document, 0, 6, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[0], entities[0].Id); entities = service.GetPagedDescendants(rootId, UmbracoObjectTypes.Document, 1, 6, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[6], entities[0].Id); //Test ordering direction entities = service.GetPagedDescendants(rootId, UmbracoObjectTypes.Document, 0, 6, out total, ordering: Ordering.By("Path", Direction.Descending)).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[ids.Count - 1], entities[0].Id); entities = service.GetPagedDescendants(rootId, UmbracoObjectTypes.Document, 1, 6, out total, ordering: Ordering.By("Path", Direction.Descending)).ToArray(); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[ids.Count - 1 - 6], entities[0].Id); } [Test] public void EntityService_Can_Get_Paged_Content_Children() { var contentType = ServiceContext.ContentTypeService.Get("umbTextpage"); var root = MockedContent.CreateSimpleContent(contentType); ServiceContext.ContentService.Save(root); var ids = new List<int>(); for (int i = 0; i < 10; i++) { var c1 = MockedContent.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ServiceContext.ContentService.Save(c1); ids.Add(c1.Id); } var service = ServiceContext.EntityService; long total; var entities = service.GetPagedChildren(root.Id, UmbracoObjectTypes.Document, 0, 6, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[0], entities[0].Id); entities = service.GetPagedChildren(root.Id, UmbracoObjectTypes.Document, 1, 6, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[6], entities[0].Id); //Test ordering direction entities = service.GetPagedChildren(root.Id, UmbracoObjectTypes.Document, 0, 6, out total, ordering: Ordering.By("SortOrder", Direction.Descending)).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[ids.Count - 1], entities[0].Id); entities = service.GetPagedChildren(root.Id, UmbracoObjectTypes.Document, 1, 6, out total, ordering: Ordering.By("SortOrder", Direction.Descending)).ToArray(); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(total, Is.EqualTo(10)); Assert.AreEqual(ids[ids.Count - 1 - 6], entities[0].Id); } [Test] public void EntityService_Can_Get_Paged_Content_Descendants() { var contentType = ServiceContext.ContentTypeService.Get("umbTextpage"); var root = MockedContent.CreateSimpleContent(contentType); ServiceContext.ContentService.Save(root); var count = 0; for (int i = 0; i < 10; i++) { var c1 = MockedContent.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ServiceContext.ContentService.Save(c1); count++; for (int j = 0; j < 5; j++) { var c2 = MockedContent.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); ServiceContext.ContentService.Save(c2); count++; } } var service = ServiceContext.EntityService; long total; var entities = service.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 0, 31, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(31)); Assert.That(total, Is.EqualTo(60)); entities = service.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 1, 31, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(29)); Assert.That(total, Is.EqualTo(60)); } [Test] public void EntityService_Can_Get_Paged_Content_Descendants_Including_Recycled() { var contentType = ServiceContext.ContentTypeService.Get("umbTextpage"); var root = MockedContent.CreateSimpleContent(contentType); ServiceContext.ContentService.Save(root); var toDelete = new List<IContent>(); for (int i = 0; i < 10; i++) { var c1 = MockedContent.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ServiceContext.ContentService.Save(c1); if (i % 2 == 0) { toDelete.Add(c1); } for (int j = 0; j < 5; j++) { var c2 = MockedContent.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); ServiceContext.ContentService.Save(c2); } } foreach (var content in toDelete) { ServiceContext.ContentService.MoveToRecycleBin(content); } var service = ServiceContext.EntityService; long total; //search at root to see if it returns recycled var entities = service.GetPagedDescendants(-1, UmbracoObjectTypes.Document, 0, 1000, out total) .Select(x => x.Id) .ToArray(); foreach (var c in toDelete) { Assert.True(entities.Contains(c.Id)); } } [Test] public void EntityService_Can_Get_Paged_Content_Descendants_Without_Recycled() { var contentType = ServiceContext.ContentTypeService.Get("umbTextpage"); var root = MockedContent.CreateSimpleContent(contentType); ServiceContext.ContentService.Save(root); var toDelete = new List<IContent>(); for (int i = 0; i < 10; i++) { var c1 = MockedContent.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); ServiceContext.ContentService.Save(c1); if (i % 2 == 0) { toDelete.Add(c1); } for (int j = 0; j < 5; j++) { var c2 = MockedContent.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), c1); ServiceContext.ContentService.Save(c2); } } foreach (var content in toDelete) { ServiceContext.ContentService.MoveToRecycleBin(content); } var service = ServiceContext.EntityService; long total; //search at root to see if it returns recycled var entities = service.GetPagedDescendants(UmbracoObjectTypes.Document, 0, 1000, out total, includeTrashed: false) .Select(x => x.Id) .ToArray(); foreach (var c in toDelete) { Assert.IsFalse(entities.Contains(c.Id)); } } [Test] public void EntityService_Can_Get_Paged_Content_Descendants_With_Search() { var contentType = ServiceContext.ContentTypeService.Get("umbTextpage"); var root = MockedContent.CreateSimpleContent(contentType); ServiceContext.ContentService.Save(root); for (int i = 0; i < 10; i++) { var c1 = MockedContent.CreateSimpleContent(contentType, "ssss" + Guid.NewGuid(), root); ServiceContext.ContentService.Save(c1); for (int j = 0; j < 5; j++) { var c2 = MockedContent.CreateSimpleContent(contentType, "tttt" + Guid.NewGuid(), c1); ServiceContext.ContentService.Save(c2); } } var service = ServiceContext.EntityService; long total; var entities = service.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 0, 10, out total, filter: SqlContext.Query<IUmbracoEntity>().Where(x => x.Name.Contains("ssss"))).ToArray(); Assert.That(entities.Length, Is.EqualTo(10)); Assert.That(total, Is.EqualTo(10)); entities = service.GetPagedDescendants(root.Id, UmbracoObjectTypes.Document, 0, 50, out total, filter: SqlContext.Query<IUmbracoEntity>().Where(x => x.Name.Contains("tttt"))).ToArray(); Assert.That(entities.Length, Is.EqualTo(50)); Assert.That(total, Is.EqualTo(50)); } [Test] public void EntityService_Can_Get_Paged_Media_Children() { var folderType = ServiceContext.MediaTypeService.Get(1031); var imageMediaType = ServiceContext.MediaTypeService.Get(1032); var root = MockedMedia.CreateMediaFolder(folderType, -1); ServiceContext.MediaService.Save(root); for (int i = 0; i < 10; i++) { var c1 = MockedMedia.CreateMediaImage(imageMediaType, root.Id); ServiceContext.MediaService.Save(c1); } var service = ServiceContext.EntityService; long total; var entities = service.GetPagedChildren(root.Id, UmbracoObjectTypes.Media, 0, 6, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(6)); Assert.That(total, Is.EqualTo(10)); entities = service.GetPagedChildren(root.Id, UmbracoObjectTypes.Media, 1, 6, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(total, Is.EqualTo(10)); } [Test] public void EntityService_Can_Get_Paged_Media_Descendants() { var folderType = ServiceContext.MediaTypeService.Get(1031); var imageMediaType = ServiceContext.MediaTypeService.Get(1032); var root = MockedMedia.CreateMediaFolder(folderType, -1); ServiceContext.MediaService.Save(root); var count = 0; for (int i = 0; i < 10; i++) { var c1 = MockedMedia.CreateMediaImage(imageMediaType, root.Id); ServiceContext.MediaService.Save(c1); count++; for (int j = 0; j < 5; j++) { var c2 = MockedMedia.CreateMediaImage(imageMediaType, c1.Id); ServiceContext.MediaService.Save(c2); count++; } } var service = ServiceContext.EntityService; long total; var entities = service.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 0, 31, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(31)); Assert.That(total, Is.EqualTo(60)); entities = service.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 1, 31, out total).ToArray(); Assert.That(entities.Length, Is.EqualTo(29)); Assert.That(total, Is.EqualTo(60)); } [Test] public void EntityService_Can_Get_Paged_Media_Descendants_Including_Recycled() { var folderType = ServiceContext.MediaTypeService.Get(1031); var imageMediaType = ServiceContext.MediaTypeService.Get(1032); var root = MockedMedia.CreateMediaFolder(folderType, -1); ServiceContext.MediaService.Save(root); var toDelete = new List<IMedia>(); for (int i = 0; i < 10; i++) { var c1 = MockedMedia.CreateMediaImage(imageMediaType, root.Id); ServiceContext.MediaService.Save(c1); if (i % 2 == 0) { toDelete.Add(c1); } for (int j = 0; j < 5; j++) { var c2 = MockedMedia.CreateMediaImage(imageMediaType, c1.Id); ServiceContext.MediaService.Save(c2); } } foreach (var content in toDelete) { ServiceContext.MediaService.MoveToRecycleBin(content); } var service = ServiceContext.EntityService; long total; //search at root to see if it returns recycled var entities = service.GetPagedDescendants(-1, UmbracoObjectTypes.Media, 0, 1000, out total) .Select(x => x.Id) .ToArray(); foreach (var media in toDelete) { Assert.IsTrue(entities.Contains(media.Id)); } } [Test] public void EntityService_Can_Get_Paged_Media_Descendants_Without_Recycled() { var folderType = ServiceContext.MediaTypeService.Get(1031); var imageMediaType = ServiceContext.MediaTypeService.Get(1032); var root = MockedMedia.CreateMediaFolder(folderType, -1); ServiceContext.MediaService.Save(root); var toDelete = new List<IMedia>(); for (int i = 0; i < 10; i++) { var c1 = MockedMedia.CreateMediaImage(imageMediaType, root.Id); ServiceContext.MediaService.Save(c1); if (i % 2 == 0) { toDelete.Add(c1); } for (int j = 0; j < 5; j++) { var c2 = MockedMedia.CreateMediaImage(imageMediaType, c1.Id); ServiceContext.MediaService.Save(c2); } } foreach (var content in toDelete) { ServiceContext.MediaService.MoveToRecycleBin(content); } var service = ServiceContext.EntityService; long total; //search at root to see if it returns recycled var entities = service.GetPagedDescendants(UmbracoObjectTypes.Media, 0, 1000, out total, includeTrashed: false) .Select(x => x.Id) .ToArray(); foreach (var media in toDelete) { Assert.IsFalse(entities.Contains(media.Id)); } } [Test] public void EntityService_Can_Get_Paged_Media_Descendants_With_Search() { var folderType = ServiceContext.MediaTypeService.Get(1031); var imageMediaType = ServiceContext.MediaTypeService.Get(1032); var root = MockedMedia.CreateMediaFolder(folderType, -1); ServiceContext.MediaService.Save(root); for (int i = 0; i < 10; i++) { var c1 = MockedMedia.CreateMediaImage(imageMediaType, root.Id); c1.Name = "ssss" + Guid.NewGuid(); ServiceContext.MediaService.Save(c1); for (int j = 0; j < 5; j++) { var c2 = MockedMedia.CreateMediaImage(imageMediaType, c1.Id); c2.Name = "tttt" + Guid.NewGuid(); ServiceContext.MediaService.Save(c2); } } var service = ServiceContext.EntityService; long total; var entities = service.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 0, 10, out total, filter: SqlContext.Query<IUmbracoEntity>().Where(x => x.Name.Contains("ssss"))).ToArray(); Assert.That(entities.Length, Is.EqualTo(10)); Assert.That(total, Is.EqualTo(10)); entities = service.GetPagedDescendants(root.Id, UmbracoObjectTypes.Media, 0, 50, out total, filter: SqlContext.Query<IUmbracoEntity>().Where(x => x.Name.Contains("tttt"))).ToArray(); Assert.That(entities.Length, Is.EqualTo(50)); Assert.That(total, Is.EqualTo(50)); } [Test] public void EntityService_Can_Find_All_Content_By_UmbracoObjectTypes() { var service = ServiceContext.EntityService; var entities = service.GetAll(UmbracoObjectTypes.Document).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(entities.Any(x => x.Trashed), Is.True); } [Test] public void EntityService_Can_Find_All_Content_By_UmbracoObjectType_Id() { var service = ServiceContext.EntityService; var objectTypeId = Constants.ObjectTypes.Document; var entities = service.GetAll(objectTypeId).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(entities.Any(x => x.Trashed), Is.True); } [Test] public void EntityService_Can_Find_All_Content_By_Type() { var service = ServiceContext.EntityService; var entities = service.GetAll<IContent>().ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(4)); Assert.That(entities.Any(x => x.Trashed), Is.True); } [Test] public void EntityService_Can_Get_Child_Content_By_ParentId_And_UmbracoObjectType() { var service = ServiceContext.EntityService; var entities = service.GetChildren(-1, UmbracoObjectTypes.Document).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(1)); Assert.That(entities.Any(x => x.Trashed), Is.False); } [Test] public void EntityService_Can_Get_Content_By_UmbracoObjectType_With_Variant_Names() { var service = ServiceContext.EntityService; var alias = "test" + Guid.NewGuid(); var contentType = MockedContentTypes.CreateSimpleContentType(alias, alias, false); contentType.Variations = ContentVariation.Culture; ServiceContext.ContentTypeService.Save(contentType); var c1 = MockedContent.CreateSimpleContent(contentType, "Test", -1); c1.SetCultureName("Test - FR", _langFr.IsoCode); c1.SetCultureName("Test - ES", _langEs.IsoCode); ServiceContext.ContentService.Save(c1); var result = service.Get(c1.Id, UmbracoObjectTypes.Document); Assert.AreEqual("Test - FR", result.Name); // got name from default culture Assert.IsNotNull(result as IDocumentEntitySlim); var doc = (IDocumentEntitySlim)result; var cultureNames = doc.CultureNames; Assert.AreEqual("Test - FR", cultureNames[_langFr.IsoCode]); Assert.AreEqual("Test - ES", cultureNames[_langEs.IsoCode]); } [Test] public void EntityService_Can_Get_Child_Content_By_ParentId_And_UmbracoObjectType_With_Variant_Names() { var service = ServiceContext.EntityService; var contentType = MockedContentTypes.CreateSimpleContentType("test1", "Test1", false); contentType.Variations = ContentVariation.Culture; ServiceContext.ContentTypeService.Save(contentType); var root = MockedContent.CreateSimpleContent(contentType); root.SetCultureName("Root", _langFr.IsoCode); // else cannot save ServiceContext.ContentService.Save(root); for (int i = 0; i < 10; i++) { var c1 = MockedContent.CreateSimpleContent(contentType, Guid.NewGuid().ToString(), root); if (i % 2 == 0) { c1.SetCultureName("Test " + i + " - FR", _langFr.IsoCode); c1.SetCultureName("Test " + i + " - ES", _langEs.IsoCode); } else { c1.SetCultureName("Test", _langFr.IsoCode); // else cannot save } ServiceContext.ContentService.Save(c1); } var entities = service.GetChildren(root.Id, UmbracoObjectTypes.Document).ToArray(); Assert.AreEqual(10, entities.Length); for (int i = 0; i < entities.Length; i++) { Assert.AreEqual(0, entities[i].AdditionalData.Count); if (i % 2 == 0) { var doc = (IDocumentEntitySlim)entities[i]; var keys = doc.CultureNames.Keys.ToList(); var vals = doc.CultureNames.Values.ToList(); Assert.AreEqual(_langFr.IsoCode.ToLowerInvariant(), keys[0].ToLowerInvariant()); Assert.AreEqual("Test " + i + " - FR", vals[0]); Assert.AreEqual(_langEs.IsoCode.ToLowerInvariant(), keys[1].ToLowerInvariant()); Assert.AreEqual("Test " + i + " - ES", vals[1]); } else { Assert.AreEqual(0, entities[i].AdditionalData.Count); } } } [Test] public void EntityService_Can_Get_Children_By_ParentId() { var service = ServiceContext.EntityService; var entities = service.GetChildren(folderId); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(3)); Assert.That(entities.Any(x => x.Trashed), Is.False); } [Test] public void EntityService_Can_Get_Descendants_By_ParentId() { var service = ServiceContext.EntityService; var entities = service.GetDescendants(folderId); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(4)); Assert.That(entities.Any(x => x.Trashed), Is.False); } [Test] public void EntityService_Throws_When_Getting_All_With_Invalid_Type() { var service = ServiceContext.EntityService; var objectTypeId = Constants.ObjectTypes.ContentItem; Assert.Throws<NotSupportedException>(() => service.GetAll<IContentBase>()); Assert.Throws<NotSupportedException>(() => service.GetAll(objectTypeId)); } [Test] public void EntityService_Can_Find_All_ContentTypes_By_UmbracoObjectTypes() { var service = ServiceContext.EntityService; var entities = service.GetAll(UmbracoObjectTypes.DocumentType).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(1)); } [Test] public void EntityService_Can_Find_All_ContentTypes_By_UmbracoObjectType_Id() { var service = ServiceContext.EntityService; var objectTypeId = Constants.ObjectTypes.DocumentType; var entities = service.GetAll(objectTypeId).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(1)); } [Test] public void EntityService_Can_Find_All_ContentTypes_By_Type() { var service = ServiceContext.EntityService; var entities = service.GetAll<IContentType>().ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Count(), Is.EqualTo(1)); } [Test] public void EntityService_Can_Find_All_Media_By_UmbracoObjectTypes() { var service = ServiceContext.EntityService; var entities = service.GetAll(UmbracoObjectTypes.Media).ToArray(); Assert.That(entities.Any(), Is.True); Assert.That(entities.Length, Is.EqualTo(5)); foreach (var entity in entities) { Assert.IsTrue(entity.GetType().Implements<IMediaEntitySlim>()); Console.WriteLine(((IMediaEntitySlim)entity).MediaPath); Assert.IsNotEmpty(((IMediaEntitySlim)entity).MediaPath); } } [Test] public void EntityService_Can_Get_ObjectType() { var service = ServiceContext.EntityService; var mediaObjectType = service.GetObjectType(1031); Assert.NotNull(mediaObjectType); Assert.AreEqual(mediaObjectType, UmbracoObjectTypes.MediaType); } [Test] public void EntityService_Can_Get_Key_For_Id_With_Unknown_Type() { var service = ServiceContext.EntityService; var result = service.GetKey(1061, UmbracoObjectTypes.Unknown); Assert.IsTrue(result.Success); Assert.AreEqual(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), result.Result); } [Test] public void EntityService_Can_Get_Key_For_Id() { var service = ServiceContext.EntityService; var result = service.GetKey(1061, UmbracoObjectTypes.DocumentType); Assert.IsTrue(result.Success); Assert.AreEqual(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), result.Result); } [Test] public void EntityService_Cannot_Get_Key_For_Id_With_Incorrect_Object_Type() { var service = ServiceContext.EntityService; var result1 = service.GetKey(1061, UmbracoObjectTypes.DocumentType); var result2 = service.GetKey(1061, UmbracoObjectTypes.MediaType); Assert.IsTrue(result1.Success); Assert.IsFalse(result2.Success); } [Test] public void EntityService_Can_Get_Id_For_Key_With_Unknown_Type() { var service = ServiceContext.EntityService; var result = service.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.Unknown); Assert.IsTrue(result.Success); Assert.AreEqual(1061, result.Result); } [Test] public void EntityService_Can_Get_Id_For_Key() { var service = ServiceContext.EntityService; var result = service.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.DocumentType); Assert.IsTrue(result.Success); Assert.AreEqual(1061, result.Result); } [Test] public void EntityService_Cannot_Get_Id_For_Key_With_Incorrect_Object_Type() { var service = ServiceContext.EntityService; var result1 = service.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.DocumentType); var result2 = service.GetId(Guid.Parse("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"), UmbracoObjectTypes.MediaType); Assert.IsTrue(result1.Success); Assert.IsFalse(result2.Success); } [Test] public void ReserveId() { var service = ServiceContext.EntityService; var guid = Guid.NewGuid(); // can reserve var reservedId = service.ReserveId(guid); Assert.IsTrue(reservedId > 0); // can get it back var id = service.GetId(guid, UmbracoObjectTypes.DocumentType); Assert.IsTrue(id.Success); Assert.AreEqual(reservedId, id.Result); // anything goes id = service.GetId(guid, UmbracoObjectTypes.Media); Assert.IsTrue(id.Success); Assert.AreEqual(reservedId, id.Result); // a random guid won't work Assert.IsFalse(service.GetId(Guid.NewGuid(), UmbracoObjectTypes.DocumentType).Success); } private static bool _isSetup = false; private int folderId; public override void CreateTestData() { if (_isSetup == false) { _isSetup = true; base.CreateTestData(); //Create and Save folder-Media -> 1050 var folderMediaType = ServiceContext.MediaTypeService.Get(1031); var folder = MockedMedia.CreateMediaFolder(folderMediaType, -1); ServiceContext.MediaService.Save(folder, 0); folderId = folder.Id; //Create and Save image-Media -> 1051 var imageMediaType = ServiceContext.MediaTypeService.Get(1032); var image = MockedMedia.CreateMediaImage(imageMediaType, folder.Id); ServiceContext.MediaService.Save(image, 0); //Create and Save file-Media -> 1052 var fileMediaType = ServiceContext.MediaTypeService.Get(1033); var file = MockedMedia.CreateMediaFile(fileMediaType, folder.Id); ServiceContext.MediaService.Save(file, 0); var subfolder = MockedMedia.CreateMediaFolder(folderMediaType, folder.Id); ServiceContext.MediaService.Save(subfolder, 0); var subfolder2 = MockedMedia.CreateMediaFolder(folderMediaType, subfolder.Id); ServiceContext.MediaService.Save(subfolder2, 0); } } } }
April 23rd is St George’s day and is also regarded as Shakespeare’s birthday. A good month then to read a novel set in England. There are plenty to choose from in the ‘Literature in Education Collection’. The classics are well represented by ‘Nicholas Nickleby’ or’ Hard Times’ by Charles Dickens, ‘The Professor’ by Charlotte Bronte or ‘Dr Wortle’s School’ by Anthony Trollope. Why not try ‘Lucky Jim’ by Kingsley Amis, ‘An Academic Question ‘ by Barbara Pym, ‘ To Sir With Love’ by E.R. Braithwaite or ‘The Longest Journey’ by E. M. Forster? Alternatively, read the futuristic ‘Never Let Me Go’ by Kazuo Ishiguro, ‘Jill’ the only novel written by the poet Philip Larkin, ‘Oranges Are Not the Only Fruit’ by Jeanette Winterson or ‘Almost English‘ by Charlotte Mendelson. If you are in the mood for a gently humorous read then ‘The Village School’ by Miss Read or ‘The Little Village School‘ by Gervase Phinn certainly fit the bill. Crime novels are always popular; read about what happens when a Ghanaian girl is sent to a boarding school in Devon in ‘True Murder‘ by Yaba Badoe. Or, for a more traditional example of the genre, you might like to read ‘Gaudy Night’ by Dorothy L Sayers. Of course, you could also borrow a DVD if you would prefer to watch a film. ‘If’, ‘Another Country’, ‘The Browning Version’, ‘The History Boys’ and ‘The Happiest Days of Your Life’ are all highly recommended. This entry was posted in Library and Archives and tagged Education in Literature Collection. Bookmark the permalink.
I think I’d like prize 2 bc I like facials! I am most interested in #2. I like them both, but #2 a little more. I like them both, but I would pick number 2. I like prize one. The rose cleanser sounds great. I would choose #1 (Rose Cream Cleanser and the Rose Tonic). It sounds lovely. Thanks for the giveaway!
----------------------------------- -- Area: Newton Movalpolos -- NPC: HomePoint#1 -- !pos 444 27 -22 12 ----------------------------------- require("scripts/globals/homepoint") ----------------------------------- local hpEvent = 8700 local hpIndex = 83 function onTrigger(player,npc) dsp.homepoint.onTrigger(player, hpEvent, hpIndex) end function onEventFinish(player,csid,option) dsp.homepoint.onEventFinish(player, csid, option, hpEvent) end
To many, the Polaris Ace single-seat UTV seems revolutionary, but Honda offered the first solo UTV, the Odyssey, in 1977. The machine had trailing-arm front suspension with a bit more than 4 inches of travel up front and no rear suspension, except the tires and seat. The throttle and brake controls were on the unusual aircraft-like steering yoke. The Honda museum had this ’ 79 Odyssey on display. $1395. It was powered by a 600cc, air-cooled, twin-cylinder engine with 36 hp. It’s smaller, lighter and less powerful than the Pioneer 700 UTV! Most riders are familiar with Honda’s Big Red UTV, but the first Honda Big Red was a utility three-wheeler. The unusual trike was introduced in 1985 and had racks and reverse. The Super Cub, a lightweight 50cc motorcycle, was the best-selling vehicle in history, with over 30 million units produced.
Paula is doing a (solo) reading from her new poetry book, “Tossing Off the Gloves,” Wednesday, January 8th, 2014, at 8 p.m. at Barron Arts Center, 582 Rahway Avenue, Woodbridge, NJ. Prior to her reading that evening, she will teach a poetry workshop, “From My Childhood Trunk,” at 7 p.m. All are welcome. After her reading, she will be available to sign books, and the program continues with an open read for poets. Barron Arts Center 732-634-0413; Parkway north to Rariton Toll Booth, exit 127 to Rt 9 north, exit right to Main St. through business district, left on Rahway Ave., right at second light onto Port Reading Ave, Arts Center on right. Click here for directions. This entry was posted in News on January 3, 2014 by kbtadmin.
> > are the other alternatives? > are attacked by lions (which isn't very often). and water buffalo. I still say they're nuts, but . . . > then the lions may have a chance. popcorn the buffalo's just not worth it. > aid and driving the lions off. good foot or two in length. Ceratopian horns just don't compete. > have other means of escape (running and flying in these examples). animal's distressed, but otherwise they have more mundane uses. > the ability to put them to efficient use. Unless it was all bluff.
/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.drinkjava2.cglib.core; import com.github.drinkjava2.asm.Type; public class Local { private Type type; private int index; public Local(int index, Type type) { this.type = type; this.index = index; } public int getIndex() { return index; } public Type getType() { return type; } }
A woman from Cheboygan in Michigan has revealed how she felt ‘shaky and sick’ after landing a massive Mega Millions prize. The lucky lady, Brenda Jewell, matched all five main white balls in the drawing on Tuesday 13th February to win $1 million and is now looking forward to a future where she will ‘be able to actually breathe’. Brenda bought her ticket at Dave’s Place, located at 9851 North Straits Highway in Cheboygan. She matched the numbers 5, 12, 15, 46 and 49 - just missing out on the Mega Ball 1 - and admitted she did not cope too well when she discovered she was a winner. “I checked my numbers and just felt shaky and sick. I’ve played for years and dreamed of winning, but you never think it’s going to happen to you,” said Brenda after coming forward to vist lottery headquarters to claim the big prize. Brenda was accompanied by her husband, although she says he did not believe her at first. They now plan to go on vacation and build a new house, but they will not go crazy and intend to save a lot of the money just to make sure their lives are easier from now on. The Mega Millions jackpot has continued to roll over since Shane Missler from Port Richey in Florida won $451 million on Friday January 5th, and the draw on Tuesday February 20th also came and went without a winner in either of the top two tiers. Take a look at the Mega Millions Numbers page to see the latest results, including a full breakdown of prizes. The jackpot for the next draw will be worth an extraordinary $204 million, and tickets can be picked up from authorised retailers in any of the participating states.
Anderson Regional Medical Center (Meridian, MS) was one of several organizations to share their financial success story during MEDITECH’s recent Revenue Cycle Summit. The event highlighted strategies our customers can take to maintain profitability while navigating industry regulations and new reimbursement models. With a renewed focus on revenue cycle and the implementation of MEDITECH’s 6.1 platform in April 2015, Anderson Regional has cut their A/R days from 95 down to 47, while also reducing lost revenue by 90 percent. All the while, the 300-bed hospital has remained in the top 2 percent nationally for patient safety and experience, according to Healthgrades. Adams detailed three of the biggest benefits he’s seen from their EHR--improved efficiency, transparency, and accountability. “The transparency of the data within the Financial Status Desktop has driven numerous efficiencies in our processes. We are now able to identify and react more quickly to trends--such as insurance denials--that can have a negative impact on our A/R days,” he said. Using the EHR’s leadership reports, executives at Anderson are accurately monitoring their staff’s progress on productivity goals. “We’re able to see the daily tasks associated to each biller and collector, so we can hold them accountable,” Adams said. Those attending HIMSS17 can learn more about Anderson Regional’s strategies for driving efficiency throughout the revenue cycle at the HIMSS Revenue Cycle Solutions Summit, next February in Orlando, FL.
So this is something I'd like to understand. As stated on this main project page, Mises Wiki content is released under Creative Commons Attribution 3.0 Unported license while Wikipedia is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported license. Now. The only difference between these two is that the latter requires any derivative works to be distributed under the same or a similar license. In other words, the content itself is freely copyable, distributable, and adaptable, but any new work created using it must also be made freely copyable, distributable, and adaptable. That's the whole point of the "share alike" provision. This means that in the case of the Mises Wiki (as it does not have this provision), the content itself is freely copyable, distributable, and adaptable, but any derivative work made using this content falls under normal copyright law...meaning that anything anyone makes using content from our Mises Wiki, they have an intellectual monopoly on, and all they have to do is attribute the base work. Thanks for the quick response and suggestion for the info source, but I didn't find much of a discussion there. The only addressing of this was your first post (which said even less about my question than you did here), and Jeff Tucker mentioning how Kinsella suggested a hybrid to allow Wikipedia content. Is there more discussion elsewhere? It’s a bit too paternalistic, rude, untrusting, to force others to do it like you do, to assume they’ll “abuse” their power. And, it might stop the work from being re-published. We want our libertarian ideas spread far and wide. I want an editor of a book considering reprinting one of our pieces to see no obstacles. A “viral share-alike” provision could be. Let ideas be free. Hmm, I guess that's why mw:Manual:$wgRightsIcon was left blank until recently! Some of our pages are imported from Wikipedia, so it's not really appropriate to have that icon at the bottom of those pages. I've thought that it might be good to create an extension that will change the copyright notice depending on how individual pages are licensed; I even filed a bug along similar (although not identical) lines. I will get to work on this immediately, and see how practicable it is. I don't like to see pages not have any license notice at all, because then people might not realize they can copy our content without asking permission. This page was last edited on 25 October 2016, at 11:49.
Can you recover pictures I accidentally deleted on my memory card? Yes we can recover accidental deletions for memory cards. However, if you continued to use the memory card after you deleted the photos, then the pictures deleted will be overwritten and irretrievable. For every picture you take on the card, another picture will be overwritten. Best chance of recovery is to send the card into us as soon as the photos are deleted. Flash Fixers 2016-03-11T14:21:24+00:00 March 11th, 2016|Comments Off on Can you recover pictures I accidentally deleted on my memory card?
SubRosa - a community space: It's Spring! Time for scavenging! It's Spring! Time for scavenging! It's spring! Sunshine! Clear skies. Here at SubRosa folks are emerging from their winter cocoon, and there's a bustle of activities around the space. People feels active and smiley and social. This brings to mind two synchronous possibilities: 1) You may be doing a little spring cleaning, and 2) SubRosa staff will be putting some extra love into the space in a series of spring workdays. Perhaps we can provide a little mutual support. Here is our scavenge list, things we find we are needing around the space. Can you look in your garage or backlot or squat to see if you might have a few things on this list? Oh and a 6 or 7 foot step ladder!
<?php $loader = require dirname(dirname(dirname(dirname(dirname(__FILE__))))) . DS . 'vendor' . DS . 'autoload.php'; $loader->setPsr4("makallio85\\YamlRoute\\Test\\", dirname(dirname(dirname(dirname(dirname(__FILE__))))) . DS . 'vendor' . DS . 'makallio85' . DS . 'yaml-route' . DS . 'tests' . DS . 'YamlRoute'); require_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . DS . 'config' . DS . 'bootstrap.php'; \Cake\Core\Configure::write( ['plugins' => [ 'PluginCars' => dirname(dirname(dirname(dirname(dirname(__FILE__))))) . DS . 'plugins' . DS . 'PluginCars', 'PluginAnimals' => dirname(dirname(dirname(dirname(dirname(__FILE__))))) . DS . 'plugins' . DS . 'PluginAnimals', ]] );