answer
stringlengths
15
1.25M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace <API key>.Objects { public class Price { public int Amount { get; set; } public float PriceValue { get; set; } public bool Special { get; set; } } }
.heroEl { font-size: 13px; line-height: 18px; } .nameValue { font-size: 18px; line-height: 20px; } .charsheetList { list-style-type: none; display: inline; } .statItem { display: inline; } .statItem img { padding: 0 1px 4px 0; vertical-align: middle; } li.statItem { padding-left: 2px; } li.statItem:first-child { padding-left: 0; } .statValue { font-size: 14px; line-height: 20px; } #heroesList .nameValue { display: inline-block; width: 200px; } #heroesList ul { padding-left: 1em; } #heroesList li { padding: 3px 3px 3px 5px; } #heroesList li.heroEl:nth-child(odd) { background: #d0d0d0; }
(function(FM) { Ractive.components.color = Ractive.extend({ template: "<input type='color' value='{{hex}}'>", computed: { hex: { get: function() { return FM.argb_to_hex(this.get('argb')); }, set: function(hex) { this.set('argb', FM.hex_to_argb(hex)); } } } }); Ractive.components.font = Ractive.extend({ template: "<style>\n" + "@font-face {\n" + " font-family: {{name}};\n" + " src: url(data:font/ttf;base64,{{data}}) format('truetype');\n" + "};\n" + "</style>" }); Ractive.components.image = Ractive.extend({ template: "<style>\n" + ".image-{{name}} {\n" + " width: {{width}}px;\n" + " height: {{height}}px;\n" + " background: url({{src}});\n" + "};\n" + "</style>" }); FM.prototype.init_editor = function() { var fm = this; console.log("Initializing Editor"); fm.editor = {}; fm.editor.ractive = new Ractive({ el: fm.options.editor, template: '#editor-template', data: fm, debug: true }); r = fm.editor.ractive; r.on('call', function(event, method) { console.log(event, event.context, method); event.context[method](); }); r.on('removeLayer', function(event, method) { console.log(this, event, method); fm.face.watchface.splice(event.index.index, 1); fm.face.watchface.splice(event.index.index, 1); }); r.on('moveLayerUp', function(event, method) { var path = event.keypath.substring(0, event.keypath.lastIndexOf(".") + 1), index = event.index.index; var lower = r.get(path + (index - 1)), upper = r.get(path + (index)); r.set(path + (index), lower); r.set(path + (index - 1), upper); fm.normalize_ids(); }); r.on('moveLayerDown', function(event, method) { var path = event.keypath.substring(0, event.keypath.lastIndexOf(".") + 1), index = event.index.index; var lower = r.get(path + (index)), upper = r.get(path + (index + 1)); r.set(path + (index), upper); r.set(path + (index + 1), lower); fm.normalize_ids(); }); function intObserv(n, o, k) { this.set(k, parseInt(n)); } r.observe( 'face.watchface.*.alignment face.watchface.*.transform face.watchface.*.shape_type ' + 'face.watchface.*.shape_opt', intObserv.bind(r) ); return true; }; FM.prototype.reload_editor = function() { this.editor.ractive.reset(this); }; FM.prototype.remove_layer = function() { console.log(this); }; FM.prototype.add_font_file = function(font_file) { var fm = this, r = fm.editor.ractive, hash = null, font = {}; font.name = family_name; font.filename = font_name; font.file = file; font.data = data; r.set("face.fonts." + font.name, font); }; FM.prototype.add_image_file = function(image_file) { var fm = this, r = fm.editor.ractive, hash = null, image = { file: image_file, }; r.set("face.images." + hash, image); }; FM.BLANK_SHAPE = { "color": "-1", "id": 0, "low_power": true, "opacity": "100", "r": "0", "radius": "50", "shape_opt": 0, "shape_type": 1, "sides": "6", "stroke_size": "5", "type": "shape", "height": "50", "width": "50", "x": "0", "y": "0" }; FM.BLANK_IMAGE = { "alignment": 4, "hash": "", "height": "0", "id": 0, "low_power": true, "opacity": "100", "r": "0", "type": "image", "width": "0", "x": "0", "y": "0" }; FM.BLANK_TEXT = { "alignment": 1, "bgcolor": "0", "color": "-1", "low_power_color": "-1", "bold": false, "font_family": 0, "id": 0, "italic": false, "low_power": true, "opacity": "100", "r": "0", "size": "24", "text": "New Text", "transform": 0, "type": "text", "x": "0", "y": "0" }; FM.prototype.add_shape = function() { var fm = this, new_shape = $.extend({}, FM.BLANK_SHAPE); fm.editor.ractive.push("face.watchface", new_shape); fm.normalize_ids() }; FM.prototype.add_text = function() { var fm = this, new_text = $.extend({}, FM.BLANK_TEXT); fm.editor.ractive.push("face.watchface", new_text); fm.normalize_ids() }; FM.prototype.add_image = function() { console.log("add_image"); var fm = this, new_image = $.extend({}, FM.BLANK_IMAGE); fm.editor.ractive.push("face.watchface", new_image); fm.normalize_ids() }; FM.prototype.normalize_ids = function() { var fm = this, r = fm.editor.ractive, faces = r.get('face.watchface'), i = faces.length; while (i r.set('face.watchface.' + i + '.id', i); } }; })(FaceMaker)
#include "sendmessagesentry.h" #include "<API key>.h" #include "guiutil.h" #include "addressbookpage.h" #include "walletmodel.h" #include "messagemodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "smessage.h" #include <QApplication> #include <QClipboard> SendMessagesEntry::SendMessagesEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendMessagesEntry), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC ui->sendToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->sendTo->setPlaceholderText(tr("Enter a BZLCoin address (e.g. <API key>)")); ui->publicKey->setPlaceholderText(tr("Enter the public key for the address above, it is not in the blockchain")); ui->messageText->setErrorText(tr("You cannot send a blank message!")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->sendTo); GUIUtil::setupAddressWidget(ui->sendTo, this); } SendMessagesEntry::~SendMessagesEntry() { delete ui; } void SendMessagesEntry::<API key>() { // Paste text from clipboard into recipient field ui->sendTo->setText(QApplication::clipboard()->text()); } void SendMessagesEntry::<API key>() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getWalletModel()-><API key>()); if(dlg.exec()) { ui->sendTo->setText(dlg.getReturnValue()); if(ui->publicKey->text() == "") ui->publicKey->setFocus(); else ui->messageText->setFocus(); } } void SendMessagesEntry::<API key>(const QString &address) { if(!model) return; QString pubkey; QString sendTo = address; if(model->getAddressOrPubkey(sendTo, pubkey)) { ui->publicKey->setText(pubkey); } else { ui->publicKey->show(); ui->publicKeyLabel->show(); } // Fill in label from address book, if address has an associated label QString associatedLabel = model->getWalletModel()-><API key>()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendMessagesEntry::setModel(MessageModel *model) { this->model = model; //clear(); } void SendMessagesEntry::loadRow(int row) { if(model->data(model->index(row, model->Type, QModelIndex()), Qt::DisplayRole).toString() == MessageModel::Received) ui->sendTo->setText(model->data(model->index(row, model->FromAddress, QModelIndex()), Qt::DisplayRole).toString()); else ui->sendTo->setText(model->data(model->index(row, model->ToAddress, QModelIndex()), Qt::DisplayRole).toString()); } void SendMessagesEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendMessagesEntry::clear() { ui->sendTo->clear(); ui->addAsLabel->clear(); ui->messageText->clear(); ui->sendTo->setFocus(); } void SendMessagesEntry::<API key>() { emit removeEntry(this); } bool SendMessagesEntry::validate() { // Check input validity bool retval = true; if(ui->messageText->toPlainText() == "") { ui->messageText->setValid(false); retval = false; } if(!ui->sendTo->hasAcceptableInput() || (!model->getWalletModel()->validateAddress(ui->sendTo->text()))) { ui->sendTo->setValid(false); retval = false; } if(ui->publicKey->text() == "") { ui->publicKey->setValid(false); ui->publicKey->show(); retval = false; } return retval; } <API key> SendMessagesEntry::getValue() { <API key> rv; rv.address = ui->sendTo->text(); rv.label = ui->addAsLabel->text(); rv.pubkey = ui->publicKey->text(); rv.message = ui->messageText->toPlainText(); return rv; } QWidget *SendMessagesEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->sendTo); QWidget::setTabOrder(ui->sendTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); QWidget::setTabOrder(ui->addAsLabel, ui->publicKey); QWidget::setTabOrder(ui->publicKey, ui->messageText); return ui->messageText; } void SendMessagesEntry::setValue(const <API key> &value) { ui->sendTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->publicKey->setText(value.pubkey); ui->messageText->setPlainText(value.message); } bool SendMessagesEntry::isClear() { return ui->sendTo->text().isEmpty(); } void SendMessagesEntry::setFocus() { ui->sendTo->setFocus(); }
package me.shadaj.genalgo.alignment import me.shadaj.genalgo.sequences.{BioSequence, BaseLike, Indel} import java.awt.image.BufferedImage import java.awt.{Color, Graphics2D} import java.io.File import javax.imageio.ImageIO class Alignment[B <: BaseLike, C <: BioSequence[B]]( val seq1: AlignmentSequence[B], val seq2: AlignmentSequence[B], val score: Int) { override def toString = { val comparison = seq1.zip(seq2).map { case (b1, b2) => if (b1.isRight || b2.isRight) { " " } else if (b1 != b2) { ":" } else { "*" } }.mkString seq1 + "\n" + seq2 + "\n" + comparison } def toImage(height: Int = 160) = { val comparisonWidth = seq1.length val image = new BufferedImage(comparisonWidth, height, BufferedImage.TYPE_INT_RGB) val graphics = image.getGraphics.asInstanceOf[Graphics2D] graphics.setColor(Color.white) graphics.fillRect(0, 0, comparisonWidth, height) seq1.zip(seq2).zipWithIndex.foreach { case ((b1, b2), index) => if (b1.isRight) { graphics.setColor(Color.blue) graphics.drawLine(index, 0, index, height/2) } else if (b2.isRight) { graphics.setColor(Color.blue) graphics.drawLine(index, height/2, index, height) } else if (b1 != b2) { graphics.setColor(Color.red) graphics.drawLine(index, 0, index, height) } else { graphics.setColor(Color.green) graphics.drawLine(index, 0, index, height) } } image } def toImageFile(file: File, height: Int = 160) = { ImageIO.write(toImage(height), "png", file) } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Mirror II - n montano</title> <meta name="description" content="An english cocker spaniel walked into the elegant room. It had unkempt fur that shaggily covered its eyes. Montano, having changed out of his nun habit,..."> <link href='https://fonts.googleapis.com/css?family=Roboto+Mono|Roboto:300,400,900,400italic' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="/css/main.css"> <link rel="canonical" href="http://erikradio.github.io/2010/08/Mirror-II"> <link rel="alternate" type="application/rss+xml" title="n montano" href="http://erikradio.github.io/feed.xml"> </head> <body> <main class="u-container"> <div class="c-page"> <header class="c-page__header"> <p> <a href="/">*</a> <!-- <span class="u-separate"></span> <a href="/about/">About</a><span class="u-separate"></span><a href="/feed.xml">RSS</a> --> </p> </header> <div class="c-page__main"> <article class="c-article"> <header class="c-article__header"> <h1 class="c-article__title">Mirror II</h1> <p class="c-article__time"><time datetime="2010-08-15T00:00:00-05:00" itemprop="datePublished">Aug 15, 2010</time></p> </header> <div class="c-article__main"> <p>An english cocker spaniel walked into the elegant room. It had unkempt fur that shaggily covered its eyes. Montano, having changed out of his nun habit, approached and bent down to pet it. “Ohhhhh are you my pluppy dog?” he asked. It was not The One Who Left.</p> </div> <footer class="c-article__footer"> <p> </p> </footer> </article> </div> <footer class="c-page__footer"> <p>&copy; erik radio 2016</p> <!-- <p>Follow: </p> --> </footer> </div> </main> </body> </html>
<h1><a href="index.html">angular-elevatezoom-<b>plus</b></a></h1> <ul> <li><a ng-class="{active: $state.includes('main')} " ui-sref="main">Home</a></li> <li><a ng-class="{active: $state.includes('api')} " ui-sref="api">API &amp; Options</a></li> <li><a ng-class="{active: $state.includes('examples')} " ui-sref="examples">Examples</a></li> </ul>
var webshot = require('webshot'); var screenConfig = { thumb: { siteType: 'url', streamType: 'png', <API key>: true, screenSize: { width: 640, height: 480 }, shotSize: { width: 640, height: 480 } }, mobile: { siteType: 'url', streamType: 'png', <API key>: true, screenSize: { width: 320, height: 480 }, shotSize: { width: 'all', height: 'all' } }, desktop: { siteType: 'url', streamType: 'png', <API key>: true, screenSize: { width: 960, height: 540 }, shotSize: { width: 'all', height: 'all' } }, document: { siteType: 'url', streamType: 'png', <API key>: false, screenSize: { width: 800, height: 600 }, shotSize: { width: 800, height: 600 } }, component: { siteType: 'url', streamType: 'png', <API key>: true, captureSelector: '#Standalone-wrapper', screenSize: { width: 0 } }, }; var queue = []; function screenshot() { if (queue.length) { console.log('queue.length', queue.length); var job = queue.pop(); webshot(job.url, job.dest, job.config, (err) => { if (err) { throw new Error(err); } console.log(`Screen ${job.url} saved to ${job.dest}`); screenshot(); }); } } function parseComponents(structure, baseUrl) { Object.keys(structure).forEach((componentName) => { var component = structure[componentName]; var url = `${baseUrl}/api${component.id}?_screenshot=true`; var dest = `dist/screens${component.id}.png` var publicpath = `/assets/screens${component.id}.png`; var config; if (component.children) { parseComponents(component.children, baseUrl); } if (component.template) { url = url + '&_standalone=true' config = component.category === 'view' ? screenConfig.desktop : screenConfig.component; } else if (component.example) { url = url + '&_type=example' config = screenConfig.thumb; } else if (component.script) { url = url + '&_type=js' config = screenConfig.thumb; } else if (component.styles) { url = url + '&_type=css' config = screenConfig.thumb; } else if (component.info && !component.children) { url = url + '&_type=info' config = screenConfig.document; } else { return false; } queue.push({ url, dest, config }); component.screen = publicpath; }); } function screenDump (structure, group, baseUrl) { if (group) { parseComponents(structure[group], baseUrl); } else { // parse all root categories Object.keys(structure).forEach((group) => { parseComponents(structure[group], baseUrl); }); } screenshot(); } module.exports = screenDump;
SUBROUTINE INT_READ( I_VAL, BUFF, IP ) !*********************************************************************** !* Reads a 4-Byte Integer from Buffer and Advances Pointer !* !* Language: Fortran !* !* Author: Stuart G. Mentzer !* !* Date: 1999/08/20 !*********************************************************************** INTEGER I_VAL, IP, I_REP CHARACTER BUFF*(*), C_REP*4 EQUIVALENCE ( I_REP, C_REP ) ! Load the integer from current position in buffer C_REP = BUFF(IP:IP+3) I_VAL = I_REP ! Use integer to avoid invalid non-native fl. pt. ! Advance buffer pointer IP = IP + 4 RETURN END SUBROUTINE REAL_READ( R_VAL, BUFF, IP ) !*********************************************************************** !* Reads a 4-Byte Real from Buffer and Advances Pointer !* . Real is aliased as integer to handle non-native fl. pt. values !* !* Language: Fortran !* !* Author: Stuart G. Mentzer !* !* Date: 1999/08/20 !*********************************************************************** INTEGER R_VAL, IP, I_REP CHARACTER BUFF*(*), C_REP*4 EQUIVALENCE ( I_REP, C_REP ) ! Load the integer from current position in buffer C_REP = BUFF(IP:IP+3) R_VAL = I_REP ! Use integer to avoid invalid non-native fl. pt. ! Advance buffer pointer IP = IP + 4 RETURN END SUBROUTINE STR_READ( S_VAL, BUFF, IP ) !*********************************************************************** !* Reads a String Field from Buffer and Advances Pointer !* !* Language: Fortran !* !* Author: Stuart G. Mentzer !* !* Date: 1999/08/20 !*********************************************************************** INTEGER IP, S_LEN CHARACTER S_VAL*(*), BUFF*(*) ! Load the string from current position in buffer S_LEN = LEN( S_VAL ) S_VAL = BUFF(IP:IP+S_LEN-1) ! Advance buffer pointer IP = IP + S_LEN RETURN END
function repeat(pattern, count) { "use strict"; if (count < 1) return ''; var result = ''; while (count > 0) { if (count & 1) result += pattern; count >>= 1; pattern += pattern; } return result; } // Convert a byte array to a hex string var bytesToHex = function (bytes) { "use strict"; for (var hex = [], i = 0; i < bytes.length; i++) { hex.push((bytes[i] >>> 4).toString(16)); hex.push((bytes[i] & 0xF).toString(16)); } return hex.join(""); }; // Convert a hex string to a byte array var hexToBytes = function (hex, length) { "use strict"; var str = hex.length % 2 ? "0" + hex : hex; if(length){ str = (repeat("00", length) + str); str = str.substr(str.length - length * 2); } for (var bytes = [], c = 0; c < str.length; c += 2) bytes.push(parseInt(str.substr(c, 2), 16)); return bytes; }; var dateToStr = function(date, onlyNums) { "use strict"; var z = function(i) { if (parseInt(i) < 10) return "0" + i; return i; }; if(onlyNums){ return '' + date.getFullYear() + z(date.getMonth() + 1) + z(date.getDate())+ '_' + z(date.getHours()) + z(date.getMinutes()); } return '' + date.getFullYear() + '-' + z(date.getMonth() + 1) + '-' + z(date.getDate()) + ' ' + z(date.getHours()) + ':' + z(date.getMinutes()); }; var b64tohex = function(b64) { "use strict"; var s = atob(b64), ret = ''; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i).toString(16); if (c.length != 2) c = '0' + c; ret += c; } return ret; }; var hex2b64 = function(hex) { "use strict"; var ret = ''; for (var i = 0; i < hex.length; i += 2) { ret += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); } return btoa(ret); }; var strToDataUri = function(str){ "use strict"; return arrayBufferDataUri(stringToByteArray(str)); }; var stringToByteArray = function(str) { "use strict"; var array = makeUin8(str.length), i, il; for (i = 0, il = str.length; i < il; ++i) { array[i] = str.charCodeAt(i) & 0xff; } return array; }; var arrayBufferDataUri = function(raw) { "use strict"; var base64 = '', encodings = '<API key>+/', bytes = new Uint8Array(raw), byteLength = bytes.byteLength, byteRemainder = byteLength % 3, mainLength = byteLength - byteRemainder, a, b, c, d, chunk; // Main loop deals with bytes in chunks of 3 for (var i = 0; i < mainLength; i = i + 3) { // Combine the three bytes into a single integer chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; // Use bitmasks to extract 6-bit segments from the triplet a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18 b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12 c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6 d = chunk & 63; // 63 = 2^6 - 1 // Convert the raw binary segments to the appropriate ASCII encoding base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; } // Deal with the remaining bytes and padding if (byteRemainder == 1) { chunk = bytes[mainLength]; a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2 // Set the 4 least significant bits to zero b = (chunk & 3) << 4; // 3 = 2^2 - 1 base64 += encodings[a] + encodings[b] + '=='; } else if (byteRemainder == 2) { chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]; a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10 b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4 // Set the 2 least significant bits to zero c = (chunk & 15) << 2; // 15 = 2^4 - 1 base64 += encodings[a] + encodings[b] + encodings[c] + '='; } return base64; }; var dataURLtoUint8Array = function(dataURL, dataType) { "use strict"; // Decode the dataURL var binary = atob(dataURL.split(',')[1]); // Create 8-bit unsigned array var array = []; for (var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } // Return our Blob object return new Uint8Array(array); }; var uint8toBlob = function(data, dataType) { "use strict"; return new Blob([data], { type: dataType }); }; var appendBuffer = function(buffer1, buffer2) { "use strict"; var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength); tmp.set(buffer1, 0); tmp.set(buffer2, buffer1.byteLength); return tmp; }; var ab2Str = function(buffer) { "use strict"; var length = buffer.length; var result = ''; for (var i = 0; i < length; i += 65535) { var addition = 65535; if (i + 65535 > length) { addition = length - i; } result += String.fromCharCode.apply(null, buffer.subarray(i, i + addition)); } return result; }; var getHost = function(url){ "use strict"; var a = document.createElement('a'); a.href = url; return {href: a.href, host: a.host, crossdomain: location.host.toLowerCase() != a.host.toLowerCase()}; }; var getURLasAB = function(rawURL, cb) { "use strict"; var url = getHost(rawURL); if(["2ch.hk", "2ch.pm", "2ch.re", "2ch.tf", "2ch.wf", "2ch.yt", "2-ch.so"].indexOf(url.host.toLowerCase()) != -1){ url.href += "?t=" + Math.floor(Math.random()*1000000); } /*jshint newcap: false */ if (typeof GM_xmlhttpRequest === "function") { GM_xmlhttpRequest({ method: "GET", url: url.href, overrideMimeType: "text/plain; charset=x-user-defined", onload: function(oEvent) { var ff_buffer = stringToByteArray(oEvent.responseText || oEvent.response); cb(ff_buffer.buffer, new Date(0)); } }); }else{ var oReq = new XMLHttpRequest(); oReq.open("GET", url.href, true); oReq.responseType = "arraybuffer"; oReq.onload = function(oEvent) { cb(oReq.response, new Date(oEvent.target.getResponseHeader('Last-Modified'))); }; oReq.send(null); } }; var padBytes = function (array, length) { "use strict"; if (length === undefined) { length = fieldSize; } for (var i = 0; array.length < length; ++i) { array.unshift(0); } return array; }; var shuffleArray = function (array) { "use strict"; var counter = array.length, temp, index; // While there are elements in the array while (counter > 0) { // Pick a random index index = Math.floor(Math.random() * counter); // Decrease counter by 1 counter // And swap the last element with it temp = array[counter]; array[counter] = array[index]; array[index] = temp; } return array; }; var xorBytes = function (a, b) { "use strict"; if (a.length != b.length) { throw new Error("Длины не сходятся"); } for (var i in a) { a[i] ^= b[i]; } return a; };
class Topic < ActiveRecord::Base <API key> end
@extends('app') @section('title', '') @section('content') <h2 class="ui teal header center aligned"> </h2> <a href="{{ route('sensor.index') }}" class="ui icon blue inverted button"> <i class="arrow left icon" aria-hidden="true"></i> </a> {!! Form::open([ 'method' => 'POST', 'route' => ['envdata.clear'], 'style' => 'display: inline', 'onSubmit' => "return confirm('');" ]) !!} <button type="submit" class="ui icon red inverted button"> <i class="recycle icon"></i> </button> {!! Form::close() !!} <table class="ui selectable celled padded unstackable table"> <thead> <tr style="text-align: center"> <th class="single line"></th> <th class="single line"></th> <th class="single line"></th> <th class="single line"></th> </tr> </thead> <tbody> @foreach($datas as $data) <tr> <td class="two wide"> {{ $data->created_at }} </td> <td class="three wide"> {{ $data->sensor->name }}<br> <small><i class="angle double right icon"></i>{{ $data->sensor->type }}/{{ $data->sensor->location }}</small> </td> <td> {{ $data->data }} {{ $data->sensor->unit }} </td> <td class="two wide"> {!! Form::open([ 'method' => 'DELETE', 'route' => ['envdata.destroy', $data], 'style' => 'display: inline', 'onSubmit' => "return confirm('');" ]) !!} <button type="submit" class="ui icon red inverted disabled button"> <i class="trash icon"></i> </button> {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> @endsection
import random import arcade SPRITE_SCALING = 0.5 SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 MOVEMENT_SPEED = 5 window = None class MyApplication(arcade.Window): """ Main application class. """ def setup(self): """ Set up the game and initialize the variables. """ # Sprite lists self.all_sprites_list = arcade.SpriteList() self.wall_list = arcade.SpriteList() # Set up the player self.score = 0 self.player_sprite = arcade.Sprite("images/character.png", SPRITE_SCALING) self.player_sprite.center_x = 50 self.player_sprite.center_y = 64 self.all_sprites_list.append(self.player_sprite) # -- Set up the walls # Create a row of boxes for x in range(173, 650, 64): wall = arcade.Sprite("images/boxCrate_double.png", SPRITE_SCALING) wall.center_x = x wall.center_y = 200 self.all_sprites_list.append(wall) self.wall_list.append(wall) # Create a column of boxes for y in range(273, 500, 64): wall = arcade.Sprite("images/boxCrate_double.png", SPRITE_SCALING) wall.center_x = 465 wall.center_y = y self.all_sprites_list.append(wall) self.wall_list.append(wall) self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.wall_list) # Set the background color arcade.<API key>(arcade.color.AMAZON) def on_draw(self): """ Render the screen. """ # This command has to happen before we start drawing arcade.start_render() # Draw all the sprites. self.all_sprites_list.draw() # Put the text on the screen. output = "Score: {}".format(self.score) arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14) def on_key_press(self, key, modifiers): """ Called whenever the mouse moves. """ if key == arcade.key.UP: self.player_sprite.change_y = MOVEMENT_SPEED elif key == arcade.key.DOWN: self.player_sprite.change_y = -MOVEMENT_SPEED elif key == arcade.key.LEFT: self.player_sprite.change_x = -MOVEMENT_SPEED elif key == arcade.key.RIGHT: self.player_sprite.change_x = MOVEMENT_SPEED def on_key_release(self, key, modifiers): """ Called when the user presses a mouse button. """ if key == arcade.key.UP or key == arcade.key.DOWN: self.player_sprite.change_y = 0 elif key == arcade.key.LEFT or key == arcade.key.RIGHT: self.player_sprite.change_x = 0 def animate(self, delta_time): """ Movement and game logic """ # Call update on all sprites (The sprites don't do much in this # example though.) self.physics_engine.update() window = MyApplication(SCREEN_WIDTH, SCREEN_HEIGHT) window.setup() arcade.run()
#sideNav{ -<API key>: linear; <API key>: linear; height:100vh; }
class <API key> < ActiveRecord::Migration def up change_column :defendants, :phone_number, :string, null: true end def down change_column :defendants, :phone_number, :string, null: false end end
# == Schema Information # Table name: <API key> # id :integer not null, primary key # customer_order_id :integer not null # provider_item_id :integer not null # <API key> :integer # <API key> :string default("USD"), not null # cantidad :integer default(1), not null # observaciones :text # created_at :datetime not null # updated_at :datetime not null class CustomerOrderItem < ActiveRecord::Base monetize :<API key>, numericality: false, allow_nil: true begin :relationships belongs_to :customer_order belongs_to :provider_item end begin :callbacks after_save :<API key>! after_save :<API key>! after_destroy :<API key>! after_destroy :<API key>! end begin :validations validates :cantidad, numericality: { greater_than: 0, only_integer: true } validates :<API key>, allow_nil: true, numericality: { greater_than: 0 } validate :<API key> end # @return [Money] def subtotal cantidad * <API key> end # reads cached <API key> if present # or asks the provider_item otherwise # @return [Money] def <API key> cached_precio = read_attribute(:<API key>) if cached_precio.present? Money.new( cached_precio, <API key> # DB defaults it to USD ) else provider_item.precio end end # re-adds this customer order item to the cart # including new attributes def <API key>(parameters) self.cantidad += parameters[:cantidad].to_i if parameters[:observaciones].present? self.observaciones = self.observaciones.to_s + "\n" + parameters[:observaciones] end end def <API key>! update_attribute( :<API key>, provider_item.precio ) end def <API key>! customer_order.<API key>! end def <API key>! if <API key>.blank? customer_order.deliveries.create!( delivery_method: "shipping", customer_order: customer_order, provider_profile: provider_item.provider_profile, customer_address: customer_order.customer_profile.customer_addresses.first ) end end def <API key>! <API key> = customer_order.<API key>( provider_item.provider_profile ) if <API key>.none? <API key>.destroy end end def <API key> customer_order.<API key>( provider_item.provider_profile ) end private def <API key> if cantidad > provider_item.cantidad errors.add(:cantidad, :<API key>, count: provider_item.cantidad, num: cantidad) end end end
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "twitter_current");
<?php /* CroogoNav::add('sidebar', 'blocks', array( 'icon' => 'columns', 'title' => __d('croogo', 'Blocks'), 'url' => array( 'admin' => true, 'plugin' => 'blocks', 'controller' => 'blocks', 'action' => 'index', ), 'weight' => 30, 'children' => array( 'blocks' => array( 'title' => __d('croogo', 'Blocks'), 'url' => array( 'admin' => true, 'plugin' => 'blocks', 'controller' => 'blocks', 'action' => 'index', ), ), 'regions' => array( 'title' => __d('croogo', 'Regions'), 'url' => array( 'admin' => true, 'plugin' => 'blocks', 'controller' => 'regions', 'action' => 'index', ), ), ), ));*/
layout: post title: "[Lua] MetaTable and MetaMethod" date: 2017-07-27 author: mdgsf comments: true categories: lua tags: [Lua] description: published: true #default true lua fraction_a = {numerator=2, denominator=3} fraction_b = {numerator=4, denominator=7} 2/3 + 4/7 fraction_a + fraction_b MetaTable lua fraction_op={} function fraction_op.__add(f1, f2) ret = {} ret.numerator = f1.numerator * f2.denominator + f2.numerator * f1.denominator ret.denominator = f1.denominator * f2.denominator return ret end tableMetaTablesetmetatble lua setmetatable(fraction_a, fraction_op) setmetatable(fraction_b, fraction_op) fraction_op.__add() lua fraction_s = fraction_a + fraction_b __addMetaMethodLuaMetaMethod lua __add(a, b) a + b __sub(a, b) a - b __mul(a, b) a * b __div(a, b) a / b __mod(a, b) a % b __pow(a, b) a ^ b __unm(a) -a __concat(a, b) a .. b __len(a) __eq(a, b) a == b __lt(a, b) a < b __le(a, b) a <= b __index(a, b) a.b __newindex(a, b, c) a.b = c __call(a, ...) a(...) lua Set = {} Set.mt = {} -- metatable for sets function Set.new(t) t = t or {} local set = {} setmetatable(set, Set.mt) for _, l in ipairs(t) do set[l] = true end return set end function Set.union(a, b) if getmetatable(a) ~= Set.mt or getmetatable(b) ~= Set.mt then error("Attempt to 'add' a set with a not-set value", 2) end local res = Set.new() for k in pairs(a) do res[k] = true end for k in pairs(b) do res[k] = true end return res end function Set.intersection(a, b) local res = Set.new() for k in pairs(a) do res[k] = b[k] end return res end function Set.tostring(set) set = set or {} local s = "{" local sep = "" for e in pairs(set) do s = s .. sep .. e sep = ", " end return s .. "}" end function Set.print(s) print(Set.tostring(s)) end Set.mt.__add = Set.union Set.mt.__mul = Set.intersection s1 = Set.new({10, 20, 30, 50}) s2 = Set.new({30, 1}) print(getmetatable(s1)) print(getmetatable(s2)) Set.print(s1) Set.print(s2) s3 = s1 + s2 Set.print(s3) s = Set.new({1, 2, 3}) -- s = s + 8 -- table Set.print(s1 * s2) print(" print(s1) print(s2) -- print__tostring__tostring Set.mt.__tostring = Set.tostring print(s1) print(s2) <a href="http: <a href="http:
<?php namespace FMUP\Crypt; interface CryptInterface { /** * Hash the given string * @param string $string * @return string */ public function hash($string); /** * UnHash the given string * @param string $string * @return string */ public function unHash($string); }
package hr.caellian.flow.network.transfer; import hr.caellian.flow.data.Property; import java.util.HashMap; /** * Flux conductors are objects which support Flux flow and * contain properties which can affect it. * * @author Caellian * @since 1.0.0 */ public interface FluxConductor { /** * @return {@link HashMap} containing properties of this conductor. */ HashMap<String, Property> getProperties(); /** * @param ID ID of property to search for. * @return {@code true} if this conductor has a property with the specified * ID, {@code false} otherwise. */ default boolean hasProperty(String ID) { return getProperties().containsKey(ID); } /** * @param ID ID of property to search for. * @return Property with specified ID. */ default Property getProperty(String ID) { return getProperties().get(ID); } }
title: Welcome! published: true date: '2017-09-23 15:22' **This website is actively under construction!** If you're reading this, I'm not done with this website. I have no schedule to which I adhere, so it'll be done when it's done! ## My Goal Hi there! I want to provide step-by-step tutorials on how to set up and run various handy services using a Raspberry Pi. These guides will be limited to the realm of a homelab type environment, and only cover things that I've done myself and managed to get working. To write the content of this site, I'm translating my personal rough notes into beautified, followable, and understandable pages. ## Things to note * This website is running on my **Raspberry Pi 2**, so that's promising * I'm using **Raspbian Jessie**. At the time of writing, the next version of Raspbian dubbed "Stretch" has been released; however, I don't plan on updating until I know that issues have been ironed out. * Near the beginning I'll be more precise and long-winded, because my notes are also more detailed * As things get moving, I'll become more concise as both your understanding grows and my notes get thinner * As much as I'd like to give superbly thorough instructions all the way through, I'm not willing to re-build my raspi now that everything's configured and working harmoniously * Most of my notes have been compiled by taking fragments of a solution from multiple locations and after hours of searching. As such, I didn't bother to source a lot of my content. I will when I can. **My goal isn't to write a paper with a huge bibliography; I want to record the results of my experiences for your benefit, not make you slog through Google!**
var log = require('./logger') var assert = require('assert-plus') var xmlns1 = require('./xml').ns1; var escapeZOQL = require('./xml').escapeZOQL; var common = require('./common'); var makeError = require('./common').makeError; function query (querystring, options, cb) { if (typeof options === 'function') { cb = options; options = {}; } assert.ok(this.client._client.ZuoraService.Soap, 'missing `ZuoraService.Soap` on client reference') var client = this.client; // TODO: change how we attach this extra hasQueryOptions thing // can check the headers themselves ? unless is string if (!client.hasQueryOptions) { var headers = { 'QueryOptions': options } client._client.addSoapHeader(headers, '', xmlns1) client.hasQueryOptions = true; } var results = []; var resultStream; // TODO: create a stream for output // options for request.js for 'timeout' var requestOptions; if (options.timeout) { requestOptions = {timeout: options.timeout}; options.timeout = null; } else { requestOptions = client._requestOptions; } var zObject = { 'queryString': escapeZOQL(querystring) }; var add = function(result) { results.push.apply(results, result); // resultStream.push() // TODO: push onto stream } var onQueryResponse = function(err, res, body) { common.printDebugMessages(client, err, res); if (err) { return cb(makeError(err, { lastRequest: client.lastRequest, lastResponse: client.lastResponse })); } if (res) { add(res.records); if (!res.done) { log.debug('Next queryLocator is ' + res.queryLocator + ' of ' + res.size) var zMorePls = { 'queryLocator': res.queryLocator }; var doQueryMore = makeQueryMore(zMorePls); function makeQueryMore(zQueryLocator) { return function () { log.debug('Requesting with:\n' + JSON.stringify(zQueryLocator) ); client.runSoapMethod('queryMore', zQueryLocator, onQueryResponse, requestOptions); } } doQueryMore(); } else { return cb(null, results); } } else { return cb(new Error('Query results missing')); } } function doQuery() { client.runSoapMethod('query', zObject, onQueryResponse, requestOptions); } doQuery(); function makeResponseHandler(Fn, xmlPayload, onResponse) { return function runFn() { var _onResponse = onResponse.bind({retry: runFn}); // wrap in login Fn(xmlPayload, _onResponse, requestOptions); } runFn(); } } function attachQuery(xmasTree) { xmasTree.query = query; return xmasTree; } module.exports = attachQuery;
/// <reference path="jquery-3.4.1.js" /> <reference path="modernizr-2.8.3.js" /> <reference path="jquery-ui-1.12.1.js" /> <reference path="jquery.validate.js" /> <reference path="jquery.validate.unobtrusive.js" /> <reference path="knockout-3.4.0.debug.js" />
import React from "react"; import classNames from "classnames"; import { Field } from "redux-form"; import DateSelector from "./DateSelector"; // produces an array [start..end-1] const range = (start, end) => Array.from({ length: end - start }, (v, k) => k + start); // produces an array [start..end-1] padded with zeros, (two digits) const rangeZeroPad = (start, end) => Array.from({ length: end - start }, (v, k) => ("0" + (k + start)).slice(-2)); const extractYear = value => { return extractDateToken(value, 0); }; const extractMonth = value => { return extractDateToken(value, 1); }; const extractDay = value => { return extractDateToken(value, 2); }; const extractDateToken = (value, index) => { if (!value) { return ""; } const tokens = value.split(/-/); if (tokens.length !== 3) { return ""; } return tokens[index]; }; class CompatibleDate extends React.Component { constructor(props, context) { super(props, context); this.state = { year: null, month: null, day: null, hour: null, minute: null, second: null }; this.onBlur = this.onBlur.bind(this); } // Produces a RFC 3339 full-date from the state buildRfc3339Date() { const year = this.state.year || ""; const month = this.state.month || ""; const day = this.state.day || ""; return year + "-" + month + "-" + day; } onChangeField(field, e) { const value = e.target.value; let changeset = {}; changeset[field] = value; this.setState(changeset, () => { this.props.input.onChange(this.buildRfc3339Date()); }); } onBlur() { this.props.input.onBlur(this.buildRfc3339Date()); } render() { const field = this.props; const className = classNames([ "form-group", { "has-error": field.meta.touched && field.meta.error } ]); return ( <div className={className}> <label className="control-label" htmlFor={field.id}> {field.label} </label> <ul className="list-inline"> <li> <DateSelector extractField={extractYear} range={range(field.startYear, field.endYear)} emptyOption="year" onBlur={this.onBlur} onChange={this.onChangeField.bind(this, "year")} {...field} /> </li> <li> <DateSelector extractField={extractMonth} range={rangeZeroPad(1, 13)} emptyOption="month" onBlur={this.onBlur} onChange={this.onChangeField.bind(this, "month")} {...field} /> </li> <li> <DateSelector extractField={extractDay} range={rangeZeroPad(1, 32)} emptyOption="day" onBlur={this.onBlur} onChange={this.onChangeField.bind(this, "day")} {...field} /> </li> </ul> {field.meta.touched && field.meta.error && ( <span className="help-block">{field.meta.error}</span> )} {field.description && ( <span className="help-block">{field.description}</span> )} </div> ); } } const <API key> = props => { return ( <Field component={CompatibleDate} label={props.label} name={props.fieldName} required={props.required} id={"field-" + props.fieldName} placeholder={props.schema.default} description={props.schema.description} startYear={props.schema["start-year"] || 1900} endYear={props.schema["end-year"] || new Date().getFullYear() + 5} type={props.type} /> ); }; export default <API key>; // Only for testing purposes export { extractDateToken };
/* Styling for the comments module */ .comment-form { width: 796px; margin:4px; margin-bottom:8px; border: 1px solid #333; } .comment { width: 800px; border: 1px solid #333; margin:4px; padding-left: 8px; padding-right: 8px; background: #f0f0f0; } .content { width: 800px; font-size:15px; word-break: keep-all; } .contactinfo { font-size:15px; color: grey; border-top: 1px solid grey; } .avatar { float: left; margin-top:8px; margin-right:8px; } textarea { /*font-size: 1.2em;*/ font-size: 14px; width: 780px; min-height: 50px; }
package com.demigodsrpg.demigods.greek.ability.ultimate; import com.demigodsrpg.demigods.engine.DemigodsPlugin; import com.demigodsrpg.demigods.engine.DemigodsServer; import com.demigodsrpg.demigods.engine.entity.player.attribute.Skill; import com.demigodsrpg.demigods.engine.location.DemigodsLocation; import com.demigodsrpg.demigods.engine.util.Randoms; import com.demigodsrpg.demigods.engine.util.Spigots; import com.demigodsrpg.demigods.engine.util.Zones; import com.demigodsrpg.demigods.greek.ability.GreekAbility; import com.google.common.base.Predicate; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.bukkit.*; import org.bukkit.block.BlockFace; import org.bukkit.entity.EntityType; import org.bukkit.entity.FallingBlock; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.<API key>; import org.bukkit.scheduler.BukkitRunnable; import java.util.List; import java.util.Set; public class Discoball extends GreekAbility { private static final String NAME = "Discoball of Doom", COMMAND = "discoball"; private static final int COST = 30, DELAY = 30, REPEAT = 4; private static final List<String> DETAILS = Lists.newArrayList("Spread the music while causing destruction."); private static final Skill.Type TYPE = Skill.Type.ULTIMATE; private static Set<FallingBlock> discoBalls = Sets.newHashSet(); public Discoball(String deity) { super(NAME, COMMAND, deity, COST, DELAY, REPEAT, DETAILS, TYPE, null, new Predicate<Player>() { @Override public boolean apply(final Player player) { balls(player); player.sendMessage(ChatColor.YELLOW + "Dance!"); Bukkit.getScheduler().<API key>(DemigodsPlugin.getInst(), new Runnable() { @Override public void run() { player.sendMessage(ChatColor.RED + "B" + ChatColor.GOLD + "o" + ChatColor.YELLOW + "o" + ChatColor.GREEN + "g" + ChatColor.AQUA + "i" + ChatColor.LIGHT_PURPLE + "e" + ChatColor.DARK_PURPLE + " W" + ChatColor.BLUE + "o" + ChatColor.RED + "n" + ChatColor.GOLD + "d" + ChatColor.YELLOW + "e" + ChatColor.GREEN + "r" + ChatColor.AQUA + "l" + ChatColor.LIGHT_PURPLE + "a" + ChatColor.DARK_PURPLE + "n" + ChatColor.BLUE + "d" + ChatColor.RED + "!"); } }, 40); return true; } }, new Listener() { @EventHandler(priority = EventPriority.HIGHEST) public void onBlockChange(<API key> changeEvent) { if (Zones.inNoDemigodsZone(changeEvent.getBlock().getLocation())) return; if (changeEvent.getEntityType() != EntityType.FALLING_BLOCK) return; changeEvent.getBlock().setType(Material.AIR); FallingBlock block = (FallingBlock) changeEvent.getEntity(); if (discoBalls.contains(block)) { discoBalls.remove(block); block.remove(); } } }, new Runnable() { @Override public void run() { for (FallingBlock block : discoBalls) { if (block != null) { Location location = block.getLocation(); if (Zones.inNoDemigodsZone(location)) return; playRandomNote(location, 2F); sparkleSparkle(location); destroyNearby(location); } } } }); } public static void balls(Player player) { for (Location location : DemigodsLocation.getCirclePoints(new Location(player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockY() + 30 < 256 ? player.getLocation().getBlockY() + 30 : 256, player.getLocation().getBlockZ()), 3.0, 50)) spawnBall(location); } public static void spawnBall(Location location) { final FallingBlock discoBall = location.getWorld().spawnFallingBlock(location, Material.GLOWSTONE, (byte) 0); discoBalls.add(discoBall); Bukkit.getScheduler().<API key>(DemigodsPlugin.getInst(), new BukkitRunnable() { @Override public void run() { discoBalls.remove(discoBall); discoBall.remove(); } }, 600); } public static void rainbow(Player disco, Player player) { player.sendBlockChange(disco.getLocation().getBlock().getRelative(BlockFace.DOWN).getLocation(), Material.WOOL, (byte) Randoms.generateIntRange(0, 15)); if (DemigodsServer.isRunningSpigot()) Spigots.playParticle(disco.getLocation(), Effect.COLOURED_DUST, 1, 0, 1, 10F, 100, 30); } public static void playRandomNote(Location location, float volume) { location.getWorld().playSound(location, Sound.NOTE_BASS_GUITAR, volume, (float) ((double) Randoms.generateIntRange(5, 10) / 10.0)); } public static void sparkleSparkle(Location location) { if (DemigodsServer.isRunningSpigot()) Spigots.playParticle(location, Effect.CRIT, 1, 1, 1, 10F, 1000, 30); } public static void destroyNearby(Location location) { location.getWorld().createExplosion(location, 2F); } }
# Create an Azure Relay namespace & it's entities with SAS Policies <IMG SRC="https://<API key>.blob.core.windows.net/badges/<API key>-<API key>/PublicLastTestDate.svg" />&nbsp; <IMG SRC="https://<API key>.blob.core.windows.net/badges/<API key>-<API key>/PublicDeployment.svg" />&nbsp; <IMG SRC="https://<API key>.blob.core.windows.net/badges/<API key>-<API key>/FairfaxLastTestDate.svg" />&nbsp; <IMG SRC="https://<API key>.blob.core.windows.net/badges/<API key>-<API key>/FairfaxDeployment.svg" />&nbsp; <IMG SRC="https://<API key>.blob.core.windows.net/badges/<API key>-<API key>/BestPracticeResult.svg" />&nbsp; <IMG SRC="https://<API key>.blob.core.windows.net/badges/<API key>-<API key>/CredScanResult.svg" />&nbsp; <a href="https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%<API key>%2Fmaster%<API key>-<API key>%2Fazuredeploy.json" target="_blank"> <img src="https://raw.githubusercontent.com/Azure/<API key>/master/<API key>/images/deploytoazure.png"/> </a> <a href="http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%<API key>%2Fmaster%<API key>-<API key>%2Fazuredeploy.json" target="_blank"> <img src="https://raw.githubusercontent.com/Azure/<API key>/master/<API key>/images/visualizebutton.png"/> </a> This template creates an Azure Relay namespace, a HybridConnection and authorization rules for both the namespace and HybridConnection.
// Product Name: DotSpatial.Layout.Elements.LayoutBitmap // Description: The DotSpatial LayoutBitmap element, holds bitmaps loaded from disk for the layout // The Original Code is DotSpatial.dll Version 6.0 // The Initial Developer of this Original Code is Brian Marchionni. Created in Jul, 2009. // Contributor(s): (Open source contributors should list themselves and their modifications here). // Ted Dunsford | 8/28/2009 | Cleaned up some code formatting using resharper using System.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.Drawing.Imaging; using System.IO; namespace DotSpatial.Controls { <summary> The layout bitmap provides the ability to add any custom image to the layout </summary> public class LayoutBitmap : LayoutElement { #region Fields private Bitmap _bitmap; private int _brightness; private int _contrast; private string _fileName; private bool <API key>; #endregion <summary> Constructor </summary> public LayoutBitmap() { ResizeStyle = ResizeStyle.HandledInternally; <API key> = true; Name = "Bitmap"; ResizeStyle = ResizeStyle.StretchToFit; } #region Public Properties <summary> Preserves the aspect ratio if this boolean is true, otherwise it allows stretching of the bitmap to occur </summary> [Browsable(true), Category("Symbol")] public bool PreserveAspectRatio { get { return <API key>; } set { if (<API key> == value) return; <API key> = value; UpdateThumbnail(); OnInvalidate(); } } <summary> Modifies the brightness of the bitmap relative to its original brightness +/- 255 Doesn't modify original bitmap </summary> [Browsable(true), Category("Symbol")] public int Brightness { get { return _brightness; } set { if (_brightness == value) return; if (value < -255) _brightness = -255; else if (value > 255) _brightness = 255; else _brightness = value; UpdateThumbnail(); OnInvalidate(); } } <summary> Modifies the contrast of the bitmap relative to its original contrast +/- 255 Doesn't modify original bitmap </summary> [Browsable(true), Category("Symbol")] public int Contrast { get { return _contrast; } set { if (_contrast == value) return; if (value < -255) _contrast = -255; else if (value > 255) _contrast = 255; else _contrast = value; UpdateThumbnail(); OnInvalidate(); } } <summary> Gets or sets the string fileName of the bitmap to use </summary> [Browsable(true), Category("Symbol")] [Editor("System.Windows.Forms.Design.FileNameEditor, System.Design", typeof(UITypeEditor))] public string Filename { get { return _fileName; } set { if (_fileName == value) return; _fileName = value; Bitmap = File.Exists(_fileName) ? new Bitmap(_fileName) : null; } } <summary> Gets or sets bitmap to use </summary> [Browsable(false)] public Bitmap Bitmap { get { return _bitmap; } set { if (_bitmap == value) return; if (_bitmap != null) _bitmap.Dispose(); _bitmap = value; UpdateThumbnail(); OnInvalidate(); } } #endregion #region Public methods <summary> This gets called to instruct the element to draw itself in the appropriate spot of the graphics object </summary> <param name="g">The graphics object to draw to</param> <param name="printing">Boolean, true if this is being drawn to a print document</param> public override void Draw(Graphics g, bool printing) { if (_bitmap == null) return; //This color matrix is used to adjust how the image is drawn to the graphics object var bright = _brightness / 255.0F; var cont = (_contrast + 255.0F) / 255.0F; float[][] colorArray = { new[] {cont, 0, 0, 0, 0}, new[] {0, cont, 0, 0, 0}, new[] {0, 0, cont, 0, 0}, new float[] {0, 0, 0, 1, 0}, new[] {bright, bright, bright, 0, 1} }; var cm = new ColorMatrix(colorArray); var imgAttrib = new ImageAttributes(); imgAttrib.SetColorMatrix(cm); //Defines a parallelgram where the image is to be drawn var destPoints = new[] { LocationF, new PointF(LocationF.X + Size.Width, LocationF.Y), new PointF(LocationF.X, LocationF.Y + Size.Height) }; var destSize = _bitmap.Size; if (<API key>) { if ((Size.Width / destSize.Width) < (Size.Height / destSize.Height)) destPoints[2] = new PointF(LocationF.X, LocationF.Y + (Size.Width * destSize.Height / destSize.Width)); else destPoints[1] = new PointF(LocationF.X + (Size.Height * destSize.Width / destSize.Height), LocationF.Y); } var srcRect = new Rectangle(0, 0, _bitmap.Width, _bitmap.Height); g.DrawImage(_bitmap, destPoints, srcRect, GraphicsUnit.Pixel, imgAttrib); imgAttrib.Dispose(); } #endregion } }
/* Magnific Popup CSS */ .mfp-bg { top: 0; left: 0; width: 100%; height: 100%; z-index: 1042; overflow: hidden; position: fixed; background: #0b0b0b; opacity: 0.8; filter: alpha(opacity=80); } .mfp-wrap { top: 0; left: 0; width: 100%; height: 100%; z-index: 1043; position: fixed; outline: none !important; -<API key>: hidden; } .mfp-container { text-align: center; position: absolute; width: 100%; height: 100%; left: 0; top: 0; padding: 0 8px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .mfp-container:before { content: ''; display: inline-block; height: 100%; vertical-align: middle; } .mfp-align-top .mfp-container:before { display: none; } .mfp-content { position: relative; display: inline-block; vertical-align: middle; margin: 0 auto; text-align: left; z-index: 1045; } .mfp-inline-holder .mfp-content, .mfp-ajax-holder .mfp-content { width: 100%; cursor: auto; } .mfp-ajax-cur { cursor: progress; } .mfp-zoom-out-cur, .mfp-zoom-out-cur .mfp-image-holder .mfp-close { cursor: -moz-zoom-out; cursor: -webkit-zoom-out; cursor: zoom-out; } .mfp-zoom { cursor: pointer; cursor: -webkit-zoom-in; cursor: -moz-zoom-in; cursor: zoom-in; } .mfp-auto-cursor .mfp-content { cursor: auto; } .mfp-close, .mfp-arrow, .mfp-preloader, .mfp-counter { -webkit-user-select: none; -moz-user-select: none; user-select: none; } .mfp-loading.mfp-figure { display: none; } .mfp-hide { display: none !important; } .mfp-preloader { color: #CCC; position: absolute; top: 50%; width: auto; text-align: center; margin-top: -0.8em; left: 8px; right: 8px; z-index: 1044; } .mfp-preloader a { color: #CCC; } .mfp-preloader a:hover { color: #FFF; } .mfp-s-ready .mfp-preloader { display: none; } .mfp-s-error .mfp-content { display: none; } button.mfp-close, button.mfp-arrow { overflow: visible; cursor: pointer; background: transparent; border: 0; -webkit-appearance: none; display: block; outline: none; padding: 0; z-index: 1046; -webkit-box-shadow: none; box-shadow: none; } button::-moz-focus-inner { padding: 0; border: 0; } .mfp-close { width: 44px; height: 44px; line-height: 44px; position: absolute; right: 0; top: 0; text-decoration: none; text-align: center; opacity: 0.65; filter: alpha(opacity=65); padding: 0 0 18px 10px; color: #FFF; font-style: normal; font-size: 28px; font-family: Arial, Baskerville, monospace; } .mfp-close:hover, .mfp-close:focus { opacity: 1; filter: alpha(opacity=100); } .mfp-close:active { top: 1px; } .mfp-close-btn-in .mfp-close { color: #333; } .mfp-image-holder .mfp-close, .mfp-iframe-holder .mfp-close { color: #FFF; right: -6px; text-align: right; padding-right: 6px; width: 100%; } .mfp-counter { position: absolute; top: 0; right: 0; color: #CCC; font-size: 12px; line-height: 18px; white-space: nowrap; } .mfp-arrow { position: absolute; opacity: 0.65; filter: alpha(opacity=65); margin: 0; top: 50%; margin-top: -55px; padding: 0; width: 90px; height: 110px; -<API key>: rgba(0, 0, 0, 0); } .mfp-arrow:active { margin-top: -54px; } .mfp-arrow:hover, .mfp-arrow:focus { opacity: 1; filter: alpha(opacity=100); } .mfp-arrow:before, .mfp-arrow:after, .mfp-arrow .mfp-b, .mfp-arrow .mfp-a { content: ''; display: block; width: 0; height: 0; position: absolute; left: 0; top: 0; margin-top: 35px; margin-left: 35px; border: medium inset transparent; } .mfp-arrow:after, .mfp-arrow .mfp-a { border-top-width: 13px; border-bottom-width: 13px; top: 8px; } .mfp-arrow:before, .mfp-arrow .mfp-b { border-top-width: 21px; border-bottom-width: 21px; opacity: 0.7; } .mfp-arrow-left { left: 0; } .mfp-arrow-left:after, .mfp-arrow-left .mfp-a { border-right: 17px solid #FFF; margin-left: 31px; } .mfp-arrow-left:before, .mfp-arrow-left .mfp-b { margin-left: 25px; border-right: 27px solid #3F3F3F; } .mfp-arrow-right { right: 0; } .mfp-arrow-right:after, .mfp-arrow-right .mfp-a { border-left: 17px solid #FFF; margin-left: 39px; } .mfp-arrow-right:before, .mfp-arrow-right .mfp-b { border-left: 27px solid #3F3F3F; } .mfp-iframe-holder { padding-top: 40px; padding-bottom: 40px; } .mfp-iframe-holder .mfp-content { line-height: 0; width: 100%; max-width: 900px; } .mfp-iframe-holder .mfp-close { top: -40px; } .mfp-iframe-scaler { width: 100%; height: 0; overflow: hidden; padding-top: 56.25%; } .mfp-iframe-scaler iframe { position: absolute; display: block; top: 0; left: 0; width: 100%; height: 100%; box-shadow: 0 0 8px rgba(0, 0, 0, 0.6); background: #000; } /* Main image in popup */ img.mfp-img { width: auto; max-width: 700px; height: auto; display: block; line-height: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 40px 0 40px; margin: 0 auto; } /* The shadow behind the image */ .mfp-figure { line-height: 0; } .mfp-figure:after { content: ''; position: absolute; left: 0; top: 40px; bottom: 40px; display: block; right: 0; width: auto; height: auto; z-index: -1; box-shadow: 0 0 8px rgba(0, 0, 0, 0.6); background: #444; } .mfp-figure small { color: #BDBDBD; display: block; font-size: 12px; line-height: 14px; } .mfp-figure figure { margin: 0; } .mfp-bottom-bar { margin-top: -36px; position: absolute; top: 100%; left: 0; width: 100%; cursor: auto; } .mfp-title { text-align: left; line-height: 18px; color: #F3F3F3; word-wrap: break-word; padding-right: 36px; } .mfp-image-holder .mfp-content { max-width: 100%; } .mfp-gallery .mfp-image-holder .mfp-figure { cursor: pointer; } @media screen and (max-width: 800px) and (orientation: landscape), screen and (max-height: 300px) { /** * Remove all paddings around the image on small screen */ .mfp-img-mobile .mfp-image-holder { padding-left: 0; padding-right: 0; } .mfp-img-mobile img.mfp-img { padding: 0; } .mfp-img-mobile .mfp-figure:after { top: 0; bottom: 0; } .mfp-img-mobile .mfp-figure small { display: inline; margin-left: 5px; } .mfp-img-mobile .mfp-bottom-bar { background: rgba(0, 0, 0, 0.6); bottom: 0; margin: 0; top: auto; padding: 3px 5px; position: fixed; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .mfp-img-mobile .mfp-bottom-bar:empty { padding: 0; } .mfp-img-mobile .mfp-counter { right: 5px; top: 3px; } .mfp-img-mobile .mfp-close { top: 0; right: 0; width: 35px; height: 35px; line-height: 35px; background: rgba(0, 0, 0, 0.6); position: fixed; text-align: center; padding: 0; } } @media all and (max-width: 900px) { .mfp-arrow { -webkit-transform: scale(0.75); transform: scale(0.75); } .mfp-arrow-left { -<API key>: 0; transform-origin: 0; } .mfp-arrow-right { -<API key>: 100%; transform-origin: 100%; } .mfp-container { padding-left: 6px; padding-right: 6px; } } .mfp-ie7 .mfp-img { padding: 0; } .mfp-ie7 .mfp-bottom-bar { width: 600px; left: 50%; margin-left: -300px; margin-top: 5px; padding-bottom: 5px; } .mfp-ie7 .mfp-container { padding: 0; } .mfp-ie7 .mfp-content { padding-top: 44px; } .mfp-ie7 .mfp-close { top: 0; right: 0; padding-top: 0; }
module.exports = {"OpenSans":{"bold":"OpenSans-Bold.ttf","bolditalics":"OpenSans-BoldItalic.ttf","extrabold":"OpenSans-ExtraBold.ttf","extrabolditalics":"<API key>.ttf","italics":"OpenSans-Italic.ttf","light":"OpenSans-Light.ttf","lightitalics":"<API key>.ttf","normal":"OpenSans-Regular.ttf","semibold":"OpenSans-Semibold.ttf","semibolditalics":"<API key>.ttf"}};
# <API key>: true class <API key> < Grape::Entity expose :name expose :status_name, as: :status expose :status_reason expose :external_ip, if: -> (e, _) { e.respond_to?(:external_ip) } expose :hostname, if: -> (e, _) { e.respond_to?(:hostname) } expose :email, if: -> (e, _) { e.respond_to?(:email) } end
import comp from './Lists.vue' export default comp
layout: default <article class="post" itemscope itemtype="http://schema.org/BlogPosting"> <header class="post-header"> <h1 class="post-title" itemprop="name headline">{{ page.title }}</h1> <p class="post-metadata"> <time datetime="{{ page.date | date_to_xmlschema }}" itemprop="datePublished"> <i class="fa fa-calendar" aria-hidden="true"></i> {{ page.date | date: "%d.%m.%Y" }} </time> {% if page.author %} &nbsp;&nbsp; <span itemprop="author" itemscope itemtype="http://schema.org/Person"><span itemprop="name"><i class="fa fa-user" aria-hidden="true"></i> {{ page.author }}</span></span>{% endif %} {% if page.categories %} &nbsp;&nbsp; <span><i class="fa fa-tag" aria-hidden="true"></i> {% assign tags = page.categories %}{% for tag in tags %}{{tag}}{% unless forloop.last %},&nbsp;{% endunless %}{% endfor %}</span> {% endif %} {% assign words = content | strip_html | number_of_words %} &nbsp;&nbsp; <span><i class="fa fa-clock-o" aria-hidden="true"></i> {% if words < 360 %} 1 min {% else %} {{ words | divided_by:180 }} mins {% endif %} </span> </p> </header> <div class="post-content" itemprop="articleBody">{{ content }}</div> </article> <br /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
module Oczor.CodeGen.CodeGenJs where import Oczor.CodeGen.Utl codeGen :: Ast -> Doc codeGen = x where x = cata $ \case NoneF -> empty UniqObjectF {} -> text "{}" CodeF x -> text x NotEqualF x y -> sep [x, text "!=", y] EqualF x y -> sep [x, text "==", y] LitF value -> lit value IdentF name -> ident name VarF name ast -> stmt [text "var", text name, equals, ast] SetF astl astr -> stmt [astl, equals, astr] ThrowF error -> stmt [text "throw", dquotes $ text error] IfF p l r -> hcat [text "if", parens p] <> bracesNest l <> if onull r then empty else text "else" <> bracesNest r ReturnF ast -> stmt [text "return", ast] FieldF ast name -> field ast name HasFieldF ast name -> sep [field ast name, text "!==", text "undefined"] ObjectF list -> bracesNest $ punctuate comma (list <&> (\(name,ast) -> hsep [ident name, text ":", ast])) FunctionF params body -> func params body ScopeF list y -> parens (func [] (list ++ [text "return" <+> y]) ) <> parens empty CallF name args -> name <> parens (hcat $ punctuate comma args) OperatorF name param -> (hsep $ case param of {[x] -> [text name, x]; [x,y] -> [x,text name, y]} ) ArrayF list -> jsArray list ConditionOperatorF astb astl astr -> parens $ hsep [astb, text "?", astl, text ":", astr] BoolAndsF list -> parens $ hcat $ punctuate (text " && ") list StmtListF list -> vcat list ParensF x -> parens x LabelF x y -> stmt [text "var", text x, equals, y] func params body = hcat [text "function", parens $ hcat $ punctuate comma (params <&> text) ] <> bracesNest body lit = createLit show "null" ("true", "false") keywords = setFromList ["false", "true", "null", "abstract", "arguments", "boolean", "break", "byte case", "catch", "char", "class", "const continue", "debugger", "default", "delete", "do double", "else", "enum", "eval", "export extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements import", "in", "instanceof", "int", "interface let", "long", "native", "new", "null package", "private", "protected", "public", "return short", "static", "super", "switch", "synchronized this", "throw", "throws", "transient", "true try", "typeof", "var", "void", "volatile while", "with", "yield"] ident = createIdent keywords stmt x = hsep x <> text ";" field ast name = ast <> dot <> ident name
using NUnit.Framework; namespace IuguClientAPI.Tests.Serialization { [TestFixture] public class <API key> { [Test] public void TestMethod() { var jsonSerializer = <API key>.Instance; jsonSerializer.DateFormat = "dd/MM/yyyy"; jsonSerializer.Namespace = "empty"; jsonSerializer.RootElement = "empty"; Assert.AreEqual("dd/MM/yyyy", jsonSerializer.DateFormat); Assert.AreEqual("empty", jsonSerializer.Namespace); Assert.AreEqual("empty", jsonSerializer.RootElement); Assert.AreEqual("application/json", jsonSerializer.ContentType); } } }
<!-- Contact Section --> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2>Contact The Band</h2> {% include social.html %} <p class="lead">Will - <a href="tel:07454198316">07454 198 316</a></p> <p class="lead">Joe - <a href="tel:07907187665">07907 187 665</a></p> </div> </div> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <form method="POST" action="http://formspree.io/{{ site.email }}"> <div class="form-group col-xs-12 <API key> controls"> <input class="form-control" type="text" name="Name" placeholder="Name"> </div> <div class="form-group col-xs-12 <API key> controls"> <input class="form-control" type="email" name="email" placeholder="Email Address"> </div> <div class="form-group col-xs-12 <API key> controls"> <input class="form-control" type="text" name="Number" placeholder="Number"> </div> <div class="form-group col-xs-12 <API key> controls"> <textarea name="message" placeholder="Message" class="form-control"></textarea> </div> <button class="btn btn-success btn-lg" type="submit">Send</button> <input type="hidden" name="_next" value="/#contact-thanks"/> </form> <div id="contact-thanks"> <div class="alert alert-dismissible alert-success"> <button type="button" class="close" data-dismiss="alert">×</button> <p>Thanks for getting in touch</p><strong>We will get back to you as soon as we can</strong> </div> </div> </div> </div> </div> </section>
'use strict'; /* Directives */ angular.module('uiucEmailForm.directives', []). directive('appVersion', ['version', function(version) { return function(scope, elm, attrs) { elm.text(version); }; }]) .directive('formDefault',function(){ return { restrict: "E", transclude: true, scope:true, templateUrl:"partials/form-default.html", controller: function($scope){ // Create form data object $scope.form.data = {}; // Returns whether the form is valid $scope.isValid = function(){ var name = $scope.form.name; return $scope[name].$valid; }; // Add default form reset functionality to the functionality // specified by $scope.form.resetForm option var _resetForm = $scope.form.resetForm; $scope.form.resetForm = function(){ // Call optional user-defined resetForm if(typeof(_resetForm) == "function"){ _resetForm(); } $scope.form.data = {}; var name = $scope.form.name; $scope[name].$setPristine(); }; } }; }) .directive('formEmail',function(){ return { restrict: "E", scope: true, templateUrl:"partials/form-email.html" }; }) .directive('formName',function(){ return { restrict: "E", scope: true, templateUrl:"partials/form-name.html" }; }) .directive('formPassword',function(){ return { restrict: "E", scope: true, templateUrl:"partials/form-password.html" }; }) .directive('formLists',function(){ return { restrict: "E", scope: true, templateUrl:"partials/form-lists.html", controller: function($scope){ $scope.form.listsAvail = []; angular.forEach($scope.form.listsOrig,function(list,key){ $scope.form.listsAvail.push({ selected: list["selected"], name: list["name"] }); }); // Add code to reset list form to parent's resetForm var _resetForm = $scope.form.resetForm; $scope.form.resetForm = function(){ _resetForm(); for (var key in $scope.form.listsAvail){ $scope.form.listsAvail[key]["selected"] = $scope.form.listsOrig[key]["selected"]; } }; // helper method to get selected lists var selectedLists = function selectedLists() { return filterFilter($scope.form.listsAvail, { selected: true }); }; // watch lists for changes and add them to form.data.lists $scope.$watch('form.listsAvail|filter:{selected:true}', function (nv) { $scope.form.data.lists = nv.map(function (list) { return list.name; }); }, true); } }; });
extern crate iron; extern crate staticfile; extern crate mount; use iron::{status, Iron, Request, Response, IronResult, IronError}; use iron::mime::Mime; use staticfile::Static; use mount::Mount; use std::process::{Command, Output}; use std::error::Error; #[derive(Debug)] struct ServerError(String); impl ::std::fmt::Display for ServerError { #[inline] fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { self.0.fmt(f) } } impl Error for ServerError { fn description(&self) -> &str { &*self.0 } } impl ::std::convert::From<&'static str> for ServerError { fn from(s: &'static str) -> ServerError { ServerError(s.to_owned()) } } fn serve(req: &mut Request) -> IronResult<Response> { match req.url.query { Some(ref param) if param.starts_with("module=") => { let module = &param[7..]; match Command::new(format!("modules/shell_files/{}.sh", module)).output() { Ok(Output { stdout, .. }) => Ok(Response::with((status::Ok, stdout, "application/json".parse::<Mime>().unwrap()))), Err(err) => Err(IronError::new(err, status::InternalServerError)), } }, Some(_) => Err(IronError::new::<ServerError, _>("module parameter required".into(), status::BadRequest)), None => Err(IronError::new::<ServerError, _>("object not found".into(), status::NotFound)), } } fn main() { let mut root = Mount::new(); root.mount("/", Static::new("../")) .mount("/server", serve); Iron::new(root).http("localhost:8081").unwrap(); }
# MetadataHash - A specific use of ruby's Hash # overrides Hash's method missing, providing the following functionality: # 1. Access Nested hashes using the method / attribute syntax # i.e.: h = {} # h.middle.inner == {} # 2. Access to values stored in nested hashes via method call syntax # i.e.: h = { middle: { inner: { key: "value" } } } # h.middle.inner.key == "value" # 3. Set values for nested hash structures without middle nested hashes # having to be defined # i.e.: h = {} # h.middle.inner = 3 # h == { middle: { inner: 3 } } # 4. Old hash square bracket access still works # i.e.: h = { inner: { key: "value" } } # h[:inner][:key] == "value" class Metadata < Hash include ::MetaInstance # in the event we are overriding a method, have a way to # get back to the original METHOD_BACKUP_KEY = "metadata_original_" # the hash being passed in will have all its subhashes converted to # metadata hashes. # this is needed to we can have the # @raise [ArgumentError] if one of the keys is method of Hash # @raise [ArgumentError] if hash is not a type of Hash or Metadata # @param [Hash] hash the structure to convert to Metadata def initialize(hash = {}) # for maybe instantiating nested hashes that we # aren't yet sure if they are going to have values or not @empty_nested_hashes = [] if hash.is_a?(Metadata) # we have nothing to do return hash elsif hash.is_a?(Hash) # recursively create nested metadata objects hash.each do |key, value| self[ key ] = ( if value.is_a?(Hash) Metadata.new(value) elsif value.is_a?(Array) # ensure hashes kept in an array are also converted to metadata array = value.map{ |element| element.is_a?(Hash) ? Metadata.new(element) : element } else value end ) end else raise ArgumentError.new("Field must be a Hash or Metadata") end end # this is what allows functionality mentioned in the class comment to happen # @raise [ArgumentError] if one of the keys is method of Hash def method_missing(method_name, *args) # check for assignment if method_name.to_s[-1] == "=" assign_value(method_name, args[0]) else value = self[method_name] if value.nil? @empty_nested_hashes << method_name value = self end value end end # Metdata has indifferent access def [](key) # self.send(key) super(key.to_sym) end # # Metadata has indifferent access, # # so just say that all the keys are symbols. def []=(key, value) if value.is_a?(Hash) && !value.is_a?(Metadata) value = Metadata.new(value) end super(key.to_sym, value) end # tests the ability to use this key as a key in a hash # @param [Symbol] key # @return [Boolean] whether or not this can be used as a hash key def key_not_in_use?(key) not self.respond_to?(key) end # convert to regular hash, recursively def to_hash hash = {} self.each do |k,v| hash[k] = ( if v.is_a?(Metadata) v.to_hash elsif v.is_a?(Array) v.map{ |e| e.is_a?(Metadata) ? e.to_hash : e } else v end ) end hash end def to_ary self.to_hash.to_a end alias_method :to_a, :to_ary private # @param [Symbol] key "field_name="" def assign_value(key, value) key = key.to_s.chop deepest_metadata = self value = Metadata.new(value) if value.is_a?(Hash) if not @empty_nested_hashes.empty? @empty_nested_hashes.each do |key| deepest_metadata = deepest_metadata[key] = Metadata.new end @empty_nested_hashes = [] deepest_metadata[key] = value # override any existing method with the key deepest_metadata.instance_define(key){ self[key] } else self[key] = value # override any existing method with the key self.instance_define(key){ value } end end end
%%Created by jPicEdt 1.4.1_03: mixed JPIC-XML/LaTeX format %%Sat May 03 10:04:08 MSD 2008 %%Begin JPIC-XML %<?xml version="1.0" standalone="yes"?> %<jpic x-min="0" x-max="50" y-min="0" y-max="60" auto-bounding="true"> %<multicurve fill-style= "none" % stroke-width= "0.15" % right-arrow= "head" % points= "(10,5);(10,5);(10,40);(10,40)" % /> %<multicurve fill-style= "none" % stroke-width= "0.15" % right-arrow= "head" % points= "(10,5);(10,5);(45,5);(45,5)" % /> %<text text-vert-align= "center-v" % anchor-point= "(0,10)" % text-hor-align= "center-h" % text-frame= "noframe" % fill-style= "none" % stroke-width= "0.15" % > % %</text> %<multicurve stroke-style= "dashed" % stroke-dasharray= "1;1" % fill-style= "none" % stroke-width= "0.15" % points= "(35,30);(35,30);(35,5);(35,5)" % /> %<multicurve stroke-style= "dashed" % stroke-dasharray= "1;1" % fill-style= "none" % stroke-width= "0.15" % points= "(10,30);(10,30);(35,30);(35,30)" % /> %<text text-vert-align= "center-v" % anchor-point= "(5,45)" % text-hor-align= "center-h" % text-frame= "noframe" % fill-style= "none" % stroke-width= "0.15" % > %$Im \, \alpha$ %</text> %<text text-vert-align= "center-v" % anchor-point= "(25,60)" % text-hor-align= "center-h" % text-frame= "noframe" % fill-style= "none" % stroke-width= "0.15" % > % %</text> %<text text-vert-align= "center-v" % anchor-point= "(20,60)" % text-hor-align= "center-h" % text-frame= "noframe" % fill-style= "none" % stroke-width= "0.15" % > % %</text> %<text text-vert-align= "center-v" % anchor-point= "(50,0)" % text-hor-align= "center-h" % text-frame= "noframe" % fill-style= "none" % stroke-width= "0.15" % > %$Re \, \alpha$ %</text> %<multicurve fill-style= "none" % stroke-width= "0.15" % points= "(10,5);(10,5);(35,30);(35,30)" % /> %<text text-vert-align= "center-v" % anchor-point= "(20,22)" % text-hor-align= "center-h" % text-frame= "noframe" % fill-style= "none" % stroke-width= "0.15" % > %$\left|\alpha\right|$ %</text> %<multicurve fill-style= "none" % stroke-width= "0.15" % points= "(15,10);(18.33,10);(20,8.33);(20,5)" % /> %<text text-vert-align= "center-v" % anchor-point= "(25,10)" % text-hor-align= "center-h" % text-frame= "noframe" % fill-style= "none" % stroke-width= "0.15" % > %$arg \, \alpha$ %</text> %</jpic> %%End JPIC-XML %LaTeX-picture environment using emulated lines and arcs %You can rescale the whole picture (to 80% for instance) by using the command \def\JPicScale{0.8} \ifx\JPicScale\undefined\def\JPicScale{1}\fi \unitlength \JPicScale mm \begin{picture}(50,60)(0,0) \linethickness{0.15mm} \put(10,5){\line(0,1){35}} \put(10,40){\vector(0,1){0.12}} \linethickness{0.15mm} \put(10,5){\line(1,0){35}} \put(45,5){\vector(1,0){0.12}} \put(0,10){\makebox(0,0)[cc]{}} \linethickness{0.15mm} \multiput(35,5)(0,2){13}{\line(0,1){1}} \linethickness{0.15mm} \multiput(10,30)(2,0){13}{\line(1,0){1}} \put(5,45){\makebox(0,0)[cc]{$Im \, \alpha$}} \put(25,60){\makebox(0,0)[cc]{}} \put(20,60){\makebox(0,0)[cc]{}} \put(50,0){\makebox(0,0)[cc]{$Re \, \alpha$}} \linethickness{0.15mm} \multiput(10,5)(0.12,0.12){208}{\line(1,0){0.12}} \put(20,22){\makebox(0,0)[cc]{$\left|\alpha\right|$}} \linethickness{0.15mm} \qbezier(15,10)(17.5,10)(18.75,8.75) \qbezier(18.75,8.75)(20,7.5)(20,5) \put(25,10){\makebox(0,0)[cc]{$arg \, \alpha$}} \end{picture}
layout: post title: Journey to Bloc I started Bloc in August of 2015 I believe and before then i had only done a bit of coding. I had done some html and css in the past but nothing like rails or javascript . Honestly I didn't even know what rails was until a few weeks before I started the course. I had done a bit of Codecademy and treehouse in the past. I would always be on Youtube, you know wasting time watching stupid videos that will literally get you no where. > Though I did Learn that you cant snore and dreams at the same time on a weird fact video... interesting right? One of those times I saw an ad for learning how to code on Treehouse. I was intrigued with their claims that you can "get a job in little as 3 months". I was like "holly cow why the hell am i still on youtube watching random videos when i could be watching videos on coding and be making bank right now".Well turns out it isnt that easy. I did some courses on their, started with Ruby and some How to Build a Website Track and like many times before when i tried to learn anything new I started to get stuck and my motivation would vanish. A few months after trying treehouse i had a meeting with a old high school friend and she slapped me right in the face and told me "get back into coding I know you like it. Look into it and find yourself a school". I searched online and found two "Coding bootcamps", Devcamp and APP academy but both were to far away from me which would mean I would have to relocate. So I kept on searching till I found Bloc. What really caught my eye about Bloc was its mentorship side. At that moment i realized that is what i was missing . Something to keep me motivated and kick my ass whenever I was slacking off or thinking of giving up and trust me, Bloc and my mentor kicked my ass on several occasions (not literally of course). Becoming a student at bloc has to be one of the best decision ive made so far :)
require "spec_helper" describe Mediators::Devices::Creator do end
import _plotly_utils.basevalidators class YValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="y", parent_name="volume.colorbar", **kwargs): super(YValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), max=kwargs.pop("max", 3), min=kwargs.pop("min", -2), role=kwargs.pop("role", "style"), **kwargs )
<article class="experiment empty"> <h1>Your search - <strong>&quot;<%= query %>&quot;</strong> - did not match any experiments.</h1> <p>Suggestions</p> <ul> <li>Verify the keywords used. Is it the right accession number, for example?</li> <li>Try different keywords. How about words in the experiment's title?</li> <li><a class="email" href="<%= encodeURI('mailto:' + email + '?Subject=ArrayExpress v' + apiVersion + '.' + apiRevision + ' - Unmatched query: "' + query + '"') %>">Contact us </a> if the query refers to an experiment that should be included in the database.</li> </ul> </article>
// @flow import {googleKey} from './config'; export function getLocations(place) { // <API key> return fetch(`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${place}&key=${googleKey}`) .then((response) => response.json()) .then((responseJson) => { if (responseJson.status === 'ZERO_RESULTS') { return []; } if (responseJson.status === 'OK') { return responseJson.predictions.map((loc) => ({ description: loc.description, id: loc.place_id })); } return []; }) .catch((error) => { console.error(error); }); } export function getLocationByCoords(coords) { // <API key> return fetch(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${coords.latitude},${coords.longitude}&radius=500&key=${googleKey}`) .then((response) => response.json()) .then((responseJson) => { if (responseJson.status === 'ZERO_RESULTS') { return null; } if (responseJson.status === 'OK') { const firstResult = responseJson.results[0]; if (firstResult.types[0] === 'locality' && firstResult.types[1] === 'political') { return { id: firstResult.place_id, description: firstResult.description }; } } return null; }) .catch((error) => { console.error(error); }); } const monthTable = { common: [0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5], leap: [6, 2, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5] }; const months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; const currentDate = new Date(); const curMonth = currentDate.getMonth(); const curYear = currentDate.getFullYear(); let isLeap = false; if (curYear % 400 === 0 || (curYear % 4 === 0 && curYear % 100 !== 0)) { months[1] = 29; isLeap = true; } function getDayOfWeek(year, month, day) { const y = year % 100; return (day + monthTable[isLeap ? 'leap' : 'common'][month] + Math.floor(y / 4) + y) % 7; } export function getCalendarDates() { let firstDay = getDayOfWeek(curYear, curMonth, 1); firstDay = firstDay - 2 >= 0 ? firstDay - 2 : firstDay - 2 + 7; // offset for correct days order (mon - sun) const dates = []; for (let i = 0; i < 12; i++) { const m = (i + curMonth) % 12; const daysInMonth = months[m]; dates.push({ dates: [], month: m, year: m !== (i + curMonth) ? curYear + 1 : curYear }); let dayOfWeek, date; let week = [null, null, null, null, null, null, null]; dayOfWeek = firstDay; for (date = 1; date <= daysInMonth; ++date) { week[dayOfWeek] = date; if (++dayOfWeek > 6) { dates[i].dates.push(week); week = [null, null, null, null, null, null, null]; dayOfWeek = 0; } } if (dayOfWeek !== 0) { dates[i].dates.push(week); } firstDay = dayOfWeek; } return dates; } export const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; export const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wen', 'Thu', 'Fri', 'Sat']; type CustomDate = { year: number; month: number; day: number; } export function getDateString(date: CustomDate | Date) { if (!date) { return null; } const month = date.month || date.getMonth(); const day = date.day || date.getDate(); return date && `${monthNames[month]} ${day}`; } export const statusMap = { accepting: { label: 'Accepting Guests', textColor: 'white', areaColor: '#43b667' }, maybe: { label: 'Maybe Accepting Guests', textColor: 'white', areaColor: '#273c53' }, not: { label: 'Not Accepting Guests', textColor: 'black', areaColor: '#bfcad1' }, meetUp: { label: 'Want to Meet Up', textColor: 'black', areaColor: '#bfcad1' } }; export function <API key>(str: string) { return `${str[0].toUpperCase()}${str.slice(1)}`; } export function <API key>(arrives: CustomDate, departs: CustomDate) { const calendarDates = {}; for (let i = 0; i < 12; i++) { calendarDates[i] = {}; } if (arrives) { calendarDates[arrives.month][arrives.day] = true; } if (departs) { for (let i = arrives.month; i <= departs.month; i++) { var start = 1; var end = 31; if (i === arrives.month) { start = arrives.day; } if (i === departs.month) { end = departs.day; } for (let j = start; j <= end; j++) { calendarDates[i][j] = true; } } } return calendarDates; }
System.config({ defaultJSExtensions: true, transpiler: "babel", babelOptions: { "optional": [ "runtime", "optimisation.modules.system" ] }, paths: {
#include <node.h> #include "myobject.h" using namespace v8; void CreateObject(const <API key><Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); MyObject::NewInstance(args); } void InitAll(Handle<Object> exports, Handle<Object> module) { MyObject::Init(); NODE_SET_METHOD(module, "exports", CreateObject); } NODE_MODULE(addon, InitAll);
<?php namespace perf\Caching; class VolatileStorage implements Storage { /** * Cached entries. * * @var {string:CacheEntry} */ private $entries = array(); /** * Attempts to store provided cache entry into storage. * * @param CacheEntry $entry * @return void */ public function store(CacheEntry $entry) { $this->entries[$entry->id()] = $entry; } /** * * * @param string $id Cache item unique identifier (ex: 123). * @return null|CacheEntry */ public function tryFetch($id) { if (!array_key_exists($id, $this->entries)) { return null; } return $this->entries[$id]; } /** * * * @param string $id Cache entry unique identifier. * @return void */ public function flushById($id) { unset($this->entries[$id]); } /** * Deletes every cache file. * * @return void */ public function flushAll() { $this->entries = array(); } }
using <API key>.Cache; using EPiServer; namespace <API key>.EPiServer { internal class <API key> : ICacheManager { public void Insert(string key, object value) { CacheManager.Insert(key, value); } public object Get(string key) { return CacheManager.Get(key); } public void Remove(string key) { CacheManager.Remove(key); } } }
using System; using System.Collections.Generic; using System.Reflection; namespace <API key>.Refactoring { public abstract class <API key> { private readonly List<RefactorStep> _list = new List<RefactorStep>(); internal ICollection<RefactorStep> Steps => _list; public RefactorPhase<T> For<T>() { var t = typeof (RefactorPhase<>).MakeGenericType(typeof (T)); return Activator.CreateInstance(t, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { typeof (T), _list }, null) as RefactorPhase<T>; } public abstract void DefineChanges(); } }
#ifndef <API key> #define <API key> namespace PyCuDNN { typedef <API key> <API key>; } // PyCuDNN #endif // <API key>
<?php return [ //Admin forms language tabs 'en' => 'English', 'nl' => 'Dutch', 'de' => 'German', 'fr' => 'French', //Enable language 'is_online_language' => 'Content online in this language?', //Global datatable controls 'add' => '<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add new', 'with_selected' => '<span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> With selected', 'delete' => '<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete', 'edit' => '<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> Edit', //Global form controls 'save' => 'Save', 'datatable_language' => '{ "sEmptyTable": "No data available in table", "sInfo": "Showing _START_ to _END_ of _TOTAL_ entries", "sInfoEmpty": "Showing 0 to 0 of 0 entries", "sInfoFiltered": "(filtered from _MAX_ total entries)", "sInfoPostFix": "", "sInfoThousands": ",", "sLengthMenu": "Show _MENU_ entries", "sLoadingRecords": "Loading...", "sProcessing": "Processing...", "sSearch": "Search:", "sZeroRecords": "No matching records found", "oPaginate": { "sFirst": "First", "sLast": "Last", "sNext": "Next", "sPrevious": "Previous" }, "oAria": { "sSortAscending": ": activate to sort column ascending", "sSortDescending": ": activate to sort column descending" } }', //Admin menu 'admin_link_users' => 'Users', 'admin_link_groups' => 'Groups', 'admin_link_pages' => 'Pages', 'admin_link_articles' => 'Articles', '<API key>' => 'Categories', '<API key>' => 'Paragraphs', ];
package vn.aboutme.demoviewpager; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class PHPFragment extends Fragment { public PHPFragment() {} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_php, container, false); } }
require 'rails_helper' require 'support/fixture_file' require 'support/<API key>' describe Api::V3::SrcImagesController, type: :controller do include StatsD::Instrument::Matchers let(:user) { FactoryGirl.create(:user) } before(:each) do session[:user_id] = user.try(:id) end describe "GET 'index'" do let(:src_image1) do FactoryGirl.create(:finished_src_image, name: 'src image 1') end let(:src_image2) do FactoryGirl.create(:finished_src_image, name: 'src image 2') end let(:src_image3) do FactoryGirl.create(:finished_src_image, name: 'src image 3') end let(:src_images) { [src_image1, src_image2, src_image3] } before do src_images.each do |src_image| src_image.<API key> src_image.save! end end it 'gets the src images for the user, query and page' do expect(SrcImage).to receive(:for_user).with(user, 'test query', '7') .and_return(src_images) get(:index, params: { q: 'test query', page: '7', format: :json }) end it 'sets the image url on each src image' do allow(SrcImage).to receive(:for_user).with(user, nil, nil).and_return( src_images ) expect(src_image1).to receive(:'image_url=').with( "http://test.host/src_images/#{src_image1.id_hash}.jpg" ) expect(src_image2).to receive(:'image_url=').with( "http://test.host/src_images/#{src_image2.id_hash}.jpg" ) expect(src_image3).to receive(:'image_url=').with( "http://test.host/src_images/#{src_image3.id_hash}.jpg" ) get(:index, format: :json) end it 'returns the src images as JSON' do allow(SrcImage).to receive(:for_user).with(user, nil, nil).and_return( src_images ) get(:index, format: :json) json_body = JSON.parse(response.body) expect(json_body).to eq( [ { 'id_hash' => src_image1.id_hash, 'width' => 399, 'height' => 399, 'size' => 9141, 'content_type' => 'image/jpeg', 'created_at' => src_image1.created_at.strftime( '%Y-%m-%dT%H:%M:%S.%LZ' ), 'updated_at' => src_image1.updated_at.strftime( '%Y-%m-%dT%H:%M:%S.%LZ' ), 'name' => 'src image 1', 'image_url' => "http://test.host/src_images/#{src_image1.id_hash}.jpg" }, { 'id_hash' => src_image2.id_hash, 'width' => 399, 'height' => 399, 'size' => 9141, 'content_type' => 'image/jpeg', 'created_at' => src_image2.created_at.strftime( '%Y-%m-%dT%H:%M:%S.%LZ' ), 'updated_at' => src_image2.updated_at.strftime( '%Y-%m-%dT%H:%M:%S.%LZ' ), 'name' => 'src image 2', 'image_url' => "http://test.host/src_images/#{src_image2.id_hash}.jpg" }, { 'id_hash' => src_image3.id_hash, 'width' => 399, 'height' => 399, 'size' => 9141, 'content_type' => 'image/jpeg', 'created_at' => src_image3.created_at.strftime( '%Y-%m-%dT%H:%M:%S.%LZ' ), 'updated_at' => src_image3.updated_at.strftime( '%Y-%m-%dT%H:%M:%S.%LZ' ), 'name' => 'src image 3', 'image_url' => "http://test.host/src_images/#{src_image3.id_hash}.jpg" } ] ) end it 'sets the content type to application/json' do get(:index, format: :json) expect(response.content_type).to eq('application/json') end end describe "POST 'create'" do before { request.accept = 'application/json' } context 'with valid attributes' do context 'when uploading image data' do it 'creates a src image with the image data' do post(:create, params: { src_image: { image: fixture_file_upload( '/files/ti_duck.jpg', 'image/jpeg' ) } }) expect(response).to have_http_status(:ok) expected_image_data = fixture_file_data('ti_duck.jpg') expect(SrcImage.last.image).to eq(expected_image_data) end it 'increments the src image upload statsd counter' do expect do post(:create, params: { src_image: { image: fixture_file_upload( '/files/ti_duck.jpg', 'image/jpeg' ) } }) expect(response).to have_http_status(:ok) end.to <API key>('src_image.upload') end it 'sets the creator_ip to the remote ip address' do post(:create, params: { src_image: { image: fixture_file_upload( '/files/ti_duck.jpg', 'image/jpeg' ) } }) expect(SrcImage.last.creator_ip).to eq('0.0.0.0') end context 'when the request has a CloudFlare IP header' do before { request.headers['CF-Connecting-IP'] = '6.6.2.2' } it 'sets the creator_ip to the value of CF-Connecting-IP' do post(:create, params: { src_image: { image: fixture_file_upload( '/files/ti_duck.jpg', 'image/jpeg' ) } }) expect(SrcImage.last.creator_ip).to eq('6.6.2.2') end end end context 'when loading an image url' do it 'creates a src image with the url' do post(:create, params: { src_image: { url: 'http://test.com/image.jpg' } }) expect(response).to have_http_status(:ok) expect(SrcImage.last.url).to eq('http://test.com/image.jpg') end it 'does not increment the src image upload statsd counter' do expect do post(:create, params: { src_image: { url: 'http://test.com/image.jpg' } }) expect(response).to have_http_status(:ok) end.to_not <API key>('src_image.upload') end end it 'creates the src image with the private flag' do post(:create, params: { src_image: { url: 'http://test.com/image.jpg', private: true } }) expect(response).to have_http_status(:ok) expect(SrcImage.last.private).to eq(true) end it 'creates the src image with the name' do post(:create, params: { src_image: { url: 'http://test.com/image.jpg', name: 'test name' } }) expect(response).to have_http_status(:ok) expect(SrcImage.last.name).to eq('test name') end it 'creates the src image owned by the current user' do post(:create, params: { src_image: { url: 'http://test.com/image.jpg' } }) expect(response).to have_http_status(:ok) expect(SrcImage.last.user).to eq(user) end it 'returns ok' do post(:create, params: { src_image: { url: 'http://test.com/image.jpg' } }) expect(response).to have_http_status(:ok) end it 'returns json with the src image id' do post(:create, params: { src_image: { url: 'http://test.com/image.jpg' } }) expect(response).to have_http_status(:ok) created_src_image = SrcImage.last expect(JSON.parse(response.body)).to include( 'id' => created_src_image.id_hash ) end it 'returns json with the status url' do post(:create, params: { src_image: { url: 'http://test.com/image.jpg' } }) expect(response).to have_http_status(:ok) created_src_image = SrcImage.last expect(JSON.parse(response.body)).to include( 'status_url' => 'http://test.host/api/v3/pending_src_images/' \ "#{created_src_image.id_hash}" ) end end context 'with invalid attributes' do it 'returns unprocessable entity' do post(:create, params: { src_image: { name: 'test name' } }) expect(response).to have_http_status(:<API key>) end it 'returns json with the errors' do post(:create, params: { src_image: { name: 'test name' } }) expect(JSON.parse(response.body)).to eq( 'image' => ['is required if url or image external key and bucket ' \ 'are not set.'] ) end end end describe "PUT 'update'" do before do request.accept = 'application/json' request.content_type = 'application/json' end context 'when the user is not logged in' do let(:user) { nil } let(:src_image) { FactoryGirl.create(:finished_src_image) } it 'returns forbidden' do put(:update, params: { id: src_image.id_hash }) expect(response).to be_forbidden end end context 'when the user does not own the image' do let(:src_image) do FactoryGirl.create( :finished_src_image, user: FactoryGirl.create(:user) ) end context 'when the user is not an admin' do it 'returns forbidden' do put(:update, params: { id: src_image.id_hash, captions_attributes: [ { top_left_x_pct: 0.01 } ] }) expect(response).to be_forbidden end end context 'when the user is an admin' do let(:user) { FactoryGirl.create(:admin_user) } it 'updates the image' do put(:update, params: { id: src_image.id_hash, captions_attributes: [ { top_left_x_pct: '0.01', top_left_y_pct: '0.02', width_pct: '0.03', height_pct: '0.04', text: 'test' } ] }) expect(response).to have_http_status(204) expect(src_image.captions.size).to eq(1) caption = src_image.captions[0] expect(caption.top_left_x_pct).to eq(0.01) expect(caption.top_left_y_pct).to eq(0.02) expect(caption.width_pct).to eq(0.03) expect(caption.height_pct).to eq(0.04) expect(caption.text).to eq('test') end end end context 'when the user owns the image' do let(:src_image) { FactoryGirl.create(:finished_src_image, user: user) } it 'updates the image' do put(:update, params: { id: src_image.id_hash, captions_attributes: [ { top_left_x_pct: '0.01', top_left_y_pct: '0.02', width_pct: '0.03', height_pct: '0.04', text: 'test' }, { top_left_x_pct: '0.05', top_left_y_pct: '0.06', width_pct: '0.07', height_pct: '0.08', text: 'test 2' } ] }) expect(response).to have_http_status(204) expect(src_image.captions.size).to eq(2) caption1 = src_image.captions[0] expect(caption1.top_left_x_pct).to eq(0.01) expect(caption1.top_left_y_pct).to eq(0.02) expect(caption1.width_pct).to eq(0.03) expect(caption1.height_pct).to eq(0.04) expect(caption1.text).to eq('test') caption2 = src_image.captions[1] expect(caption2.top_left_x_pct).to eq(0.05) expect(caption2.top_left_y_pct).to eq(0.06) expect(caption2.width_pct).to eq(0.07) expect(caption2.height_pct).to eq(0.08) expect(caption2.text).to eq('test 2') end end context 'with invalid attributes' do let(:src_image) { FactoryGirl.create(:finished_src_image, user: user) } it 'returns unprocessable entity with errors' do put(:update, params: { id: src_image.id_hash, captions_attributes: [ { top_left_x_pct: '0.01', top_left_y_pct: '0.02', width_pct: '0.03', text: 'test' } ] }) expect(response).to have_http_status(422) expect(JSON.parse(response.body)).to eq( 'captions.height_pct' => ["can't be blank"] ) end end end end
<?php namespace CodeJet\Http\Factory; use CodeJet\Http\Request; use CodeJet\Http\Uri; use Interop\Http\Factory\<API key>; use Psr\Http\Message\UriInterface; class RequestFactory implements <API key> { /** * @inheritdoc */ public function createRequest($method, $uri) { if (!$uri instanceof UriInterface) { $uri = new Uri($uri); } return (new Request()) ->withMethod($method) ->withUri($uri); } }
import DS from 'ember-data'; var <API key> = DS.Model.extend({ name: DS.attr('string'), telecom: DS.hasMany('contact-point', {embedded: true}) }); export default <API key>;
export interface PanelOptions { seq: number; url: string; id?: number; width?: number; height?: number; top?: number; left?: number; title?: string; active?: boolean; fullScreen?: boolean; canClose?: boolean; cssClass?: string[]; }
package bytebuffer import ( bi "encoding/binary" "math" "testing" ) func BenchmarkGet512_C(b *testing.B) { benchmarkGet(b, NewBB(1<<20), makeSlice(1<<9)) } func BenchmarkGet1K_C(b *testing.B) { benchmarkGet(b, NewBB(1<<20), makeSlice(1<<10)) } func BenchmarkGet32K_C(b *testing.B) { benchmarkGet(b, NewBB(1<<20), makeSlice(1<<15)) } func BenchmarkRead512_C(b *testing.B) { benchmarkRead(b, NewBB(1<<20), 1<<9) } func BenchmarkRead1K_C(b *testing.B) { benchmarkRead(b, NewBB(1<<20), 1<<10) } func BenchmarkRead32K_C(b *testing.B) { benchmarkRead(b, NewBB(1<<20), 1<<15) } func BenchmarkPut1K_C(b *testing.B) { benchmarkPut(b, NewBB(1<<20), makeSlice(1024)) } func BenchmarkPut_C(b *testing.B) { benchmarkPut(b, NewBB(1<<20), byte(math.MaxUint8)) } func BenchmarkGet_C(b *testing.B) { benchmarkGet(b, NewBB(1<<20), byte(math.MaxUint8)) } func <API key>(b *testing.B) { benchmarkPut(b, NewBB(1<<20), uint16(math.MaxUint16)) } func <API key>(b *testing.B) { benchmarkGet(b, NewBB(1<<20), uint16(math.MaxUint16)) } func TestWrap_C(t *testing.T) { cases := []byte{0, 1, 127, 128, 255} bb := WrapBB(cases) for _, wanted := range cases { b := bb.Get() if wanted != b { t.Errorf("wanted:%d, got:%d\n", wanted, b) } } checkErrCase(t, ErrUnderflow, func() { bb.Get() }) } func TestByteAccess_C(t *testing.T) { cases := []byte{0, 1, 127, 128, 255} bb := NewBB(5) bb.OrderTo(bi.LittleEndian) for _, c := range cases { bb.Put(c) } checkErrCase(t, ErrOverflow, func() { bb.Put(2) }) bb.Flip() for _, wanted := range cases { b := bb.Get() if wanted != b { t.Errorf("wanted:%d, got:%d\n", wanted, b) } } checkErrCase(t, ErrUnderflow, func() { bb.Get() }) } func TestUint16Access_C(t *testing.T) { cases := []uint16{0, 1, 32767, 32768, math.MaxUint16} bb := NewBB(len(cases) * 2) bb.OrderTo(bi.LittleEndian) for _, c := range cases { bb.PutUint16(c) } checkErrCase(t, ErrOverflow, func() { bb.PutUint16(2) }) bb.Flip() for _, wanted := range cases { b := bb.GetUint16() if wanted != b { t.Errorf("wanted:%d, got:%d\n", wanted, b) } } checkErrCase(t, ErrUnderflow, func() { bb.GetUint16() }) }
package tw.com.ischool.oauth2signin; import ischool.signin.WebAppInterface; import ischool.signin.WebAppInterface.On<API key>; import tw.com.ischool.oauth2signin.AccessToken.<API key>; import tw.com.ischool.oauth2signin.util.Util; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; /* * Activity OAuth2 ischool * <API key> Acitivity * * Intent i = new Intent(MainActivity.this, SignActivity.class); * <API key>(i, SignInActivity.ACTION_REQUESTCODE); * * * onActivityResult resultCode * @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // SignIn if (requestCode == SignInActivity.ACTION_REQUESTCODE) { // if (resultCode == RESULT_OK) { User user = User.get(); String firstName = user.getFirstName(); } else { String errMsg = data.getExtraString(SignActvity.<API key>) } } } * * * intent * * i.putExtra(SignInActivity.ACTION_TYPE, SignInActivity.ACTION_TYPE_SIGNOUT); * * Activity */ public class SignInActivity extends FragmentActivity { /* intent */ public final static String ACTION_TYPE = "SignActivity.IsSignOut"; public final static int ACTION_TYPE_SIGNIN = 0; public final static int ACTION_TYPE_SIGNOUT = -1; /* Activity Key */ public final static String <API key> = "SignInActivity.SignInErrorMessage"; /* Activity Request Code */ public final static int ACTION_REQUESTCODE = 65535; /* Tag for Debugging */ public final static String DEBUG_TAG = "<API key>.Debug_Tag"; private final static String PREF_NAME = "<API key>"; private final static String PREF_REFRESHTOKEN = "RefreshToken"; private WebView mWebLogin; @Override protected void onCreate(Bundle savedInstanceState) { showLog("SignInActvity.onCreate() ...."); super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign); initWebView(); boolean <API key> = Util.isNetworkOnline(this); Intent i = getIntent(); if (<API key>(i)) { signOut(<API key>); if (!<API key>) { returnResult(false, ""); } } else { // Dialog showLog(" ..."); if (!<API key>) { returnResult(false, ""); } else signIn(); } getActionBar().hide(); } /* * WebView */ private void initWebView() { showLog("SignInActvity.initWebView() ...."); // 1. WebView mWebLogin = (WebView) findViewById(R.id.webLogin); // 2. WebView Javascript WebSettings setting = mWebLogin.getSettings(); setting.<API key>(true); // 3. Javascript Access Token WebAppInterface webInterface = new WebAppInterface(); webInterface.setOn<API key>(new On<API key>() { @Override public void onTokenRetrieved(String tokenJSONString) { AccessToken.<API key>(tokenJSONString); AccessToken token = AccessToken.<API key>(); // Singleton, // AccessToken if (token.hasError()) { returnResult(false, token.getErrorMessage(), false); } else { // Refresh Token Shared Preference <API key>(token.<API key>() .getRefreshToken()); getUserInfo(token.getAccessToken()); } } }); mWebLogin.<API key>(webInterface, "Android"); mWebLogin.setWebViewClient(new WebViewClient() { // redirect @Override public boolean <API key>(WebView view, String url) { showLog(" url : " + url); view.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); showLog("url : " + url); if (url.equals(Constant.SingIn.OAUTH_LOGOUT_URL)) { toSignInPage(); } // // web2 reload if (url.indexOf(Constant.SingIn.STRANGE_URL) > -1) { toSignInPage(); } } }); } private void toSignInPage() { mWebLogin.loadUrl(Constant.SingIn.OAUTH_URL); } private void toSignOutPage() { mWebLogin.loadUrl(Constant.SingIn.OAUTH_LOGOUT_URL); } private void signOut(boolean <API key>) { showLog("SignInActvity.signOut() ...."); // 1. AccessToken showLog("erase Access Token ...."); AccessToken.<API key>(null); // Clear Current Access Token // 2. preference Refresh Token showLog("remove Refredh Token from Preference ...."); <API key>(); if (<API key>) { showLog(" to Signout Page ...."); this.toSignOutPage(); } } /* * Access Token 1.1 Token * 1.1.1 1.1.2 refresh token Access * Token * * 1.2 preference refresh token 1.2.1 Refresh * Token Refresh Token Access Token 1.2.2 * Refresh Token */ private void signIn() { Log.d(DEBUG_TAG, "SignInActivity.SignIn() ..."); AccessToken token = AccessToken.<API key>(); // Access Token showLog(" Access Token"); if (token != null) { // token Log.e(DEBUG_TAG, "Token" + token.getAccessToken()); Log.e(DEBUG_TAG, " Token "); if (!token.isExpired()) { Log.e(DEBUG_TAG, "Token ..." + token.getExpiredDate().toString()); setResult(RESULT_OK); } else { // AccessToken Log.e(DEBUG_TAG, "SignIn() ..."); renewToken(AccessToken.<API key>() .getRefreshToken()); } } else { // Access Token // a. Preference Refresh Token showLog(" Access Token, Preference Refresh Token ? ...."); SharedPreferences settings = <API key>(PREF_NAME, 0); String refresh_token = settings.getString(PREF_REFRESHTOKEN, ""); if (!refresh_token.equals("")) { showLog(" refresk token :" + refresh_token + ", "); renewToken(refresh_token); } else { // Preference Refresh Token showLog("preference refresk token"); this.toSignInPage(); } } } /* * Refresh Token Access Token / Refresh Token, * AccessToken shared preference refresh Token */ private void renewToken(String refreshToken) { showLog("SignInActivity.renewToken(...);"); // access token AccessToken.refreshAccessToken(refreshToken, new <API key>() { @Override public void onSuccess(AccessToken token) { showLog(" refresh token AccessToken : " + token); // Refresh Token Shared Preference <API key>(token .<API key>().getRefreshToken()); getUserInfo(token.getAccessToken()); } @Override public void onException(Exception ex) { showLog(" refresh token AccessToken : " + ex.getLocalizedMessage()); returnResult(false, ex.getLocalizedMessage()); } }); } /* * auth.ischool.com.tw */ private void getUserInfo(String token) { showLog("SignInActivity.getUserInfo( tokenv) ..."); final User user = User.get(); // Singleton user.getUserInfo(token, new User.GetUserInfoListener() { @Override public void onSuccess() { Log.d("DEBUG", " Get User Info Success : User Name : " + user.getFirstName() + user.getLastName()); returnResult(true, ""); } @Override public void onException(Exception ex) { showLog("" + ex.getLocalizedMessage()); returnResult(false, ex.getLocalizedMessage()); } }); } /* * Activity (caller) Activity */ private void returnResult(boolean isSuccessful, String errMsg) { returnResult(isSuccessful, errMsg, true); } /* * Activity (caller) */ private void returnResult(boolean isSuccessful, String errMsg, boolean wantToCloseActivity) { showLog(" Activity : SignInActivity.returnResult (" + isSuccessful + "," + errMsg + "," + wantToCloseActivity + ")"); if (isSuccessful) { setResult(RESULT_OK); } else { Intent i = new Intent(); i.putExtra(<API key>, errMsg); setResult(RESULT_CANCELED, i); } // Activity if (wantToCloseActivity) { finish(); } } // refresh Token Preference private void <API key>(String refreshToken) { SharedPreferences settings = this.<API key>(PREF_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString(PREF_REFRESHTOKEN, refreshToken); // Commit the edits! editor.commit(); } // refresh token Preference private void <API key>() { SharedPreferences settings = this.<API key>(PREF_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.remove(PREF_REFRESHTOKEN); editor.commit(); } private boolean <API key>(Intent i) { boolean result = false; if (i.hasExtra(ACTION_TYPE)) { result = (i.getIntExtra(ACTION_TYPE, ACTION_TYPE_SIGNIN) == ACTION_TYPE_SIGNOUT); } return result; } /* * Debug */ private void showLog(String msg) { Log.d(SignInActivity.DEBUG_TAG, msg); } }
#ifndef <API key> #define <API key> // $Id: arg_typedef.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Revision: 49267 $ #include <cutl/details/boost/mpl/aux_/config/lambda.hpp> #include <cutl/details/boost/mpl/aux_/config/workaround.hpp> #if defined(<API key>) \ || BOOST_WORKAROUND(__DMC__, BOOST_TESTED_AT(0x840)) # define <API key>(T, name) typedef T name; #else # define <API key>(T, name) #endif #endif // <API key>
/** * Comment */ var marked = require("marked"), uuid = require('node-uuid'); marked.setOptions({ renderer: new marked.Renderer(), gfm: true, tables: true, breaks: false, pedantic: false, sanitize: true, smartLists: true, smartypants: false, highlight: function (code) { return require('highlight.js').highlightAuto(code).value; } }); module.exports = { tableName: 'comments', attributes: { uuid: { type: 'uuidv4', unique: true, index: true, defaultsTo: function(){return uuid.v4()} }, title: { type: 'string', required: true, maxLength: 150 }, rawContent: { type: 'text', defaultsTo: '', columnName: 'raw_content' }, content: { type: 'text', defaultsTo: '' }, commentableType: { type: 'string', columnName: 'commentable_type' }, commentableUrl: { type: 'string', columnName: 'commentable_url' }, commentableTitle: { type: 'string', columnName: 'commentable_title' }, ip: 'ip', email: { type: 'email', required: true, maxLength: 150 }, depth: { type: 'integer', defaultsTo: 0 }, // `confirmed` or `spam` or `draft` state: { type: 'string', defaultsTo: 'draft' }, // Associations user: { model: 'user', columnName: 'user_id' }, post: { model: 'post', columnName: 'post_id' }, parent: { model: 'comment', columnName: 'parant_id' }, child: { model: 'comment' } }, beforeCreate: function(values, next) { // Convert markdown to html marked(values.rawContent, function(err, content){ if (err) return next(err); values.content = content; next(); }); }, beforeUpdate: function(values, next) { // Convert markdown to html marked(values.rawContent, function(err, content){ if (err) return next(err); values.content = content; next(); }); } };
package solutions.digamma.damas.session; /** * A used session information along side a session token. * * An object of this type is returned upon successful authentication. Both * session information and token are usually needed for actions following once * user is logged in. */ public interface UserToken extends UserSession, Token { }
using UnityEngine; namespace UnityEngine.Experimental.Rendering { public class CameraSwitcher : MonoBehaviour { public Camera[] m_Cameras; private int <API key> = -1; private Camera m_OriginalCamera = null; private Vector3 <API key>; private Quaternion <API key>; private Camera m_CurrentCamera = null; GUIContent[] m_CameraNames = null; int[] m_CameraIndices = null; DebugUI.EnumField m_DebugEntry; //saved enum fields for when repainting int <API key>; void OnEnable() { m_OriginalCamera = GetComponent<Camera>(); m_CurrentCamera = m_OriginalCamera; if (m_OriginalCamera == null) { Debug.LogError("Camera Switcher needs a Camera component attached"); return; } <API key> = GetCameraCount() - 1; m_CameraNames = new GUIContent[GetCameraCount()]; m_CameraIndices = new int[GetCameraCount()]; for (int i = 0; i < m_Cameras.Length; ++i) { Camera cam = m_Cameras[i]; if (cam != null) { m_CameraNames[i] = new GUIContent(cam.name); } else { m_CameraNames[i] = new GUIContent("null"); } m_CameraIndices[i] = i; } m_CameraNames[GetCameraCount() - 1] = new GUIContent("Original Camera"); m_CameraIndices[GetCameraCount() - 1] = GetCameraCount() - 1; m_DebugEntry = new DebugUI.EnumField { displayName = "Camera Switcher", getter = () => <API key>, setter = value => SetCameraIndex(value), enumNames = m_CameraNames, enumValues = m_CameraIndices, getIndex = () => <API key>, setIndex = value => <API key> = value }; var panel = DebugManager.instance.GetPanel("Camera", true); panel.children.Add(m_DebugEntry); } void OnDisable() { if (m_DebugEntry != null && m_DebugEntry.panel != null) { var panel = m_DebugEntry.panel; panel.children.Remove(m_DebugEntry); } } int GetCameraCount() { return m_Cameras.Length + 1; // We need +1 for handling the original camera. } Camera GetNextCamera() { if (<API key> == m_Cameras.Length) return m_OriginalCamera; else return m_Cameras[<API key>]; } void SetCameraIndex(int index) { if (index > 0 || index < GetCameraCount()) { <API key> = index; if (m_CurrentCamera == m_OriginalCamera) { <API key> = m_OriginalCamera.transform.position; <API key> = m_OriginalCamera.transform.rotation; } m_CurrentCamera = GetNextCamera(); if (m_CurrentCamera != null) { // If we witch back to the original camera, put back the transform in it. if (m_CurrentCamera == m_OriginalCamera) { m_OriginalCamera.transform.position = <API key>; m_OriginalCamera.transform.rotation = <API key>; } transform.position = m_CurrentCamera.transform.position; transform.rotation = m_CurrentCamera.transform.rotation; } } } } }
<?php namespace Transformatika\Utility; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Exception\<API key>; class Str { public function validateEmail($str) { return filter_var($str, <API key>); } public function validateIP($str) { return filter_var($str, FILTER_VALIDATE_IP); } public function getId($version = 4, $includeDash = false) { return $this->generateId($version, $includeDash); } public function getUUID($version = 4, $includeDash = false) { return $this->generateId($version, $includeDash); } public function uuid($version = 4, $includeDash = false) { return $this->generateId($version, $includeDash); } /** * Generate ID * @return String */ public function generateId($version = 4, $includeDash = false) { try { switch ($version) { case 1: $uuid = Uuid::uuid1(); break; case 3: $uuid = Uuid::uuid3(Uuid::NAMESPACE_DNS, php_uname('n')); break; case 5: $uuid = Uuid::uuid5(Uuid::NAMESPACE_DNS, php_uname('n')); break; default: $uuid = Uuid::uuid4(); break; } return $includeDash ? $uuid->toString() : str_replace('-', '', $uuid->toString()); } catch (<API key> $e) { // Some dependency was not met. Either the method cannot be called on a // 32-bit system, or it can, but it relies on Moontoast\Math to be present. echo 'Caught exception: ' . $e->getMessage() . "\n"; exit(); } } /** * Limit Character * @param String * @param Integer * @return String */ public function limitChar($content, $limit = 100) { if (strlen($content) <= $limit) { return $content; } else { $hasil = substr($content, 0, $limit); return $hasil . "..."; } } /** * Limit Word * @param String * @param Integer * @return String */ public function limitWord($string, $limit = 10) { $words = explode(" ", $string); return implode(" ", array_splice($words, 0, $limit)); } public function urlSlug($text) { // replace non letter or digits by - $text = preg_replace('~[^\\pL\d]+~u', '-', $text); // trim $text = trim($text, '-'); // transliterate $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); // lowercase $text = strtolower($text); // remove unwanted characters $text = preg_replace('~[^-\w]+~', '', $text); if (empty($text)) { return 'n-a'; } return $text; } /** * Validate POST */ public function validatePOST($name) { if (isset($_POST[$name]) && !empty($_POST[$name])) { return true; } else { return false; } } /** * Generate Random Color */ public function randomColor() { mt_srand((double)microtime() * 1000000); $c = ''; while (strlen($c) < 6) { $c .= sprintf("%02X", mt_rand(0, 255)); } return ' } /** * Alias randomColor function * @return [type] [description] */ public function generateRandomColor() { return $this->randomColor(); } /** * Generate Random String * Exclude 0 and O * @param integer $length [description] * @param [type] $specialCharacters [description] * @return [type] [description] */ public function <API key>($length = 32, $specialCharacters = true) { $digits = ''; $chars = "<API key>"; if ($specialCharacters === true) { $chars .= "!?=/&+,."; } for ($i = 0; $i < $length; $i++) { $x = mt_rand(0, strlen($chars) - 1); $digits .= $chars{$x}; } return $digits; } }
/* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the bottom of the * compiled file so the styles you add here take precedence over styles defined in any styles * defined in the other CSS/SCSS files in this directory. It is generally better to create a new * file per style scope. * *= require_tree . *= require_self *= require bootstrap.min */ body { overflow: hidden; } ul { list-style-type: none; margin: 0; padding: 0; } #nav-title { font-family: 'Marck Script', cursive; } #added-space { margin-bottom: 30px; }
![FireLoop](https://storage.googleapis.com/fireloop/fireloop-gh-header.svg) > ### **[FireLoop.io][fireloop]** > > > > > > > > Real-Time **[NodeJS]** Platform by **[MEAN Expert]** [![All Contributors](https://img.shields.io/badge/<API key>.svg?style=flat-square)]( # What is **[FireLoop]**? > **[FireLoop]** is a **[NodeJS]** _`Real-Time Platform`_ that makes it effortless to build modern and complex applications by seamlessly integrating amazing _`MEAN Stack`_ technologies, such as: - IBM's **[LoopBack][ibm's loopback framework]** - Google's **[Angular 4+]** - Microsoft's **[TypeScript]** - Telerik's **[NativeScript 2]** - **[Ionic 2]** - **[NodeJS]** - **[MongoDB](https: > **[FireLoop]** also provides you with exclusive modules that will allow you to quickly: - Build your own **Real-Time APIs** - Generate **Client SDKs** to interact with Back-End APIs - Enhance Charts and Graphs with **Real-Time Statistics** - Develop Advanced, **Full-Stack** Web Applications written in **[TypeScript]** # **[FireLoop]** Features - Simple **[Installation](#<API key>)** and Setup - Easy to **[Learn](#<API key>)** - **Automatically Scaffold Your Application Base and Generate Your Own Custom SDK** - **1 Command Line Tool** for everything (Server, Web Clients, Mobile Clients, SDK Builder) - **Full-Stack [TypeScript]** Development - **[LoopBack][ibm's loopback framework]** 2 and 3 Integration - **[Angular 4+]** Integration - **[NativeScript 2]** Integration - **[Ionic 2]** Integration - **[SDK Builder]** Integration - **[Real-Time]** Integration # **[FireLoop]** Installation > ### **Pre-Requisites** - **[Node]** 6.9.0 or greater - **[NPM]** 3.0.0 or greater > - _`apps`_ - Your Applications - **webapp** - Your Web App built with **[Angular 4+]** and integrated with **[FireLoop]**. - **api-server** - Your REST API built with **[LoopBack]** and integrated with **[FireLoop]**. - _`modules`_ - Modules that add functionality to your `apps`. - _`packages`_ - Shareable packages used by your `apps` and `modules`. > ### **Global [NPM] Packages** sh > npm install -g @mean-expert/fireloop lerna @angluar/cli loopback-cli rimraf - **[FireLoop]** - **[LernaJS](https://lernajs.io)** - **[Angular CLI](https://github.com/angular/angular-cli)** - **[loopback-cli]** - **[rimraf](https://github.com/isaacs/rimraf)** > ### **Clone this repo, _`cd`_ to it, and _`install`_ project dependencies** sh > git clone https://github.com/fireloop/platform > cd fireloop > npm install # **[FireLoop]** Documentation > ### **Read the Docs!** | English | Spanish | | : | **<http: # Contributors > <!-- <API key>:START - Do not remove or modify this section --> | [<img src="https: | : <!-- <API key>:END --> [angular 4+]: https://angular.io [firebase]: https://firebase.google.com/ [fireloop]: http://fireloop.io [fireloop.io]: http://fireloop.io [google's firebase]: https://firebase.google.com/ [horizon]: http://horizon.io/ [ibm's loopback framework]: http://loopback.io [ionic 2]: http://ionic.io [loopback]: http://loopback.io [loopback-cli]: https://github.com/strongloop/loopback-cli [loopback component real-time]: http://github.com/<API key>/<API key> [loopback sdk builder]: http://github.com/<API key>/<API key> [<API key>]: http://npmjs.org/package/<API key> [<API key>]: http://npmjs.org/package/<API key> [mean expert]: https://github.com/<API key> [nativescript 2]: http://nativescript.org [nodejs]: http://nodejs.org [node]: http://nodejs.org [npm]: https: [real-time]: https://github.com/<API key>/<API key> [sdk builder]: https://github.com/<API key>/<API key> [typescript]: https:
'use strict'; var ensureObject = require('es5-ext/object/valid-object') , capitalize = require('es5-ext/string/#/capitalize') , deferred = require('deferred') , resolve = require('path').resolve , _ = require('mano').i18n.bind('Statistics time per person pdf') , db = require('../../db') , resolveFullStepPath = require('../../utils/<API key>') , <API key> = require('../../view/utils/<API key>') , getUserFullName = require('../utils/get-user-full-name') , htmlToPdf = require('../html-to-pdf') , processingStepsMeta = require('../../<API key>') , root = resolve(__dirname, '../..') , templatePath = resolve(root, 'apps-common/pdf-templates/<API key>.html'); module.exports = function (result, config) { ensureObject(config); var inserts = { steps: [], locale: db.locale, logo: config.logo, currentDate: db.DateTime().toString() }; return deferred.map(Object.keys(result.byStep), function (key) { var step = {}, total; step.label = db['BusinessProcess' + capitalize.call(processingStepsMeta[key]._services[0])].prototype .processingSteps.map.getBySKeyPath(resolveFullStepPath(key)).label; inserts.steps.push(step); total = result.byStep[key].processing; total.fullName = _("Total & times"); total.avgTime = total.timedCount ? <API key>(total.avgTime) : '-'; total.minTime = total.timedCount ? <API key>(total.minTime) : '-'; total.maxTime = total.timedCount ? <API key>(total.maxTime) : '-'; return deferred.map(Object.keys(result.byStepAndProcessor[key]), function (userId) { var item = result.byStepAndProcessor[key][userId].processing; item.avgTime = item.timedCount ? <API key>(item.avgTime) : '-'; item.minTime = item.timedCount ? <API key>(item.minTime) : '-'; item.maxTime = item.timedCount ? <API key>(item.maxTime) : '-'; return getUserFullName(userId)(function (fullName) { item.fullName = fullName; return { processing: item }; }); })(function (data) { step.data = data; data.push({ processing: total }); }); })(function () { return htmlToPdf(templatePath, '', { width: "297mm", height: "210mm", streamable: true, templateInserts: inserts }); }); };
<!DOCTYPE html> <html lang=nl> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, maximum-scale=1.0" /> <link rel="apple-touch-icon" sizes="180x180" href="../apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="../favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../favicon-16x16.png"> <link rel="manifest" href="../manifest.json"> <link rel="mask-icon" href="../safari-pinned-tab.svg" color="#5bbad5"> <meta name="theme-color" content="#ffffff"> <title>KaskeMuse</title> <link rel="stylesheet" href="../css/kaskestijl.css"> <link rel="stylesheet" href="../css/nav.css"> <link rel="stylesheet" href="../css/kleur.css"> </head> <body class="groen"> <div> <h1>Koor Kaskedieze Bladmuziek in Musescore</h1> </div> <nav> <ul> <li><a href="../kaskepubliek/koor.html">K</a> <ul> <li><a href="../kaskepubliek/koor.html#naam">Naam</a></li> <li><a href="../kaskepubliek/koor.html#repeteren">Repeteren</a></li> <li><a href="../kaskepubliek/koor.html#liedlijst">Liedlijst</a></li> </ul> </li> <li><a href="./start.html">Leden</a></li> <li><a href="./luisteren.html">Luisteren</a></li> <li><a href="./musescore.html">Musescore</a></li> <li><a href="./afdrukken.html">Afdrukken</a></li> <li><a href="./trein.html">Trein</a></li> <li><a href="./documenten.html">Documenten</a></li> <li><a href="./estafette.html">Estafette</a></li> </ul> </nav> <main> <h2>MuseScore</h3> <div class="row"> <div class="col-4 col-m-4"> <p> Hier kun je van een aantal liederen de bladmuziek ophalen in MuseScore formaat. </p> <p> MuseScore is een programma om bladmuziek te maken, te beluisteren en af te drukken. Om MuseScore te kunnen gebruiken moet je het eerst op je computer installeren. Je kunt het vinden <a href="https://musescore.org/nl" target="_blank">musescore.org</a>. Het is beschikbaar voor Windows, Mac en andere platforms. </p> <p> Nadat je hebt ovegehaald ("gedownload") en ge&iuml;nstalleerd kun je de mscz bestanden hieronder gebruiken om de muziek af te spelen. Met de Mixer van het menu Weergave kun je ook apart naar de partij van je eigen stemgroep luisteren. </p> </div> <div class="col-8 col-m-8"> <div class="rechts"> <img src="../images/musescore.jpg" alt="plaatje scherm van musescore programma eerste regel lied Ty Paduj getoond" width="560" height="327"> </div> </div> </div> <div class="row"> <div class="col-6 col-m-16"> Stille Nacht: <a href="../media/mscz/stillenacht.mscz" target="_blank">stillenacht.mscz</a> </div> <div class="col-6 col-m-16"> Todos los bienes: <a href="../media/mscz/todos.mscz" target="_blank">todos.mscz</a> </div> </div> <div class="row"> <div class="col-6 col-m-16"> Bogoroditse Devo: <a href="../media/mscz/bogoroditse.mscz" target="_blank">bogoroditse.mscz</a> </div> <div class="col-6 col-m-16"> Tebe pojem (Rachmaninov): <a href="../media/mscz/teberach.mscz" target="_blank">teberach.mscz</a> </div> </div> <div class="row"> <div class="col-6 col-m-16"> Ukolebavka: <a href="../media/mscz/ukolebavka.mscz" target="_blank">ukolebavka.mscz</a> </div> <div class="col-6 col-m-16"> Santa Maria strela do dia: <a href="../media/mscz/maria.mscz" target="_blank">maria.mscz</a> </div> </div> <div class="row"> <div class="col-6 col-m-16"> Adio Kerida: <a href="../media/mscz/adiokerida.mscz" target="_blank">adiokerida.mscz</a> </div> <div class="col-6 col-m-16"> Olijven vallen: <a href="../media/mscz/olijven.mscz" target="_blank">olijven.mscz</a> </div> </div> <div class="row"> <div class="col-6 col-m-16"> Boroech Ate: <a href="../media/mscz/boroech.mscz" target="_blank">boroech.mscz</a> </div> <div class="col-6 col-m-16"> Polegala: <a href="../media/mscz/polegala.mscz" target="_blank">polegala.mscz</a> </div> </div> <div class="row"> <div class="col-6 col-m-16"> Daar is de lente: <a href="../media/mscz/lente.mscz" target="_blank">lente.mscz</a> </div> <div class="col-6 col-m-16"> Step da step krugom: <a href="../media/mscz/step.mscz" target="_blank">step.mscz</a> </div> </div> <div class="row"> <div class="col-6 col-m-16"> Ejder ich lejg mich: <a href="../media/mscz/ejder.mscz" target="_blank">ejder.mscz</a> </div> <div class="col-6 col-m-16"> Ty paduj: <a href="../media/mscz/typaduj.mscz" target="_blank">typaduj.mscz</a> </div> </div> <div class="row"> <div class="col-6 col-m-16"> Erev shell shoshanim: <a href="../media/mscz/erev.mscz" target="_blank">erev.mscz</a> </div> <div class="col-6 col-m-16"> Vecher: <a href="../media/mscz/vecher.mscz" target="_blank">vecher.mscz</a> </div> </div> <div class="row"> <div class="col-6 col-m-16"> Gorani: <a href="../media/mscz/gorani.mscz" target="_blank">gorani.mscz</a> </div> <div class="col-6 col-m-16"> Waar bleeft ge: <a href="../media/mscz/waar.mscz" target="_blank">waar.mscz</a> </div> </div> <div class="row"> <div class="col-6 col-m-16"> Koszonto: <a href="../media/mscz/koszonto.mscz" target="_blank">koszonto.mscz</a> </div> <div class="col-6 col-m-16"> Za dvinoj: <a href="../media/mscz/zadvinoj.mscz" target="_blank">zadvinoj.mscz</a> </div> </div> <div class="row"> <div class="col-6 col-m-16"> Mnogaja ljeta: <a href="../media/mscz/mnogaja.mscz" target="_blank">mnogaja.mscz</a> </div> <div class="col-6 col-m-16"> Shier Noded: <a href="../media/mscz/shier.mscz" target="_blank">shier.mscz</a> </div> </div> </main> <footer> <p>&copy;&nbsp;1989-heden, Koor Kaskedieze, Krommenie, Nederland; alle rechten voorbehouden</p> </footer> </body> </html>
layout: post title: "Modern React with Redux" date: 2016-01-14 16:00:00 +0100 categories: React Redux Since I liked Stephen Griders video course "Build Web Apps with React JS and Flux" I immediately bought his new course <a href="https: The course contains 7.5 hours of video lessons that is divided into lessons between 2.5 minutes to 13 minutes long. It's easy to go back and repeat things later if you need to. The course material is available at GitHub. If you're intrested of a Udemy course, there are coupons and promo codes available on the web so a bit of googling is recommended. <a href="https:
id: 228 title: ThemeForest Dukandari v1.2.6 A Modern Minimalist eCommerce Theme 20919764 date: 2020-10-26T18:59:42+00:00 author: admin layout: post guid: https: permalink: /2020/10/26/<API key>/ tdc_dirty_content: - "1" tdc_icon_fonts: - 'a:0:{}' cyberseo_rss_source: - https: cyberseo_post_link: - https: categories: - Uncategorized <div class="jeg_featured featured_image" readability="7"> <div class="thumbnail-container animate-lazy"> <img width="590" height="300" src="https: </div> <p class="wp-caption-text"> ThemeForest Dukandari v1.2.6 A Modern Minimalist eCommerce Theme 20919764 </p> </div> <div class="entry-content no-share"> <div class="content-inner "> <div class="wp-block-group" readability="6.7561711464619"> <div class="<API key>" readability="8.6865057597367"> <div class="wp-block-group" readability="6.7409673659674"> <div class="<API key>" readability="8.666958041958"> <p> Download Free <strong>ThemeForest Dukandari v1.2.6 A Modern Minimalist eCommerce Theme 20919764</strong> with high speed google drive and mega link. These awesome&nbsp;<strong>ThemeForest Dukandari v1.2.6 A Modern Minimalist eCommerce Theme 20919764</strong>&nbsp;made by&nbsp;<strong>ThemeForest</strong> Download Free. </p> <h2> <strong>ThemeForest – Dukandari v1.2.6 A Modern Minimalist eCommerce Theme 20919764</strong> – Wp Theme Free Download </h2> <p> <strong>Goal:</strong> </p> <ol> <li> Creating a theme the design clean and cogent, selling products with storytelling. </li> <li> Easy and fast to create the website without knowledge of code with drag and drop page builder. </li> <li> Seamless performance </li> <li> Admin Interface that offers all the possible features you need to create a good site. </li> </ol> <h3 id="<API key>"> Theme Features </h3> <ul> <li> Powerful&nbsp;& Easy-to-Use Powerful Admin Interface </li> <li> Drag and drop Page Builder </li> <li> One-click import of demo site </li> <li> Valid HTML5 / CSS3 pages </li> <li> Fully responsive </li> <li> Highly Customizable </li> <li> No coding knowledge required </li> <li> One-Click Demo Content Import </li> <li> Multiple Catalogs/Portfolio List templates </li> <li> Catalogs/Portfolio Masonry List template </li> <li> Catalogs/Portfolio Gallery List&nbsp;template </li> <li> Multiple Catalogs/portfolio list hover types </li> <li> Catalogs/Portfolio List Item content entry animations </li> <li> Parallax effect on Catalogs/portfolio lists </li> <li> Standard pagination on Portfolio Lists </li> <li> Category Filter on Catalogs/Portfolio Lists </li> <li> Catalogs/Portfolio Slider </li> <li> Multiple Portfolio Single Project layouts </li> <li> Catalogs/Portfolio Single Big Images layout </li> <li> Catalogs/Portfolio Single Big Slider layout </li> <li> Catalogs/Portfolio Single Full Width Images layout </li> <li> Catalogs/Portfolio Single Gallery layout </li> <li> Catalogs/Portfolio Single Masonry Gallery layouts </li> <li> Catalogs/Portfolio Single Pinterest layouts </li> <li> Catalogs/Portfolio Single Small Images layout </li> <li> Catalogs/Portfolio Single Small Slider layout </li> <li> Stander Blog list </li> <li> Masonry Blog list </li> <li> Card Blog list </li> <li> Six Customizable Header Types </li> <li> Each web page can have different header style </li> <li> Customization options for each header type </li> <li> Full Screen Menu option </li> <li> Customizable Title Area </li> <li> Customizable Mega Menu </li> <li> Side Menu Area </li> <li> Every Shortcode have custom Google Font </li> <li> CSS Animations&nbsp;for every&nbsp;Shortcode </li> <li> Parallax&nbsp; Animations for every&nbsp;Shortcode </li> <li> Numbered Process Shortcode </li> <li> Interactive Link Showcase shortcode </li> <li> Video Button shortcode </li> <li> Elements Holder shortcode </li> <li> Customizable Google Map shortcode </li> <li> Counter shortcode </li> <li> Call to Action shortcode </li> </ul> <ul> <li> Team shortcode </li> <li> Images shortcode </li> <li> Catalogs/Product List – Carousel shortcode </li> <li> Banner shortcode </li> <li> Video Background Sections </li> <li> Parallax Sections </li> <li> Separate logo versions for Dark and Light Header skins </li> <li> Optionally set different logos on each page </li> <li> Optional Header Top area </li> <li> Integrated search functionality </li> <li> Choose icon pack for search icon </li> <li> Customizable Footer </li> <li> Footer Top and Footer Bottom areas </li> <li> Responsive video </li> <li> Choose from 1-4 column layout for Footer Top </li> <li> Instagram feed widget </li> <li> Image or Text Logo </li> <li> Blog List widget </li> <li> Customizable Shop pages </li> <li> Variable grid size </li> <li> Smooth Page transitions </li> <li> Multiple Blog List Layouts </li> <li> Blog Masonry Layout </li> <li> Blog Standard Layout </li> <li> Custom Post Formats: Standard, Gallery, Quote, Video, Audio </li> <li> WooCommerce compatible </li> <li> Retina Ready </li> <li> Create multiple custom sidebars </li> <li> Mobile Nav </li> <li> 800+ Google Fonts </li> <li> Font Awesome </li> <li> WPML Plugin Compatibility </li> <li> Translation Ready </li> <li> SEO Optimized </li> <li> Child Theme Included </li> </ul> <p> <strong>Sources and Credits</strong> </p> <h5> <strong>Checkout Our More Theme</strong> </h5> <h2 class="<API key>"> <strong>Download Free ThemeForest Dukandari v1.2.6 A Modern Minimalist eCommerce Theme 20919764</strong> </h2> </div> </div> <p> Thank you for Downloading&nbsp;<strong>ThemeForest Dukandari v1.2.6 A Modern Minimalist eCommerce Theme 20919764</strong>. If you face any kind of problem during download then kindly leave a comment. we will fix it as soon as possible. </p> </div> </div> </div> </div>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Yanoshi.CalcHLACGUI.Models; using OpenCvSharp.CPlusPlus; using OpenCvSharp.Extensions; using Yanoshi.CalcHLACGUI.Common; namespace Yanoshi.CalcHLACGUI.Calculator { <summary> HLAC </summary> public static class HLACCalculator { public static RectAndFeature GetFeatures(Mat matObj, RectEx rect, int[] stepSizes) { RectAndFeature returnRect = new RectAndFeature(rect); int start_x = rect.X + 1; int start_y = rect.Y + 1; int end_x = rect.X + rect.Width - 2; int end_y = rect.Y + rect.Height - 2; foreach(int step in stepSizes) { returnRect.Features.AddRange(CalcFeatures(matObj, start_x, start_y, end_x, end_y, step)); } double allFeaturesAddition = 0; for (int i = 0; i < returnRect.Features.Count;i++ ) { allFeaturesAddition += Math.Pow(returnRect.Features[i], 2.0); } double scalar = Math.Sqrt(allFeaturesAddition); for (int i = 0; i < returnRect.Features.Count; i++) { returnRect.Features[i] /= scalar; } return returnRect; } private static double[] CalcFeatures(Mat matObj ,int start_x,int start_y,int end_x,int end_y,int step) { double[] returnData = new double[25]; for (int iy = start_y; iy <= end_y; iy += step) { for (int ix = start_x; ix <= end_x; ix += step) { byte p5 = matObj.GetPixel(ix, iy); if (p5 != 0) { byte p1 = matObj.GetPixel(ix - 1, iy - 1); byte p2 = matObj.GetPixel(ix, iy - 1); byte p3 = matObj.GetPixel(ix + 1, iy - 1); byte p4 = matObj.GetPixel(ix - 1, iy); byte p6 = matObj.GetPixel(ix + 1, iy); byte p7 = matObj.GetPixel(ix - 1, iy + 1); byte p8 = matObj.GetPixel(ix, iy + 1); byte p9 = matObj.GetPixel(ix + 1, iy + 1); returnData[0]++; if (p1 != 0) { returnData[1]++; if (p8 != 0) returnData[13]++; if (p3 != 0) returnData[21]++; if (p7 != 0) returnData[22]++; } if (p2 != 0) { returnData[2]++; if (p8 != 0) returnData[7]++; if (p7 != 0) returnData[11]++; if (p9 != 0) returnData[12]++; if (p6 != 0) returnData[17]++; } if (p3 != 0) { returnData[3]++; if (p7 != 0) returnData[6]++; if (p4 != 0) returnData[9]++; if (p8 != 0) returnData[14]++; } if (p4 != 0) { returnData[4]++; if (p6 != 0) returnData[5]++; if (p9 != 0) returnData[10]++; if (p2 != 0) returnData[18]++; if (p8 != 0) returnData[19]++; } if (p6 != 0) { if (p7 != 0) returnData[15]++; if (p1 != 0) returnData[16]++; if (p8 != 0) returnData[20]++; } if (p9 != 0) { if (p1 != 0) returnData[8]++; if (p7 != 0) returnData[23]++; if (p3 != 0) returnData[24]++; } } } } return returnData; } } }
import sys import os import random import numpy as np import matplotlib.pyplot as plt import math import time import itertools import shutil import tensorflow as tf import tree as tr from utils import Vocab from collections import OrderedDict import seaborn as sns sns.set_style('whitegrid') def <API key>(session): uninitialized = [ var for var in tf.all_variables() if not session.run(tf.<API key>(var)) ] session.run(tf.<API key>(uninitialized)) def variable_summaries(variable, name): with tf.name_scope("summaries"): mean = tf.reduce_mean(variable) tf.summary.scalar('mean/' + name, mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_sum(tf.square(variable - mean))) tf.summary.scalar('stddev/' + name, stddev) tf.summary.scalar('max/' + name, tf.reduce_max(variable)) tf.summary.scalar('min/' + name, tf.reduce_min(variable)) # tf.summary.histogram(name, variable) RESET_AFTER = 50 class Config(object): """Holds model hyperparams and data information. Model objects are passed a Config() object at instantiation. """ embed_size = 50 label_size = 2 early_stopping = 2 anneal_threshold = 0.99 anneal_by = 1.5 max_epochs = 30 lr = 0.01 l2 = 0.02 model_name = 'rnn_embed=%d_l2=%f_lr=%f.weights'%(embed_size, l2, lr) #initial attempt to create graph # currently implicitly assumes tree structure (which can't be passed into tf) # vector_stack = tf.TensorArray(tf.float32, # size=0, # dynamic_size=True, # clear_after_read=True, # infer_shape=True) # index = tf.placeholder(shape=(), dtype=tf.int32) # def embed_word(word_index): # with tf.device('/cpu:0'): # with tf.variable_scope("Composition", reuse=True): # embedding = tf.get_variable('embedding') # return tf.expand_dims(tf.gather(embedding, word_index), 0) # def combine_children(left_location, right_location): # with tf.variable_scope('Composition', reuse=True): # W1 = tf.get_variable('W1') # b1 = tf.get_variable('b1') # return tf.nn.relu(tf.matmul(tf.concat(1, [vector_stack.read(left_location), vector_stack.read(right_location)]), W1) + b1) # tf.gather(is_leaf, index) # #get if this a leaf # tf.gather(word, index) # #get the word associated # tf.gather(left_child, index) # tf.gather(right_child, index) ## ORIGINAL IDEA: # def walk_node(index): # #tf.cond(tf.gather(isLeaf, index,), .. # if in_node.isLeaf is True: # #push the value onto the stack and return index? # word_id = self.vocab.encode(in_node.word) # print("word_id = ", word_id) # vector_stack.write(vector_stack.size() - 1, embed_word(word_id)) # return vector_stack.size() - 1 # #so we return the index # if in_node.isLeaf is False: # left_node = walk_node(in_node.left, vocab) # right_node = walk_node(in_node.right, vocab) # vector_stack.concat(combine_children(left_node, right_node)) # return vector_stack.size() - 1 # #merge the left - right pair, add it back to the stack # #this should never be hit(?) # return 0 class RNN_Model(): def __init__(self, config): self.config = config self.load_data() self.merged_summaries = None self.summary_writer = None self.is_a_leaf = tf.placeholder(tf.bool, [None], name="is_a_leaf") self.left_child = tf.placeholder(tf.int32, [None], name="lchild") self.right_child = tf.placeholder(tf.int32, [None], name="rchild") self.word_index = tf.placeholder(tf.int32, [None], name="word_index") self.labelholder = tf.placeholder(tf.int32, [None], name="labels_holder") self.add_model_vars() self.tensor_array = tf.TensorArray(tf.float32, size=0, dynamic_size=True, clear_after_read=False, infer_shape=False) #tensor array stores the vectors (embedded or composed) self.tensor_array_op = None self.prediction = None self.logits = None self.root_logits = None self.root_predict = None self.root_loss = None self.full_loss = None self.training_op = None #tensor_array_op is the operation on the TensorArray # private functions used to construct the graph. def _embed_word(self, word_index): with tf.variable_scope("Composition", reuse=True) as scope: print(scope.name) embedding = tf.get_variable("embedding") print(embedding.name) return tf.expand_dims(tf.gather(embedding, word_index), 0) # private functions used to construct the graph. def _combine_children(self, left_index, right_index): left_tensor = self.tensor_array.read(left_index) right_tensor = self.tensor_array.read(right_index) with tf.variable_scope('Composition', reuse=True): W1 = tf.get_variable('W1') b1 = tf.get_variable('b1') return tf.nn.relu(tf.matmul(tf.concat(1, [left_tensor, right_tensor]), W1) + b1) # i is the index (over data stored in the placeholders) # identical type[out] = type[in]; can be used in while_loop # so first iteration -> puts left most leaf on the tensorarray (and increments i) # next iteration -> puts next left most (leaf on stack) and increments i # until all the leaves are on the stack in the correct order # starts combining the leaves after and adding to the stack def _loop_over_tree(self, tensor_array, i): is_leaf = tf.gather(self.is_a_leaf, i) word_idx = tf.gather(self.word_index, i) left_child = tf.gather(self.left_child, i) right_child = tf.gather(self.right_child, i) node_tensor = tf.cond(is_leaf, lambda : self._embed_word(word_idx), lambda : self._combine_children(left_child, right_child)) tensor_array = tensor_array.write(i, node_tensor) i = tf.add(i,1) return tensor_array, i def <API key>(self): loop_condition = lambda tensor_array, i: \ tf.less(i, tf.squeeze(tf.shape(self.is_a_leaf))) #iterate over all leaves + composition tensor_array_op = tf.while_loop(cond=loop_condition, body=self._loop_over_tree, loop_vars=[self.tensor_array, 0], parallel_iterations=1)[0] return tensor_array_op def inference_op(self, predict_only_root=False): if predict_only_root: return self.root_logits_op() return self.logits_op() def load_data(self): """Loads train/dev/test data and builds vocabulary.""" self.train_data, self.dev_data, self.test_data = tr.simplified_data(700, 100, 200) # build vocab from training data self.vocab = Vocab() train_sents = [t.get_words() for t in self.train_data] self.vocab.construct(list(itertools.chain.from_iterable(train_sents))) def add_model_vars(self): ''' You model contains the following parameters: embedding: tensor(vocab_size, embed_size) W1: tensor(2* embed_size, embed_size) b1: tensor(1, embed_size) U: tensor(embed_size, output_size) bs: tensor(1, output_size) Hint: Add the tensorflow variables to the graph here and *reuse* them while building the compution graphs for composition and projection for each tree Hint: Use a variable_scope "Composition" for the composition layer, and "Projection") for the linear transformations preceding the softmax. ''' with tf.variable_scope('Composition') as scope: YOUR CODE HERE #initializer=initializer=tf.<API key>(0,3) print(scope.name) embedding = tf.get_variable("embedding", [self.vocab.total_words, self.config.embed_size]) print(embedding.name) W1 = tf.get_variable("W1", [2 * self.config.embed_size, self.config.embed_size]) b1 = tf.get_variable("b1", [1, self.config.embed_size]) l2_loss = tf.nn.l2_loss(W1) tf.add_to_collection(name="l2_loss", value=l2_loss) variable_summaries(embedding, embedding.name) variable_summaries(W1, W1.name) variable_summaries(b1, b1.name) END YOUR CODE with tf.variable_scope('Projection'): YOUR CODE HERE U = tf.get_variable("U", [self.config.embed_size, self.config.label_size]) bs = tf.get_variable("bs", [1, self.config.label_size]) variable_summaries(U, U.name) variable_summaries(bs, bs.name) l2_loss = tf.nn.l2_loss(U) tf.add_to_collection(name="l2_loss", value=l2_loss) END YOUR CODE def add_model(self): """Recursively build the model to compute the phrase embeddings in the tree Hint: Refer to tree.py and vocab.py before you start. Refer to the model's vocab with self.vocab Hint: Reuse the "Composition" variable_scope here Hint: Store a node's vector representation in node.tensor so it can be used by it's parent Hint: If node is a leaf node, it's vector representation is just that of the word vector (see tf.gather()). Args: node: a Node object Returns: node_tensors: Dict: key = Node, value = tensor(1, embed_size) """ if self.tensor_array_op is None: self.tensor_array_op = self.<API key>() return self.tensor_array_op def add_projections_op(self, node_tensors): """Add projections to the composition vectors to compute the raw sentiment scores Hint: Reuse the "Projection" variable_scope here Args: node_tensors: tensor(?, embed_size) Returns: output: tensor(?, label_size) """ logits = None YOUR CODE HERE with tf.variable_scope("Projection", reuse=True): U = tf.get_variable("U") bs = tf.get_variable("bs") logits = tf.matmul(node_tensors, U) + bs END YOUR CODE return logits def logits_op(self): #this is an operation on the updated tensor_array if self.logits is None: self.logits = self.add_projections_op(self.tensor_array_op.concat()) return self.logits def root_logits_op(self): #construct once if self.root_logits is None: self.root_logits = self.add_projections_op(self.tensor_array_op.read(self.tensor_array_op.size() -1)) return self.root_logits def root_prediction_op(self): if self.root_predict is None: self.root_predict = tf.squeeze(tf.argmax(self.root_logits_op(), 1)) return self.root_predict def full_loss_op(self, logits, labels): """Adds loss ops to the computational graph. Hint: Use <API key> Hint: Remember to add l2_loss (see tf.nn.l2_loss) Args: logits: tensor(num_nodes, output_size) labels: python list, len = num_nodes Returns: loss: tensor 0-D """ if self.full_loss is None: loss = None # YOUR CODE HERE l2_loss = self.config.l2 * tf.add_n(tf.get_collection("l2_loss")) idx = tf.where(tf.less(self.labelholder,2)) logits = tf.gather(logits, idx) labels = tf.gather(labels, idx) objective_loss = tf.reduce_sum(tf.nn.<API key>(logits=logits, labels=labels)) loss = objective_loss + l2_loss tf.summary.scalar("loss_l2", l2_loss) tf.summary.scalar("loss_objective", tf.reduce_sum(objective_loss)) tf.summary.scalar("loss_total", loss) self.full_loss = loss # END YOUR CODE return self.full_loss def loss_op(self, logits, labels): """Adds loss ops to the computational graph. Hint: Use <API key> Hint: Remember to add l2_loss (see tf.nn.l2_loss) Args: logits: tensor(num_nodes, output_size) labels: python list, len = num_nodes Returns: loss: tensor 0-D """ if self.root_loss is None: #construct once guard loss = None # YOUR CODE HERE l2_loss = self.config.l2 * tf.add_n(tf.get_collection("l2_loss")) objective_loss = tf.reduce_sum(tf.nn.<API key>(logits=logits, labels=labels)) loss = objective_loss + l2_loss tf.summary.scalar("root_loss_l2", l2_loss) tf.summary.scalar("root_loss_objective", tf.reduce_sum(objective_loss)) tf.summary.scalar("root_loss_total", loss) self.root_loss = loss # END YOUR CODE return self.root_loss def training(self, loss): if self.training_op is None: # YOUR CODE HERE optimizer = tf.train.AdamOptimizer(self.config.lr)#tf.train.<API key>(self.config.lr) #optimizer = tf.train.AdamOptimizer(self.config.lr) self.training_op = optimizer.minimize(loss) # END YOUR CODE return self.training_op def predictions(self, y): """Returns predictions from sparse scores Args: y: tensor(?, label_size) Returns: predictions: tensor(?,1) """ if self.prediction is None: # YOUR CODE HERE self.prediction = tf.argmax(y, dimension=1) # END YOUR CODE return self.prediction def build_feed_dict(self, in_node): nodes_list = [] tr.leftTraverse(in_node, lambda node, args: args.append(node), nodes_list) node_to_index = OrderedDict() for idx, i in enumerate(nodes_list): node_to_index[i] = idx feed_dict = { self.is_a_leaf : [ n.isLeaf for n in nodes_list ], self.left_child : [ node_to_index[n.left] if not n.isLeaf else -1 for n in nodes_list ], self.right_child : [ node_to_index[n.right] if not n.isLeaf else -1 for n in nodes_list ], self.word_index : [ self.vocab.encode(n.word) if n.word else -1 for n in nodes_list ], self.labelholder : [ n.label for n in nodes_list ] } return feed_dict def predict(self, trees, weights_path, get_loss = False): """Make predictions from the provided model.""" results = [] losses = [] logits = self.root_logits_op() #evaluation is based upon the root node root_loss = self.loss_op(logits=logits, labels=self.labelholder[-1:]) root_prediction_op = self.root_prediction_op() with tf.Session() as sess: saver = tf.train.Saver() saver.restore(sess, weights_path) for t in trees: feed_dict = self.build_feed_dict(t.root) if get_loss: root_prediction, loss = sess.run([root_prediction_op, root_loss], feed_dict=feed_dict) losses.append(loss) results.append(root_prediction) else: root_prediction = sess.run(root_prediction_op, feed_dict=feed_dict) results.append(root_prediction) return results, losses #need to rework this: (OP creation needs to be made independent of using OPs) def run_epoch(self, new_model = False, verbose=True, epoch=0): loss_history = [] random.shuffle(self.train_data) with tf.Session() as sess: if new_model: add_model_op = self.add_model() logits = self.logits_op() loss = self.full_loss_op(logits=logits, labels=self.labelholder) train_op = self.training(loss) init = tf.<API key>() sess.run(init) else: saver = tf.train.Saver() saver.restore(sess, './weights/%s.temp'%self.config.model_name) logits = self.logits_op() loss = self.full_loss_op(logits=logits, labels=self.labelholder) train_op = self.training(loss) for step, tree in enumerate(self.train_data): feed_dict = self.build_feed_dict(tree.root) loss_value, _ = sess.run([loss, train_op], feed_dict=feed_dict) loss_history.append(loss_value) if verbose: sys.stdout.write('\r{} / {} : loss = {}'.format( step+1, len(self.train_data), np.mean(loss_history))) sys.stdout.flush() saver = tf.train.Saver() if not os.path.exists("./weights"): os.makedirs("./weights") #print('./weights/%s.temp'%self.config.model_name) saver.save(sess, './weights/%s.temp'%self.config.model_name) train_preds, _ = self.predict(self.train_data, './weights/%s.temp'%self.config.model_name) val_preds, val_losses = self.predict(self.dev_data, './weights/%s.temp'%self.config.model_name, get_loss=True) train_labels = [t.root.label for t in self.train_data] val_labels = [t.root.label for t in self.dev_data] train_acc = np.equal(train_preds, train_labels).mean() val_acc = np.equal(val_preds, val_labels).mean() print() print('Training acc (only root node): {}'.format(train_acc)) print('Valiation acc (only root node): {}'.format(val_acc)) print(self.make_conf(train_labels, train_preds)) print(self.make_conf(val_labels, val_preds)) return train_acc, val_acc, loss_history, np.mean(val_losses) def train(self, verbose=True): <API key> = [] train_acc_history = [] val_acc_history = [] prev_epoch_loss = float('inf') best_val_loss = float('inf') best_val_epoch = 0 stopped = -1 for epoch in range(self.config.max_epochs): print('epoch %d'%epoch) if epoch==0: train_acc, val_acc, loss_history, val_loss = self.run_epoch(new_model=True, epoch=epoch) else: train_acc, val_acc, loss_history, val_loss = self.run_epoch(epoch=epoch) <API key>.extend(loss_history) train_acc_history.append(train_acc) val_acc_history.append(val_acc) #lr annealing epoch_loss = np.mean(loss_history) if epoch_loss>prev_epoch_loss*self.config.anneal_threshold: self.config.lr/=self.config.anneal_by print('annealed lr to %f'%self.config.lr) prev_epoch_loss = epoch_loss #save if model has improved on val if val_loss < best_val_loss: shutil.copyfile('./weights/%s.temp'%self.config.model_name, './weights/%s'%self.config.model_name) best_val_loss = val_loss best_val_epoch = epoch # if model has not imprvoved for a while stop if epoch - best_val_epoch > self.config.early_stopping: stopped = epoch #break if verbose: sys.stdout.write('\r') sys.stdout.flush() print('\n\nstopped at %d\n'%stopped) return { 'loss_history': <API key>, 'train_acc_history': train_acc_history, 'val_acc_history': val_acc_history, } def make_conf(self, labels, predictions): confmat = np.zeros([2, 2]) for l,p in zip(labels, predictions): confmat[l, p] += 1 return confmat def test_RNN(): """Test RNN model implementation. You can use this function to test your implementation of the Named Entity Recognition network. When debugging, set max_epochs in the Config object to 1 so you can rapidly iterate. """ config = Config() model = RNN_Model(config) start_time = time.time() stats = model.train(verbose=True) print('Training time: {}'.format(time.time() - start_time)) plt.plot(stats['loss_history']) plt.title('Loss history') plt.xlabel('Iteration') plt.ylabel('Loss') plt.savefig("loss_history.png") plt.show() print('Test') print('=-=-=') predictions, _ = model.predict(model.test_data, './weights/%s'%model.config.model_name) labels = [t.root.label for t in model.test_data] test_acc = np.equal(predictions, labels).mean() print('Test acc: {}'.format(test_acc)) if __name__ == "__main__": test_RNN()
<?php /** <API key> */ require_once 'Zend/Dojo/Form/Element/Dijit.php'; class <API key> extends <API key> { /** * @var string View helper */ public $helper = 'Editor'; /** * Add a single event to connect to the editing area * * @param string $event * @return <API key> */ public function addCaptureEvent($event) { $event = (string) $event; $captureEvents = $this->getCaptureEvents(); if (in_array($event, $captureEvents)) { return $this; } $captureEvents[] = (string) $event; $this->setDijitParam('captureEvents', $captureEvents); return $this; } /** * Add multiple capture events * * @param array $events * @return <API key> */ public function addCaptureEvents(array $events) { foreach ($events as $event) { $this->addCaptureEvent($event); } return $this; } /** * Overwrite many capture events at once * * @param array $events * @return <API key> */ public function setCaptureEvents(array $events) { $this->clearCaptureEvents(); $this->addCaptureEvents($events); return $this; } /** * Get all capture events * * @return array */ public function getCaptureEvents() { if (!$this->hasDijitParam('captureEvents')) { return array(); } return $this->getDijitParam('captureEvents'); } /** * Is a given capture event registered? * * @param string $event * @return bool */ public function hasCaptureEvent($event) { $captureEvents = $this->getCaptureEvents(); return in_array((string) $event, $captureEvents); } /** * Remove a given capture event * * @param string $event * @return <API key> */ public function removeCaptureEvent($event) { $event = (string) $event; $captureEvents = $this->getCaptureEvents(); if (false === ($index = array_search($event, $captureEvents))) { return $this; } unset($captureEvents[$index]); $this->setDijitParam('captureEvents', $captureEvents); return $this; } /** * Clear all capture events * * @return <API key> */ public function clearCaptureEvents() { return $this->removeDijitParam('captureEvents'); } /** * Add a single event to the dijit * * @param string $event * @return <API key> */ public function addEvent($event) { $event = (string) $event; $events = $this->getEvents(); if (in_array($event, $events)) { return $this; } $events[] = (string) $event; $this->setDijitParam('events', $events); return $this; } /** * Add multiple events * * @param array $events * @return <API key> */ public function addEvents(array $events) { foreach ($events as $event) { $this->addEvent($event); } return $this; } /** * Overwrite many events at once * * @param array $events * @return <API key> */ public function setEvents(array $events) { $this->clearEvents(); $this->addEvents($events); return $this; } /** * Get all events * * @return array */ public function getEvents() { if (!$this->hasDijitParam('events')) { return array(); } return $this->getDijitParam('events'); } /** * Is a given event registered? * * @param string $event * @return bool */ public function hasEvent($event) { $events = $this->getEvents(); return in_array((string) $event, $events); } /** * Remove a given event * * @param string $event * @return <API key> */ public function removeEvent($event) { $events = $this->getEvents(); if (false === ($index = array_search($event, $events))) { return $this; } unset($events[$index]); $this->setDijitParam('events', $events); return $this; } /** * Clear all events * * @return <API key> */ public function clearEvents() { return $this->removeDijitParam('events'); } /** * Add a single editor plugin * * @param string $plugin * @return <API key> */ public function addPlugin($plugin) { $plugin = (string) $plugin; $plugins = $this->getPlugins(); if (in_array($plugin, $plugins) && $plugin !== '|') { return $this; } $plugins[] = (string) $plugin; $this->setDijitParam('plugins', $plugins); return $this; } /** * Add multiple plugins * * @param array $plugins * @return <API key> */ public function addPlugins(array $plugins) { foreach ($plugins as $plugin) { $this->addPlugin($plugin); } return $this; } /** * Overwrite many plugins at once * * @param array $plugins * @return <API key> */ public function setPlugins(array $plugins) { $this->clearPlugins(); $this->addPlugins($plugins); return $this; } /** * Get all plugins * * @return array */ public function getPlugins() { if (!$this->hasDijitParam('plugins')) { return array(); } return $this->getDijitParam('plugins'); } /** * Is a given plugin registered? * * @param string $plugin * @return bool */ public function hasPlugin($plugin) { $plugins = $this->getPlugins(); return in_array((string) $plugin, $plugins); } /** * Remove a given plugin * * @param string $plugin * @return <API key> */ public function removePlugin($plugin) { $plugins = $this->getPlugins(); if (false === ($index = array_search($plugin, $plugins))) { return $this; } unset($plugins[$index]); $this->setDijitParam('plugins', $plugins); return $this; } /** * Clear all plugins * * @return <API key> */ public function clearPlugins() { return $this->removeDijitParam('plugins'); } /** * Set edit action interval * * @param int $interval * @return <API key> */ public function <API key>($interval) { return $this->setDijitParam('editActionInterval', (int) $interval); } /** * Get edit action interval; defaults to 3 * * @return int */ public function <API key>() { if (!$this->hasDijitParam('editActionInterval')) { $this-><API key>(3); } return $this->getDijitParam('editActionInterval'); } /** * Set focus on load flag * * @param bool $flag * @return <API key> */ public function setFocusOnLoad($flag) { return $this->setDijitParam('focusOnLoad', (bool) $flag); } /** * Retrieve focus on load flag * * @return bool */ public function getFocusOnLoad() { if (!$this->hasDijitParam('focusOnLoad')) { return false; } return $this->getDijitParam('focusOnLoad'); } /** * Set editor height * * @param string|int $height * @return <API key> */ public function setHeight($height) { if (!preg_match('/^\d+(em|px|%)?$/i', $height)) { require_once 'Zend/Form/Element/Exception.php'; throw new <API key>('Invalid height provided; must be integer or CSS measurement'); } if (!preg_match('/(em|px|%)$/', $height)) { $height .= 'px'; } return $this->setDijitParam('height', $height); } /** * Retrieve height * * @return string */ public function getHeight() { if (!$this->hasDijitParam('height')) { return '300px'; } return $this->getDijitParam('height'); } /** * Set whether or not to inherit parent's width * * @param bool $flag * @return <API key> */ public function setInheritWidth($flag) { return $this->setDijitParam('inheritWidth', (bool) $flag); } /** * Whether or not to inherit the parent's width * * @return bool */ public function getInheritWidth() { if (!$this->hasDijitParam('inheritWidth')) { return false; } return $this->getDijitParam('inheritWidth'); } /** * Set minimum height of editor * * @param string|int $minHeight * @return <API key> */ public function setMinHeight($minHeight) { if (!preg_match('/^\d+(em)?$/i', $minHeight)) { require_once 'Zend/Form/Element/Exception.php'; throw new <API key>('Invalid minHeight provided; must be integer or CSS measurement'); } if ('em' != substr($minHeight, -2)) { $minHeight .= 'em'; } return $this->setDijitParam('minHeight', $minHeight); } /** * Get minimum height of editor * * @return string */ public function getMinHeight() { if (!$this->hasDijitParam('minHeight')) { return '1em'; } return $this->getDijitParam('minHeight'); } /** * Add a custom stylesheet * * @param string $styleSheet * @return <API key> */ public function addStyleSheet($styleSheet) { $stylesheets = $this->getStyleSheets(); if (strstr($stylesheets, ';')) { $stylesheets = explode(';', $stylesheets); } elseif (!empty($stylesheets)) { $stylesheets = (array) $stylesheets; } else { $stylesheets = array(); } if (!in_array($styleSheet, $stylesheets)) { $stylesheets[] = (string) $styleSheet; } return $this->setDijitParam('styleSheets', implode(';', $stylesheets)); } /** * Add multiple custom stylesheets * * @param array $styleSheets * @return <API key> */ public function addStyleSheets(array $styleSheets) { foreach ($styleSheets as $styleSheet) { $this->addStyleSheet($styleSheet); } return $this; } /** * Overwrite all stylesheets * * @param array $styleSheets * @return <API key> */ public function setStyleSheets(array $styleSheets) { $this->clearStyleSheets(); return $this->addStyleSheets($styleSheets); } /** * Get all stylesheets * * @return string */ public function getStyleSheets() { if (!$this->hasDijitParam('styleSheets')) { return ''; } return $this->getDijitParam('styleSheets'); } /** * Is a given stylesheet registered? * * @param string $styleSheet * @return bool */ public function hasStyleSheet($styleSheet) { $styleSheets = $this->getStyleSheets(); $styleSheets = explode(';', $styleSheets); return in_array($styleSheet, $styleSheets); } /** * Remove a single stylesheet * * @param string $styleSheet * @return <API key> */ public function removeStyleSheet($styleSheet) { $styleSheets = $this->getStyleSheets(); $styleSheets = explode(';', $styleSheets); if (false !== ($index = array_search($styleSheet, $styleSheets))) { unset($styleSheets[$index]); $this->setDijitParam('styleSheets', implode(';', $styleSheets)); } return $this; } /** * Clear all stylesheets * * @return <API key> */ public function clearStyleSheets() { if ($this->hasDijitParam('styleSheets')) { $this->removeDijitParam('styleSheets'); } return $this; } /** * Set update interval * * @param int $interval * @return <API key> */ public function setUpdateInterval($interval) { return $this->setDijitParam('updateInterval', (int) $interval); } /** * Get update interval * * @return int */ public function getUpdateInterval() { if (!$this->hasDijitParam('updateInterval')) { return 200; } return $this->getDijitParam('updateInterval'); } }
package io.myweb.camera; import android.app.Activity; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.TextureView; import android.view.View; import android.view.Window; import com.android.grafika.AspectFrameLayout; import com.android.grafika.CameraUtils; import java.io.IOException; import io.myweb.LocalService; public class <API key> extends Activity implements LocalService.ConnectionListener<Streaming> { private static final String LOG_TAG = <API key>.class.getName(); private Camera mCamera; private TextureView mTextureView; private int mCameraPreviewWidth; private int <API key>; private volatile boolean portraitMode = false; private LocalService.Connection<Streaming> streamingConnection; private SurfaceTexture mSurfaceTexture; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); <API key>(Window.FEATURE_NO_TITLE); setContentView(R.layout.<API key>); mTextureView = (TextureView) findViewById(R.id.textureView); mTextureView.<API key>(<API key>()); mTextureView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); streamingConnection = StreamingService.connection(this).withListener(this); } @Override protected void onDestroy() { super.onDestroy(); streamingConnection.close(); } @Override protected void onResume() { super.onResume(); if(streamingConnection.getService()!=null) { streamingConnection.getService().startStreaming(mCamera); } } @Override protected void onPause() { super.onPause(); if(streamingConnection.getService()!=null) { streamingConnection.getService().stopStreaming(); } } private TextureView.<API key> <API key>() { return new TextureView.<API key>() { @Override public void <API key>(SurfaceTexture surfaceTexture, int width, int height) { portraitMode = (width < height); <API key>(surfaceTexture, 640, 480); } @Override public void <API key>(SurfaceTexture surfaceTexture, int width, int height) { } @Override public boolean <API key>(SurfaceTexture surfaceTexture) { return <API key>(surfaceTexture); } @Override public void <API key>(SurfaceTexture surfaceTexture) { } }; }; private void <API key>(SurfaceTexture surface, int width, int height) { mSurfaceTexture = surface; openCamera(width, height); // Set the preview aspect ratio. AspectFrameLayout layout = (AspectFrameLayout) findViewById(R.id.cameraPreview_afl); layout.setAspectRatio((double) mCameraPreviewWidth / <API key>); try { mCamera.setPreviewTexture(surface); mCamera.startPreview(); } catch (IOException ex) { Log.e(LOG_TAG, ex.getMessage(), ex); } new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { streamingConnection.getService().startStreaming(mCamera); } }); } private boolean <API key>(SurfaceTexture surface) { mSurfaceTexture = null; releaseCamera(); return true; } /** * This is basicly copied as-is from grafika example * * Opens a camera, and attempts to establish preview mode at the specified width and height. * <p> * Sets mCameraPreviewWidth and <API key> to the actual width/height of the preview. */ private void openCamera(int desiredWidth, int desiredHeight) { if (mCamera != null) { throw new RuntimeException("Camera already initialized"); } Camera.CameraInfo info = new Camera.CameraInfo(); // Try to find a front-facing camera (e.g. for videoconferencing). int numCameras = Camera.getNumberOfCameras(); for (int i = 0; i < numCameras; i++) { Camera.getCameraInfo(i, info); if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { mCamera = Camera.open(i); if(portraitMode) mCamera.<API key>(90); break; } } if (mCamera == null) { Log.d(LOG_TAG, "No front-facing camera found; opening default"); mCamera = Camera.open(); // opens first back-facing camera } if (mCamera == null) { throw new RuntimeException("Unable to open camera"); } Camera.Parameters parms = mCamera.getParameters(); CameraUtils.choosePreviewSize(parms, desiredWidth, desiredHeight); // Give the camera a hint that we're recording video. This can have a big // impact on frame rate. parms.setRecordingHint(true); // leave the frame rate set to default mCamera.setParameters(parms); int[] fpsRange = new int[2]; Camera.Size mCameraPreviewSize = parms.getPreviewSize(); parms.getPreviewFpsRange(fpsRange); String previewFacts = mCameraPreviewSize.width + "x" + mCameraPreviewSize.height; if (fpsRange[0] == fpsRange[1]) { previewFacts += " @" + (fpsRange[0] / 1000.0) + "fps"; } else { previewFacts += " @[" + (fpsRange[0] / 1000.0) + " - " + (fpsRange[1] / 1000.0) + "] fps"; } Log.d(LOG_TAG, previewFacts); // TextView text = (TextView) findViewById(R.id.cameraParams_text); // text.setText(previewFacts); if(portraitMode) { mCameraPreviewWidth = mCameraPreviewSize.height; <API key> = mCameraPreviewSize.width; } else { mCameraPreviewWidth = mCameraPreviewSize.width; <API key> = mCameraPreviewSize.height; } Log.d(LOG_TAG, "openCamera -- done"); } /** * Stops camera preview, and releases the camera to the system. */ private void releaseCamera() { if (mCamera != null) { mCamera.stopPreview(); mCamera.release(); mCamera = null; Log.d(LOG_TAG, "releaseCamera -- done"); } } @Override public void onServiceConnected(Streaming service) { Log.d(LOG_TAG, "Streaming service connected"); } @Override public void <API key>(Streaming service) { Log.d(LOG_TAG, "Streaming service disconnected"); } }
cddd = cqrs+es for c++14
lychee.define('app.net.server.REQUEST').tags({ platform: 'node' }).requires([ 'app.data.Config', 'app.data.Filter', 'app.data.Filesystem', 'app.net.server.PUBLIC' ]).supports(function(lychee, global) { try { require('http'); require('https'); require('url'); return true; } catch (err) { } return false; }).exports(function(lychee, global, attachments) { const _Config = lychee.import('app.data.Config'); const _Filesystem = lychee.import('app.data.Filesystem'); const _Filter = lychee.import('app.data.Filter'); const _http = require('http'); const _https = require('https'); const _url = require('url'); const _CACHE = new _Filesystem({ root: '/cache' }); const _CONFIG = new _Config({ root: '/config.d' }); const _FILTER = new _Filter({ root: '/settings' }); const _PUBLIC = lychee.import('app.net.server.PUBLIC'); const _MIME = { 'default': { binary: true, type: 'application/octet-stream' }, 'appcache': { binary: false, type: 'text/cache-manifest' }, 'css': { binary: false, type: 'text/css' }, 'env': { binary: false, type: 'application/json' }, 'eot': { binary: false, type: 'application/vnd.ms-fontobject' }, 'gz': { binary: true, type: 'application/x-gzip' }, 'fnt': { binary: false, type: 'application/json' }, 'html': { binary: false, type: 'text/html' }, 'ico': { binary: true, type: 'image/x-icon' }, 'jpg': { binary: true, type: 'image/jpeg' }, 'js': { binary: false, type: 'application/javascript' }, 'json': { binary: false, type: 'application/json' }, 'md': { binary: false, type: 'text/x-markdown' }, 'mf': { binary: false, type: 'text/cache-manifest' }, 'mp3': { binary: true, type: 'audio/mp3' }, 'ogg': { binary: true, type: 'application/ogg' }, 'pkg': { binary: false, type: 'application/json' }, 'store': { binary: false, type: 'application/json' }, 'tar': { binary: true, type: 'application/x-tar' }, 'ttf': { binary: false, type: 'application/x-font-truetype' }, 'txt': { binary: false, type: 'text/plain' }, 'png': { binary: true, type: 'image/png' }, 'svg': { binary: true, type: 'image/svg+xml' }, 'woff': { binary: true, type: 'application/font-woff' }, 'woff2': { binary: true, type: 'application/font-woff' }, 'xml': { binary: false, type: 'text/xml' }, 'zip': { binary: true, type: 'application/zip' } }; /* * HELPERS */ const _filter_payload = function(host, payload) { return _FILTER.process(host, _PUBLIC.get('/index.html'), payload); }; const _request_https = function() { }; const _request_http = function(url, callback) { let filtered = false; let options = _url.parse(url); if (_CONFIG.isBlockedHost(options.host)) { filtered = true; } else if (_CONFIG.isBlockedLink(options.href)) { filtered = true; } if (filtered === false) { let request = _http.request(options, function(response) { let chunks = []; response.on('data', function(chunk) { chunks.push(chunk); }); response.on('end', function() { callback(Buffer.concat(chunks)); }); }); request.write('\n'); request.end(); } else { callback(null); } }; const _get_headers = function(info, mime) { let headers = { 'status': '200 OK', 'e-tag': '"' + info.length + '-' + Date.parse(info.mtime) + '"', 'last-modified': new Date(info.mtime).toUTCString(), 'content-control': 'no-transform', 'content-type': mime.type, 'expires': new Date(Date.now() + 1000 * 60 * 60 * 24 * 7).toUTCString(), 'vary': 'Accept-Encoding', '@binary': mime.binary }; if (mime.type.substr(0, 4) === 'text') { headers['content-type'] = mime.type + '; charset=utf-8'; } return headers; }; /* * IMPLEMENTATION */ const Module = { /* * MODULE API */ // deserialize: function(blob) {}, serialize: function() { return { 'reference': 'app.net.server.REQUEST', 'arguments': [] }; }, /* * CUSTOM API */ receive: function(payload, headers) { let info = null; let path = null; let tunnel = this.tunnel; let url = headers['url']; let proto = null; if (url.substr(0, 8) === 'https: proto = 'https'; url = url.substr(8); } else if (url.substr(0, 7) === 'http: proto = 'http'; url = url.substr(7); } let i1 = url.indexOf('?'); if (i1 !== -1) { url = url.substr(0, i1); } if (url.substr(-1) === '/') { path = '/' + url + 'index.html'; } else { let tmp = url.split('.').pop(); if (tmp.length > 4) { path = '/' + url + '/index.html'; } else { path = '/' + url; } } info = _CACHE.info(path); if (proto === 'http') { _request_http('http://' + url, function(payload) { let mime = _MIME[url.split('.').pop()] || null; if (mime === null) { mime = _MIME['html']; } let headers = null; if (payload !== null) { _CACHE.write(path, payload); if (mime === _MIME['html']) { payload = _filter_payload(path.split('/')[1], payload); } info = _CACHE.info(path); headers = _get_headers(info, mime); } else { headers = { 'status': '404 Not Found', 'content-type': 'text/plain; charset=utf-8' }; payload = 'Request blocked by AdBlock Proxy.'; } tunnel.send(payload, headers); }); return true; } else if (proto === 'https') { // TODO: Request HTTPS } return false; } }; return Module; });
define(['backbone', '../views/provinceView' ], function(Backbone, ProvinceView) { provinceModel = Backbone.Model.extend({ initialize: function() { this.view = new ProvinceView({ model: this, gameModel: this.gameModel }); this.set('influence', Math.random()); this.establishArmy(); }, establishArmy: function() { this.set('communist_army_size', _.random(10000, 50000)) this.set('<API key>', _.random(2, 4)) this.set('rebel_army_size', _.random(5000, 20000)) this.set('rebel_arms_level', _.random(1, 3)) }, gameLoop: function() { var comm_army = this.get('communist_army_size'); var rebel_army = this.get('rebel_army_size'); var comm_deaths = _.random(1, 500) * (comm_army / rebel_army); this.set('communist_army_size', Math.round(comm_army - comm_deaths)); } }); return provinceModel; })
from rest_framework.permissions import BasePermission, SAFE_METHODS class IsOwnerOrReadOnly(BasePermission): message = 'You must be the owner of this object.' # my_safe_method = ['GET', 'PUT'] # if request.method in self.my_safe_method: # return True # return False def <API key>(self, request, view, obj): # member = Membership.objects.get(user=request.user) # member.is_active if request.method in SAFE_METHODS: return True return obj.user == request.user
module Monita class <API key> < ActionController::Base end end
// tslint:disable:max-line-length import { Navigatable, Codes } from "./tabIndex" import { expect } from "chai" import { suite, test } from "mocha-typescript" /** * 0 1||1 2| 4| 0 1 2 |4 |2 * 0 1||1 2| 5| 1 2 3 |5 |2 * 0 1||1 2| 6| 2 |6 |2 */ let navA = () => new Navigatable("column", 0, [new Navigatable("column", 1), new Navigatable("column", 2, [ new Navigatable("row", 4, [new Navigatable("column", 0), new Navigatable("column", 1), new Navigatable("column", 2)]), new Navigatable("row", 5, [new Navigatable("column", 1), new Navigatable("column", 2).isActive(), new Navigatable("column", 3)]), new Navigatable("row", 6, [new Navigatable("column", 2)]), ])]) @suite export default class TabIndexSpec { @test public "find active"() { expect(navA().getActive().index).to.eq(2) } @test public "find next active in same row"() { expect(navA().getActive().next(Codes.LEFT, true).index).to.eq(1) expect(navA().getActive().next(Codes.RIGHT, true).index).to.eq(3) } @test public "find next active in above/below row"() { expect(navA().getActive().next(Codes.UP, true).index).to.eq(4) expect(navA().getActive().next(Codes.DOWN, true).index).to.eq(6) } @test public "parent indexOf"() { let inner = new Navigatable("row", 6) let cs = [new Navigatable("column", 1), new Navigatable("column", 2, [inner]).isActive(), new Navigatable("column", 3)] let nav = new Navigatable("row", 5, cs) expect(nav.indexOf(cs[0])).to.eq(0) expect(nav.indexOf(cs[1])).to.eq(1) expect(nav.indexOf(cs[2])).to.eq(2) expect(nav.indexOf(inner)).to.eq(1) } @test public "switch to other index if above/below contain different indices"() { let nav = navA() expect(nav.getActive().next(Codes.RIGHT).index).to.eq(3) nav.getActive().isActive(false).next(Codes.RIGHT).isActive() let active = nav.getActive() expect(active.index).to.eq(3) expect(active.parent.index).to.eq(5) expect(active.getParent(Codes.UP).index).to.eq(2) expect(active.next(Codes.UP, true).index).to.eq(4) nav = navA() nav.getActive().isActive(false).next(Codes.RIGHT).isActive() active = nav.getActive() expect(active.index).to.eq(3) expect(active.next(Codes.DOWN, true).index).to.eq(6) } }
using Xamarin.Forms; namespace VideoPlayerSample.Controls { public class <API key> : Grid { #region Private fields and properties private <API key> <API key>; private VideoPlayer _videoPlayer; private Image _overlayImage; #endregion #region Constructors public <API key>() { readdVideoPlayer(); _videoPlayer.<API key> += <API key>; } #endregion #region Public API public VideoPlayer Player => _videoPlayer; public static BindableProperty VideoPathProperty = BindableProperty.Create<<API key>, string>(o => o.VideoPath, null, propertyChanged: OnVideoPathChanged); public string VideoPath { get { return (string) GetValue(VideoPathProperty); } set { SetValue(VideoPathProperty, value); } } public void ToggleFullscreen() { //If the <API key> is not null, it means it's already displayed if (<API key> == null) { if (!string.IsNullOrWhiteSpace(VideoPath)) { <API key> = new <API key>(VideoPath); <API key>.Disappearing += (sender, args) => { //Destroy the full screen video player reference <API key> = null; /WE need to re-add the video player, because if we don't the video will not load //readdVideoPlayer (); }; Navigation.PushModalAsync(<API key>, false); } } } #endregion #region Utility methods private static void OnVideoPathChanged(BindableObject bindable, string oldvalue, string newvalue) { var player = bindable as <API key>; player.Player.VideoPath = newvalue; } private void readdVideoPlayer() { _videoPlayer = new VideoPlayer(); Children.Add(_videoPlayer); _overlayImage = new Image() { Source = "icon_play_overlay.png", HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center }; Children.Add(_overlayImage); } private void <API key>(object sender, bool isPlaying) { _overlayImage.IsVisible = !isPlaying; } #endregion } }
const AppDispatcher = require('../dispatcher/AppDispatcher'); const Constants = require('../constants/Constants'); const ArticleApi = require('../api/ArticlesApi'); const Actions = { /** * @param {number} start * @param {number} skip */ getList: function(start, skip, clearStore) { ArticleApi.getEntityListData(start, skip); if (clearStore){ AppDispatcher.dispatch({actionType: Constants.<API key>}) } }, /** * @param {number} start * @param {number} skip */ getListByTag: function(tag, start, skip, clearStore) { ArticleApi.getEntityListData(start, skip, tag); if (clearStore){ AppDispatcher.dispatch({actionType: Constants.<API key>}) } }, /** * @param {string} id */ getById: function(id) { ArticleApi.getEntityDataById(id); }, /** * @param {obj} article data */ create: function(obj) { ArticleApi.postEntityData(obj); }, /** * @param {string} id * @param {obj} article data */ update: function(id, obj) { ArticleApi.putEntityData(id, obj); }, /** * @param {object} update */ destroy: function(id) { ArticleApi.deleteEntityData(id); }, /** * @param {string} articleId * @param {obj} comment data */ createComment: function(articleId, obj) { ArticleApi.<API key>(articleId, obj); }, /** * @param {string} articleId * @param {obj} commentId */ destroyComment: function(articleId, commentId) { ArticleApi.<API key>(articleId, commentId); } }; module.exports = Actions;
var $M = require("@effectful/debugger"), $x = $M.context, $ret = $M.ret, $unhandled = $M.unhandled, $brk = $M.brk, $m = $M.module("file.js", null, typeof module === "undefined" ? null : module, null, "$", { __webpack_require__: typeof __webpack_require__ !== "undefined" && __webpack_require__ }, null), $s$1 = [{ a: [1, "1:9-1:10"] }, null, 0], $s$2 = [{}, $s$1, 1], $s$3 = [{ i: [1, "2:11-2:12"] }, $s$2, 1], $m$0 = $M.fun("m$0", "file.js", null, null, [], 0, 2, "1:0-6:0", 32, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $l[1] = $m$1($); $.goto = 2; continue; case 1: $.goto = 2; return $unhandled($.error); case 2: return $ret($.result); default: throw new Error("Invalid state"); } }, null, null, 0, [[0, "1:0-5:1", $s$1], [16, "6:0-6:0", $s$1], [16, "6:0-6:0", $s$1]]), $m$1 = $M.fun("m$1", "a", null, $m$0, [], 0, 2, "1:0-5:1", 0, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 2; $p = ($x.call = init)(); $.state = 2; case 2: $l[1] = $p; $.state = 3; case 3: $.goto = 4; $brk(); $.state = 4; case 4: $.goto = 5; $p = ($x.call = check)(); $.state = 5; case 5: if ($p === true) { $.state = 6; } else { $.goto = 14; continue; } case 6: $.goto = 7; $brk(); $.state = 7; case 7: if ($l[0][1]) { $.state = 8; } else { $.goto = 13; continue; } case 8: $.goto = 9; $brk(); $.state = 9; case 9: $.goto = 10; ($x.call = eff)(1); $.state = 10; case 10: $.state = 11; case 11: $.goto = 12; $brk(); $.state = 12; case 12: $.goto = 3; ($x.call = upd)(); continue; case 13: $.goto = 11; $brk(); continue; case 14: $.goto = 16; $brk(); continue; case 15: $.goto = 16; return $unhandled($.error); case 16: return $ret($.result); default: throw new Error("Invalid state"); } }, null, null, 1, [[4, "2:2-4:18", $s$2], [2, "2:15-2:21", $s$3], [0, "2:11-2:21", $s$3], [4, "2:23-2:39", $s$3], [2, "2:23-2:30", $s$3], [0, null, $s$2], [4, "3:4-4:18", $s$3], [0, null, $s$2], [4, "3:11-3:18", $s$3], [2, "3:11-3:17", $s$3], [0, null, $s$2], [4, "2:41-2:46", $s$3], [2, "2:41-2:46", $s$3], [4, "4:9-4:18", $s$3], [36, "5:1-5:1", $s$2], [16, "5:1-5:1", $s$2], [16, "5:1-5:1", $s$2]]); $M.moduleExports();
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; <summary> A spread of text to display to the player for a given ammount of time Used in Toast script </summary> public struct Spread{ Text to display public string text { get; set; } Ammount of time in seconds for the text to display public float seconds {get; set;} } <summary> Displays popup text on the screen for player information for a length of specified time. </summary> <remarks> By Alexander Tilley (Last edit 13/10/2017) Modified by INSERTNAME HERE for ???? </remarks> public class Toast : MonoBehaviour { static Toast toast; The Maximum number of lines of text at one time. private const int queueLength = 3; GameObject that displays the text. public GameObject textobj; A queue of text to display in order of expirery. private Spread[] toaster = new Spread[queueLength]; //Queue in order of expirey <summary> Initialises Toast by setting up Spread[] to be empty. </summary> void Start () { //textobj.SetActive (false); //textobj = gameObject; //Get Object its attached to if (textobj == null) { Debug.Log("textobj not assigned assigning gameobject attached too"); textobj = gameObject; //Get Object its attached to } for (int i = 0; i < queueLength; i++) { //Intitalise spots to empty toaster[i].text = ""; toaster [i].seconds = -1.0f; } } <summary> </summary> void Awake() { if (toast == null) { toast = this; } else { Destroy(gameObject); } } <summary> </summary> <returns><c>true</c>, if toast was added, <c>false</c> otherwise.</returns> <param name="text">Text.</param> <param name="seconds">Seconds.</param> public static bool addToast(string text, float seconds) { return Toast.toast.addText(text, seconds); } <summary> Update is called once per frame to reduce each Spread time and remove expired spreads. </summary> void Update () { for (int i = 0; i < queueLength; i++) { //Remove time if (toaster[i].text != null && toaster [i].seconds <= 0.0f) { //If Item needs to be cleared for (int n = 0; (n + 1) < queueLength; n++) { //shift queue toaster [n] = toaster [n + 1]; } toaster [queueLength - 1].seconds = -1.0f; toaster [queueLength - 1].text = null; textobj.GetComponent<Text> ().text = ""; updateText (); } toaster [i].seconds = toaster [i].seconds - Time.deltaTime; //reduce time } } <summary> Adds Text to display for an ammount of time and displays in order of how quickly it should be removed. </summary> <returns><c>true</c>, if text was added, <c>false</c> otherwise.</returns> <param name="text">Text to display.</param> <param name="seconds">Seconds to display for.</param> public bool addText(string text, float seconds){ Spread jam; jam.text = text; jam.seconds = seconds; for (int i = 0; i < queueLength; i++) { //Debug.Log ("" + toaster [i].seconds); if (toaster[i].seconds <= jam.seconds || toaster[i].seconds <= 0.0f) { //If Correct Spot Insert or Empty Slot Insert if (toaster [i].seconds <= 0.0f) { //IF Empty Slot Insert toaster [i] = jam; updateText (); //Debug.Log("Toaster: "+text+" for "+seconds+" Seconds"); return true; } else if((i+1)<queueLength) { //IF toaster isnt full if(toaster[i+1].seconds <= 0.0f){ //If next spot is free. //Debug.Log("Toaster reordering"); toaster[i+1] = toaster[i]; //Reorder Toast toaster [i] = jam; updateText (); return true; } }else{ //Debug.Log("Slot FULL"); //Toaster is full. //return false; } } //Debug.Log("Slot Full2"); //return false; } Debug.Log("Toaster IS FULL"); return false; } <summary> Updates the text to display on the HUD </summary> void updateText(){ textobj.GetComponent<Text> ().text = ""; for (int i = 0; i < queueLength; i++) { //Update Text textobj.GetComponent<Text> ().text += toaster[i].text+"\n"; } } }
<?php /** * Zookeeper class. */ class Zookeeper { /* class constants */ const PERM_READ = 1; const PERM_WRITE = 2; const PERM_CREATE = 4; const PERM_DELETE = 8; const PERM_ADMIN = 16; const PERM_ALL = 31; const EPHEMERAL = 1; const SEQUENCE = 2; const <API key> = -112; const AUTH_FAILED_STATE = -113; const CONNECTING_STATE = 1; const ASSOCIATING_STATE = 2; const CONNECTED_STATE = 3; const NOTCONNECTED_STATE = 999; const CREATED_EVENT = 1; const DELETED_EVENT = 2; const CHANGED_EVENT = 3; const CHILD_EVENT = 4; const SESSION_EVENT = -1; const NOTWATCHING_EVENT = -2; const LOG_LEVEL_ERROR = 1; const LOG_LEVEL_WARN = 2; const LOG_LEVEL_INFO = 3; const LOG_LEVEL_DEBUG = 4; const SYSTEMERROR = -1; const <API key> = -2; const DATAINCONSISTENCY = -3; const CONNECTIONLOSS = -4; const MARSHALLINGERROR = -5; const UNIMPLEMENTED = -6; const OPERATIONTIMEOUT = -7; const BADARGUMENTS = -8; const INVALIDSTATE = -9; const OK = 0; const APIERROR = -100; const NONODE = -101; const NOAUTH = -102; const BADVERSION = -103; const <API key> = -108; const NODEEXISTS = -110; const NOTEMPTY = -111; const SESSIONEXPIRED = -112; const INVALIDCALLBACK = -113; const INVALIDACL = -114; const AUTHFAILED = -115; const CLOSING = -116; const NOTHING = -117; const SESSIONMOVED = -118; /** * Create a handle to used communicate with zookeeper. * if the host is provided, attempt to connect. * * @param string $host * @param callable $watcher_cb * @param int $recv_timeout * * @throws <API key> when host is provided and when failed to connect to the host. */ public function __construct($host = '', $watcher_cb = null, $recv_timeout = 10000) { } /** * Create a handle to used communicate with zookeeper. * * @param string $host * @param callable $watcher_cb * @param int $recv_timeout * * @throws <API key> when failed to connect to Zookeeper */ public function connect($host, $watcher_cb = null, $recv_timeout = 10000) { } /** * Create a node synchronously. * * @param string $path * @param string $value * @param array $acl * @param int $flags * * @return string * @throws ZookeeperException */ public function create($path, $value, $acl, $flags = null) { } /** * Delete a node in zookeeper synchronously. * * @param string $path * @param int $version * * @return bool * @throws ZookeeperException */ public function delete($path, $version = -1) { } /** * Sets the data associated with a node. * * @param string $path * @param string $data * @param int $version * @param array $stat * * @return bool * @throws ZookeeperException */ public function set($path, $data, $version = -1, &$stat = null) { } /** * Gets the data associated with a node synchronously. * * @param string $path * @param callable $watcher_cb * @param array $stat * @param int $max_size * * @return string * @throws ZookeeperException */ public function get($path, $watcher_cb = null, &$stat = null, $max_size = 0) { } /** * Get children data of a path. * * @param string $path * @param callable $watcher_cb * * @return array * @throws ZookeeperException when connection not in connected status */ public function getChildren($path, $watcher_cb = null) { } /** * Checks the existence of a node in zookeeper synchronously. * * @param string $path * @param callable $watcher_cb * * @return bool * @throws ZookeeperException */ public function exists($path, $watcher_cb = null) { } /** * Gets the acl associated with a node synchronously. * * @param string $path * * @return array * @throws ZookeeperException when connection not in connected status */ public function getAcl($path) { } /** * Sets the acl associated with a node synchronously. * * @param string $path * @param int $version * @param array $acls * * @return bool * @throws ZookeeperException when connection not in connected status */ public function setAcl($path, $version, $acls) { } /** * return the client session id, only valid if the connections is currently connected * (ie. last watcher state is ZOO_CONNECTED_STATE) * * @return int * @throws <API key> when connection not in connected status */ public function getClientId() { } /** * Set a watcher function. * * @param callable $watcher_cb * * @return bool * @throws <API key> when connection not in connected status */ public function setWatcher($watcher_cb) { } /** * Get the state of the zookeeper connection. * * @return int * @throws <API key> when connection not in connected status */ public function getState() { } /** * Return the timeout for this session, only valid if the connections is currently connected * (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server reconnect. * * @return int * @throws <API key> when connection not in connected status */ public function getRecvTimeout() { } /** * Specify application credentials. * * @param string $scheme * @param string $cert * @param callable $completion_cb * * @return bool */ public function addAuth($scheme, $cert, $completion_cb = null) { } /** * Checks if the current zookeeper connection state can be recovered. * * @return bool * @throws <API key> when connection not in connected status */ public function isRecoverable() { } /** * Sets the stream to be used by the library for logging. * * TODO: might be able to set a stream like php://stderr or something * * @param resource $file * * @return bool */ public function setLogStream($file) { } /** * Sets the debugging level for the library. * * @param int $level * * @return bool */ public static function setDebugLevel($level) { } /** * Enable/disable quorum endpoint order randomization. * * @param bool $trueOrFalse * * @return bool */ public static function <API key>($trueOrFalse) { } } class ZookeeperException extends Exception { } class <API key> extends ZookeeperException { } class <API key> extends ZookeeperException { } class <API key> extends ZookeeperException { } class Zookeeper<API key> extends ZookeeperException { } class <API key> extends ZookeeperException { } class <API key> extends ZookeeperException { }
# This file is auto-generated by the Perl DateTime Suite time locale # generator (0.04). This code generator comes with the # DateTime::Locale distribution in the tools/ directory, and is called # generate_from_cldr. # This file as generated from the CLDR XML locale data. See the # This file was generated from the source file ss.xml. # The source file version number was 1.17, generated on # 2007/07/14 23:02:17. # Do not edit this file directly. package DateTime::Locale::ss; use strict; BEGIN { if ( $] >= 5.006 ) { require utf8; utf8->import; } } use DateTime::Locale::root; @DateTime::Locale::ss::ISA = qw(DateTime::Locale::root); my @day_names = ( "uMsombuluko", "Lesibili", "Lesitsatfu", "Lesine", "Lesihlanu", "uMgcibelo", "Lisontfo", ); my @day_abbreviations = ( "Mso", "Bil", "Tsa", "Ne", "Hla", "Mgc", "Son", ); my @day_narrows = ( "2", "3", "4", "5", "6", "7", "1", ); my @month_names = ( "Bhimbidvwane", "iNdlovana", "iNdlovu\-lenkhulu", "Mabasa", "iNkhwekhweti", "iNhlaba", "Kholwane", "iNgci", "iNyoni", "iMphala", "Lweti", "iNgongoni", ); my @month_abbreviations = ( "Bhi", "Van", "Vol", "Mab", "Nkh", "Nhl", "Kho", "Ngc", "Nyo", "Mph", "Lwe", "Ngo", ); my @month_narrows = ( "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", ); my @quarter_names = ( "Q1", "Q2", "Q3", "Q4", ); my @<API key> = ( "Q1", "Q2", "Q3", "Q4", ); my @am_pms = ( "AM", "PM", ); my @era_names = ( "BC", "AD", ); my @era_abbreviations = ( "BC", "AD", ); my $date_before_time = "1"; my $date_parts_order = "ymd"; sub day_names { \@day_names } sub day_abbreviations { \@day_abbreviations } sub day_narrows { \@day_narrows } sub month_names { \@month_names } sub month_abbreviations { \@month_abbreviations } sub month_narrows { \@month_narrows } sub quarter_names { \@quarter_names } sub <API key> { \@<API key> } sub am_pms { \@am_pms } sub era_names { \@era_names } sub era_abbreviations { \@era_abbreviations } sub full_date_format { "\%A\,\ \%\{ce_year\}\ \%B\ \%d" } sub long_date_format { "\%\{ce_year\}\ \%B\ \%\{day\}" } sub medium_date_format { "\%\{ce_year\}\ \%b\ \%\{day\}" } sub short_date_format { "\%y\/\%m\/\%d" } sub full_time_format { "\%H\:\%M\:\%S\ v" } sub long_time_format { "\%H\:\%M\:\%S\ \%\{time_zone_long_name\}" } sub medium_time_format { "\%H\:\%M\:\%S" } sub short_time_format { "\%H\:\%M" } sub date_before_time { $date_before_time } sub date_parts_order { $date_parts_order } 1;
import { PropTypes } from 'react'; // For a more detailed list of PropTypes // see http://ricostacruz.com/cheatsheets/react.html#property-validation const propTypes = { allFeatures: PropTypes.arrayOf(PropTypes.object), currentFeature: PropTypes.object, selectFeature: PropTypes.func.isRequired, ignoreFeature: PropTypes.func.isRequired }; export default propTypes;
interface BakedGood { sugar: number; name: string; bake(mins: number): string; icing?: boolean; // optional question mark } const cake: BakedGood = { sugar: 23, name: 'Cherry Cake', bake(min: number) { return 'will be done in ${min}...' } };
// Generated by class-dump 3.5 (64 bit). #import "NSLocale.h" #import "IBBinaryArchiving.h" @class NSString; @interface NSLocale (<API key>) <IBBinaryArchiving> - (void)<API key>:(id)arg1; - (id)<API key>:(id)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.<API key> = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.<API key> = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.<API key> = true config.action_mailer.default_url_options = { host: 'localhost:3000' } # Raises error for missing translations # config.action_view.<API key> = true end
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) require 'rspec' require 'pp' require 'active_support' require 'active_support/core_ext' require "bill_hicks" # support files root = File.expand_path('../..', __FILE__)
package hackerrank; import org.junit.Test; import java.io.FileInputStream; public class CandiesTest { @Test public void test1() throws Exception { System.setIn(new FileInputStream("src/test/resources/candies/test1.txt")); Candies.main(new String[]{}); } @Test public void test2() throws Exception { System.setIn(new FileInputStream("src/test/resources/candies/test2.txt")); Candies.main(new String[]{}); } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>(R) How to scrape highcharts</title> <meta name="description" content="Highcharts are popular Javascript charts that have stock extension. These charts are sort of commercial but easy to use, often used by bitcoin exchanges. The disadvantage is the source of data can be obscured if the data is not supposed to be available."> <meta name="author" content="Trading Fanbois"> <!-- Enable responsive viewport --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Le HTML5 shim, for IE6-8 support of HTML elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif] <!-- Le styles --> <link href="https://cryptotradingtools.com/assets/resources/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cryptotradingtools.com/assets/resources/font-awesome/css/font-awesome.min.css" rel="stylesheet"> <link href="https://cryptotradingtools.com/assets/resources/syntax/syntax.css" rel="stylesheet"> <link href="https://cryptotradingtools.com/assets/css/style.css" rel="stylesheet"> <!-- Le fav and touch icons --> <!-- Update these with your own images <link rel="shortcut icon" href="images/favicon.ico"> <link rel="apple-touch-icon" href="images/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="images/<API key>.png"> <link rel="apple-touch-icon" sizes="114x114" href="images/<API key>.png"> <link rel="alternate" type="application/rss+xml" title="" href="https://cryptotradingtools.com/feed.xml"> </head> <body> <nav class="navbar navbar-default visible-xs" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#<API key>"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a type="button" class="navbar-toggle nav-link" href="http://twitter.com/tradingfanbois"> <i class="fa fa-twitter"></i> </a> <a type="button" class="navbar-toggle nav-link" href="mailto:admin@bestbitcoinexchange.co"> <i class="fa fa-envelope"></i> </a> <a class="navbar-brand" href="https://cryptotradingtools.com/"> <img src="http: Crypto Trading Tools </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="<API key>"> <ul class="nav navbar-nav"> <li class="active"><a href="https://cryptotradingtools.com/">Home</a></li> <li><a href="https://cryptotradingtools.com/categories/">Categories</a></li> <li><a href="https://cryptotradingtools.com/tags/">Tags</a></li> </ul> </div><!-- /.navbar-collapse --> </nav> <!-- nav-menu-dropdown --> <div class="btn-group hidden-xs" id="nav-menu"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bars"></i> </button> <ul class="dropdown-menu" role="menu"> <li><a href="https://cryptotradingtools.com/"><i class="fa fa-home"></i>Home</a></li> <li><a href="https://cryptotradingtools.com/categories/"><i class="fa fa-folder"></i>Categories</a></li> <li><a href="https://cryptotradingtools.com/tags/"><i class="fa fa-tags"></i>Tags</a></li> <li class="divider"></li> <li><a href="#"><i class="fa fa-arrow-up"></i>Top of Page</a></li> </ul> </div> <div class="col-sm-3 sidebar hidden-xs" style=""> <!-- sidebar.html --> <header class="sidebar-header" role="banner"> <a href="https://cryptotradingtools.com/"> <img src="/img/cryptotradingtools.jpeg" class="img-circle" /> </a> <h3 class="title"> <a href="https://cryptotradingtools.com/">Crypto Trading Tools</a> </h3> </header> <div id="bio" class="text-center"> Repo with tools and scripts for bitcoin and altcoin trading. <hr> <p><a href="/trading-stats">Historical Data: Best Days To Trade</a></p> <p><a href="/datasets">Datasets for backtesting and sentiment</a></p> <p><a href="/widgets">Tickers, data for widgets</a></p> <p><a href="/bots">Trading and lending bots</a></p> <hr> <p><a href="/">All Tools</a></p> <p><a target="_blank" href="/submit">Know a repo that isn't here?</a></p> <hr> </div> <div id="contact-list" class="text-center"> <ul class="list-unstyled list-inline"> <li> <a class="btn btn-default btn-sm" href="https://twitter.com/tradingfanbois"> <i class="fa fa-twitter fa-lg"></i> </a> </li> <li> <a class="btn btn-default btn-sm" href="mailto:admin@bestbitcoinexchange.co"> <i class="fa fa-envelope fa-lg"></i> </a> </li> </ul> <ul id="<API key>" class="list-unstyled list-inline"> <li> <a class="btn btn-default btn-sm" href="https://cryptotradingtools.com/feed.xml"> <i class="fa fa-rss fa-lg"></i> </a> </li> </ul> </div> <!-- sidebar.html end --> </div> <div class="col-sm-9 col-sm-offset-3"> <div class="page-header"> <h1>(R) How to scrape highcharts </h1> </div> <article> <iframe data-aa="178999" src="https://ad.a-ads.com/178999?size=728x90" scrolling="no" style="width:728px; height:90px; border:0px; padding:0;overflow:hidden" allowtransparency="true" frameborder="0"></iframe> </article> <article> <div class="col-sm-10"> <span class="post-date"> May 29th, 2016 </span> <div class="article_body"> <p><a target="_blank" href="https://r-forge.r-project.org/R/?group_id=594" class="btn btn-down"><i class="fa fa-github fa-lg"></i> Download sourcecode</a></p> <p><br /></p> <p><img src="https://i.imgur.com/V5L9KNF.png" alt="okcoin top trader sentiment" /></p> <p>Take for instance OkCoin, the Chinese spot and futures exchange. Unlike Bitfinex, they don’t provide API access to their lending data and trader sentiment. The data is still available though, but only for a few hours in form of a chart on their website.</p> <div class="reddit-embed" data-embed-media="www.redditmedia.com" data-embed-parent="false" data-embed-live="false" data-embed-created="2016-05-29T11:04:09.342Z"><a href="https: <script async="" src="https: <p>Bitfinex on the other hand has this data public. You can take a look at them at <a href="http: <p>Nonetheless, Okcoin provides none of such data. Just the chart.</p> <p>Luckily, it is possible to scrape SVG charts - like the one that OKcoin uses. If you are up for the challenge. There is a package for that in R language.</p> <figure class="highlight"><pre><code class="language-html" data-lang="html">digitize : a plot digitizer in R Allows to get the data from a graph by providing calibration points Version: 0.0.1-07 | Last change: 2011-01-21 22:58:28+01 | Rev.: 51 Download: linux(.tar.gz) | windows(.zip) | Build status: Current R install command: install.packages("digitize", repos="http://R-Forge.R-project.org")</code></pre></figure> <p>Alternatively, there are graph reading software packages. You load an image, click somewhere, it reads up the coordinates of where you clicked. It is the easiest way but probably not feasible for continuous data collection. <a href="#<API key>">See here list of available packages</a></p> <h2 id="chart-scraping-in-r">Chart scraping in R</h2> <p>R language has a package called <strong>digitize</strong> that can recognize lines and chart patterns and read the data as coordinated. It was implemented into some graphic software packages (<a href="#<API key>">here</a>) but if you want it modular you will need to use the backage itself and fine tune it.</p> <p>Here is a paper with how-to and use cases: <a href="https: <p>The package used to be available from the <a href="https://cran.r-project.org/">archive network</a>, but it has been a long time since the last update. At some point it was abandoned and archived.</p> <p>Now you can get the package <a href="https: <p>There are few problems:</p> <blockquote> <p>Digitize depends on another archived package ReadImages which cannot be loaded in R 3.0.2 , because (I suspect) it doesn’t have a NAMESPACE. Likewise digitize fails to load under R 3.0.2.</p> </blockquote> <h2 id="dont-speak-r">Don’t speak R?</h2> <p><a href="https: <p>It is not completely off to know R. It’s a laguage built for data processing and statistics. It’s been used by quants since always. And all datasets from Quandl.com can be imported into it with one line of code.</p> <p>Here’s <a href="https: <h2 id="<API key>">Graph reading packages</h2> <ul> <li><a href="http://digitizer.sourceforge.net/">Digitizer</a> (shareware) auto point / line recognition. Available in Ubuntu repository (engauge-digitizer)</li> <li><a href="http: <li><a href="http: <li><a href="http://rsbweb.nih.gov/ij/">ImageJ</a> (open source)</li> <li><a href="http: <li><a href="http://arohatgi.info/WebPlotDigitizer/">WebPlotDigitzer</a> (free, online). Browser based, extracts data from images. Reviewed here.</li> <li><a href="http: <li><a href="http: <li><a href="http: </ul> <p><a href="http://stats.stackexchange.com/a/14440">More: StackOverflow</a></p> <p><br /></p> </div> <ul class="tag_box list-unstyled list-inline"> <li><i class="fa fa-folder-open"></i></li> <li><a href="https://cryptotradingtools.com/categories/#trading-ref"> trading <span>(7)</span> , </a></li> <li><a href="https://cryptotradingtools.com/categories/#scraping-ref"> scraping <span>(1)</span> </a></li> </ul> <ul class="list-inline"> <li><i class="fa fa-tags"></i></li> <li> <a href="https://cryptotradingtools.com/tags/#r-ref"> r <span>(1)</span> , </a> </li> <li> <a href="https://cryptotradingtools.com/tags/#charting-ref"> charting <span>(4)</span> </a> </li> </ul> <hr> <div> <section class="share col-sm-6"> <h4 class="section-title">Share Post</h4> <a class="btn btn-default btn-sm twitter" href="http://twitter.com/share?text=(R) How to scrape highcharts&via=tradingfanbois" onclick="window.open(this.href, 'twitter-share', 'width=550,height=235');return false;"> <i class="fa fa-twitter fa-lg"></i> Twitter </a> <a class="btn btn-default btn-sm facebook" href="https: onclick="window.open(this.href, 'facebook-share','width=580,height=296');return false;"> <i class="fa fa-facebook fa-lg"></i> Facebook </a> <a class="btn btn-default btn-sm gplus" onclick="window.open('https://plus.google.com/share?url='+window.location.href, 'google-plus-share', 'width=490,height=530');return false;"> <i class="fa fa-google-plus fa-lg"></i> Google+ </a> </section> <section class="col-sm-6 author"> <img src="http: <h4 class="section-title author-name">Trading Fanbois</h4> <p class="author-bio">Repo with tools and scripts for bitcoin and altcoin trading.</p> </section> </div> <div class="clearfix"></div> <ul class="pager"> <li class="previous"><a href="https://cryptotradingtools.com/bots-ruby/" title="(Ruby) Bitcoin Trading Bots in Ruby">&larr; Previous</a></li> <li class="next"><a href="https://cryptotradingtools.com/btc-volatility/" title="(JSON) Bitcoin Volatility Historical Data - Backup">Next &rarr;</a></li> </ul> <hr> </div> <div class="col-sm-2 sidebar-2"> </div> </article> <div class="clearfix"></div> <footer> <hr/> <p> <API key> || &copy; 2016-2017 <a target="_blank" href="https://bestbitcoinexchange.co">Trading Fanbois</a> </p> </footer> </div> <script type="text/javascript" src="https://cryptotradingtools.com/assets/resources/jquery/jquery.min.js"></script> <script type="text/javascript" src="https://cryptotradingtools.com/assets/resources/bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript" src="https://cryptotradingtools.com/assets/js/app.js"></script> </body> </html> <!-- Asynchronous Google Analytics snippet --> <script> (function(i,s,o,g,r,a,m){i['<API key>']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.<API key>(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https: ga('create', 'UA-71937981-3', 'auto'); ga('send', 'pageview'); </script>
<?php use yii\helpers\Html; use yii\bootstrap\Nav; use yii\bootstrap\NavBar; use yii\widgets\Breadcrumbs; use app\assets\AppAsset; /* @var $this \yii\web\View */ /* @var $content string */ AppAsset::register($this); ?> <?php $this->beginPage() ?> <!DOCTYPE html> <html lang="<?= Yii::$app->language ?>"> <head> <meta charset="<?= Yii::$app->charset ?>"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <?= Html::csrfMetaTags() ?> <title><?= Html::encode($this->title) ?></title> <?php $this->head() ?> </head> <body> <?php $this->beginBody() ?> <div class="wrap"> <?php NavBar::begin( [ 'options' => [ 'class' => 'navbar-inverse navbar-fixed-top', ], ] ); echo Nav::widget( [ 'options' => ['class' => 'navbar-nav navbar-right'], 'items' => [ ['label' => 'Home', 'url' => ['/index']], ], ] ); NavBar::end(); ?> <div class="container"> <?= Breadcrumbs::widget( [ 'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [], ] ) ?> <?= $content ?> </div> </div> <footer class="footer"> <div class="container"> <p class="pull-left">&copy; <?= Yii::$app->id ?> <?= date('Y') ?></p> <p class="pull-right"> <?= Yii::t( 'yii', 'Framework {version_core} CP {version_cp}', [ 'version_core' => Yii::getVersion(), 'version_cp' => '1.0', ] ) ?> </p> </div> </footer> <?php $this->endBody() ?> </body> </html> <?php $this->endPage() ?>
<?php if ($comments): ?> <table class="table table-striped"> <thead> <tr> <th>Name</th> <th>Status</th> <th>Post</th> <th></th> </tr> </thead> <tbody> <?php foreach ($comments as $item): ?> <tr> <td><?php echo $item->name; ?></td> <td><?php echo $item->status; ?></td> <td><?php echo $item->post ? $item->post->title : '<i>Post deleted</i>'; ?></td> <td> <div class="btn-toolbar"> <div class="btn-group pull-right"> <?php echo Html::anchor('comment/admin/comment/edit/'.$item->id, 'Edit', array('class' => 'btn btn-default btn-sm')); ?> <?php echo Html::anchor('comment/admin/comment/delete/'.$item->id.'?'.\Config::get('security.csrf_token_key').'='.\Security::fetch_token(), 'Delete', array('onclick' => "return confirm('Are you sure?')", 'class' => 'btn btn-sm btn-danger')); ?> </div> </div> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php else: ?> <p>No Comments.</p> <?php endif; ?>
<?php /* * * Creado por Ricardo Alcantara <richpolis@gmail.com> * */ namespace Richpolis\BackendBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\<API key>; use Doctrine\Common\Persistence\ObjectManager; use Symfony\Component\DependencyInjection\<API key>; use Symfony\Component\DependencyInjection\ContainerInterface; use Richpolis\PublicacionesBundle\Entity\<API key>; /** * Fixtures de la entidad <API key>. * Crea los tres tipos de categorias de las publicaciones. */ class <API key> extends AbstractFixture implements <API key>, <API key> { public function getOrder() { return 20; } private $container; public function setContainer(ContainerInterface $container = null) { $this->container = $container; } public function load(ObjectManager $manager) { // Crear las categorias de las publicaciones $destinos = new <API key>(); $destinos->setNombre("Destinos"); $destinos->setPosition(1); $eventos = new <API key>(); $eventos->setNombre("Eventos"); $eventos->setPosition(2); $tours = new <API key>(); $tours->setNombre("Tours"); $tours->setPosition(3); $manager->persist($destinos); $manager->persist($eventos); $manager->persist($tours); $manager->flush(); } }
.NOTPARALLEL : SOURCES_PATH ?= $(BASEDIR)/sources BASE_CACHE ?= $(BASEDIR)/built SDK_PATH ?= $(BASEDIR)/SDKs NO_QT ?= NO_WALLET ?= NO_UPNP ?= <API key> ?= https://download.bitcoinabc.org/depends-sources BUILD = $(shell ./config.guess) HOST ?= $(BUILD) PATCHES_PATH = $(BASEDIR)/patches BASEDIR = $(CURDIR) HASH_LENGTH:=11 <API key>:=30 DOWNLOAD_RETRIES:=3 HOST_ID_SALT ?= salt BUILD_ID_SALT ?= salt JOBS ?= $(shell echo $$(($(shell nproc 2> /dev/null || sysctl -n hw.ncpu 2> /dev/null || echo 0) + 1))) host:=$(BUILD) ifneq ($(HOST),) host:=$(HOST) host_toolchain:=$(HOST)- endif ifneq ($(DEBUG),) release_type=debug else release_type=release endif base_build_dir=$(BASEDIR)/work/build base_staging_dir=$(BASEDIR)/work/staging base_download_dir=$(BASEDIR)/work/download canonical_host:=$(shell ./config.sub $(HOST)) build:=$(shell ./config.sub $(BUILD)) build_arch =$(firstword $(subst -, ,$(build))) build_vendor=$(word 2,$(subst -, ,$(build))) full_build_os:=$(subst $(build_arch)-$(build_vendor)-,,$(build)) build_os:=$(findstring linux,$(full_build_os)) build_os+=$(findstring darwin,$(full_build_os)) build_os:=$(strip $(build_os)) ifeq ($(build_os),) build_os=$(full_build_os) endif host_arch=$(firstword $(subst -, ,$(canonical_host))) host_vendor=$(word 2,$(subst -, ,$(canonical_host))) full_host_os:=$(subst $(host_arch)-$(host_vendor)-,,$(canonical_host)) host_os:=$(findstring linux,$(full_host_os)) host_os+=$(findstring darwin,$(full_host_os)) host_os+=$(findstring mingw32,$(full_host_os)) host_os:=$(strip $(host_os)) ifeq ($(host_os),) host_os=$(full_host_os) endif $(host_arch)_$(host_os)_prefix=$(BASEDIR)/$(host) $(host_arch)_$(host_os)_host=$(host) host_prefix=$($(host_arch)_$(host_os)_prefix) build_prefix=$(host_prefix)/native build_host=$(build) AT_$(V):= AT_:=@ AT:=$(AT_$(V)) all: install include hosts/$(host_os).mk include hosts/default.mk include builders/$(build_os).mk include builders/default.mk include packages/packages.mk build_id_string:=$(BUILD_ID_SALT) build_id_string+=$(shell $(build_CC) --version 2>/dev/null) build_id_string+=$(shell $(build_AR) --version 2>/dev/null) build_id_string+=$(shell $(build_CXX) --version 2>/dev/null) build_id_string+=$(shell $(build_RANLIB) --version 2>/dev/null) build_id_string+=$(shell $(build_STRIP) --version 2>/dev/null) $(host_arch)_$(host_os)_id_string:=$(HOST_ID_SALT) $(host_arch)_$(host_os)_id_string+=$(shell $(host_CC) --version 2>/dev/null) $(host_arch)_$(host_os)_id_string+=$(shell $(host_AR) --version 2>/dev/null) $(host_arch)_$(host_os)_id_string+=$(shell $(host_CXX) --version 2>/dev/null) $(host_arch)_$(host_os)_id_string+=$(shell $(host_RANLIB) --version 2>/dev/null) $(host_arch)_$(host_os)_id_string+=$(shell $(host_STRIP) --version 2>/dev/null) qt_packages_$(NO_QT) = $(qt_packages) $(qt_$(host_os)_packages) $(qt_$(host_arch)_$(host_os)_packages) wallet_packages_$(NO_WALLET) = $(wallet_packages) upnp_packages_$(NO_UPNP) = $(upnp_packages) packages += $($(host_arch)_$(host_os)_packages) $($(host_os)_packages) $(qt_packages_) $(wallet_packages_) $(upnp_packages_) native_packages += $($(host_arch)_$(host_os)_native_packages) $($(host_os)_native_packages) ifneq ($(qt_packages_),) native_packages += $(qt_native_packages) endif all_packages = $(packages) $(native_packages) meta_depends = Makefile funcs.mk builders/default.mk hosts/default.mk hosts/$(host_os).mk builders/$(build_os).mk $(host_arch)_$(host_os)_native_toolchain?=$($(host_os)_native_toolchain) include funcs.mk toolchain_path=$($($(host_arch)_$(host_os)_native_toolchain)_prefixbin) final_build_id_long+=$(shell $(build_SHA256SUM) config.site.in) final_build_id+=$(shell echo -n "$(final_build_id_long)" | $(build_SHA256SUM) | cut -c-$(HASH_LENGTH)) $(host_prefix)/.stamp_$(final_build_id): $(native_packages) $(packages) $(AT)rm -rf $(@D) $(AT)mkdir -p $(@D) $(AT)echo copying packages: $^ $(AT)echo to: $(@D) $(AT)cd $(@D); $(foreach package,$^, tar xf $($(package)_cached); ) $(AT)touch $@ $(host_prefix)/share/config.site : config.site.in $(host_prefix)/.stamp_$(final_build_id) $(AT)@mkdir -p $(@D) $(AT)sed -e 's|@HOST@|$(host)|' \ -e 's|@CC@|$(toolchain_path)$(host_CC)|' \ -e 's|@CXX@|$(toolchain_path)$(host_CXX)|' \ -e 's|@AR@|$(toolchain_path)$(host_AR)|' \ -e 's|@RANLIB@|$(toolchain_path)$(host_RANLIB)|' \ -e 's|@NM@|$(toolchain_path)$(host_NM)|' \ -e 's|@STRIP@|$(toolchain_path)$(host_STRIP)|' \ -e 's|@build_os@|$(build_os)|' \ -e 's|@host_os@|$(host_os)|' \ -e 's|@CFLAGS@|$(strip $(host_CFLAGS) $(host_$(release_type)_CFLAGS))|' \ -e 's|@CXXFLAGS@|$(strip $(host_CXXFLAGS) $(host_$(release_type)_CXXFLAGS))|' \ -e 's|@CPPFLAGS@|$(strip $(host_CPPFLAGS) $(host_$(release_type)_CPPFLAGS))|' \ -e 's|@LDFLAGS@|$(strip $(host_LDFLAGS) $(host_$(release_type)_LDFLAGS))|' \ -e 's|@no_qt@|$(NO_QT)|' \ -e 's|@no_wallet@|$(NO_WALLET)|' \ -e 's|@no_upnp@|$(NO_UPNP)|' \ -e 's|@debug@|$(DEBUG)|' \ $< > $@ $(AT)touch $@ define <API key> mkdir -p $(BASE_CACHE)/$(host)/$(package) && cd $(BASE_CACHE)/$(host)/$(package); \ $(build_SHA256SUM) -c $($(package)_cached_checksum) >/dev/null 2>/dev/null || \ ( rm -f $($(package)_cached_checksum); \ if test -f "$($(package)_cached)"; then echo "Checksum mismatch for $(package). Forcing rebuild.."; rm -f $($(package)_cached_checksum) $($(package)_cached); fi ) endef define <API key> mkdir -p $($(package)_source_dir); cd $($(package)_source_dir); \ test -f $($(package)_fetched) && ( $(build_SHA256SUM) -c $($(package)_fetched) >/dev/null 2>/dev/null || \ ( echo "Checksum missing or mismatched for $(package) source. Forcing re-download."; \ rm -f $($(package)_all_sources) $($(1)_fetched))) || true endef check-packages: @$(foreach package,$(all_packages),$(call <API key>,$(package));) check-sources: @$(foreach package,$(all_packages),$(call <API key>,$(package));) $(host_prefix)/share/config.site: check-packages check-packages: check-sources install: check-packages $(host_prefix)/share/config.site download-one: check-sources $(all_sources) download-osx: @$(MAKE) -s HOST=<API key> download-one download-linux: @$(MAKE) -s HOST=<API key> download-one download-win: @$(MAKE) -s HOST=x86_64-w64-mingw32 download-one download: download-osx download-linux download-win build-linux64: download-linux @$(MAKE) -s HOST=x86_64-linux-gnu install build-linux32: download-linux @$(MAKE) -s HOST=i686-pc-linux-gnu install build-linux-arm: download-linux @$(MAKE) -s HOST=arm-linux-gnueabihf install build-linux-aarch64: download-linux @$(MAKE) -s HOST=aarch64-linux-gnu install build-osx: download-osx @$(MAKE) -s HOST=<API key> install build-win32: download-win @$(MAKE) -s HOST=i686-w64-mingw32 install build-win64: download-win @$(MAKE) -s HOST=x86_64-w64-mingw32 install build-all: build-linux64 build-linux32 build-linux-arm build-linux-aarch64 build-osx build-win32 build-win64 .PHONY: install cached download-one download-osx download-linux download-win download check-packages check-sources
package com.tom.core; public abstract class IMod { public abstract String getModID(); public abstract boolean hadPreInit(); @Override public boolean equals(Object obj) { if (obj instanceof String) return getModID().equals(obj); return super.equals(obj); } }
package compile import ( "os" "os/exec" "path/filepath" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestDcj(t *testing.T) {