repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
DimitarGaydardzhiev/TelerikAcademy
02. C# Part 2/06. Strings-and-Text-Processing/03.CorrectBrackets/CorrectBrackets.cs
1134
/* Problem 3. Correct brackets Write a program to check if in a given expression the brackets are put correctly. Example of correct expression: ((a+b)/5-d) . Example of incorrect expression: )(a+b)) . */ using System; class CorrectBrackets { static bool CheckBreckets (string text) { int counterOpeningBreckets = 0; int counterClosingBreckets = 0; bool isCorrect = true; foreach (var symbol in text) { if (symbol == '(') { counterOpeningBreckets++; } if (symbol == ')') { counterClosingBreckets++; } } if (counterOpeningBreckets == counterClosingBreckets) { isCorrect = true; } else { isCorrect = false; } return isCorrect; } static void Main() { Console.Write("Enter your expression: "); string expresion = Console.ReadLine(); var result = CheckBreckets(expresion); Console.WriteLine("The expression is correct? => {0}", result); } }
mit
armadillo-systems/inquire
iNQUIRE.v2/Models/IInqItem.cs
1794
using System; using System.Collections.Generic; using System.Xml.Linq; using iNQUIRE.Helper; namespace iNQUIRE.Models { public interface IInqItem { #region properties // fields here MUST match \\armserv\solr\multicore\core1\conf\schema.xml, // else when updating a Solr record (when creating a jp2) an error will be thrown, causing jp2 creation to fail string ID { get; set; } string Title { get; set; } string Author { get; set; } string Description { get; set; } string File { get; set; } // has a set accessor as solr record needs to be updated if jpeg converted to jpeg2000 string DateStr { get; set; } ICollection<string> ParentNodes { get; set; } ICollection<string> ChildNodes { get; set; } ImageMetadata ImageMetadata { get; set; } #endregion string ViewItemUrl { get; } #region methods string ExportRis(string lang_id); XElement ExportXml(string lang_id); string ExportHtml(string content_id, string lang_id); string ExportHtmlImage(string content_id); string ExportHtmlFields(string lang_id); #endregion //string Title { get; set; } //DateTime Date { get; set; } //int Year { get; set; } //int YearStart { get; set; } //int YearEnd { get; set; } ////int Width { get; set; } ////int Height { get; set; } //string Description { get; set; } //string Author { get; set; } //string Type { get; set; } //string Subject { get; set; } //string Source { get; set; } //string Collection { get; set; } //ICollection<string> Categories { get; set; } //DateTime Timestamp { get; set; } } }
mit
shunjikonishi/flectSalesforce
src/main/java/jp/co/flect/salesforce/io/ImportRequest.java
2007
package jp.co.flect.salesforce.io; import java.io.File; import java.io.IOException; import java.util.TimeZone; import jp.co.flect.soap.SoapException; import jp.co.flect.salesforce.SalesforceClient; import jp.co.flect.salesforce.SObjectDef; import jp.co.flect.salesforce.update.ModifyOperation; import jp.co.flect.salesforce.update.ModifyRequest; /** * Queryリクエスト */ public abstract class ImportRequest { private File inputFile; private ModifyOperation op; private String objectName; private boolean stopAtError; private boolean stopAtInvalidColumn; private TimeZone timezone; private int maxCount; private String externalIdField; public ImportRequest(ModifyOperation op, String objectName, File inputFile) { this.op = op;; this.objectName = objectName; this.inputFile = inputFile; } public ModifyOperation getOperation() { return this.op;} public void setOperation(ModifyOperation op) { this.op = op;} public String getObjectName() { return this.objectName;} public void setObjectName(String s) { this.objectName = s;} public File getInputFile() { return this.inputFile;} public void setInputFile(File f) { this.inputFile = f;} public String getExternalIdField() { return this.externalIdField;} public void setExternalIdField(String s) { this.externalIdField = s;} public boolean isStopAtError() { return this.stopAtError;} public void setStopAtError(boolean b) { this.stopAtError = b;} public boolean isStopAtInvalidColumn() { return this.stopAtInvalidColumn;} public void setStopAtInvalidColumn(boolean b) { this.stopAtInvalidColumn = b;} public TimeZone getTimeZone() { return this.timezone;} public void setTimeZone(TimeZone t) { this.timezone = t;} public int getMaxCount() { return this.maxCount;} public void setMaxCount(int n) { this.maxCount = n;} public abstract ImportResult invoke(SalesforceClient client, SObjectDef objectDef) throws IOException, SoapException; }
mit
whiteboardmonk/droplet
node_modules/mongodb/lib/mongodb/cursor.js
22403
var QueryCommand = require('./commands/query_command').QueryCommand, GetMoreCommand = require('./commands/get_more_command').GetMoreCommand, KillCursorCommand = require('./commands/kill_cursor_command').KillCursorCommand, Integer = require('./goog/math/integer').Integer, Long = require('./goog/math/long').Long; /** * Constructor for a cursor object that handles all the operations on query result * using find. This cursor object is unidirectional and cannot traverse backwards. * As an alternative, {@link Cursor#toArray} can be used to obtain all the results. * Clients should not be creating a cursor directly, but use {@link Collection#find} * to acquire a cursor. * * @constructor * * @param db {Db} The database object to work with * @param collection {Colleciton} The collection to query * @param selector * @param fields * @param skip {number} * @param limit {number} The number of results to return. -1 has a special meaning and * is used by {@link Db#eval}. A value of 1 will also be treated as if it were -1. * @param sort {string|Array<Array<string|object> >} Please refer to {@link Cursor#sort} * @param hint * @param explain * @param snapshot * @param timeout * @param tailable {?boolean} * @param batchSize {?number} The number of the subset of results to request the database * to return for every request. This should initially be greater than 1 otherwise * the database will automatically close the cursor. The batch size can be set to 1 * with {@link Cursor#batchSize} after performing the initial query to the database. * * @see Cursor#toArray * @see Cursor#skip * @see Cursor#sort * @see Cursor#limit * @see Cursor#batchSize * @see Collection#find * @see Db#eval */ var Cursor = exports.Cursor = function(db, collection, selector, fields, skip, limit, sort, hint, explain, snapshot, timeout, tailable, batchSize) { this.db = db; this.collection = collection; this.selector = selector; this.fields = fields; this.skipValue = skip == null ? 0 : skip; this.limitValue = limit == null ? 0 : limit; this.sortValue = sort; this.hint = hint; this.explainValue = explain; this.snapshot = snapshot; this.timeout = timeout == null ? true : timeout; this.tailable = tailable; this.batchSizeValue = batchSize == null ? 0 : batchSize; this.totalNumberOfRecords = 0; this.items = []; this.cursorId = this.db.bson_serializer.Long.fromInt(0); // State variables for the cursor this.state = Cursor.INIT; // Keep track of the current query run this.queryRun = false; this.getMoreTimer = false; this.collectionName = (this.db.databaseName ? this.db.databaseName + "." : '') + this.collection.collectionName; }; /** * Resets this cursor to its initial state. All settings like the query string, * tailable, batchSizeValue, skipValue and limits are preserved. */ Cursor.prototype.rewind = function() { var self = this; if (self.state != Cursor.INIT) { if (self.state != Cursor.CLOSED) { self.close(function() {}); } self.numberOfReturned = 0; self.totalNumberOfRecords = 0; self.items = []; self.cursorId = self.db.bson_serializer.Long.fromInt(0); self.state = Cursor.INIT; self.queryRun = false; } }; /** * Returns an array of documents. The caller is responsible for making sure that there * is enough memory to store the results. Note that the array only contain partial * results when this cursor had been previouly accessed. In that case, * {@link Cursor#rewind} can be used to reset the cursor. * * @param callback {function(Error, Array<Object>)} This will be called after executing * this method successfully. The first paramter will contain the Error object if an * error occured, or null otherwise. The second paramter will contain an array of * BSON deserialized objects as a result of the query. * * Error cases include: * <ol> * <li>Attempting to call this method with a tailable cursor.</li> * </ol> * * @see Cursor#rewind * @see Cursor#each */ Cursor.prototype.toArray = function(callback) { var self = this; try { if(this.tailable) { callback(new Error("Tailable cursor cannot be converted to array"), null); } else if(this.state != Cursor.CLOSED) { var items = []; this.each(function(err, item) { if (item != null) { items.push(item); } else { callback(err, items); items = null; } item = null; }); } else { callback(new Error("Cursor is closed"), null); } } catch(err) { callback(new Error(err.toString()), null); } }; /** * Iterates over all the documents for this cursor. As with {@link Cursor#toArray}, * not all of the elements will be iterated if this cursor had been previouly accessed. * In that case, {@link Cursor#rewind} can be used to reset the cursor. However, unlike * {@link Cursor#toArray}, the cursor will only hold a maximum of batch size elements * at any given time if batch size is specified. Otherwise, the caller is responsible * for making sure that the entire result can fit the memory. * * @param callback {function(Error, Object)} This will be called for while iterating * every document of the query result. The first paramter will contain the Error * object if an error occured, or null otherwise. While the second paramter will * contain the document. * * @see Cursor#rewind * @see Cursor#toArray * @see Cursor#batchSize */ Cursor.prototype.each = function(callback) { var self = this; if(this.state != Cursor.CLOSED) { //FIX: stack overflow (on deep callback) (cred: https://github.com/limp/node-mongodb-native/commit/27da7e4b2af02035847f262b29837a94bbbf6ce2) process.nextTick(function(){ // Fetch the next object until there is no more objects self.nextObject(function(err, item) { if(item != null) { callback(null, item); self.each(callback); } else { self.state = Cursor.CLOSED; callback(err, null); } item = null; }); }); } else { callback(new Error("Cursor is closed"), null); } }; /** * Determines how many result the query for this cursor will return * * @param callback {function(?Error, ?number)} This will be after executing this method. * The first paramter will contain the Error object if an error occured, or null * otherwise. While the second paramter will contain the number of results or null * if an error occured. */ Cursor.prototype.count = function(callback) { this.collection.count(this.selector, callback); }; /** * Sets the sort parameter of this cursor to the given value. * * This method has the following method signatures: * (keyOrList, callback) * (keyOrList, direction, callback) * * @param keyOrList {string|Array<Array<string|object> >} This can be a string or an array. * If passed as a string, the string will be the field to sort. If passed an array, * each element will represent a field to be sorted and should be an array that contains * the format [string, direction]. Example of a valid array passed: * * <pre><code> * [ * ["id", "asc"], //direction using the abbreviated string format * ["name", -1], //direction using the number format * ["age", "descending"], //direction using the string format * ] * </code></pre> * * @param direction {string|number} This determines how the results are sorted. "asc", * "ascending" or 1 for asceding order while "desc", "desceding or -1 for descending * order. Note that the strings are case insensitive. * @param callback {?function(?Error, ?Cursor)} This will be called after executing * this method. The first parameter will contain an error object when the * cursor is already closed while the second parameter will contain a reference * to this object upon successful execution. * * @return {Cursor} an instance of this object. * * @see Cursor#formatSortValue */ Cursor.prototype.sort = function(keyOrList, direction, callback) { callback = callback || function(){}; if(typeof direction === "function") { callback = direction; direction = null; } if(this.tailable) { callback(new Error("Tailable cursor doesn't support sorting"), null); } else if(this.queryRun == true || this.state == Cursor.CLOSED) { callback(new Error("Cursor is closed"), null); } else { var order = keyOrList; if(direction != null) { order = [[keyOrList, direction]]; } this.sortValue = order; callback(null, this); } return this; }; /** * Sets the limit parameter of this cursor to the given value. * * @param limit {Number} The new limit. * @param callback {?function(?Error, ?Cursor)} This will be called after executing * this method. The first parameter will contain an error object when the * limit given is not a valid number or when the cursor is already closed while * the second parameter will contain a reference to this object upon successful * execution. * * @return {Cursor} an instance of this object. */ Cursor.prototype.limit = function(limit, callback) { callback = callback || function(){}; if(this.tailable) { callback(new Error("Tailable cursor doesn't support limit"), null); } else if(this.queryRun == true || this.state == Cursor.CLOSED) { callback(new Error("Cursor is closed"), null); } else { if(limit != null && limit.constructor != Number) { callback(new Error("limit requires an integer"), null); } else { this.limitValue = limit; callback(null, this); } } return this; }; /** * Sets the skip parameter of this cursor to the given value. * * @param skip {Number} The new skip value. * @param callback {?function(?Error, ?Cursor)} This will be called after executing * this method. The first parameter will contain an error object when the * skip value given is not a valid number or when the cursor is already closed while * the second parameter will contain a reference to this object upon successful * execution. * * @return {Cursor} an instance of this object. */ Cursor.prototype.skip = function(skip, callback) { callback = callback || function(){}; if(this.tailable) { callback(new Error("Tailable cursor doesn't support skip"), null); } else if(this.queryRun == true || this.state == Cursor.CLOSED) { callback(new Error("Cursor is closed"), null); } else { if(skip != null && skip.constructor != Number) { callback(new Error("skip requires an integer"), null); } else { this.skipValue = skip; callback(null, this); } } return this; }; /** * Sets the batch size parameter of this cursor to the given value. * * @param batchSize {Number} The new batch size. * @param callback {?function(?Error, ?Cursor)} This will be called after executing * this method. The first parameter will contain an error object when the * batchSize given is not a valid number or when the cursor is already closed while * the second parameter will contain a reference to this object upon successful * execution. * * @return {Cursor} an instance of this object. */ Cursor.prototype.batchSize = function(batchSize, callback) { callback = callback || function(){}; if(this.state == Cursor.CLOSED) { callback(new Error("Cursor is closed"), null); } else if(batchSize != null && batchSize.constructor != Number) { callback(new Error("batchSize requires an integer"), null); } else { this.batchSizeValue = batchSize; callback(null, this); } return this; }; /** * @return {number} The number of records to request per batch. */ Cursor.prototype.limitRequest = function() { var requestedLimit = this.limitValue; if (this.limitValue > 0) { if (this.batchSizeValue > 0) { requestedLimit = this.limitValue < this.batchSizeValue ? this.limitValue : this.batchSizeValue; } } else { requestedLimit = this.batchSizeValue; } return requestedLimit; }; /** * Generates a QueryCommand object using the parameters of this cursor. * * @return {QueryCommand} The command object */ Cursor.prototype.generateQueryCommand = function() { // Unpack the options var queryOptions = QueryCommand.OPTS_NONE; if (!this.timeout) { queryOptions += QueryCommand.OPTS_NO_CURSOR_TIMEOUT; } if (this.tailable != null) { queryOptions += QueryCommand.OPTS_TAILABLE_CURSOR; this.skipValue = this.limitValue = 0; } // limitValue of -1 is a special case used by Db#eval var numberToReturn = this.limitValue == -1 ? -1 : this.limitRequest(); // Check if we need a special selector if(this.sortValue != null || this.explainValue != null || this.hint != null || this.snapshot != null) { // Build special selector var specialSelector = {'query':this.selector}; if(this.sortValue != null) specialSelector['orderby'] = this.formattedOrderClause(); if(this.hint != null && this.hint.constructor == Object) specialSelector['$hint'] = this.hint; if(this.explainValue != null) specialSelector['$explain'] = true; if(this.snapshot != null) specialSelector['$snapshot'] = true; return new QueryCommand(this.db, this.collectionName, queryOptions, this.skipValue, numberToReturn, specialSelector, this.fields); } else { return new QueryCommand(this.db, this.collectionName, queryOptions, this.skipValue, numberToReturn, this.selector, this.fields); } }; /** * @return {Object} Returns an object containing the sort value of this cursor with * the proper formatting that can be used internally in this cursor. */ Cursor.prototype.formattedOrderClause = function() { var orderBy = {}; var self = this; if(Array.isArray(this.sortValue)) { this.sortValue.forEach(function(sortElement) { if(sortElement.constructor == String) { orderBy[sortElement] = 1; } else { orderBy[sortElement[0]] = self.formatSortValue(sortElement[1]); } }); } else if(Object.prototype.toString.call(this.sortValue) === '[object Object]') { //throw new Error("Invalid sort argument was supplied"); return orderBy = this.sortValue; } else if(this.sortValue.constructor == String) { orderBy[this.sortValue] = 1 } else { throw Error("Illegal sort clause, must be of the form " + "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); } return orderBy; }; /** * Converts the value of the sort direction into its equivalent numerical value. * * @param sortDirection {String|number} Range of acceptable values: * 'ascending', 'descending', 'asc', 'desc', 1, -1 * * @return {number} The equivalent numerical value * @throws Error if the given sortDirection is invalid */ Cursor.prototype.formatSortValue = function(sortDirection) { var value = ("" + sortDirection).toLowerCase(); if(value == 'ascending' || value == 'asc' || value == 1) return 1; if(value == 'descending' || value == 'desc' || value == -1 ) return -1; throw Error("Illegal sort clause, must be of the form " + "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); }; /** * Gets the next document from the database. * * @param callback {function(?Error, ?Object)} This will be called after executing * this method. The first parameter will contain an error object on error while * the second parameter will contain a document from the returned result or null * if there are no more results. * * @see Cursor#limit * @see Cursor#batchSize */ Cursor.prototype.nextObject = function(callback) { var self = this; if(self.state == Cursor.INIT) { try { var commandHandler = function(err, result) { if(!err && result.documents[0] && result.documents[0]['$err']) { self.close(function() {callback(result.documents[0]['$err'], null);}); return; } self.queryRun = true; self.state = Cursor.OPEN; // Adjust the state of the cursor self.cursorId = result.cursorId; self.totalNumberOfRecords = result.numberReturned; // Add the new documents to the list of items self.items = self.items.concat(result.documents); self.nextObject(callback); result = null; }; self.db.executeCommand(self.generateQueryCommand(), commandHandler); commandHandler = null; } catch(err) { callback(new Error(err.toString()), null); } } else if(self.items.length) { callback(null, self.items.shift()); } else if(self.cursorId.greaterThan(self.db.bson_serializer.Long.fromInt(0))) { self.getMore(callback); } else { self.close(function() {callback(null, null);}); } } /** * Gets more results from the database if any. * * @param callback {function(?Error, ?Object)} This will be called after executing * this method. The first parameter will contain an error object on error while * the second parameter will contain a document from the returned result or null * if there are no more results. */ Cursor.prototype.getMore = function(callback) { var self = this; var limit = 0; if (!self.tailable && self.limitValue > 0) { limit = self.limitValue - self.totalNumberOfRecords; if (limit < 1) { self.close(function() {callback(null, null);}); return; } } try { var getMoreCommand = new GetMoreCommand(self.db, self.collectionName, self.limitRequest(), self.cursorId); // Execute the command self.db.executeCommand(getMoreCommand, function(err, result) { self.cursorId = result.cursorId; self.totalNumberOfRecords += result.numberReturned; // Determine if there's more documents to fetch if(result.numberReturned > 0) { if (self.limitValue > 0) { var excessResult = self.totalNumberOfRecords - self.limitValue; if (excessResult > 0) { result.documents.splice(-1*excessResult, excessResult); } } self.items = self.items.concat(result.documents); callback(null, self.items.shift()); } else if(self.tailable) { self.getMoreTimer = setTimeout(function() {self.getMore(callback);}, 500); } else { self.close(function() {callback(null, null);}); } result = null; }); getMoreCommand = null; } catch(err) { var handleClose = function() { callback(new Error(err.toString()), null); }; self.close(handleClose); handleClose = null; } } /** * Gets a detailed information about how the query is performed on this cursor and how * long it took the database to process it. * * @param callback {function(null, Object)} This will be called after executing this * method. The first parameter will always be null while the second parameter * will be an object containing the details. * * @see http://www.mongodb.org/display/DOCS/Optimization#Optimization-Explain */ Cursor.prototype.explain = function(callback) { var limit = (-1)*Math.abs(this.limitValue); // Create a new cursor and fetch the plan var cursor = new Cursor(this.db, this.collection, this.selector, this.fields, this.skipValue, limit, this.sortValue, this.hint, true, this.snapshot, this.timeout, this.tailable, this.batchSizeValue); cursor.nextObject(function(err, item) { // close the cursor cursor.close(function(err, result) { callback(null, item); }); }); }; Cursor.prototype.streamRecords = function(options) { var args = Array.prototype.slice.call(arguments, 0); options = args.length ? args.shift() : {}; var self = this, stream = new process.EventEmitter(), recordLimitValue = this.limitValue || 0, emittedRecordCount = 0, queryCommand = this.generateQueryCommand(); // see http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol queryCommand.numberToReturn = options.fetchSize ? options.fetchSize : 500; execute(queryCommand); function execute(command) { self.db.executeCommand(command, function(err,result) { if (!self.queryRun && result) { self.queryRun = true; self.cursorId = result.cursorId; self.state = Cursor.OPEN; self.getMoreCommand = new GetMoreCommand(self.db, self.collectionName, queryCommand.numberToReturn, result.cursorId); } if (result.documents && result.documents.length) { try { result.documents.forEach(function(doc){ if (recordLimitValue && emittedRecordCount>=recordLimitValue) { throw("done"); } emittedRecordCount++; stream.emit('data', doc); }); } catch(err) { if (err != "done") { throw err; } else { stream.emit('end', recordLimitValue); self.close(function(){}); return(null); } } // rinse & repeat execute(self.getMoreCommand); } else { self.close(function(){ stream.emit('end', recordLimitValue); }); } }); } return stream; }; /** * Close this cursor. * * @param callback {?function(null, ?Object)} This will be called after executing * this method. The first parameter will always contain null while the second * parameter will contain a reference to this cursor. */ Cursor.prototype.close = function(callback) { var self = this this.getMoreTimer && clearTimeout(this.getMoreTimer); // Close the cursor if not needed if(this.cursorId instanceof self.db.bson_serializer.Long && this.cursorId.greaterThan(self.db.bson_serializer.Long.fromInt(0))) { try { var command = new KillCursorCommand(this.db, [this.cursorId]); this.db.executeCommand(command, null); } catch(err) {} } this.cursorId = self.db.bson_serializer.Long.fromInt(0); this.state = Cursor.CLOSED; if (callback) callback(null, this); this.items = null; }; /** * @return true if this cursor is closed */ Cursor.prototype.isClosed = function() { return this.state == Cursor.CLOSED ? true : false; }; // Static variables Cursor.INIT = 0; Cursor.OPEN = 1; Cursor.CLOSED = 2;
mit
akbarsatria/test-pidsus-ci
application/modules/admin/views-Ori/themes/default/kasuss_create.php
6417
<div id="page-wrapper"> <div class="row"> <div class="col-lg-12"> <h2> Kasus <a href="<?= base_url('admin/kasuss') ?>" class="btn btn-warning">Kembali ke Daftar Kasus</a> </h2> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> Tambah Kasus Baru </div> <div class="panel-body"> <div class="row"> <?php if ($this->session->flashdata('message')): ?> <div class="col-lg-12 col-md-12"> <div class="alert alert-info alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <?=$this->session->flashdata('message')?> </div> </div> <?php endif; ?> <div class="col-lg-12"> <form role="form" method="POST" action="<?=base_url('admin/kasuss/create')?>"> <!-- <div class="form-group"> <label>Kasus Id Input</label> <input class="form-control" placeholder="Auto generated" disabled="1"> </div> --> <div class="form-group"> <label>Judul Kasus</label> <input class="form-control" placeholder="Masukan judul kasus" id="judul_kasus" name="judul_kasus"> </div> <div class="row"> <div class="col-lg-6"> <div class="form-group"> <label>Nama Terlapor</label> <input class="form-control" placeholder="Masukan nama terlapor" id="judul_kasus" name="judul_kasus"> </div> <div class="form-group"> <label>Jabatan Resmi</label> <input class="form-control" placeholder="Masukan jabatan resmi" id="judul_kasus" name="judul_kasus"> </div> <div class="form-group"> <label>Lembaga</label> <input class="form-control" placeholder="Masukan lembaga" id="nama_pelapor" name="nama_pelapor"> </div> </div> <div class="col-lg-6"> <div class="form-group"> <label>Waktu Kejadian</label> <input class="form-control" placeholder="Masukan waktu kejadian" id="waktu_kejadian" name="waktu_kejadian"> </div> <div class="form-group"> <label>Lokasi Kejadian</label> <input class="form-control" placeholder="Masukan lokasi kejadian" id="lokasi_kejadian" name="lokasi_kejadian"> </div> <div class="form-group"> <label>Kasus Posisi</label> <input class="form-control" placeholder="Masukan kasusu posisi" id="kasusu_posisi" name="kasusu_posisi"> </div> </div> </div> <div class="form-group"> <label>Masalah</label> <textarea class="form-control" rows="5" placeholder="Masukan masalah" id="masalah" name="masalah"></textarea> </div> <div class="form-group"> <label>Kesimpulan</label> <textarea placeholder="Masukan kesimpulan" class="form-control" rows="5" id="kesimpulan" name="kesimpulan"></textarea> </div> <div class="form-group"> <label>Saran</label> <textarea class="form-control" rows="5" placeholder="Masukan saran" id="saran" name="saran"></textarea> </div> <!-- <div class="form-group"> <label>ID Surat</label> <select class="form-control" id="id_surat" name="id_surat"> <?php if (count($surats)): ?> <?php foreach ($surats as $key => $surat): ?> <option value="<?= $surat['id_surat'] ?>"><?= $surat['judul_surat'] ?></option> <?php endforeach; ?> <?php endif; ?> </select> </div> --> <button type="submit" class="btn btn-primary">Submit Button</button> <button type="reset" class="btn btn-default">Reset Button</button> </form> </div> </div> <!-- /.row (nested) --> </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> </div> <!-- /#page-wrapper -->
mit
smitchell/exploringspatial
js/demos/demo7/collections/Counties.js
1148
/** * Activities is a Backbone Collection of Activity Backbone Models. * Each model represents a single activity from a Garmin device.. */ define([ 'backbone', 'models/Feature' ], function(Backbone, Feature) { var Counties = Backbone.Collection.extend({ state: 'ks', url: "http://data.exploringspatial.com/states/ks/counties", model: Feature, /** * Override Backbone parse to convert properties of properties into child Backbone models. * @param data * @returns {{}} */ parse: function (data) { this.type = data.type; this.crs = data.crs; return data.features; }, /** * Override Backbone toJSON to return child Backbone models into properties of properties. */ toJSON: function() { var json = {}; json.type = this.type; json.crs = this.crs; json.features = []; this.each(function(feature){ json.features.push(feature.toJSON()); }); return json; }, comparator: function( model ){ return( model.get( 'properties').get('name') ); }, getState: function() { return this.state; }, setState: function(state) { this.state = state; } }); return Counties; });
mit
danieljoppi/gulp-html-i18n
lib/index.js
8241
(function() { var EOL, Q, async, fs, getLangResource, getProperty, gutil, handleUndefined, langRegExp, options, path, replaceProperties, supportedType, through, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; Q = require('q'); fs = require('fs'); path = require('path'); async = require('async'); gutil = require('gulp-util'); through = require('through2'); EOL = '\n'; options = void 0; langRegExp = /\${{ ?([\w\-\.]+) ?}}\$/g; supportedType = ['.js', '.json']; getProperty = function(propName, properties) { var res, tmp; tmp = propName.split('.'); res = properties; while (tmp.length && res) { res = res[tmp.shift()]; if (res === void 0) { handleUndefined(propName); } } if (options.escapeQuotes === true) { res = res.replace(/"/g, '\\"'); res = res.replace(/'/g, "\\'"); } return res; }; handleUndefined = function(propName) { if (options.failOnMissing) { throw propName + " not found in definition file!"; } else { return console.warn(propName + " not found in definition file!"); } }; replaceProperties = function(content, properties, lv) { lv = lv || 1; if (!properties) { return content; } return content.replace(langRegExp, function(full, propName) { var res; res = getProperty(propName, properties); if (typeof res !== 'string') { if (!options.fallback) { res = '*' + propName + '*'; } else { res = '${{ ' + propName + ' }}$'; } } else if (langRegExp.test(res)) { if (lv > 3) { res = '**' + propName + '**'; } else { res = replaceProperties(res, properties, lv + 1); } } return res; }); }; getLangResource = (function() { var define, getJSONResource, getJsResource, getResource, getResourceFile, langResource, require; define = function() { var al; al = arguments.length; if (al >= 3) { return arguments[2]; } else { return arguments[al - 1]; } }; require = function() {}; langResource = null; getResourceFile = function(filePath) { var e, res; try { if (path.extname(filePath) === '.js') { res = getJsResource(filePath); } else if (path.extname(filePath) === '.json') { res = getJSONResource(filePath); } } catch (_error) { e = _error; throw new Error('Language file "' + filePath + '" syntax error! - ' + e.toString()); } if (typeof res === 'function') { res = res(); } return res; }; getJsResource = function(filePath) { var res; res = eval(fs.readFileSync(filePath).toString()); if (typeof res === 'function') { res = res(); } return res; }; getJSONResource = function(filePath) { return define(JSON.parse(fs.readFileSync(filePath).toString())); }; getResource = function(langDir) { return Q.Promise(function(resolve, reject) { var fileList, res; if (fs.statSync(langDir).isDirectory()) { res = {}; fileList = fs.readdirSync(langDir); return async.each(fileList, function(filePath, cb) { var _ref; if (_ref = path.extname(filePath), __indexOf.call(supportedType, _ref) >= 0) { filePath = path.resolve(langDir, filePath); res[path.basename(filePath).replace(/\.js(on)?$/, '')] = getResourceFile(filePath); } return cb(); }, function(err) { if (err) { return reject(err); } return resolve(res); }); } else { return resolve(); } }); }; return getLangResource = function(dir) { return Q.Promise(function(resolve, reject) { var langList, res; if (langResource) { return resolve(langResource); } res = { LANG_LIST: [] }; langList = fs.readdirSync(dir); if (options.inline) { if (fs.statSync(path.resolve(dir, options.inline)).isDirectory()) { langList = [options.inline]; } else { throw new Error('Language ' + opt.inline + ' has no definitions!'); } } return async.each(langList, function(langDir, cb) { var langCode; if (langDir.indexOf('.') === 0) { return cb(); } langDir = path.resolve(dir, langDir); langCode = path.basename(langDir); if (fs.statSync(langDir).isDirectory()) { res.LANG_LIST.push(langCode); return getResource(langDir).then(function(resource) { res[langCode] = resource; return cb(); }, function(err) { return reject(err); }).done(); } else { return cb(); } }, function(err) { if (err) { return reject(err); } return resolve(res); }); }); }; })(); module.exports = function(opt) { var langDir, seperator; if (opt == null) { opt = {}; } options = opt; if (!opt.langDir) { throw new gutil.PluginError('gulp-html-i18n', 'Please specify langDir'); } langDir = path.resolve(process.cwd(), opt.langDir); seperator = opt.seperator || '-'; return through.obj(function(file, enc, next) { if (file.isNull()) { return this.emit('error', new gutil.PluginError('gulp-html-i18n', 'File can\'t be null')); } if (file.isStream()) { return this.emit('error', new gutil.PluginError('gulp-html-i18n', 'Streams not supported')); } return getLangResource(langDir).then((function(_this) { return function(langResource) { var content; if (file._lang_) { content = replaceProperties(file.contents.toString(), langResource[file._lang_]); file.contents = new Buffer(content); _this.push(file); } else { langResource.LANG_LIST.forEach(function(lang) { var newFile, newFilePath, originPath, trace, tracePath; originPath = file.path; newFilePath = originPath.replace(/\.src\.html$/, '\.html'); if (opt.createLangDirs) { newFilePath = path.resolve(path.dirname(newFilePath), lang, path.basename(newFilePath)); } else if (opt.inline) { newFilePath = originPath; } else { newFilePath = gutil.replaceExtension(newFilePath, seperator + lang + '.html'); } content = replaceProperties(file.contents.toString(), langResource[lang]); if (options.fallback) { console.log(lang); console.log(content); content = replaceProperties(content, langResource[options.fallback]); console.log(content); } if (opt.trace) { tracePath = path.relative(process.cwd(), originPath); trace = '<!-- trace:' + tracePath + ' -->'; if (/(<body[^>]*>)/i.test(content)) { content = content.replace(/(<body[^>]*>)/i, '$1' + EOL + trace); } else { content = trace + EOL + content; } } newFile = new gutil.File({ base: file.base, cwd: file.cwd, path: newFilePath, contents: new Buffer(content) }); newFile._lang_ = lang; newFile._originPath_ = originPath; return _this.push(newFile); }); } return next(); }; })(this), (function(_this) { return function(err) { return _this.emit('error', new gutil.PluginError('gulp-html-i18n', err)); }; })(this)).done(); }); }; }).call(this);
mit
shopping24/pagerDutySynchronizer
src/test/java/com/s24/pagerduty/bridge/transformer/PagerdutyIncidentstatusToStatusPageIOIncidentstatusTransformerTest.java
1022
package com.s24.pagerduty.bridge.transformer; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.s24.pagerduty.bridge.pagerduty.PagerdutyIncidentStatus; import com.s24.pagerduty.bridge.statuspageio.StatusPageIOIncidentStatus; public class PagerdutyIncidentstatusToStatusPageIOIncidentstatusTransformerTest { @Test public void testTransforming() throws Exception { PagerdutyIncidentstatusToStatusPageIOIncidentstatusTransformer transformer = new PagerdutyIncidentstatusToStatusPageIOIncidentstatusTransformer(); assertEquals(StatusPageIOIncidentStatus.undefined,transformer.apply(PagerdutyIncidentStatus.undefined)); assertEquals(StatusPageIOIncidentStatus.investigating,transformer.apply(PagerdutyIncidentStatus.triggered)); assertEquals(StatusPageIOIncidentStatus.identified,transformer.apply(PagerdutyIncidentStatus.acknowledged)); assertEquals(StatusPageIOIncidentStatus.resolved,transformer.apply(PagerdutyIncidentStatus.resolved)); } }
mit
Hexeption/Youtube-Hacked-Client-1.8
minecraft/net/minecraft/client/resources/SimpleResource.java
4022
package net.minecraft.client.resources; import com.google.common.collect.Maps; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Map; import net.minecraft.client.resources.data.IMetadataSection; import net.minecraft.client.resources.data.IMetadataSerializer; import net.minecraft.util.ResourceLocation; import org.apache.commons.io.IOUtils; public class SimpleResource implements IResource { private final Map mapMetadataSections = Maps.newHashMap(); private final String field_177242_b; private final ResourceLocation srResourceLocation; private final InputStream resourceInputStream; private final InputStream mcmetaInputStream; private final IMetadataSerializer srMetadataSerializer; private boolean mcmetaJsonChecked; private JsonObject mcmetaJson; private static final String __OBFID = "CL_00001093"; public SimpleResource(String p_i46090_1_, ResourceLocation p_i46090_2_, InputStream p_i46090_3_, InputStream p_i46090_4_, IMetadataSerializer p_i46090_5_) { this.field_177242_b = p_i46090_1_; this.srResourceLocation = p_i46090_2_; this.resourceInputStream = p_i46090_3_; this.mcmetaInputStream = p_i46090_4_; this.srMetadataSerializer = p_i46090_5_; } public ResourceLocation func_177241_a() { return this.srResourceLocation; } public InputStream getInputStream() { return this.resourceInputStream; } public boolean hasMetadata() { return this.mcmetaInputStream != null; } public IMetadataSection getMetadata(String p_110526_1_) { if (!this.hasMetadata()) { return null; } else { if (this.mcmetaJson == null && !this.mcmetaJsonChecked) { this.mcmetaJsonChecked = true; BufferedReader var2 = null; try { var2 = new BufferedReader(new InputStreamReader(this.mcmetaInputStream)); this.mcmetaJson = (new JsonParser()).parse(var2).getAsJsonObject(); } finally { IOUtils.closeQuietly(var2); } } IMetadataSection var6 = (IMetadataSection)this.mapMetadataSections.get(p_110526_1_); if (var6 == null) { var6 = this.srMetadataSerializer.parseMetadataSection(p_110526_1_, this.mcmetaJson); } return var6; } } public String func_177240_d() { return this.field_177242_b; } public boolean equals(Object p_equals_1_) { if (this == p_equals_1_) { return true; } else if (!(p_equals_1_ instanceof SimpleResource)) { return false; } else { SimpleResource var2 = (SimpleResource)p_equals_1_; if (this.srResourceLocation != null) { if (!this.srResourceLocation.equals(var2.srResourceLocation)) { return false; } } else if (var2.srResourceLocation != null) { return false; } if (this.field_177242_b != null) { if (!this.field_177242_b.equals(var2.field_177242_b)) { return false; } } else if (var2.field_177242_b != null) { return false; } return true; } } public int hashCode() { int var1 = this.field_177242_b != null ? this.field_177242_b.hashCode() : 0; var1 = 31 * var1 + (this.srResourceLocation != null ? this.srResourceLocation.hashCode() : 0); return var1; } }
mit
andreykata/SoftUni
Programming Basics/2017 January/ProgrammingBasics05Loops/Task03.AToZ/AToZ.cs
236
using System; class AToZ { static void Main(string[] args) { for (char i = 'a'; i <= 'z'; i++) { Console.WriteLine(i); // Console.WriteLine("{0} -> {1}", i, (int)i); } } }
mit
Zuehlke/cookbook-windev
resources/cache_package.rb
363
# # Author:: Vassilis Rizopoulos (<var@zuehlke.com>) # Cookbook Name:: windev # Resource:: cache_package # # Copyright:: 2015, Zühlke actions :cache default_action :cache attribute :save_as, :name_attribute => true,:kind_of => String, :required=>true attribute :depot, :kind_of => String, :required=>true attribute :source, :kind_of => String, :required=>true
mit
BeltranGomezUlises/machineAdminAPI
src/main/java/com/auth/managers/commons/ManagerFacade.java
3887
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.auth.managers.commons; import com.auth.entities.commons.IEntity; import java.util.List; /** * fachada de manager general * * @author Alonso --- alonso@kriblet.com * @param <T> class entity used to restrict the class of use * @param <K> */ public abstract class ManagerFacade<T extends IEntity, K> { public ManagerFacade() { } /** * metodo para persistir la entidad a base de datos * * @param entity entidad a persistir en base de datos * @return la entidad persistida con su _id * @throws Exception si existió un problema al intertar persistir */ public abstract T persist(T entity) throws Exception; /** * metodo para persistir todas las entidades proporsioadas en base de datos * * @param entities lista de entidades a persistir * @return la lista de entidades persistidas con su propiedad _id * @throws Exception si existió un problema la intentar persistir */ public abstract List<T> persistAll(List<T> entities) throws Exception; /** * remueve de base de datos la entidad que corresponda al id proporsionado * * @param id propiedad que identifia al objeto * @throws Exception */ public abstract void delete(K id) throws Exception; /** * remueve de base de datos las entidades que su propiedad id corresponda con los objetos proporsionados * * @param ids lista de identificadores de las entidades * @throws Exception si existió algún problema al intentar remover */ public abstract void deleteAll(List<K> ids) throws Exception; /** * reemplaza la entidad proporsionada por la existente en base de datos que coincida con su propiedad id * * @param entity la entidad con la cual reemplazar la existente en base de datos * @throws Exception si exitió un problema al actualizar */ public abstract void update(T entity) throws Exception; /** * busca la entidad correspondiente al identificador proporsionado * * @param id identificador de la entidad * @return entidad de la base de datos * @throws java.lang.Exception */ public abstract T findOne(K id) throws Exception; /** * busca la primer entidad existente en base de datos * * @return la entidad manejada en primer posición en base de datos * @throws java.lang.Exception */ public abstract T findFirst() throws Exception; /** * busca todas las entidades existentes en base de datos * * @return lista con las entidades manejadas que existen en base de datos * @throws java.lang.Exception */ public abstract List<T> findAll() throws Exception; /** * busca todas las entidades existentes en base de datos con un numero maximo de elementos a retornas * * @param max numero maximo de entidades a tomar de base de datos * @return lista con las entidades manejadas que existen en base de datos * @throws java.lang.Exception */ public abstract List<T> findAll(int max) throws Exception; /** * busca las entidades comprendidas en el rango especificado por los parametros * * @param initialPosition posicion inicial de busqueda * @param lastPosition posicion final de busqueda * @return lista de entidades comprendidas entre las posiciones proporcionadas */ public abstract List<T> findRange(final int initialPosition, final int lastPosition); /** * cuenta las entidades manejadas * * @return numero de entidades existentes en base de datos * @throws java.lang.Exception */ public abstract long count() throws Exception; }
mit
DRIVER-EU/CISadaptor
templates/REST example implementation/CISAdaptorStandaloneAIT/src/main/java/com/frequentis/cis/template/controller/CISConnectorRestController.java
1518
package com.frequentis.cis.template.controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.frequentis.cis.connector.CISToolConnector; import com.frequentis.cis.connector.CISToolConnectorImpl; import com.frequentis.cis.template.response.NotifyResponse; /** * The RestControler that exposes the Connector if as REST Endpoint. * * @author TObritzh * @version 1.0 * */ @RestController public class CISConnectorRestController { private final CISToolConnector connector = new CISToolConnectorImpl(); /** * The Connector Rest Endpoint to distribute messages from the application via the CIS to other applications. * * @param msgType * The type of the message (e.g.: CAP, EMIS, WMS/WFS) * @param msg * The String representation of the message (e.g.: CAL XML) * @param deParameters * The EDXL DE parameters that should be filled in the EDXL DE envelope * @return notifyResponse Object that contains detailed information about the execution status */ @RequestMapping("/notify") public NotifyResponse notify(@RequestBody String messageToCis) { try { connector.notify("CAP", messageToCis, null, false); } catch (Exception e) { return new NotifyResponse("ERROR", "The message was not sent!", e.getMessage()); } return new NotifyResponse("SUCCESS", "The message was successfully sent!"); } }
mit
Dzhey/DroidWorker
droidworker/src/main/java/com/be/android/library/worker/models/LoadJobResult.java
2266
package com.be.android.library.worker.models; import com.be.android.library.worker.base.JobEvent; import com.be.android.library.worker.models.JobResultStatus; import com.be.android.library.worker.base.JobStatus; public class LoadJobResult<TData> extends JobEvent { private TData mData; public static <T> LoadJobResult<T> loadFailure() { return new LoadJobResult<T>(JobResultStatus.FAILED); } public static <T> LoadJobResult<T> loadOk() { return new LoadJobResult<T>(JobResultStatus.OK); } public static <TData> LoadJobResult fromEvent(JobEvent other, TData mData) { return new LoadJobResult<TData>(other, mData); } protected LoadJobResult(JobEvent other, TData mData) { super(other); this.mData = mData; } public LoadJobResult(LoadJobResult<TData> other) { super(other); mData = other.getData(); } public LoadJobResult(int resultCode, JobStatus status, TData resultData) { setEventCode(resultCode); setJobStatus(status); mData = resultData; } public LoadJobResult(JobResultStatus status, TData resultData) { setJobStatus(status); setEventCode(JobResultStatus.getResultCode(status)); mData = resultData; } public LoadJobResult(int resultCode, JobResultStatus status, TData resultData) { setEventCode(resultCode); setJobStatus(status); mData = resultData; } public LoadJobResult(JobResultStatus status) { setJobStatus(status); setEventCode(JobResultStatus.getResultCode(status)); } public LoadJobResult(TData resultData) { setJobStatus(JobResultStatus.OK); setEventCode(JobEvent.EVENT_CODE_OK); mData = resultData; } public LoadJobResult() { } public LoadJobResult<TData> setExtraMessage(String message) { super.setExtraMessage(message); return this; } public void setEventCode(int eventCode) { super.setEventCode(eventCode); } public void setExtraCode(int extraCode) { super.setExtraCode(extraCode); } public TData getData() { return mData; } public void setData(TData data) { mData = data; } }
mit
fedeaux/brain_damage
lib/generators/brain_damage/lib/displays/base.rb
701
require_relative '../templateable/base' module BrainDamage module Displays class Base < Templateable::Base def initialize(options) super end def input_html(args = {}) field_description.input.html(args) end def include_nested_on_guard? field_description.relation and field_description.relation.type == :belongs_to end def include_nested_on_guard if include_nested_on_guard? and !@html_args[:skip_include_nested_on_guard] @inner_html = ERB.new(File.open("#{dir}/templates/nested_on_guard.html.haml").read).result(binding).strip end end def dir __dir__ end end end end
mit
ljepojevic/Phactory-PHP-framework
Core/Cookie.php
448
<?php namespace Core; class Cookie { public static function get($name){ if (isset($_COOKIE[$name])) { return $_COOKIE[$name]; } else { return false; } } public static function set($name, $value, $expire, $path = '', $domain = '', $secure = false, $httponly = false){ setcookie($name, $value, time() + $expire); } public static function delete($name) { setcookie($name, '', time()-360000); unset($_COOKIE[$name]); } }
mit
RiZAR88/SoftUni
Advanced Collections - Exercises/03. Forum Topics/Properties/AssemblyInfo.cs
1408
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("03. Forum Topics")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03. Forum Topics")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ae1d3449-06b7-4977-ad0c-ba5d107ed3aa")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
sferik/octokit.rb
lib/octokit/client/repositories.rb
29419
module Octokit class Client # Methods for the Repositories API # # @see http://developer.github.com/v3/repos/ module Repositories # Check if a repository exists # # @see http://developer.github.com/v3/repos/#get # @param repo [String, Hash, Repository] A GitHub repository # @return [Sawyer::Resource] if a repository exists, false otherwise def repository?(repo, options = {}) repository(repo, options) rescue Octokit::NotFound false end # Get a single repository # # @see http://developer.github.com/v3/repos/#get # @param repo [String, Hash, Repository] A GitHub repository # @return [Sawyer::Resource] Repository information def repository(repo, options = {}) get "repos/#{Repository.new repo}", options end alias :repo :repository # Edit a repository # # @see http://developer.github.com/v3/repos/#edit # @param repo [String, Hash, Repository] A GitHub repository # @param options [Hash] Repository information to update # @option options [String] :name Name of the repo # @option options [String] :description Description of the repo # @option options [String] :homepage Home page of the repo # @option options [String] :private `true` makes the repository private, and `false` makes it public. # @option options [String] :has_issues `true` enables issues for this repo, `false` disables issues. # @option options [String] :has_wiki `true` enables wiki for this repo, `false` disables wiki. # @option options [String] :has_downloads `true` enables downloads for this repo, `false` disables downloads. # @option options [String] :default_branch Update the default branch for this repository. # @return [Sawyer::Resource] Repository information def edit_repository(repo, options = {}) repo = Repository.new(repo) options[:name] ||= repo.name patch "repos/#{repo}", options end alias :edit :edit_repository alias :update_repository :edit_repository alias :update :edit_repository # List repositories # # If username is not supplied, repositories for the current # authenticated user are returned # # @see http://developer.github.com/v3/repos/#list-your-repositories # @see http://developer.github.com/v3/repos/#list-user-repositories # @param username [String] Optional username for which to list repos # @return [Array<Sawyer::Resource>] List of repositories def repositories(username=nil, options = {}) if username.nil? paginate 'user/repos', options else paginate "users/#{username}/repos", options end end alias :list_repositories :repositories alias :list_repos :repositories alias :repos :repositories # List all repositories # # This provides a dump of every repository, in the order that they were # created. # # @see http://developer.github.com/v3/repos/#list-all-public-repositories # # @param options [Hash] Optional options # @option options [Integer] :since The integer ID of the last Repository # that you’ve seen. # @return [Array<Sawyer::Resource>] List of repositories. def all_repositories(options = {}) paginate 'repositories', options end # Star a repository # # @param repo [String, Hash, Repository] A GitHub repository # @return [Boolean] `true` if successfully starred # @see http://developer.github.com/v3/activity/starring/#star-a-repository def star(repo, options = {}) boolean_from_response :put, "user/starred/#{Repository.new repo}", options end # Unstar a repository # # @param repo [String, Hash, Repository] A GitHub repository # @return [Boolean] `true` if successfully unstarred # @see http://developer.github.com/v3/activity/starring/#unstar-a-repository def unstar(repo, options = {}) boolean_from_response :delete, "user/starred/#{Repository.new repo}", options end # Watch a repository # # @param repo [String, Hash, Repository] A GitHub repository # @return [Boolean] `true` if successfully watched # @deprecated Use #star instead # @see http://developer.github.com/v3/activity/watching/#watch-a-repository-legacy def watch(repo, options = {}) boolean_from_response :put, "user/watched/#{Repository.new repo}", options end # Unwatch a repository # # @param repo [String, Hash, Repository] A GitHub repository # @return [Boolean] `true` if successfully unwatched # @deprecated Use #unstar instead # @see http://developer.github.com/v3/activity/watching/#stop-watching-a-repository-legacy def unwatch(repo, options = {}) boolean_from_response :delete, "user/watched/#{Repository.new repo}", options end # Fork a repository # # @param repo [String, Hash, Repository] A GitHub repository # @return [Sawyer::Resource] Repository info for the new fork # @see http://developer.github.com/v3/repos/forks/#create-a-fork def fork(repo, options = {}) post "repos/#{Repository.new repo}/forks", options end # Create a repository for a user or organization # # @param name [String] Name of the new repo # @option options [String] :description Description of the repo # @option options [String] :homepage Home page of the repo # @option options [String] :private `true` makes the repository private, and `false` makes it public. # @option options [String] :has_issues `true` enables issues for this repo, `false` disables issues. # @option options [String] :has_wiki `true` enables wiki for this repo, `false` disables wiki. # @option options [String] :has_downloads `true` enables downloads for this repo, `false` disables downloads. # @option options [String] :organization Short name for the org under which to create the repo. # @option options [Integer] :team_id The id of the team that will be granted access to this repository. This is only valid when creating a repo in an organization. # @option options [Boolean] :auto_init `true` to create an initial commit with empty README. Default is `false`. # @option options [String] :gitignore_template Desired language or platform .gitignore template to apply. Ignored if auto_init parameter is not provided. # @return [Sawyer::Resource] Repository info for the new repository # @see http://developer.github.com/v3/repos/#create def create_repository(name, options = {}) organization = options.delete :organization options.merge! :name => name if organization.nil? post 'user/repos', options else post "orgs/#{organization}/repos", options end end alias :create_repo :create_repository alias :create :create_repository # Delete repository # # Note: If OAuth is used, 'delete_repo' scope is required # # @see http://developer.github.com/v3/repos/#delete-a-repository # @param repo [String, Hash, Repository] A GitHub repository # @return [Boolean] `true` if repository was deleted def delete_repository(repo, options = {}) boolean_from_response :delete, "repos/#{Repository.new repo}", options end alias :delete_repo :delete_repository # Hide a public repository # # @param repo [String, Hash, Repository] A GitHub repository # @return [Sawyer::Resource] Updated repository info def set_private(repo, options = {}) # GitHub Api for setting private updated to use private attr, rather than public update_repository repo, options.merge({ :private => true }) end # Unhide a private repository # # @param repo [String, Hash, Repository] A GitHub repository # @return [Sawyer::Resource] Updated repository info def set_public(repo, options = {}) # GitHub Api for setting private updated to use private attr, rather than public update_repository repo, options.merge({ :private => false }) end # Get deploy keys on a repo # # Requires authenticated client. # # @param repo [String, Hash, Repository] A GitHub repository # @return [Array<Sawyer::Resource>] Array of hashes representing deploy keys. # @see http://developer.github.com/v3/repos/keys/#list # @example # @client.deploy_keys('octokit/octokit.rb') # @example # @client.list_deploy_keys('octokit/octokit.rb') def deploy_keys(repo, options = {}) paginate "repos/#{Repository.new repo}/keys", options end alias :list_deploy_keys :deploy_keys # Get a single deploy key for a repo # # @param repo [String, Hash, Repository] A GitHub repository. # @param id [Integer] Deploy key ID. # @return [Sawyer::Resource] Deploy key. # @see http://developer.github.com/v3/repos/keys/#get # @example # @client.deploy_key('octokit/octokit.rb', 8675309) def deploy_key(repo, id, options={}) get "repos/#{Repository.new repo}/keys/#{id}", options end # Add deploy key to a repo # # Requires authenticated client. # # @param repo [String, Hash, Repository] A GitHub repository. # @param title [String] Title reference for the deploy key. # @param key [String] Public key. # @return [Sawyer::Resource] Hash representing newly added key. # @see http://developer.github.com/v3/repos/keys/#create # @example # @client.add_deploy_key('octokit/octokit.rb', 'Staging server', 'ssh-rsa AAA...') def add_deploy_key(repo, title, key, options = {}) post "repos/#{Repository.new repo}/keys", options.merge(:title => title, :key => key) end # Edit a deploy key # # @param repo [String, Hash, Repository] A GitHub repository. # @param id [Integer] Deploy key ID. # @param options [Hash] Attributes to edit. # @option title [String] Key title. # @option key [String] Public key. # @return [Sawyer::Resource] Updated deploy key. # @see http://developer.github.com/v3/repos/keys/#edit # @example Update the key for a deploy key. # @client.edit_deploy_key('octokit/octokit.rb', 8675309, :key => 'ssh-rsa BBB...') # @example # @client.update_deploy_key('octokit/octokit.rb', 8675309, :title => 'Uber', :key => 'ssh-rsa BBB...')) def edit_deploy_key(repo, id, options) patch "repos/#{Repository.new repo}/keys/#{id}", options end alias :update_deploy_key :edit_deploy_key # Remove deploy key from a repo # # Requires authenticated client. # # @param repo [String, Hash, Repository] A GitHub repository. # @param id [Integer] Id of the deploy key to remove. # @return [Boolean] True if key removed, false otherwise. # @see http://developer.github.com/v3/repos/keys/#delete # @example # @client.remove_deploy_key('octokit/octokit.rb', 100000) def remove_deploy_key(repo, id, options = {}) boolean_from_response :delete, "repos/#{Repository.new repo}/keys/#{id}", options end # List collaborators # # Requires authenticated client for private repos. # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Array<Sawyer::Resource>] Array of hashes representing collaborating users. # @see http://developer.github.com/v3/repos/collaborators/#list # @example # Octokit.collaborators('octokit/octokit.rb') # @example # Octokit.collabs('octokit/octokit.rb') # @example # @client.collabs('octokit/octokit.rb') def collaborators(repo, options = {}) paginate "repos/#{Repository.new repo}/collaborators", options end alias :collabs :collaborators # Add collaborator to repo # # Requires authenticated client. # # @param repo [String, Hash, Repository] A GitHub repository. # @param collaborator [String] Collaborator GitHub username to add. # @return [Boolean] True if collaborator added, false otherwise. # @see http://developer.github.com/v3/repos/collaborators/#add-collaborator # @example # @client.add_collaborator('octokit/octokit.rb', 'holman') # @example # @client.add_collab('octokit/octokit.rb', 'holman') def add_collaborator(repo, collaborator, options = {}) boolean_from_response :put, "repos/#{Repository.new repo}/collaborators/#{collaborator}", options end alias :add_collab :add_collaborator # Remove collaborator from repo. # # Requires authenticated client. # # @param repo [String, Hash, Repository] A GitHub repository. # @param collaborator [String] Collaborator GitHub username to remove. # @return [Boolean] True if collaborator removed, false otherwise. # @see http://developer.github.com/v3/repos/collaborators/#remove-collaborator # @example # @client.remove_collaborator('octokit/octokit.rb', 'holman') # @example # @client.remove_collab('octokit/octokit.rb', 'holman') def remove_collaborator(repo, collaborator, options = {}) boolean_from_response :delete, "repos/#{Repository.new repo}/collaborators/#{collaborator}", options end alias :remove_collab :remove_collaborator # Checks if a user is a collaborator for a repo. # # Requires authenticated client. # # @param repo [String, Hash, Repository] A GitHub repository. # @param collaborator [String] Collaborator GitHub username to check. # @return [Boolean] True if user is a collaborator, false otherwise. # @see http://developer.github.com/v3/repos/collaborators/#get # @example # @client.collaborator?('octokit/octokit.rb', 'holman') def collaborator?(repo, collaborator, options={}) boolean_from_response :get, "repos/#{Repository.new repo}/collaborators/#{collaborator}", options end # List teams for a repo # # Requires authenticated client that is an owner or collaborator of the repo. # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Array<Sawyer::Resource>] Array of hashes representing teams. # @see http://developer.github.com/v3/repos/#list-teams # @example # @client.repository_teams('octokit/pengwynn') # @example # @client.repo_teams('octokit/pengwynn') # @example # @client.teams('octokit/pengwynn') def repository_teams(repo, options = {}) paginate "repos/#{Repository.new repo}/teams", options end alias :repo_teams :repository_teams alias :teams :repository_teams # List contributors to a repo # # Requires authenticated client for private repos. # # @param repo [String, Hash, Repository] A GitHub repository. # @param anon [Boolean] Set true to include annonymous contributors. # @return [Array<Sawyer::Resource>] Array of hashes representing users. # @see http://developer.github.com/v3/repos/#list-contributors # @example # Octokit.contributors('octokit/octokit.rb', true) # @example # Octokit.contribs('octokit/octokit.rb') # @example # @client.contribs('octokit/octokit.rb') def contributors(repo, anon = nil, options = {}) options[:anon] = 1 if anon.to_s[/1|true/] paginate "repos/#{Repository.new repo}/contributors", options end alias :contribs :contributors # List stargazers of a repo # # Requires authenticated client for private repos. # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Array<Sawyer::Resource>] Array of hashes representing users. # @see http://developer.github.com/v3/activity/starring/#list-stargazers # @example # Octokit.stargazers('octokit/octokit.rb') # @example # @client.stargazers('octokit/octokit.rb') def stargazers(repo, options = {}) paginate "repos/#{Repository.new repo}/stargazers", options end # @deprecated Use {#stargazers} instead # # List watchers of repo. # # Requires authenticated client for private repos. # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Array<Sawyer::Resource>] Array of hashes representing users. # @see http://developer.github.com/v3/repos/watching/#list-watchers # @example # Octokit.watchers('octokit/octokit.rb') # @example # @client.watchers('octokit/octokit.rb') def watchers(repo, options = {}) paginate "repos/#{Repository.new repo}/watchers", options end # List forks # # Requires authenticated client for private repos. # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Array<Sawyer::Resource>] Array of hashes representing repos. # @see http://developer.github.com/v3/repos/forks/#list-forks # @example # Octokit.forks('octokit/octokit.rb') # @example # Octokit.network('octokit/octokit.rb') # @example # @client.forks('octokit/octokit.rb') def forks(repo, options = {}) paginate "repos/#{Repository.new repo}/forks", options end alias :network :forks # List languages of code in the repo. # # Requires authenticated client for private repos. # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Array<Sawyer::Resource>] Array of Hashes representing languages. # @see http://developer.github.com/v3/repos/#list-languages # @example # Octokit.langauges('octokit/octokit.rb') # @example # @client.languages('octokit/octokit.rb') def languages(repo, options = {}) paginate "repos/#{Repository.new repo}/languages", options end # List tags # # Requires authenticated client for private repos. # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Array<Sawyer::Resource>] Array of hashes representing tags. # @see http://developer.github.com/v3/repos/#list-tags # @example # Octokit.tags('octokit/octokit.rb') # @example # @client.tags('octokit/octokit.rb') def tags(repo, options = {}) paginate "repos/#{Repository.new repo}/tags", options end # List branches # # Requires authenticated client for private repos. # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Array<Sawyer::Resource>] Array of hashes representing branches. # @see http://developer.github.com/v3/repos/#list-branches # @example # Octokit.branches('octokit/octokit.rb') # @example # @client.branches('octokit/octokit.rb') def branches(repo, options = {}) paginate "repos/#{Repository.new repo}/branches", options end # Get a single branch from a repository # # @param repo [String, Hash, Repository] A GitHub repository. # @param branch [String] Branch name # @return [Sawyer::Resource] The branch requested, if it exists # @see http://developer.github.com/v3/repos/#get-branch # @example Get branch 'master` from octokit/octokit.rb # Octokit.branch("octokit/octokit.rb", "master") def branch(repo, branch, options = {}) get "repos/#{Repository.new repo}/branches/#{branch}", options end alias :get_branch :branch # List repo hooks # # Requires authenticated client. # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Array<Sawyer::Resource>] Array of hashes representing hooks. # @see http://developer.github.com/v3/repos/hooks/#list # @example # @client.hooks('octokit/octokit.rb') def hooks(repo, options = {}) paginate "repos/#{Repository.new repo}/hooks", options end # Get single hook # # Requires authenticated client. # # @param repo [String, Hash, Repository] A GitHub repository. # @param id [Integer] Id of the hook to get. # @return [Sawyer::Resource] Hash representing hook. # @see http://developer.github.com/v3/repos/hooks/#get-single-hook # @example # @client.hook('octokit/octokit.rb', 100000) def hook(repo, id, options = {}) get "repos/#{Repository.new repo}/hooks/#{id}", options end # Create a hook # # Requires authenticated client. # # @param repo [String, Hash, Repository] A GitHub repository. # @param name [String] The name of the service that is being called. See # {https://api.github.com/hooks Hooks} for the possible names. # @param config [Hash] A Hash containing key/value pairs to provide # settings for this hook. These settings vary between the services and # are defined in the {https://github.com/github/github-services github-services} repo. # @option options [Array<String>] :events ('["push"]') Determines what # events the hook is triggered for. # @option options [Boolean] :active Determines whether the hook is # actually triggered on pushes. # @return [Sawyer::Resource] Hook info for the new hook # @see https://api.github.com/hooks # @see https://github.com/github/github-services # @see http://developer.github.com/v3/repos/hooks/#create-a-hook # @example # @client.create_hook( # 'octokit/octokit.rb', # 'web', # { # :url => 'http://something.com/webhook', # :content_type => 'json' # }, # { # :events => ['push', 'pull_request'], # :active => true # } # ) def create_hook(repo, name, config, options = {}) options = {:name => name, :config => config, :events => ["push"], :active => true}.merge(options) post "repos/#{Repository.new repo}/hooks", options end # Edit a hook # # Requires authenticated client. # # @param repo [String, Hash, Repository] A GitHub repository. # @param id [Integer] Id of the hook being updated. # @param name [String] The name of the service that is being called. See # {https://api.github.com/hooks Hooks} for the possible names. # @param config [Hash] A Hash containing key/value pairs to provide # settings for this hook. These settings vary between the services and # are defined in the {https://github.com/github/github-services github-services} repo. # @option options [Array<String>] :events ('["push"]') Determines what # events the hook is triggered for. # @option options [Array<String>] :add_events Determines a list of events # to be added to the list of events that the Hook triggers for. # @option options [Array<String>] :remove_events Determines a list of events # to be removed from the list of events that the Hook triggers for. # @option options [Boolean] :active Determines whether the hook is # actually triggered on pushes. # @return [Sawyer::Resource] Hook info for the updated hook # @see https://api.github.com/hooks # @see https://github.com/github/github-services # @see http://developer.github.com/v3/repos/hooks/#edit-a-hook # @example # @client.edit_hook( # 'octokit/octokit.rb', # 100000, # 'web', # { # :url => 'http://something.com/webhook', # :content_type => 'json' # }, # { # :add_events => ['status'], # :remove_events => ['pull_request'], # :active => true # } # ) def edit_hook(repo, id, name, config, options = {}) options = {:name => name, :config => config, :events => ["push"], :active => true}.merge(options) patch "repos/#{Repository.new repo}/hooks/#{id}", options end # Delete hook # # Requires authenticated client. # # @param repo [String, Hash, Repository] A GitHub repository. # @param id [Integer] Id of the hook to remove. # @return [Boolean] True if hook removed, false otherwise. # @see http://developer.github.com/v3/repos/hooks/#delete-a-hook # @example # @client.remove_hook('octokit/octokit.rb', 1000000) def remove_hook(repo, id, options = {}) boolean_from_response :delete, "repos/#{Repository.new repo}/hooks/#{id}", options end # Test hook # # Requires authenticated client. # # @param repo [String, Hash, Repository] A GitHub repository. # @param id [Integer] Id of the hook to test. # @return [Boolean] Success # @see http://developer.github.com/v3/repos/hooks/#test-a-push-hook # @example # @client.test_hook('octokit/octokit.rb', 1000000) def test_hook(repo, id, options = {}) boolean_from_response :post, "repos/#{Repository.new repo}/hooks/#{id}/tests", options end # List users available for assigning to issues. # # Requires authenticated client for private repos. # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Array<Sawyer::Resource>] Array of hashes representing users. # @see http://developer.github.com/v3/issues/assignees/#list-assignees # @example # Octokit.repository_assignees('octokit/octokit.rb') # @example # Octokit.repo_assignees('octokit/octokit.rb') # @example # @client.repository_assignees('octokit/octokit.rb') def repository_assignees(repo, options = {}) paginate "repos/#{Repository.new repo}/assignees", options end alias :repo_assignees :repository_assignees # Check to see if a particular user is an assignee for a repository. # # @param repo [String, Hash, Repository] A GitHub repository. # @param assignee [String] User login to check # @return [Boolean] True if assignable on project, false otherwise. # @see http://developer.github.com/v3/issues/assignees/#check-assignee # @example # Octokit.check_assignee('octokit/octokit.rb', 'andrew') def check_assignee(repo, assignee, options = {}) boolean_from_response :get, "repos/#{Repository.new repo}/assignees/#{assignee}", options end # List watchers subscribing to notifications for a repo # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Array<Sawyer::Resource>] Array of users watching. # @see http://developer.github.com/v3/activity/watching/#list-watchers # @example # @client.subscribers("octokit/octokit.rb") def subscribers(repo, options = {}) paginate "repos/#{Repository.new repo}/subscribers", options end # Get a repository subscription # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Sawyer::Resource] Repository subscription. # @see http://developer.github.com/v3/activity/watching/#get-a-repository-subscription # @example # @client.subscription("octokit/octokit.rb") def subscription(repo, options = {}) get "repos/#{Repository.new repo}/subscription", options end # Update repository subscription # # @param repo [String, Hash, Repository] A GitHub repository. # @param options [Hash] # # @option options [Boolean] :subscribed Determines if notifications # should be received from this repository. # @option options [Boolean] :ignored Deterimines if all notifications # should be blocked from this repository. # @return [Sawyer::Resource] Updated repository subscription. # @see http://developer.github.com/v3/activity/watching/#set-a-repository-subscription # @example Subscribe to notifications for a repository # @client.update_subscription("octokit/octokit.rb", {subscribed: true}) def update_subscription(repo, options = {}) put "repos/#{Repository.new repo}/subscription", options end # Delete a repository subscription # # @param repo [String, Hash, Repository] A GitHub repository. # @return [Boolean] True if subscription deleted, false otherwise. # @see http://developer.github.com/v3/activity/watching/#delete-a-repository-subscription # # @example # @client.delete_subscription("octokit/octokit.rb") def delete_subscription(repo, options = {}) boolean_from_response :delete, "repos/#{Repository.new repo}/subscription", options end end end end
mit
blendee/blendee
src/main/java/org/blendee/assist/Values.java
4544
package org.blendee.assist; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.UUID; import org.blendee.sql.Bindable; import org.blendee.sql.Binder; import org.blendee.sql.Column; import org.blendee.sql.InsertDMLBuilder; import org.blendee.sql.binder.BigDecimalBinder; import org.blendee.sql.binder.BooleanBinder; import org.blendee.sql.binder.DoubleBinder; import org.blendee.sql.binder.FloatBinder; import org.blendee.sql.binder.IntBinder; import org.blendee.sql.binder.LongBinder; import org.blendee.sql.binder.StringBinder; import org.blendee.sql.binder.TimestampBinder; import org.blendee.sql.binder.UUIDBinder; /** * INSERT 文の VALUES 句の値を個別にセットするためのサポートクラスです。 * @author 千葉 哲嗣 */ public class Values { private final InsertDMLBuilder builder; private final LinkedList<Column> columns; Values(InsertDMLBuilder builder, List<Column> columns) { this.builder = builder; this.columns = new LinkedList<>(columns); } /** * INSERT VALUES 句に値を追加します。 * @param value 代入値 * @return {@link SetProof} */ public Values value(BigDecimal value) { return value(new BigDecimalBinder(value)); } /** * INSERT VALUES 句に値を追加します。 * @param value 代入値 * @return {@link SetProof} */ public Values value(boolean value) { return value(new BooleanBinder(value)); } /** * INSERT VALUES 句に値を追加します。 * @param value 代入値 * @return {@link SetProof} */ public Values value(double value) { return value(new DoubleBinder(value)); } /** * INSERT VALUES 句に値を追加します。 * @param value 代入値 * @return {@link SetProof} */ public Values value(float value) { return value(new FloatBinder(value)); } /** * INSERT VALUES 句に値を追加します。 * @param value 代入値 * @return {@link SetProof} */ public Values value(int value) { return value(new IntBinder(value)); } /** * INSERT VALUES 句に値を追加します。 * @param value 代入値 * @return {@link SetProof} */ public Values value(long value) { return value(new LongBinder(value)); } /** * INSERT VALUES 句に値を追加します。 * @param value 代入値 * @return {@link SetProof} */ public Values value(String value) { return value(new StringBinder(value)); } /** * INSERT VALUES 句に値を追加します。 * @param value 代入値 * @return {@link SetProof} */ public Values value(Timestamp value) { return value(new TimestampBinder(value)); } /** * INSERT VALUES 句に値を追加します。 * @param value 代入値 * @return {@link SetProof} */ public Values value(UUID value) { return value(new UUIDBinder(value)); } /** * INSERT VALUES 句に値を追加します。 * @param value 代入値 * @return {@link SetProof} */ public Values value(Bindable value) { builder.add(columnName(), value); return this; } /** * INSERT VALUES 句に値を追加します。 * @param template テンプレート * @param values テンプレートにセットする値 * @return {@link SetProof} */ public Values any(String template, Object... values) { var binders = new LinkedList<Binder>(); var extractor = new BinderExtractor(); Arrays.stream(values).forEach(v -> { binders.add(extractor.extract(v)); }); builder.addBindableSQLFragment( columnName(), template, binders.toArray(new Bindable[binders.size()])); return this; } /** * INSERT VALUES 句に値を追加します。 * @param sqlFragment SQL の断片 * @return {@link SetProof} */ public Values any(String sqlFragment) { builder.addSQLFragment(columnName(), sqlFragment); return this; } /** * UPDATE SET 句に、このカラムへの代入を追加します。 * @param subquery 代入値のためのサブクエリ * @return {@link SetProof} */ public Values value(SelectStatement subquery) { subquery.forSubquery(true); var queryBuilder = subquery.toSQLQueryBuilder(); Arrays.asList(queryBuilder.currentBinders()); builder.addBindableSQLFragment( columnName(), "(" + queryBuilder.sql() + ")", queryBuilder.currentBinders()); return this; } private String columnName() { //カラム数と値の数が違います if (columns.size() == 0) throw new IllegalStateException("columns size is 0"); return columns.pop().getName(); } }
mit
jmorg/synapse
SynapseBackend/synapseScore.py
1467
from vincenty import vincenty from collections import namedtuple import math def exponentialDecay(distance, maxDelta = 10, k = 1): return maxDelta * pow(math.e, -k * distance) def extractVoteFeatures(vote): voteCoef = 1 if vote['vote'] == "\'verify\'" else -1 voteLocation = (vote['location_lat'], vote['location_long']) return voteCoef, voteLocation def extractEventFeatures(event): eventLocation = (event['location_lat'], event['location_long']) lastVerifyScore = event['last_verify_score'] currScore = event['current_score'] lastVerifyTime = event['last_verify_time'] return eventLocation, currScore, lastVerifyScore, lastVerifyTime def updateScoreVote(vote, event, maxScore = 100): voteCoef, voteLocation = extractVoteFeatures(vote) eventLocation, currScore, lastVerifyScore, lastVerifyTime = extractEventFeatures(event) distance = vincenty(eventLocation, voteLocation, miles = True) if voteCoef == 1: lastVerifyTime = vote['time'] distanceMulti = exponentialDecay(distance) currScore = currScore + (voteCoef * distanceMulti) if currScore > maxScore: currScore = maxScore if voteCoef == 1: lastVerifyScore = currScore return currScore, lastVerifyScore, lastVerifyTime def updateScoreTime(currScore, currTime, lastVerifyTime, threshold = 10): timeDiff = (currTime - lastVerifyTime).seconds secondThreshold = threshold * 60 if timeDiff < secondThreshold: return currScore = currScore - (timeDiff / secondThreshold) return currScore
mit
kalinalazarova1/TelerikAcademy
Programming/6. Databases/06.ADO.NET/ADO.NET/10.SQLite/Properties/AssemblyInfo.cs
1394
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("10.SQLite")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("10.SQLite")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("02bface1-b8e7-4c08-9f48-273e0cec98b0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
dwmkerr/node-docker-mircroservice
users-service/repository/repository.js
2119
// repository.js // // Exposes a single function - 'connect', which returns // a connected repository. Call 'disconnect' on this object when you're done. 'use strict'; var mysql = require('mysql'); // Class which holds an open connection to a repository // and exposes some simple functions for accessing data. class Repository { constructor(connectionSettings) { this.connectionSettings = connectionSettings; this.connection = mysql.createConnection(this.connectionSettings); } getUsers() { return new Promise((resolve, reject) => { this.connection.query('SELECT email, phone_number FROM directory', (err, results) => { if(err) { return reject(new Error('An error occured getting the users: ' + err)); } resolve((results || []).map((user) => { return { email: user.email, phone_number: user.phone_number }; })); }); }); } getUserByEmail(email) { return new Promise((resolve, reject) => { // Fetch the customer. this.connection.query('SELECT email, phone_number FROM directory WHERE email = ?', [email], (err, results) => { if(err) { return reject(new Error('An error occured getting the user: ' + err)); } if(results.length === 0) { resolve(undefined); } else { resolve({ email: results[0].email, phone_number: results[0].phone_number }); } }); }); } disconnect() { this.connection.end(); } } // One and only exported function, returns a connected repo. module.exports.connect = (connectionSettings) => { return new Promise((resolve, reject) => { if(!connectionSettings.host) throw new Error("A host must be specified."); if(!connectionSettings.user) throw new Error("A user must be specified."); if(!connectionSettings.password) throw new Error("A password must be specified."); if(!connectionSettings.port) throw new Error("A port must be specified."); resolve(new Repository(connectionSettings)); }); };
mit
DecodeGenetics/graphtyper
src/graph/ref.cpp
604
#include <vector> #include <graphtyper/constants.hpp> #include <graphtyper/graph/ref.hpp> namespace gyper { Ref::Ref(std::vector<char> && _seq) : seq(std::forward<std::vector<char>>(_seq)) { } Ref::Ref(std::vector<char> const & _seq) : seq(_seq) { } Ref::Ref(std::initializer_list<char> l) : seq(l) { } void Ref::clear() { seq.clear(); events.clear(); // anti_events.clear(); } bool Ref::operator==(Ref const & o) { return seq == o.seq; } bool Ref::operator!=(Ref const & o) { return !(seq == o.seq); } bool Ref::operator<(Ref const & o) { return seq < o.seq; } } // namespace gyper
mit
stonedz/pff2
src/modules/logger/Abs/ALogger.php
922
<?php namespace pff\modules\Abs; /** * Abstract class that must be exteded by any logger. * * @author paolo.fagni<at>gmail.com */ abstract class ALogger { // Log levels const LVL_NORM = 0; const LVL_ERR = 1; const LVL_FATAL = 2; /** * Log level names * * @var string[] */ protected $_levelNames; /** * Debug mode * * @var bool */ protected $_debugActive; public function __construct($debugActive = false) { $this->_debugActive = $debugActive; $this->_levelNames[self::LVL_NORM] = 'NORMAL'; $this->_levelNames[self::LVL_ERR] = 'ERROR'; $this->_levelNames[self::LVL_FATAL] = 'FATAL'; } /** * Logs a message * * @param string $message Message to log * @param int $level Level to log the message */ abstract public function logMessage($message, $level = 0); }
mit
kaukulpr/nsdk
Job Postings/Global.asax.cs
573
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace Job_Postings { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
mit
blackfireio/php-sdk
src/Blackfire/LoopClient.php
6596
<?php /* * This file is part of the Blackfire SDK package. * * (c) Blackfire <support@blackfire.io> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Blackfire; use Blackfire\Exception\LogicException; use Blackfire\Exception\RuntimeException; use Blackfire\Profile\Configuration as ProfileConfiguration; class LoopClient { private $client; private $maxIterations; private $currentIteration = 0; private $probe; private $signal = false; private $enabled = true; private $reference = false; private $referenceId; private $running = false; private $build; private $scenario; private $buildFactory; private $env = false; /** * @param int $maxIterations The number of iterations */ public function __construct(Client $client, $maxIterations) { $this->client = $client; $this->maxIterations = $maxIterations; } /** * @param int $signal A signal that triggers profiling (like SIGUSR1) */ public function setSignal($signal) { if (!extension_loaded('pcntl')) { throw new RuntimeException('pcntl must be available to use signals.'); } $enabled = &$this->enabled; pcntl_signal($signal, function ($signo) use (&$enabled) { $enabled = true; }); $this->signal = true; $this->enabled = false; } /** * @param int $signal A signal that triggers profiling for a reference (like SIGUSR2) * * @deprecated since 1.18, to be removed in 2.0. */ public function promoteReferenceSignal($signal) { @trigger_error('The method "promoteReferenceSignal" is deprecated since blackfire/php-sdk 1.18 and will be removed in 2.0.', E_USER_DEPRECATED); if (!$this->referenceId) { throw new LogicException('Cannot set signal to promote the reference without an attached reference (call attachReference() first).'); } if (!extension_loaded('pcntl')) { throw new RuntimeException('pcntl must be available to use signals.'); } if (null === $this->signal) { throw new LogicException('Cannot set a reference signal without a signal.'); } $reference = &$this->reference; $enabled = &$this->enabled; pcntl_signal($signal, function ($signo) use (&$enabled, &$reference) { $reference = true; $enabled = true; }); } /** * @param int $referenceId The reference ID to use (rolling reference) * * @deprecated since 1.18, to be removed in 2.0. */ public function attachReference($referenceId) { @trigger_error('The method "attachReference" is deprecated since blackfire/php-sdk 1.18 and will be removed in 2.0.', E_USER_DEPRECATED); $this->referenceId = $referenceId; } /** * @param string|null $env The environment name (or null to use the one configured on the client) * @param callable|null $buildFactory An optional factory callable that creates build instances */ public function generateBuilds($env = null, $buildFactory = null) { $this->env = $env; $this->buildFactory = $buildFactory; } public function startLoop(ProfileConfiguration $config = null) { if ($this->signal) { pcntl_signal_dispatch(); } if (!$this->enabled) { return; } if ($this->running) { throw new LogicException('Unable to start a loop as one is already running.'); } $this->running = true; if (0 === $this->currentIteration) { $this->probe = $this->createProbe($config); } $this->probe->enable(); } /** * @return Profile|null */ public function endLoop() { if (!$this->enabled) { return; } if (null === $this->probe) { return; } if (!$this->running) { throw new LogicException('Unable to stop a loop as none is running.'); } $this->running = false; $this->probe->close(); ++$this->currentIteration; if ($this->currentIteration === $this->maxIterations) { return $this->endProbe(); } } /** * @return Build|Build\Build */ protected function createBuild($env = null) { if ($this->buildFactory) { $build = call_user_func($this->buildFactory, $this->client, $env); if ($build instanceof Build) { @trigger_error('The buildFactory passed to "generateBuilds" must returns an instance of \Blackfire\Build\Build. Returning an instance of \Blackfire\Build is deprecated since blackfire/php-sdk 1.14 and will be removed in 2.0.', E_USER_DEPRECATED); } return $build; } return $this->client->startBuild($env); } private function createProbe($config) { if (null === $config) { $config = new ProfileConfiguration(); } else { $config = clone $config; } $config->setSamples($this->maxIterations); if (null !== $this->referenceId) { $config->setReference($this->referenceId); } if ($this->reference) { $config->setAsReference(); } if (false !== $this->env) { $this->build = $this->createBuild($this->env); if ($this->build instanceof Build) { // BC $config->setBuild($this->build); } else { $this->scenario = $this->client->startScenario($this->build); $config->setScenario($this->scenario); } } return $this->client->createProbe($config, false); } private function endProbe() { $this->currentIteration = 0; if ($this->signal) { $this->enabled = false; $this->reference = false; } $profile = $this->client->endProbe($this->probe); if (null !== $this->scenario) { $this->client->closeScenario($this->scenario); $this->client->closeBuild($this->build); $this->scenario = null; $this->build = null; } if (null !== $this->build) { $this->client->endBuild($this->build); $this->build = null; } return $profile; } }
mit
OGRECave/ogre
OgreMain/src/OgreMesh.cpp
100788
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreSkeletonManager.h" #include "OgreEdgeListBuilder.h" #include "OgreAnimation.h" #include "OgreAnimationState.h" #include "OgreAnimationTrack.h" #include "OgreOptimisedUtil.h" #include "OgreTangentSpaceCalc.h" #include "OgreLodStrategyManager.h" #include "OgrePixelCountLodStrategy.h" namespace Ogre { //----------------------------------------------------------------------- Mesh::Mesh(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader) : Resource(creator, name, handle, group, isManual, loader), mBoundRadius(0.0f), mBoneBoundingRadius(0.0f), mBoneAssignmentsOutOfDate(false), mLodStrategy(LodStrategyManager::getSingleton().getDefaultStrategy()), mHasManualLodLevel(false), mNumLods(1), mBufferManager(0), mVertexBufferUsage(HardwareBuffer::HBU_STATIC_WRITE_ONLY), mIndexBufferUsage(HardwareBuffer::HBU_STATIC_WRITE_ONLY), mVertexBufferShadowBuffer(false), mIndexBufferShadowBuffer(false), mPreparedForShadowVolumes(false), mEdgeListsBuilt(false), mAutoBuildEdgeLists(true), // will be set to false by serializers of 1.30 and above mSharedVertexDataAnimationType(VAT_NONE), mSharedVertexDataAnimationIncludesNormals(false), mAnimationTypesDirty(true), mPosesIncludeNormals(false), sharedVertexData(0) { // Init first (manual) lod MeshLodUsage lod; lod.userValue = 0; // User value not used for base LOD level lod.value = getLodStrategy()->getBaseValue(); lod.edgeData = NULL; lod.manualMesh.reset(); mMeshLodUsageList.push_back(lod); } //----------------------------------------------------------------------- Mesh::~Mesh() { // have to call this here reather than in Resource destructor // since calling virtual methods in base destructors causes crash unload(); } //----------------------------------------------------------------------- HardwareBufferManagerBase* Mesh::getHardwareBufferManager() { return mBufferManager ? mBufferManager : HardwareBufferManager::getSingletonPtr(); } //----------------------------------------------------------------------- SubMesh* Mesh::createSubMesh() { SubMesh* sub = OGRE_NEW SubMesh(); sub->parent = this; mSubMeshList.push_back(sub); if (isLoaded()) _dirtyState(); return sub; } //----------------------------------------------------------------------- SubMesh* Mesh::createSubMesh(const String& name) { SubMesh *sub = createSubMesh(); nameSubMesh(name, (ushort)mSubMeshList.size()-1); return sub ; } //----------------------------------------------------------------------- void Mesh::destroySubMesh(unsigned short index) { OgreAssert(index < mSubMeshList.size(), ""); SubMeshList::iterator i = mSubMeshList.begin(); std::advance(i, index); OGRE_DELETE *i; mSubMeshList.erase(i); // Fix up any name/index entries for(SubMeshNameMap::iterator ni = mSubMeshNameMap.begin(); ni != mSubMeshNameMap.end();) { if (ni->second == index) { SubMeshNameMap::iterator eraseIt = ni++; mSubMeshNameMap.erase(eraseIt); } else { // reduce indexes following if (ni->second > index) ni->second = ni->second - 1; ++ni; } } // fix edge list data by simply recreating all edge lists if( mEdgeListsBuilt) { this->freeEdgeList(); this->buildEdgeList(); } if (isLoaded()) _dirtyState(); } //----------------------------------------------------------------------- void Mesh::destroySubMesh(const String& name) { unsigned short index = _getSubMeshIndex(name); destroySubMesh(index); } //--------------------------------------------------------------------- void Mesh::nameSubMesh(const String& name, ushort index) { mSubMeshNameMap[name] = index ; } //--------------------------------------------------------------------- void Mesh::unnameSubMesh(const String& name) { SubMeshNameMap::iterator i = mSubMeshNameMap.find(name); if (i != mSubMeshNameMap.end()) mSubMeshNameMap.erase(i); } //----------------------------------------------------------------------- SubMesh* Mesh::getSubMesh(const String& name) const { ushort index = _getSubMeshIndex(name); return getSubMesh(index); } //----------------------------------------------------------------------- void Mesh::postLoadImpl(void) { // Prepare for shadow volumes? if (MeshManager::getSingleton().getPrepareAllMeshesForShadowVolumes()) { if (mEdgeListsBuilt || mAutoBuildEdgeLists) { prepareForShadowVolume(); } if (!mEdgeListsBuilt && mAutoBuildEdgeLists) { buildEdgeList(); } } #if !OGRE_NO_MESHLOD // The loading process accesses LOD usages directly, so // transformation of user values must occur after loading is complete. // Transform user LOD values (starting at index 1, no need to transform base value) for (MeshLodUsageList::iterator i = mMeshLodUsageList.begin() + 1; i != mMeshLodUsageList.end(); ++i) i->value = mLodStrategy->transformUserValue(i->userValue); // Rewrite first value mMeshLodUsageList[0].value = mLodStrategy->getBaseValue(); #endif } //----------------------------------------------------------------------- void Mesh::prepareImpl() { // Load from specified 'name' if (getCreator()->getVerbose()) LogManager::getSingleton().logMessage("Mesh: Loading "+mName+"."); mFreshFromDisk = ResourceGroupManager::getSingleton().openResource( mName, mGroup, this); // fully prebuffer into host RAM mFreshFromDisk = DataStreamPtr(OGRE_NEW MemoryDataStream(mName,mFreshFromDisk)); } //----------------------------------------------------------------------- void Mesh::unprepareImpl() { mFreshFromDisk.reset(); } void Mesh::loadImpl() { // If the only copy is local on the stack, it will be cleaned // up reliably in case of exceptions, etc DataStreamPtr data(mFreshFromDisk); mFreshFromDisk.reset(); if (!data) { OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Data doesn't appear to have been prepared in " + mName, "Mesh::loadImpl()"); } String baseName, strExt; StringUtil::splitBaseFilename(mName, baseName, strExt); auto codec = Codec::getCodec(strExt); if (!codec) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "No codec found to load " + mName); codec->decode(data, this); } //----------------------------------------------------------------------- void Mesh::unloadImpl() { // Teardown submeshes for (SubMeshList::iterator i = mSubMeshList.begin(); i != mSubMeshList.end(); ++i) { OGRE_DELETE *i; } if (sharedVertexData) { OGRE_DELETE sharedVertexData; sharedVertexData = NULL; } // Clear SubMesh lists mSubMeshList.clear(); mSubMeshNameMap.clear(); freeEdgeList(); #if !OGRE_NO_MESHLOD // Removes all LOD data removeLodLevels(); #endif mPreparedForShadowVolumes = false; // remove all poses & animations removeAllAnimations(); removeAllPoses(); // Clear bone assignments mBoneAssignments.clear(); mBoneAssignmentsOutOfDate = false; // Removes reference to skeleton setSkeletonName(BLANKSTRING); } //----------------------------------------------------------------------- void Mesh::reload(LoadingFlags flags) { bool wasPreparedForShadowVolumes = mPreparedForShadowVolumes; bool wasEdgeListsBuilt = mEdgeListsBuilt; bool wasAutoBuildEdgeLists = mAutoBuildEdgeLists; Resource::reload(flags); if(flags & LF_PRESERVE_STATE) { if(wasPreparedForShadowVolumes) prepareForShadowVolume(); if(wasEdgeListsBuilt) buildEdgeList(); setAutoBuildEdgeLists(wasAutoBuildEdgeLists); } } //----------------------------------------------------------------------- MeshPtr Mesh::clone(const String& newName, const String& newGroup) { // This is a bit like a copy constructor, but with the additional aspect of registering the clone with // the MeshManager // New Mesh is assumed to be manually defined rather than loaded since you're cloning it for a reason String theGroup = newGroup.empty() ? this->getGroup() : newGroup; MeshPtr newMesh = MeshManager::getSingleton().createManual(newName, theGroup); if(!newMesh) // interception by collision handler return newMesh; newMesh->mBufferManager = mBufferManager; newMesh->mVertexBufferUsage = mVertexBufferUsage; newMesh->mIndexBufferUsage = mIndexBufferUsage; newMesh->mVertexBufferShadowBuffer = mVertexBufferShadowBuffer; newMesh->mIndexBufferShadowBuffer = mIndexBufferShadowBuffer; // Copy submeshes first std::vector<SubMesh*>::iterator subi; for (subi = mSubMeshList.begin(); subi != mSubMeshList.end(); ++subi) { (*subi)->clone("", newMesh.get()); } // Copy shared geometry and index map, if any if (sharedVertexData) { newMesh->sharedVertexData = sharedVertexData->clone(true, mBufferManager); newMesh->sharedBlendIndexToBoneIndexMap = sharedBlendIndexToBoneIndexMap; } // Copy submesh names newMesh->mSubMeshNameMap = mSubMeshNameMap ; // Copy any bone assignments newMesh->mBoneAssignments = mBoneAssignments; newMesh->mBoneAssignmentsOutOfDate = mBoneAssignmentsOutOfDate; // Copy bounds newMesh->mAABB = mAABB; newMesh->mBoundRadius = mBoundRadius; newMesh->mBoneBoundingRadius = mBoneBoundingRadius; newMesh->mAutoBuildEdgeLists = mAutoBuildEdgeLists; newMesh->mEdgeListsBuilt = mEdgeListsBuilt; #if !OGRE_NO_MESHLOD newMesh->mHasManualLodLevel = mHasManualLodLevel; newMesh->mLodStrategy = mLodStrategy; newMesh->mNumLods = mNumLods; newMesh->mMeshLodUsageList = mMeshLodUsageList; #endif // Unreference edge lists, otherwise we'll delete the same lot twice, build on demand MeshLodUsageList::iterator lodi, lodOldi; lodOldi = mMeshLodUsageList.begin(); for (lodi = newMesh->mMeshLodUsageList.begin(); lodi != newMesh->mMeshLodUsageList.end(); ++lodi, ++lodOldi) { MeshLodUsage& newLod = *lodi; MeshLodUsage& lod = *lodOldi; newLod.manualName = lod.manualName; newLod.userValue = lod.userValue; newLod.value = lod.value; if (lod.edgeData) { newLod.edgeData = lod.edgeData->clone(); } } newMesh->mSkeleton = mSkeleton; // Keep prepared shadow volume info (buffers may already be prepared) newMesh->mPreparedForShadowVolumes = mPreparedForShadowVolumes; newMesh->mEdgeListsBuilt = mEdgeListsBuilt; // Clone vertex animation for (AnimationList::iterator i = mAnimationsList.begin(); i != mAnimationsList.end(); ++i) { Animation *newAnim = i->second->clone(i->second->getName()); newMesh->mAnimationsList[i->second->getName()] = newAnim; } // Clone pose list for (PoseList::iterator i = mPoseList.begin(); i != mPoseList.end(); ++i) { Pose* newPose = (*i)->clone(); newMesh->mPoseList.push_back(newPose); } newMesh->mSharedVertexDataAnimationType = mSharedVertexDataAnimationType; newMesh->mAnimationTypesDirty = true; newMesh->load(); newMesh->touch(); return newMesh; } //----------------------------------------------------------------------- const AxisAlignedBox& Mesh::getBounds(void) const { return mAABB; } //----------------------------------------------------------------------- void Mesh::_setBounds(const AxisAlignedBox& bounds, bool pad) { mAABB = bounds; mBoundRadius = Math::boundingRadiusFromAABB(mAABB); if( mAABB.isFinite() ) { Vector3 max = mAABB.getMaximum(); Vector3 min = mAABB.getMinimum(); if (pad) { // Pad out the AABB a little, helps with most bounds tests Vector3 scaler = (max - min) * MeshManager::getSingleton().getBoundsPaddingFactor(); mAABB.setExtents(min - scaler, max + scaler); // Pad out the sphere a little too mBoundRadius = mBoundRadius + (mBoundRadius * MeshManager::getSingleton().getBoundsPaddingFactor()); } } } //----------------------------------------------------------------------- void Mesh::_setBoundingSphereRadius(Real radius) { mBoundRadius = radius; } //----------------------------------------------------------------------- void Mesh::_setBoneBoundingRadius(Real radius) { mBoneBoundingRadius = radius; } //----------------------------------------------------------------------- void Mesh::_updateBoundsFromVertexBuffers(bool pad) { bool extendOnly = false; // First time we need full AABB of the given submesh, but on the second call just extend that one. if (sharedVertexData){ _calcBoundsFromVertexBuffer(sharedVertexData, mAABB, mBoundRadius, extendOnly); extendOnly = true; } for (size_t i = 0; i < mSubMeshList.size(); i++){ if (mSubMeshList[i]->vertexData){ _calcBoundsFromVertexBuffer(mSubMeshList[i]->vertexData, mAABB, mBoundRadius, extendOnly); extendOnly = true; } } if (pad) { Vector3 max = mAABB.getMaximum(); Vector3 min = mAABB.getMinimum(); // Pad out the AABB a little, helps with most bounds tests Vector3 scaler = (max - min) * MeshManager::getSingleton().getBoundsPaddingFactor(); mAABB.setExtents(min - scaler, max + scaler); // Pad out the sphere a little too mBoundRadius = mBoundRadius + (mBoundRadius * MeshManager::getSingleton().getBoundsPaddingFactor()); } } void Mesh::_calcBoundsFromVertexBuffer(VertexData* vertexData, AxisAlignedBox& outAABB, Real& outRadius, bool extendOnly /*= false*/) { if (vertexData->vertexCount == 0) { if (!extendOnly) { outAABB = AxisAlignedBox(Vector3::ZERO, Vector3::ZERO); outRadius = 0; } return; } const VertexElement* elemPos = vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); HardwareVertexBufferSharedPtr vbuf = vertexData->vertexBufferBinding->getBuffer(elemPos->getSource()); HardwareBufferLockGuard vertexLock(vbuf, HardwareBuffer::HBL_READ_ONLY); unsigned char* vertex = static_cast<unsigned char*>(vertexLock.pData); if (!extendOnly){ // init values outRadius = 0; float* pFloat; elemPos->baseVertexPointerToElement(vertex, &pFloat); Vector3 basePos(pFloat[0], pFloat[1], pFloat[2]); outAABB.setExtents(basePos, basePos); } size_t vSize = vbuf->getVertexSize(); unsigned char* vEnd = vertex + vertexData->vertexCount * vSize; Real radiusSqr = outRadius * outRadius; // Loop through all vertices. for (; vertex < vEnd; vertex += vSize) { float* pFloat; elemPos->baseVertexPointerToElement(vertex, &pFloat); Vector3 pos(pFloat[0], pFloat[1], pFloat[2]); outAABB.getMinimum().makeFloor(pos); outAABB.getMaximum().makeCeil(pos); radiusSqr = std::max<Real>(radiusSqr, pos.squaredLength()); } outRadius = std::sqrt(radiusSqr); } //----------------------------------------------------------------------- void Mesh::setSkeletonName(const String& skelName) { if (skelName != getSkeletonName()) { if (skelName.empty()) { // No skeleton mSkeleton.reset(); } else { // Load skeleton try { mSkeleton = static_pointer_cast<Skeleton>(SkeletonManager::getSingleton().load(skelName, mGroup)); } catch (...) { mSkeleton.reset(); // Log this error String msg = "Unable to load skeleton '"; msg += skelName + "' for Mesh '" + mName + "'. This Mesh will not be animated."; LogManager::getSingleton().logError(msg); } } if (isLoaded()) _dirtyState(); } } //----------------------------------------------------------------------- void Mesh::addBoneAssignment(const VertexBoneAssignment& vertBoneAssign) { mBoneAssignments.emplace(vertBoneAssign.vertexIndex, vertBoneAssign); mBoneAssignmentsOutOfDate = true; } //----------------------------------------------------------------------- void Mesh::clearBoneAssignments(void) { mBoneAssignments.clear(); mBoneAssignmentsOutOfDate = true; } //----------------------------------------------------------------------- void Mesh::_initAnimationState(AnimationStateSet* animSet) { // Animation states for skeletal animation if (mSkeleton) { // Delegate to Skeleton mSkeleton->_initAnimationState(animSet); // Take the opportunity to update the compiled bone assignments _updateCompiledBoneAssignments(); } // Animation states for vertex animation for (AnimationList::iterator i = mAnimationsList.begin(); i != mAnimationsList.end(); ++i) { // Only create a new animation state if it doesn't exist // We can have the same named animation in both skeletal and vertex // with a shared animation state affecting both, for combined effects // The animations should be the same length if this feature is used! if (!animSet->hasAnimationState(i->second->getName())) { animSet->createAnimationState(i->second->getName(), 0.0, i->second->getLength()); } } } //--------------------------------------------------------------------- void Mesh::_refreshAnimationState(AnimationStateSet* animSet) { if (mSkeleton) { mSkeleton->_refreshAnimationState(animSet); } // Merge in any new vertex animations AnimationList::iterator i; for (i = mAnimationsList.begin(); i != mAnimationsList.end(); ++i) { Animation* anim = i->second; // Create animation at time index 0, default params mean this has weight 1 and is disabled const String& animName = anim->getName(); if (!animSet->hasAnimationState(animName)) { animSet->createAnimationState(animName, 0.0, anim->getLength()); } else { // Update length incase changed AnimationState* animState = animSet->getAnimationState(animName); animState->setLength(anim->getLength()); animState->setTimePosition(std::min(anim->getLength(), animState->getTimePosition())); } } } //----------------------------------------------------------------------- void Mesh::_updateCompiledBoneAssignments(void) { if (mBoneAssignmentsOutOfDate) _compileBoneAssignments(); SubMeshList::iterator i; for (i = mSubMeshList.begin(); i != mSubMeshList.end(); ++i) { if ((*i)->mBoneAssignmentsOutOfDate) { (*i)->_compileBoneAssignments(); } } } //----------------------------------------------------------------------- typedef std::multimap<Real, Mesh::VertexBoneAssignmentList::iterator> WeightIteratorMap; unsigned short Mesh::_rationaliseBoneAssignments(size_t vertexCount, Mesh::VertexBoneAssignmentList& assignments) { // Iterate through, finding the largest # bones per vertex unsigned short maxBones = 0; bool existsNonSkinnedVertices = false; VertexBoneAssignmentList::iterator i; for (size_t v = 0; v < vertexCount; ++v) { // Get number of entries for this vertex short currBones = static_cast<unsigned short>(assignments.count(v)); if (currBones <= 0) existsNonSkinnedVertices = true; // Deal with max bones update // (note this will record maxBones even if they exceed limit) if (maxBones < currBones) maxBones = currBones; // does the number of bone assignments exceed limit? if (currBones > OGRE_MAX_BLEND_WEIGHTS) { // To many bone assignments on this vertex // Find the start & end (end is in iterator terms ie exclusive) std::pair<VertexBoneAssignmentList::iterator, VertexBoneAssignmentList::iterator> range; // map to sort by weight WeightIteratorMap weightToAssignmentMap; range = assignments.equal_range(v); // Add all the assignments to map for (i = range.first; i != range.second; ++i) { // insert value weight->iterator weightToAssignmentMap.emplace(i->second.weight, i); } // Reverse iterate over weight map, remove lowest n unsigned short numToRemove = currBones - OGRE_MAX_BLEND_WEIGHTS; WeightIteratorMap::iterator remIt = weightToAssignmentMap.begin(); while (numToRemove--) { // Erase this one assignments.erase(remIt->second); ++remIt; } } // if (currBones > OGRE_MAX_BLEND_WEIGHTS) // Make sure the weights are normalised // Do this irrespective of whether we had to remove assignments or not // since it gives us a guarantee that weights are normalised // We assume this, so it's a good idea since some modellers may not std::pair<VertexBoneAssignmentList::iterator, VertexBoneAssignmentList::iterator> normalise_range = assignments.equal_range(v); Real totalWeight = 0; // Find total first for (i = normalise_range.first; i != normalise_range.second; ++i) { totalWeight += i->second.weight; } // Now normalise if total weight is outside tolerance if (!Math::RealEqual(totalWeight, 1.0f)) { for (i = normalise_range.first; i != normalise_range.second; ++i) { i->second.weight = i->second.weight / totalWeight; } } } if (maxBones > OGRE_MAX_BLEND_WEIGHTS) { // Warn that we've reduced bone assignments LogManager::getSingleton().logWarning("the mesh '" + mName + "' " "includes vertices with more than " + StringConverter::toString(OGRE_MAX_BLEND_WEIGHTS) + " bone assignments. " "The lowest weighted assignments beyond this limit have been removed, so " "your animation may look slightly different. To eliminate this, reduce " "the number of bone assignments per vertex on your mesh to " + StringConverter::toString(OGRE_MAX_BLEND_WEIGHTS) + "."); // we've adjusted them down to the max maxBones = OGRE_MAX_BLEND_WEIGHTS; } if (existsNonSkinnedVertices) { // Warn that we've non-skinned vertices LogManager::getSingleton().logWarning("the mesh '" + mName + "' " "includes vertices without bone assignments. Those vertices will " "transform to wrong position when skeletal animation enabled. " "To eliminate this, assign at least one bone assignment per vertex " "on your mesh."); } return maxBones; } //----------------------------------------------------------------------- void Mesh::_compileBoneAssignments(void) { if (sharedVertexData) { unsigned short maxBones = _rationaliseBoneAssignments(sharedVertexData->vertexCount, mBoneAssignments); if (maxBones != 0) { compileBoneAssignments(mBoneAssignments, maxBones, sharedBlendIndexToBoneIndexMap, sharedVertexData); } } mBoneAssignmentsOutOfDate = false; } //--------------------------------------------------------------------- void Mesh::buildIndexMap(const VertexBoneAssignmentList& boneAssignments, IndexMap& boneIndexToBlendIndexMap, IndexMap& blendIndexToBoneIndexMap) { if (boneAssignments.empty()) { // Just in case boneIndexToBlendIndexMap.clear(); blendIndexToBoneIndexMap.clear(); return; } typedef std::set<unsigned short> BoneIndexSet; BoneIndexSet usedBoneIndices; // Collect actually used bones VertexBoneAssignmentList::const_iterator itVBA, itendVBA; itendVBA = boneAssignments.end(); for (itVBA = boneAssignments.begin(); itVBA != itendVBA; ++itVBA) { usedBoneIndices.insert(itVBA->second.boneIndex); } // Allocate space for index map blendIndexToBoneIndexMap.resize(usedBoneIndices.size()); boneIndexToBlendIndexMap.resize(*usedBoneIndices.rbegin() + 1); // Make index map between bone index and blend index BoneIndexSet::const_iterator itBoneIndex, itendBoneIndex; unsigned short blendIndex = 0; itendBoneIndex = usedBoneIndices.end(); for (itBoneIndex = usedBoneIndices.begin(); itBoneIndex != itendBoneIndex; ++itBoneIndex, ++blendIndex) { boneIndexToBlendIndexMap[*itBoneIndex] = blendIndex; blendIndexToBoneIndexMap[blendIndex] = *itBoneIndex; } } //--------------------------------------------------------------------- void Mesh::compileBoneAssignments( const VertexBoneAssignmentList& boneAssignments, unsigned short numBlendWeightsPerVertex, IndexMap& blendIndexToBoneIndexMap, VertexData* targetVertexData) { // Create or reuse blend weight / indexes buffer // Indices are always a UBYTE4 no matter how many weights per vertex VertexDeclaration* decl = targetVertexData->vertexDeclaration; VertexBufferBinding* bind = targetVertexData->vertexBufferBinding; unsigned short bindIndex; // Build the index map brute-force. It's possible to store the index map // in .mesh, but maybe trivial. IndexMap boneIndexToBlendIndexMap; buildIndexMap(boneAssignments, boneIndexToBlendIndexMap, blendIndexToBoneIndexMap); const VertexElement* testElem = decl->findElementBySemantic(VES_BLEND_INDICES); if (testElem) { // Already have a buffer, unset it & delete elements bindIndex = testElem->getSource(); // unset will cause deletion of buffer bind->unsetBinding(bindIndex); decl->removeElement(VES_BLEND_INDICES); decl->removeElement(VES_BLEND_WEIGHTS); } else { // Get new binding bindIndex = bind->getNextIndex(); } // type of Weights is settable on the MeshManager. VertexElementType weightsBaseType = MeshManager::getSingleton().getBlendWeightsBaseElementType(); VertexElementType weightsVertexElemType = VertexElement::multiplyTypeCount( weightsBaseType, numBlendWeightsPerVertex ); HardwareVertexBufferSharedPtr vbuf = getHardwareBufferManager()->createVertexBuffer( sizeof( unsigned char ) * 4 + VertexElement::getTypeSize( weightsVertexElemType ), targetVertexData->vertexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY, true // use shadow buffer ); // bind new buffer bind->setBinding(bindIndex, vbuf); const VertexElement *pIdxElem, *pWeightElem; // add new vertex elements // Note, insert directly after all elements using the same source as // position to abide by pre-Dx9 format restrictions const VertexElement* firstElem = decl->getElement(0); if(firstElem->getSemantic() == VES_POSITION) { unsigned short insertPoint = 1; while (insertPoint < decl->getElementCount() && decl->getElement(insertPoint)->getSource() == firstElem->getSource()) { ++insertPoint; } const VertexElement& idxElem = decl->insertElement(insertPoint, bindIndex, 0, VET_UBYTE4, VES_BLEND_INDICES); const VertexElement& wtElem = decl->insertElement(insertPoint+1, bindIndex, sizeof(unsigned char)*4, weightsVertexElemType, VES_BLEND_WEIGHTS); pIdxElem = &idxElem; pWeightElem = &wtElem; } else { // Position is not the first semantic, therefore this declaration is // not pre-Dx9 compatible anyway, so just tack it on the end const VertexElement& idxElem = decl->addElement(bindIndex, 0, VET_UBYTE4, VES_BLEND_INDICES); const VertexElement& wtElem = decl->addElement(bindIndex, sizeof(unsigned char)*4, weightsVertexElemType, VES_BLEND_WEIGHTS ); pIdxElem = &idxElem; pWeightElem = &wtElem; } unsigned int maxIntWt = 0; // keeping a switch out of the loop switch ( weightsBaseType ) { default: OgreAssert(false, "Invalid BlendWeightsBaseElementType"); break; case VET_FLOAT1: break; case VET_UBYTE4_NORM: maxIntWt = 0xff; break; case VET_USHORT2_NORM: maxIntWt = 0xffff; break; case VET_SHORT2_NORM: maxIntWt = 0x7fff; break; } // Assign data size_t v; VertexBoneAssignmentList::const_iterator i, iend; i = boneAssignments.begin(); iend = boneAssignments.end(); HardwareBufferLockGuard vertexLock(vbuf, HardwareBuffer::HBL_DISCARD); unsigned char *pBase = static_cast<unsigned char*>(vertexLock.pData); // Iterate by vertex for (v = 0; v < targetVertexData->vertexCount; ++v) { // collect the indices/weights in these arrays unsigned char indices[ 4 ] = { 0, 0, 0, 0 }; float weights[ 4 ] = { 1.0f, 0.0f, 0.0f, 0.0f }; for (unsigned short bone = 0; bone < numBlendWeightsPerVertex; ++bone) { // Do we still have data for this vertex? if (i != iend && i->second.vertexIndex == v) { // If so, grab weight and index weights[ bone ] = i->second.weight; indices[ bone ] = static_cast<unsigned char>( boneIndexToBlendIndexMap[ i->second.boneIndex ] ); ++i; } } // if weights are integers, if ( weightsBaseType != VET_FLOAT1 ) { // pack the float weights into shorts/bytes unsigned int intWeights[ 4 ]; unsigned int sum = 0; const unsigned int wtScale = maxIntWt; // this value corresponds to a weight of 1.0 for ( int ii = 0; ii < 4; ++ii ) { unsigned int bw = static_cast<unsigned int>( weights[ ii ] * wtScale ); intWeights[ ii ] = bw; sum += bw; } // if the sum doesn't add up due to roundoff error, we need to adjust the intWeights so that the sum is wtScale if ( sum != maxIntWt ) { // find the largest weight (it isn't necessarily the first one...) int iMaxWeight = 0; unsigned int maxWeight = 0; for ( int ii = 0; ii < 4; ++ii ) { unsigned int bw = intWeights[ ii ]; if ( bw > maxWeight ) { iMaxWeight = ii; maxWeight = bw; } } // Adjust the largest weight to make sure the sum is correct. // The idea is that changing the largest weight will have the smallest effect // on the ratio of weights. This works best when there is one dominant weight, // and worst when 2 or more weights are similar in magnitude. // A better method could be used to reduce the quantization error, but this is // being done at run-time so it needs to be quick. intWeights[ iMaxWeight ] += maxIntWt - sum; } // now write the weights if ( weightsBaseType == VET_UBYTE4_NORM ) { // write out the weights as bytes unsigned char* pWeight; pWeightElem->baseVertexPointerToElement( pBase, &pWeight ); // NOTE: always writes out 4 regardless of numBlendWeightsPerVertex for ( int ii = 0; ii < 4; ++ii ) { *pWeight++ = static_cast<unsigned char>( intWeights[ ii ] ); } } else { // write out the weights as shorts unsigned short* pWeight; pWeightElem->baseVertexPointerToElement( pBase, &pWeight ); for ( int ii = 0; ii < numBlendWeightsPerVertex; ++ii ) { *pWeight++ = static_cast<unsigned short>( intWeights[ ii ] ); } } } else { // write out the weights as floats float* pWeight; pWeightElem->baseVertexPointerToElement( pBase, &pWeight ); for ( int ii = 0; ii < numBlendWeightsPerVertex; ++ii ) { *pWeight++ = weights[ ii ]; } } unsigned char* pIndex; pIdxElem->baseVertexPointerToElement( pBase, &pIndex ); for ( int ii = 0; ii < 4; ++ii ) { *pIndex++ = indices[ ii ]; } pBase += vbuf->getVertexSize(); } } //--------------------------------------------------------------------- static Real distLineSegToPoint( const Vector3& line0, const Vector3& line1, const Vector3& pt ) { Vector3 v01 = line1 - line0; Real tt = v01.dotProduct( pt - line0 ) / std::max( v01.dotProduct(v01), std::numeric_limits<Real>::epsilon() ); tt = Math::Clamp( tt, Real(0.0f), Real(1.0f) ); Vector3 onLine = line0 + tt * v01; return pt.distance( onLine ); } //--------------------------------------------------------------------- static Real _computeBoneBoundingRadiusHelper( VertexData* vertexData, const Mesh::VertexBoneAssignmentList& boneAssignments, const std::vector<Vector3>& bonePositions, const std::vector< std::vector<ushort> >& boneChildren ) { std::vector<Vector3> vertexPositions; { // extract vertex positions const VertexElement* posElem = vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); HardwareVertexBufferSharedPtr vbuf = vertexData->vertexBufferBinding->getBuffer(posElem->getSource()); // if usage is write only, if ( !vbuf->hasShadowBuffer() && (vbuf->getUsage() & HBU_DETAIL_WRITE_ONLY) ) { // can't do it return Real(0.0f); } vertexPositions.resize( vertexData->vertexCount ); HardwareBufferLockGuard vertexLock(vbuf, HardwareBuffer::HBL_READ_ONLY); unsigned char* vertex = static_cast<unsigned char*>(vertexLock.pData); float* pFloat; for(size_t i = 0; i < vertexData->vertexCount; ++i) { posElem->baseVertexPointerToElement(vertex, &pFloat); vertexPositions[ i ] = Vector3( pFloat[0], pFloat[1], pFloat[2] ); vertex += vbuf->getVertexSize(); } } Real maxRadius = Real(0); Real minWeight = Real(0.01); // for each vertex-bone assignment, for (Mesh::VertexBoneAssignmentList::const_iterator i = boneAssignments.begin(); i != boneAssignments.end(); ++i) { // if weight is close to zero, ignore if (i->second.weight > minWeight) { // if we have a bounding box around all bone origins, we consider how far outside this box the // current vertex could ever get (assuming it is only attached to the given bone, and the bones all have unity scale) size_t iBone = i->second.boneIndex; const Vector3& v = vertexPositions[ i->second.vertexIndex ]; Vector3 diff = v - bonePositions[ iBone ]; Real dist = diff.length(); // max distance of vertex v outside of bounding box // if this bone has children, we can reduce the dist under the assumption that the children may rotate wrt their parent, but don't translate for (size_t iChild = 0; iChild < boneChildren[iBone].size(); ++iChild) { // given this assumption, we know that the bounding box will enclose both the bone origin as well as the origin of the child bone, // and therefore everything on a line segment between the bone origin and the child bone will be inside the bounding box as well size_t iChildBone = boneChildren[ iBone ][ iChild ]; // compute distance from vertex to line segment between bones Real distChild = distLineSegToPoint( bonePositions[ iBone ], bonePositions[ iChildBone ], v ); dist = std::min( dist, distChild ); } // scale the distance by the weight, this prevents the radius from being over-inflated because of a vertex that is lightly influenced by a faraway bone dist *= i->second.weight; maxRadius = std::max( maxRadius, dist ); } } return maxRadius; } //--------------------------------------------------------------------- void Mesh::_computeBoneBoundingRadius() { if (mBoneBoundingRadius == Real(0) && mSkeleton) { Real radius = Real(0); std::vector<Vector3> bonePositions; std::vector< std::vector<ushort> > boneChildren; // for each bone, a list of children { // extract binding pose bone positions, and also indices for child bones uint16 numBones = mSkeleton->getNumBones(); mSkeleton->setBindingPose(); mSkeleton->_updateTransforms(); bonePositions.resize( numBones ); boneChildren.resize( numBones ); // for each bone, for (uint16 iBone = 0; iBone < numBones; ++iBone) { Bone* bone = mSkeleton->getBone( iBone ); bonePositions[ iBone ] = bone->_getDerivedPosition(); boneChildren[ iBone ].reserve( bone->numChildren() ); for (uint16 iChild = 0; iChild < bone->numChildren(); ++iChild) { Bone* child = static_cast<Bone*>( bone->getChild( iChild ) ); boneChildren[ iBone ].push_back( child->getHandle() ); } } } if (sharedVertexData) { // check shared vertices radius = _computeBoneBoundingRadiusHelper(sharedVertexData, mBoneAssignments, bonePositions, boneChildren); } // check submesh vertices SubMeshList::const_iterator itor = mSubMeshList.begin(); SubMeshList::const_iterator end = mSubMeshList.end(); while( itor != end ) { SubMesh* submesh = *itor; if (!submesh->useSharedVertices && submesh->vertexData) { Real r = _computeBoneBoundingRadiusHelper(submesh->vertexData, submesh->mBoneAssignments, bonePositions, boneChildren); radius = std::max( radius, r ); } ++itor; } if (radius > Real(0)) { mBoneBoundingRadius = radius; } else { // fallback if we failed to find the vertices mBoneBoundingRadius = mBoundRadius; } } } //--------------------------------------------------------------------- void Mesh::_notifySkeleton(const SkeletonPtr& pSkel) { mSkeleton = pSkel; } //--------------------------------------------------------------------- Mesh::BoneAssignmentIterator Mesh::getBoneAssignmentIterator(void) { return BoneAssignmentIterator(mBoneAssignments.begin(), mBoneAssignments.end()); } //--------------------------------------------------------------------- const String& Mesh::getSkeletonName(void) const { return mSkeleton ? mSkeleton->getName() : BLANKSTRING; } //--------------------------------------------------------------------- const MeshLodUsage& Mesh::getLodLevel(ushort index) const { #if !OGRE_NO_MESHLOD index = std::min(index, (ushort)(mMeshLodUsageList.size() - 1)); if (this->_isManualLodLevel(index) && index > 0 && !mMeshLodUsageList[index].manualMesh) { // Load the mesh now try { mMeshLodUsageList[index].manualMesh = MeshManager::getSingleton().load( mMeshLodUsageList[index].manualName, getGroup()); // get the edge data, if required if (!mMeshLodUsageList[index].edgeData) { mMeshLodUsageList[index].edgeData = mMeshLodUsageList[index].manualMesh->getEdgeList(0); } } catch (Exception& ) { LogManager::getSingleton().stream() << "Error while loading manual LOD level " << mMeshLodUsageList[index].manualName << " - this LOD level will not be rendered. You can " << "ignore this error in offline mesh tools."; } } return mMeshLodUsageList[index]; #else return mMeshLodUsageList[0]; #endif } //--------------------------------------------------------------------- ushort Mesh::getLodIndex(Real value) const { #if !OGRE_NO_MESHLOD // Get index from strategy return mLodStrategy->getIndex(value, mMeshLodUsageList); #else return 0; #endif } //--------------------------------------------------------------------- #if !OGRE_NO_MESHLOD void Mesh::updateManualLodLevel(ushort index, const String& meshName) { // Basic prerequisites assert(index != 0 && "Can't modify first LOD level (full detail)"); assert(index < mMeshLodUsageList.size() && "Idndex out of bounds"); // get lod MeshLodUsage* lod = &(mMeshLodUsageList[index]); lod->manualName = meshName; lod->manualMesh.reset(); OGRE_DELETE lod->edgeData; lod->edgeData = 0; } //--------------------------------------------------------------------- void Mesh::_setLodInfo(unsigned short numLevels) { assert(!mEdgeListsBuilt && "Can't modify LOD after edge lists built"); // Basic prerequisites assert(numLevels > 0 && "Must be at least one level (full detail level must exist)"); mNumLods = numLevels; mMeshLodUsageList.resize(numLevels); // Resize submesh face data lists too for (SubMeshList::iterator i = mSubMeshList.begin(); i != mSubMeshList.end(); ++i) { (*i)->mLodFaceList.resize(numLevels - 1); } } //--------------------------------------------------------------------- void Mesh::_setLodUsage(unsigned short level, const MeshLodUsage& usage) { assert(!mEdgeListsBuilt && "Can't modify LOD after edge lists built"); // Basic prerequisites assert(level != 0 && "Can't modify first LOD level (full detail)"); assert(level < mMeshLodUsageList.size() && "Index out of bounds"); mMeshLodUsageList[level] = usage; if(!mMeshLodUsageList[level].manualName.empty()){ mHasManualLodLevel = true; } } //--------------------------------------------------------------------- void Mesh::_setSubMeshLodFaceList(unsigned short subIdx, unsigned short level, IndexData* facedata) { assert(!mEdgeListsBuilt && "Can't modify LOD after edge lists built"); // Basic prerequisites assert(mMeshLodUsageList[level].manualName.empty() && "Not using generated LODs!"); assert(subIdx < mSubMeshList.size() && "Index out of bounds"); assert(level != 0 && "Can't modify first LOD level (full detail)"); assert(level-1 < (unsigned short)mSubMeshList[subIdx]->mLodFaceList.size() && "Index out of bounds"); SubMesh* sm = mSubMeshList[subIdx]; sm->mLodFaceList[level - 1] = facedata; } #endif //--------------------------------------------------------------------- bool Mesh::_isManualLodLevel( unsigned short level ) const { #if !OGRE_NO_MESHLOD return !mMeshLodUsageList[level].manualName.empty(); #else return false; #endif } //--------------------------------------------------------------------- ushort Mesh::_getSubMeshIndex(const String& name) const { SubMeshNameMap::const_iterator i = mSubMeshNameMap.find(name) ; if (i == mSubMeshNameMap.end()) OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No SubMesh named " + name + " found.", "Mesh::_getSubMeshIndex"); return i->second; } //-------------------------------------------------------------------- void Mesh::removeLodLevels(void) { #if !OGRE_NO_MESHLOD // Remove data from SubMeshes SubMeshList::iterator isub, isubend; isubend = mSubMeshList.end(); for (isub = mSubMeshList.begin(); isub != isubend; ++isub) { (*isub)->removeLodLevels(); } bool edgeListWasBuilt = isEdgeListBuilt(); freeEdgeList(); // Reinitialise mNumLods = 1; mMeshLodUsageList.resize(1); mMeshLodUsageList[0].edgeData = NULL; if(edgeListWasBuilt) buildEdgeList(); #endif } //--------------------------------------------------------------------- Real Mesh::getBoundingSphereRadius(void) const { return mBoundRadius; } //--------------------------------------------------------------------- Real Mesh::getBoneBoundingRadius(void) const { return mBoneBoundingRadius; } //--------------------------------------------------------------------- void Mesh::setVertexBufferPolicy(HardwareBuffer::Usage vbUsage, bool shadowBuffer) { mVertexBufferUsage = vbUsage; mVertexBufferShadowBuffer = shadowBuffer; } //--------------------------------------------------------------------- void Mesh::setIndexBufferPolicy(HardwareBuffer::Usage vbUsage, bool shadowBuffer) { mIndexBufferUsage = vbUsage; mIndexBufferShadowBuffer = shadowBuffer; } //--------------------------------------------------------------------- void Mesh::mergeAdjacentTexcoords( unsigned short finalTexCoordSet, unsigned short texCoordSetToDestroy ) { if( sharedVertexData ) mergeAdjacentTexcoords( finalTexCoordSet, texCoordSetToDestroy, sharedVertexData ); SubMeshList::const_iterator itor = mSubMeshList.begin(); SubMeshList::const_iterator end = mSubMeshList.end(); while( itor != end ) { if( !(*itor)->useSharedVertices ) mergeAdjacentTexcoords( finalTexCoordSet, texCoordSetToDestroy, (*itor)->vertexData ); ++itor; } } //--------------------------------------------------------------------- void Mesh::mergeAdjacentTexcoords( unsigned short finalTexCoordSet, unsigned short texCoordSetToDestroy, VertexData *vertexData ) { VertexDeclaration *vDecl = vertexData->vertexDeclaration; const VertexElement *uv0 = vDecl->findElementBySemantic( VES_TEXTURE_COORDINATES, finalTexCoordSet ); const VertexElement *uv1 = vDecl->findElementBySemantic( VES_TEXTURE_COORDINATES, texCoordSetToDestroy ); if( uv0 && uv1 ) { //Check that both base types are compatible (mix floats w/ shorts) and there's enough space VertexElementType baseType0 = VertexElement::getBaseType( uv0->getType() ); VertexElementType baseType1 = VertexElement::getBaseType( uv1->getType() ); unsigned short totalTypeCount = VertexElement::getTypeCount( uv0->getType() ) + VertexElement::getTypeCount( uv1->getType() ); if( baseType0 == baseType1 && totalTypeCount <= 4 ) { const VertexDeclaration::VertexElementList &veList = vDecl->getElements(); VertexDeclaration::VertexElementList::const_iterator uv0Itor = std::find( veList.begin(), veList.end(), *uv0 ); unsigned short elem_idx = std::distance( veList.begin(), uv0Itor ); VertexElementType newType = VertexElement::multiplyTypeCount( baseType0, totalTypeCount ); if( ( uv0->getOffset() + uv0->getSize() == uv1->getOffset() || uv1->getOffset() + uv1->getSize() == uv0->getOffset() ) && uv0->getSource() == uv1->getSource() ) { //Special case where they adjacent, just change the declaration & we're done. size_t newOffset = std::min( uv0->getOffset(), uv1->getOffset() ); unsigned short newIdx = std::min( uv0->getIndex(), uv1->getIndex() ); vDecl->modifyElement( elem_idx, uv0->getSource(), newOffset, newType, VES_TEXTURE_COORDINATES, newIdx ); vDecl->removeElement( VES_TEXTURE_COORDINATES, texCoordSetToDestroy ); uv1 = 0; } vDecl->closeGapsInSource(); } } } //--------------------------------------------------------------------- void Mesh::organiseTangentsBuffer(VertexData *vertexData, VertexElementSemantic targetSemantic, unsigned short index, unsigned short sourceTexCoordSet) { VertexDeclaration *vDecl = vertexData->vertexDeclaration ; VertexBufferBinding *vBind = vertexData->vertexBufferBinding ; const VertexElement *tangentsElem = vDecl->findElementBySemantic(targetSemantic, index); bool needsToBeCreated = false; if (!tangentsElem) { // no tex coords with index 1 needsToBeCreated = true ; } else if (tangentsElem->getType() != VET_FLOAT3) { // buffer exists, but not 3D OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Target semantic set already exists but is not 3D, therefore " "cannot contain tangents. Pick an alternative destination semantic. ", "Mesh::organiseTangentsBuffer"); } HardwareVertexBufferSharedPtr newBuffer; if (needsToBeCreated) { // To be most efficient with our vertex streams, // tack the new tangents onto the same buffer as the // source texture coord set const VertexElement* prevTexCoordElem = vertexData->vertexDeclaration->findElementBySemantic( VES_TEXTURE_COORDINATES, sourceTexCoordSet); if (!prevTexCoordElem) { OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Cannot locate the first texture coordinate element to " "which to append the new tangents.", "Mesh::orgagniseTangentsBuffer"); } // Find the buffer associated with this element HardwareVertexBufferSharedPtr origBuffer = vertexData->vertexBufferBinding->getBuffer( prevTexCoordElem->getSource()); // Now create a new buffer, which includes the previous contents // plus extra space for the 3D coords newBuffer = getHardwareBufferManager()->createVertexBuffer( origBuffer->getVertexSize() + 3*sizeof(float), vertexData->vertexCount, origBuffer->getUsage(), origBuffer->hasShadowBuffer() ); // Add the new element vDecl->addElement( prevTexCoordElem->getSource(), origBuffer->getVertexSize(), VET_FLOAT3, targetSemantic, index); // Now copy the original data across HardwareBufferLockGuard srcLock(origBuffer, HardwareBuffer::HBL_READ_ONLY); HardwareBufferLockGuard dstLock(newBuffer, HardwareBuffer::HBL_DISCARD); unsigned char* pSrc = static_cast<unsigned char*>(srcLock.pData); unsigned char* pDest = static_cast<unsigned char*>(dstLock.pData); size_t vertSize = origBuffer->getVertexSize(); for (size_t v = 0; v < vertexData->vertexCount; ++v) { // Copy original vertex data memcpy(pDest, pSrc, vertSize); pSrc += vertSize; pDest += vertSize; // Set the new part to 0 since we'll accumulate in this memset(pDest, 0, sizeof(float)*3); pDest += sizeof(float)*3; } // Rebind the new buffer vBind->setBinding(prevTexCoordElem->getSource(), newBuffer); } } //--------------------------------------------------------------------- void Mesh::buildTangentVectors(VertexElementSemantic targetSemantic, unsigned short sourceTexCoordSet, unsigned short index, bool splitMirrored, bool splitRotated, bool storeParityInW) { TangentSpaceCalc tangentsCalc; tangentsCalc.setSplitMirrored(splitMirrored); tangentsCalc.setSplitRotated(splitRotated); tangentsCalc.setStoreParityInW(storeParityInW); // shared geometry first if (sharedVertexData) { tangentsCalc.setVertexData(sharedVertexData); bool found = false; for (SubMeshList::iterator i = mSubMeshList.begin(); i != mSubMeshList.end(); ++i) { SubMesh* sm = *i; if (sm->useSharedVertices) { tangentsCalc.addIndexData(sm->indexData); found = true; } } if (found) { TangentSpaceCalc::Result res = tangentsCalc.build(targetSemantic, sourceTexCoordSet, index); // If any vertex splitting happened, we have to give them bone assignments if (!getSkeletonName().empty()) { for (TangentSpaceCalc::IndexRemapList::iterator r = res.indexesRemapped.begin(); r != res.indexesRemapped.end(); ++r) { TangentSpaceCalc::IndexRemap& remap = *r; // Copy all bone assignments from the split vertex VertexBoneAssignmentList::iterator vbstart = mBoneAssignments.lower_bound(remap.splitVertex.first); VertexBoneAssignmentList::iterator vbend = mBoneAssignments.upper_bound(remap.splitVertex.first); for (VertexBoneAssignmentList::iterator vba = vbstart; vba != vbend; ++vba) { VertexBoneAssignment newAsgn = vba->second; newAsgn.vertexIndex = static_cast<unsigned int>(remap.splitVertex.second); // multimap insert doesn't invalidate iterators addBoneAssignment(newAsgn); } } } // Update poses (some vertices might have been duplicated) // we will just check which vertices have been split and copy // the offset for the original vertex to the corresponding new vertex PoseList::iterator pose_it; for( pose_it = mPoseList.begin(); pose_it != mPoseList.end(); ++pose_it) { Pose* current_pose = *pose_it; const Pose::VertexOffsetMap& offset_map = current_pose->getVertexOffsets(); for( TangentSpaceCalc::VertexSplits::iterator it = res.vertexSplits.begin(); it != res.vertexSplits.end(); ++it ) { TangentSpaceCalc::VertexSplit& split = *it; Pose::VertexOffsetMap::const_iterator found_offset = offset_map.find( split.first ); // copy the offset if( found_offset != offset_map.end() ) { current_pose->addVertex( split.second, found_offset->second ); } } } } } // Dedicated geometry for (SubMeshList::iterator i = mSubMeshList.begin(); i != mSubMeshList.end(); ++i) { SubMesh* sm = *i; if (!sm->useSharedVertices) { tangentsCalc.clear(); tangentsCalc.setVertexData(sm->vertexData); tangentsCalc.addIndexData(sm->indexData, sm->operationType); TangentSpaceCalc::Result res = tangentsCalc.build(targetSemantic, sourceTexCoordSet, index); // If any vertex splitting happened, we have to give them bone assignments if (!getSkeletonName().empty()) { for (TangentSpaceCalc::IndexRemapList::iterator r = res.indexesRemapped.begin(); r != res.indexesRemapped.end(); ++r) { TangentSpaceCalc::IndexRemap& remap = *r; // Copy all bone assignments from the split vertex VertexBoneAssignmentList::const_iterator vbstart = sm->getBoneAssignments().lower_bound(remap.splitVertex.first); VertexBoneAssignmentList::const_iterator vbend = sm->getBoneAssignments().upper_bound(remap.splitVertex.first); for (VertexBoneAssignmentList::const_iterator vba = vbstart; vba != vbend; ++vba) { VertexBoneAssignment newAsgn = vba->second; newAsgn.vertexIndex = static_cast<unsigned int>(remap.splitVertex.second); // multimap insert doesn't invalidate iterators sm->addBoneAssignment(newAsgn); } } } } } } //--------------------------------------------------------------------- bool Mesh::suggestTangentVectorBuildParams(VertexElementSemantic targetSemantic, unsigned short& outSourceCoordSet, unsigned short& outIndex) { // Go through all the vertex data and locate source and dest (must agree) bool sharedGeometryDone = false; bool foundExisting = false; bool firstOne = true; SubMeshList::iterator i, iend; iend = mSubMeshList.end(); for (i = mSubMeshList.begin(); i != iend; ++i) { SubMesh* sm = *i; VertexData* vertexData; if (sm->useSharedVertices) { if (sharedGeometryDone) continue; vertexData = sharedVertexData; sharedGeometryDone = true; } else { vertexData = sm->vertexData; } const VertexElement *sourceElem = 0; unsigned short targetIndex = 0; for (targetIndex = 0; targetIndex < OGRE_MAX_TEXTURE_COORD_SETS; ++targetIndex) { const VertexElement* testElem = vertexData->vertexDeclaration->findElementBySemantic( VES_TEXTURE_COORDINATES, targetIndex); if (!testElem) break; // finish if we've run out, t will be the target if (!sourceElem) { // We're still looking for the source texture coords if (testElem->getType() == VET_FLOAT2) { // Ok, we found it sourceElem = testElem; } } if(!foundExisting && targetSemantic == VES_TEXTURE_COORDINATES) { // We're looking for the destination // Check to see if we've found a possible if (testElem->getType() == VET_FLOAT3) { // This is a 3D set, might be tangents foundExisting = true; } } } if (!foundExisting && targetSemantic != VES_TEXTURE_COORDINATES) { targetIndex = 0; // Look for existing semantic const VertexElement* testElem = vertexData->vertexDeclaration->findElementBySemantic( targetSemantic, targetIndex); if (testElem) { foundExisting = true; } } // After iterating, we should have a source and a possible destination (t) if (!sourceElem) { OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Cannot locate an appropriate 2D texture coordinate set for " "all the vertex data in this mesh to create tangents from. ", "Mesh::suggestTangentVectorBuildParams"); } // Check that we agree with previous decisions, if this is not the // first one, and if we're not just using the existing one if (!firstOne && !foundExisting) { if (sourceElem->getIndex() != outSourceCoordSet) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Multiple sets of vertex data in this mesh disagree on " "the appropriate index to use for the source texture coordinates. " "This ambiguity must be rectified before tangents can be generated.", "Mesh::suggestTangentVectorBuildParams"); } if (targetIndex != outIndex) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Multiple sets of vertex data in this mesh disagree on " "the appropriate index to use for the target texture coordinates. " "This ambiguity must be rectified before tangents can be generated.", "Mesh::suggestTangentVectorBuildParams"); } } // Otherwise, save this result outSourceCoordSet = sourceElem->getIndex(); outIndex = targetIndex; firstOne = false; } return foundExisting; } //--------------------------------------------------------------------- void Mesh::buildEdgeList(void) { if (mEdgeListsBuilt) return; #if !OGRE_NO_MESHLOD // Loop over LODs for (unsigned short lodIndex = 0; lodIndex < (unsigned short)mMeshLodUsageList.size(); ++lodIndex) { // use getLodLevel to enforce loading of manual mesh lods const MeshLodUsage& usage = getLodLevel(lodIndex); if (!usage.manualName.empty() && lodIndex != 0) { // Delegate edge building to manual mesh // It should have already built it's own edge list while loading if (usage.manualMesh) { usage.edgeData = usage.manualMesh->getEdgeList(0); } } else { // Build EdgeListBuilder eb; size_t vertexSetCount = 0; bool atLeastOneIndexSet = false; if (sharedVertexData) { eb.addVertexData(sharedVertexData); vertexSetCount++; } // Prepare the builder using the submesh information SubMeshList::iterator i, iend; iend = mSubMeshList.end(); for (i = mSubMeshList.begin(); i != iend; ++i) { SubMesh* s = *i; if (s->operationType != RenderOperation::OT_TRIANGLE_FAN && s->operationType != RenderOperation::OT_TRIANGLE_LIST && s->operationType != RenderOperation::OT_TRIANGLE_STRIP) { continue; } if (s->useSharedVertices) { // Use shared vertex data, index as set 0 if (lodIndex == 0) { eb.addIndexData(s->indexData, 0, s->operationType); } else { eb.addIndexData(s->mLodFaceList[lodIndex-1], 0, s->operationType); } } else if(s->isBuildEdgesEnabled()) { // own vertex data, add it and reference it directly eb.addVertexData(s->vertexData); if (lodIndex == 0) { // Base index data eb.addIndexData(s->indexData, vertexSetCount++, s->operationType); } else { // LOD index data eb.addIndexData(s->mLodFaceList[lodIndex-1], vertexSetCount++, s->operationType); } } atLeastOneIndexSet = true; } if (atLeastOneIndexSet) { usage.edgeData = eb.build(); #if OGRE_DEBUG_MODE // Override default log Log* log = LogManager::getSingleton().createLog( mName + "_lod" + StringConverter::toString(lodIndex) + "_prepshadow.log", false, false); usage.edgeData->log(log); // clean up log & close file handle LogManager::getSingleton().destroyLog(log); #endif } else { // create empty edge data usage.edgeData = OGRE_NEW EdgeData(); } } } #else // Build EdgeListBuilder eb; size_t vertexSetCount = 0; if (sharedVertexData) { eb.addVertexData(sharedVertexData); vertexSetCount++; } // Prepare the builder using the submesh information SubMeshList::iterator i, iend; iend = mSubMeshList.end(); for (i = mSubMeshList.begin(); i != iend; ++i) { SubMesh* s = *i; if (s->operationType != RenderOperation::OT_TRIANGLE_FAN && s->operationType != RenderOperation::OT_TRIANGLE_LIST && s->operationType != RenderOperation::OT_TRIANGLE_STRIP) { continue; } if (s->useSharedVertices) { eb.addIndexData(s->indexData, 0, s->operationType); } else if(s->isBuildEdgesEnabled()) { // own vertex data, add it and reference it directly eb.addVertexData(s->vertexData); // Base index data eb.addIndexData(s->indexData, vertexSetCount++, s->operationType); } } mMeshLodUsageList[0].edgeData = eb.build(); #if OGRE_DEBUG_MODE // Override default log Log* log = LogManager::getSingleton().createLog( mName + "_lod0"+ "_prepshadow.log", false, false); mMeshLodUsageList[0].edgeData->log(log); // clean up log & close file handle LogManager::getSingleton().destroyLog(log); #endif #endif mEdgeListsBuilt = true; } //--------------------------------------------------------------------- void Mesh::freeEdgeList(void) { if (!mEdgeListsBuilt) return; #if !OGRE_NO_MESHLOD // Loop over LODs MeshLodUsageList::iterator i, iend; iend = mMeshLodUsageList.end(); unsigned short index = 0; for (i = mMeshLodUsageList.begin(); i != iend; ++i, ++index) { MeshLodUsage& usage = *i; if (usage.manualName.empty() || index == 0) { // Only delete if we own this data // Manual LODs > 0 own their own OGRE_DELETE usage.edgeData; } usage.edgeData = NULL; } #else OGRE_DELETE mMeshLodUsageList[0].edgeData; mMeshLodUsageList[0].edgeData = NULL; #endif mEdgeListsBuilt = false; } //--------------------------------------------------------------------- void Mesh::prepareForShadowVolume(void) { if (mPreparedForShadowVolumes) return; if (sharedVertexData) { sharedVertexData->prepareForShadowVolume(); } SubMeshList::iterator i, iend; iend = mSubMeshList.end(); for (i = mSubMeshList.begin(); i != iend; ++i) { SubMesh* s = *i; if (!s->useSharedVertices && (s->operationType == RenderOperation::OT_TRIANGLE_FAN || s->operationType == RenderOperation::OT_TRIANGLE_LIST || s->operationType == RenderOperation::OT_TRIANGLE_STRIP)) { s->vertexData->prepareForShadowVolume(); } } mPreparedForShadowVolumes = true; } //--------------------------------------------------------------------- EdgeData* Mesh::getEdgeList(unsigned short lodIndex) { // Build edge list on demand if (!mEdgeListsBuilt && mAutoBuildEdgeLists) { buildEdgeList(); } #if !OGRE_NO_MESHLOD return getLodLevel(lodIndex).edgeData; #else assert(lodIndex == 0); return mMeshLodUsageList[0].edgeData; #endif } //--------------------------------------------------------------------- const EdgeData* Mesh::getEdgeList(unsigned short lodIndex) const { #if !OGRE_NO_MESHLOD return getLodLevel(lodIndex).edgeData; #else assert(lodIndex == 0); return mMeshLodUsageList[0].edgeData; #endif } //--------------------------------------------------------------------- void Mesh::prepareMatricesForVertexBlend(const Affine3** blendMatrices, const Affine3* boneMatrices, const IndexMap& indexMap) { assert(indexMap.size() <= 256); IndexMap::const_iterator it, itend; itend = indexMap.end(); for (it = indexMap.begin(); it != itend; ++it) { *blendMatrices++ = boneMatrices + *it; } } //--------------------------------------------------------------------- void Mesh::softwareVertexBlend(const VertexData* sourceVertexData, const VertexData* targetVertexData, const Affine3* const* blendMatrices, size_t numMatrices, bool blendNormals) { float *pSrcPos = 0; float *pSrcNorm = 0; float *pDestPos = 0; float *pDestNorm = 0; float *pBlendWeight = 0; unsigned char* pBlendIdx = 0; size_t srcPosStride = 0; size_t srcNormStride = 0; size_t destPosStride = 0; size_t destNormStride = 0; size_t blendWeightStride = 0; size_t blendIdxStride = 0; // Get elements for source const VertexElement* srcElemPos = sourceVertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); const VertexElement* srcElemNorm = sourceVertexData->vertexDeclaration->findElementBySemantic(VES_NORMAL); const VertexElement* srcElemBlendIndices = sourceVertexData->vertexDeclaration->findElementBySemantic(VES_BLEND_INDICES); const VertexElement* srcElemBlendWeights = sourceVertexData->vertexDeclaration->findElementBySemantic(VES_BLEND_WEIGHTS); OgreAssert(srcElemPos && srcElemBlendIndices && srcElemBlendWeights, "You must supply at least positions, blend indices and blend weights"); // Get elements for target const VertexElement* destElemPos = targetVertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); const VertexElement* destElemNorm = targetVertexData->vertexDeclaration->findElementBySemantic(VES_NORMAL); // Do we have normals and want to blend them? bool includeNormals = blendNormals && (srcElemNorm != NULL) && (destElemNorm != NULL); // Get buffers for source HardwareVertexBufferSharedPtr srcPosBuf = sourceVertexData->vertexBufferBinding->getBuffer(srcElemPos->getSource()); HardwareVertexBufferSharedPtr srcIdxBuf = sourceVertexData->vertexBufferBinding->getBuffer(srcElemBlendIndices->getSource()); HardwareVertexBufferSharedPtr srcWeightBuf = sourceVertexData->vertexBufferBinding->getBuffer(srcElemBlendWeights->getSource()); HardwareVertexBufferSharedPtr srcNormBuf; srcPosStride = srcPosBuf->getVertexSize(); blendIdxStride = srcIdxBuf->getVertexSize(); blendWeightStride = srcWeightBuf->getVertexSize(); if (includeNormals) { srcNormBuf = sourceVertexData->vertexBufferBinding->getBuffer(srcElemNorm->getSource()); srcNormStride = srcNormBuf->getVertexSize(); } // Get buffers for target HardwareVertexBufferSharedPtr destPosBuf = targetVertexData->vertexBufferBinding->getBuffer(destElemPos->getSource()); HardwareVertexBufferSharedPtr destNormBuf; destPosStride = destPosBuf->getVertexSize(); if (includeNormals) { destNormBuf = targetVertexData->vertexBufferBinding->getBuffer(destElemNorm->getSource()); destNormStride = destNormBuf->getVertexSize(); } // Lock source buffers for reading HardwareBufferLockGuard srcPosLock(srcPosBuf, HardwareBuffer::HBL_READ_ONLY); srcElemPos->baseVertexPointerToElement(srcPosLock.pData, &pSrcPos); HardwareBufferLockGuard srcNormLock; if (includeNormals) { if (srcNormBuf != srcPosBuf) { // Different buffer srcNormLock.lock(srcNormBuf, HardwareBuffer::HBL_READ_ONLY); } srcElemNorm->baseVertexPointerToElement(srcNormBuf != srcPosBuf ? srcNormLock.pData : srcPosLock.pData, &pSrcNorm); } // Indices must be 4 bytes assert(srcElemBlendIndices->getType() == VET_UBYTE4 && "Blend indices must be VET_UBYTE4"); HardwareBufferLockGuard srcIdxLock(srcIdxBuf, HardwareBuffer::HBL_READ_ONLY); srcElemBlendIndices->baseVertexPointerToElement(srcIdxLock.pData, &pBlendIdx); HardwareBufferLockGuard srcWeightLock; if (srcWeightBuf != srcIdxBuf) { // Lock buffer srcWeightLock.lock(srcWeightBuf, HardwareBuffer::HBL_READ_ONLY); } srcElemBlendWeights->baseVertexPointerToElement(srcWeightBuf != srcIdxBuf ? srcWeightLock.pData : srcIdxLock.pData, &pBlendWeight); unsigned short numWeightsPerVertex = VertexElement::getTypeCount(srcElemBlendWeights->getType()); // Lock destination buffers for writing HardwareBufferLockGuard destPosLock(destPosBuf, (destNormBuf != destPosBuf && destPosBuf->getVertexSize() == destElemPos->getSize()) || (destNormBuf == destPosBuf && destPosBuf->getVertexSize() == destElemPos->getSize() + destElemNorm->getSize()) ? HardwareBuffer::HBL_DISCARD : HardwareBuffer::HBL_NORMAL); destElemPos->baseVertexPointerToElement(destPosLock.pData, &pDestPos); HardwareBufferLockGuard destNormLock; if (includeNormals) { if (destNormBuf != destPosBuf) { destNormLock.lock(destNormBuf, destNormBuf->getVertexSize() == destElemNorm->getSize() ? HardwareBuffer::HBL_DISCARD : HardwareBuffer::HBL_NORMAL); } destElemNorm->baseVertexPointerToElement(destNormBuf != destPosBuf ? destNormLock.pData : destPosLock.pData, &pDestNorm); } OptimisedUtil::getImplementation()->softwareVertexSkinning( pSrcPos, pDestPos, pSrcNorm, pDestNorm, pBlendWeight, pBlendIdx, blendMatrices, srcPosStride, destPosStride, srcNormStride, destNormStride, blendWeightStride, blendIdxStride, numWeightsPerVertex, targetVertexData->vertexCount); } //--------------------------------------------------------------------- void Mesh::softwareVertexMorph(Real t, const HardwareVertexBufferSharedPtr& b1, const HardwareVertexBufferSharedPtr& b2, VertexData* targetVertexData) { HardwareBufferLockGuard b1Lock(b1, HardwareBuffer::HBL_READ_ONLY); float* pb1 = static_cast<float*>(b1Lock.pData); HardwareBufferLockGuard b2Lock; float* pb2; if (b1.get() != b2.get()) { b2Lock.lock(b2, HardwareBuffer::HBL_READ_ONLY); pb2 = static_cast<float*>(b2Lock.pData); } else { // Same buffer - track with only one entry or time index exactly matching // one keyframe // For simplicity of main code, interpolate still but with same val pb2 = pb1; } const VertexElement* posElem = targetVertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); assert(posElem); const VertexElement* normElem = targetVertexData->vertexDeclaration->findElementBySemantic(VES_NORMAL); bool morphNormals = false; if (normElem && normElem->getSource() == posElem->getSource() && b1->getVertexSize() == 24 && b2->getVertexSize() == 24) morphNormals = true; HardwareVertexBufferSharedPtr destBuf = targetVertexData->vertexBufferBinding->getBuffer( posElem->getSource()); assert((posElem->getSize() == destBuf->getVertexSize() || (morphNormals && posElem->getSize() + normElem->getSize() == destBuf->getVertexSize())) && "Positions (or positions & normals) must be in a buffer on their own for morphing"); HardwareBufferLockGuard destLock(destBuf, HardwareBuffer::HBL_DISCARD); float* pdst = static_cast<float*>(destLock.pData); OptimisedUtil::getImplementation()->softwareVertexMorph( t, pb1, pb2, pdst, b1->getVertexSize(), b2->getVertexSize(), destBuf->getVertexSize(), targetVertexData->vertexCount, morphNormals); } //--------------------------------------------------------------------- void Mesh::softwareVertexPoseBlend(Real weight, const std::map<size_t, Vector3>& vertexOffsetMap, const std::map<size_t, Vector3>& normalsMap, VertexData* targetVertexData) { // Do nothing if no weight if (weight == 0.0f) return; const VertexElement* posElem = targetVertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); const VertexElement* normElem = targetVertexData->vertexDeclaration->findElementBySemantic(VES_NORMAL); assert(posElem); // Support normals if they're in the same buffer as positions and pose includes them bool normals = normElem && !normalsMap.empty() && posElem->getSource() == normElem->getSource(); HardwareVertexBufferSharedPtr destBuf = targetVertexData->vertexBufferBinding->getBuffer( posElem->getSource()); size_t elemsPerVertex = destBuf->getVertexSize()/sizeof(float); // Have to lock in normal mode since this is incremental HardwareBufferLockGuard destLock(destBuf, HardwareBuffer::HBL_NORMAL); float* pBase = static_cast<float*>(destLock.pData); // Iterate over affected vertices for (std::map<size_t, Vector3>::const_iterator i = vertexOffsetMap.begin(); i != vertexOffsetMap.end(); ++i) { // Adjust pointer float *pdst = pBase + i->first*elemsPerVertex; *pdst = *pdst + (i->second.x * weight); ++pdst; *pdst = *pdst + (i->second.y * weight); ++pdst; *pdst = *pdst + (i->second.z * weight); ++pdst; } if (normals) { float* pNormBase; normElem->baseVertexPointerToElement((void*)pBase, &pNormBase); for (std::map<size_t, Vector3>::const_iterator i = normalsMap.begin(); i != normalsMap.end(); ++i) { // Adjust pointer float *pdst = pNormBase + i->first*elemsPerVertex; *pdst = *pdst + (i->second.x * weight); ++pdst; *pdst = *pdst + (i->second.y * weight); ++pdst; *pdst = *pdst + (i->second.z * weight); ++pdst; } } } //--------------------------------------------------------------------- size_t Mesh::calculateSize(void) const { // calculate GPU size size_t ret = 0; unsigned short i; // Shared vertices if (sharedVertexData) { for (i = 0; i < sharedVertexData->vertexBufferBinding->getBufferCount(); ++i) { ret += sharedVertexData->vertexBufferBinding ->getBuffer(i)->getSizeInBytes(); } } SubMeshList::const_iterator si; for (si = mSubMeshList.begin(); si != mSubMeshList.end(); ++si) { // Dedicated vertices if (!(*si)->useSharedVertices) { for (i = 0; i < (*si)->vertexData->vertexBufferBinding->getBufferCount(); ++i) { ret += (*si)->vertexData->vertexBufferBinding ->getBuffer(i)->getSizeInBytes(); } } if ((*si)->indexData->indexBuffer) { // Index data ret += (*si)->indexData->indexBuffer->getSizeInBytes(); } } return ret; } //----------------------------------------------------------------------------- bool Mesh::hasVertexAnimation(void) const { return !mAnimationsList.empty(); } //--------------------------------------------------------------------- VertexAnimationType Mesh::getSharedVertexDataAnimationType(void) const { if (mAnimationTypesDirty) { _determineAnimationTypes(); } return mSharedVertexDataAnimationType; } //--------------------------------------------------------------------- void Mesh::_determineAnimationTypes(void) const { // Don't check flag here; since detail checks on track changes are not // done, allow caller to force if they need to // Initialise all types to nothing mSharedVertexDataAnimationType = VAT_NONE; mSharedVertexDataAnimationIncludesNormals = false; for (SubMeshList::const_iterator i = mSubMeshList.begin(); i != mSubMeshList.end(); ++i) { (*i)->mVertexAnimationType = VAT_NONE; (*i)->mVertexAnimationIncludesNormals = false; } mPosesIncludeNormals = false; for (PoseList::const_iterator i = mPoseList.begin(); i != mPoseList.end(); ++i) { if (i == mPoseList.begin()) mPosesIncludeNormals = (*i)->getIncludesNormals(); else if (mPosesIncludeNormals != (*i)->getIncludesNormals()) // only support normals if consistently included mPosesIncludeNormals = mPosesIncludeNormals && (*i)->getIncludesNormals(); } // Scan all animations and determine the type of animation tracks // relating to each vertex data for(const auto& ai : mAnimationsList) { for (const auto& vit : ai.second->_getVertexTrackList()) { VertexAnimationTrack* track = vit.second; ushort handle = vit.first; if (handle == 0) { // shared data if (mSharedVertexDataAnimationType != VAT_NONE && mSharedVertexDataAnimationType != track->getAnimationType()) { // Mixing of morph and pose animation on same data is not allowed OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Animation tracks for shared vertex data on mesh " + mName + " try to mix vertex animation types, which is " "not allowed.", "Mesh::_determineAnimationTypes"); } mSharedVertexDataAnimationType = track->getAnimationType(); if (track->getAnimationType() == VAT_MORPH) mSharedVertexDataAnimationIncludesNormals = track->getVertexAnimationIncludesNormals(); else mSharedVertexDataAnimationIncludesNormals = mPosesIncludeNormals; } else { // submesh index (-1) SubMesh* sm = getSubMesh(handle-1); if (sm->mVertexAnimationType != VAT_NONE && sm->mVertexAnimationType != track->getAnimationType()) { // Mixing of morph and pose animation on same data is not allowed OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Animation tracks for dedicated vertex data " + StringConverter::toString(handle-1) + " on mesh " + mName + " try to mix vertex animation types, which is " "not allowed.", "Mesh::_determineAnimationTypes"); } sm->mVertexAnimationType = track->getAnimationType(); if (track->getAnimationType() == VAT_MORPH) sm->mVertexAnimationIncludesNormals = track->getVertexAnimationIncludesNormals(); else sm->mVertexAnimationIncludesNormals = mPosesIncludeNormals; } } } mAnimationTypesDirty = false; } //--------------------------------------------------------------------- Animation* Mesh::createAnimation(const String& name, Real length) { // Check name not used if (mAnimationsList.find(name) != mAnimationsList.end()) { OGRE_EXCEPT( Exception::ERR_DUPLICATE_ITEM, "An animation with the name " + name + " already exists", "Mesh::createAnimation"); } Animation* ret = OGRE_NEW Animation(name, length); ret->_notifyContainer(this); // Add to list mAnimationsList[name] = ret; // Mark animation types dirty mAnimationTypesDirty = true; return ret; } //--------------------------------------------------------------------- Animation* Mesh::getAnimation(const String& name) const { Animation* ret = _getAnimationImpl(name); if (!ret) { OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No animation entry found named " + name, "Mesh::getAnimation"); } return ret; } //--------------------------------------------------------------------- Animation* Mesh::getAnimation(unsigned short index) const { // If you hit this assert, then the index is out of bounds. assert( index < mAnimationsList.size() ); AnimationList::const_iterator i = mAnimationsList.begin(); std::advance(i, index); return i->second; } //--------------------------------------------------------------------- unsigned short Mesh::getNumAnimations(void) const { return static_cast<unsigned short>(mAnimationsList.size()); } //--------------------------------------------------------------------- bool Mesh::hasAnimation(const String& name) const { return _getAnimationImpl(name) != 0; } //--------------------------------------------------------------------- Animation* Mesh::_getAnimationImpl(const String& name) const { Animation* ret = 0; AnimationList::const_iterator i = mAnimationsList.find(name); if (i != mAnimationsList.end()) { ret = i->second; } return ret; } //--------------------------------------------------------------------- void Mesh::removeAnimation(const String& name) { AnimationList::iterator i = mAnimationsList.find(name); if (i == mAnimationsList.end()) { OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No animation entry found named " + name, "Mesh::getAnimation"); } OGRE_DELETE i->second; mAnimationsList.erase(i); mAnimationTypesDirty = true; } //--------------------------------------------------------------------- void Mesh::removeAllAnimations(void) { AnimationList::iterator i = mAnimationsList.begin(); for (; i != mAnimationsList.end(); ++i) { OGRE_DELETE i->second; } mAnimationsList.clear(); mAnimationTypesDirty = true; } //--------------------------------------------------------------------- VertexData* Mesh::getVertexDataByTrackHandle(unsigned short handle) { if (handle == 0) { return sharedVertexData; } else { return getSubMesh(handle-1)->vertexData; } } //--------------------------------------------------------------------- Pose* Mesh::createPose(ushort target, const String& name) { Pose* retPose = OGRE_NEW Pose(target, name); mPoseList.push_back(retPose); return retPose; } //--------------------------------------------------------------------- Pose* Mesh::getPose(const String& name) const { for (auto i = mPoseList.begin(); i != mPoseList.end(); ++i) { if ((*i)->getName() == name) return *i; } StringStream str; str << "No pose called " << name << " found in Mesh " << mName; OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, str.str(), "Mesh::getPose"); } //--------------------------------------------------------------------- void Mesh::removePose(ushort index) { OgreAssert(index < mPoseList.size(), ""); PoseList::iterator i = mPoseList.begin(); std::advance(i, index); OGRE_DELETE *i; mPoseList.erase(i); } //--------------------------------------------------------------------- void Mesh::removePose(const String& name) { for (PoseList::iterator i = mPoseList.begin(); i != mPoseList.end(); ++i) { if ((*i)->getName() == name) { OGRE_DELETE *i; mPoseList.erase(i); return; } } StringStream str; str << "No pose called " << name << " found in Mesh " << mName; OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, str.str(), "Mesh::removePose"); } //--------------------------------------------------------------------- void Mesh::removeAllPoses(void) { for (PoseList::iterator i = mPoseList.begin(); i != mPoseList.end(); ++i) { OGRE_DELETE *i; } mPoseList.clear(); } //--------------------------------------------------------------------- Mesh::PoseIterator Mesh::getPoseIterator(void) { return PoseIterator(mPoseList.begin(), mPoseList.end()); } //--------------------------------------------------------------------- Mesh::ConstPoseIterator Mesh::getPoseIterator(void) const { return ConstPoseIterator(mPoseList.begin(), mPoseList.end()); } //----------------------------------------------------------------------------- const PoseList& Mesh::getPoseList(void) const { return mPoseList; } //--------------------------------------------------------------------- const LodStrategy *Mesh::getLodStrategy() const { return mLodStrategy; } #if !OGRE_NO_MESHLOD //--------------------------------------------------------------------- void Mesh::setLodStrategy(LodStrategy *lodStrategy) { mLodStrategy = lodStrategy; assert(mMeshLodUsageList.size()); // Re-transform user LOD values (starting at index 1, no need to transform base value) for (MeshLodUsageList::iterator i = mMeshLodUsageList.begin()+1; i != mMeshLodUsageList.end(); ++i) i->value = mLodStrategy->transformUserValue(i->userValue); // Rewrite first value mMeshLodUsageList[0].value = mLodStrategy->getBaseValue(); } #endif }
mit
Sy4z/OpenGLTest
src/graphicsRender/Render.java
3972
package graphicsRender; import org.lwjgl.LWJGLException; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.GL11; import static org.lwjgl.opengl.GL11.GL_DEPTH_TEST; import static org.lwjgl.opengl.GL11.GL_BLEND; import static org.lwjgl.opengl.GL11.GL_SRC_ALPHA; import static org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA; import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT; import static org.lwjgl.opengl.GL11.glDisable; import static org.lwjgl.opengl.GL11.glEnable; import static org.lwjgl.opengl.GL11.glClearColor; import static org.lwjgl.opengl.GL11.glBlendFunc; import static org.lwjgl.opengl.GL11.glViewport; import static org.lwjgl.opengl.GL11.glClear; /** * Class which Renders an Animated Square in OpenGL */ public class Render { // Width and Height of Render Window public static final int WIDTH = 800; public static final int HEIGHT = 600; /** angle of rotation for square*/ float rotation = 0; /** position of Current square vertice */ float x = 300, y = 200; public static void main(String[] args) throws LWJGLException { new Render().display(); } /** * Method which starts the OpenGL Window */ public void display() throws LWJGLException{ Display.setTitle("Render Window Example"); Display.setResizable(false); Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT)); Display.setVSyncEnabled(true); //Show the Display Display.create(); //some GL11 Parameters GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0, 800, 0, 600, 1, -1); GL11.glMatrixMode(GL11.GL_MODELVIEW); //Initialise Resources in OpenGL create(); //call this to set initial size resize(); //TODO Write small algorithm here to resize graphics when window is resized while (!Display.isCloseRequested()) { ; // Render game moveObject(); draw(); // Flip the buffers and sync to 60 FPS (Uses a double buffer system so what is stored in the other buffer will become displayed) Display.update(); Display.sync(60); } // Dispose any resources and destroy the game window dispose(); Display.destroy(); } // Called to setup game and context protected void create() { // Enable blending - Without this, transparent sprites may not render correctly glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Set clear to transparent black glClearColor(0f, 0f, 0f, 0f); // ... initialize resources here ... } // Called to resize our game protected void resize() { glViewport(0, 0, Display.getWidth(), Display.getHeight()); //update projection matrices here } // Called to destroy game upon exiting protected void dispose() { //destroy any textures or other assets here } // Game Loop protected void draw() { // Clear the screen and also the depth buffer GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); //game render logic here, can probably pass off to another class if it gets comprehensive //set quad colour GL11.glColor3f(0.5f,1.5f,0.5f); GL11.glPushMatrix(); GL11.glTranslatef(x, y, 0); GL11.glRotatef(rotation, 0f, 0f, 1f); GL11.glTranslatef(-x, -y, 0); //draw quad vertices GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2f(x,y); GL11.glVertex2f(x+80,y); GL11.glVertex2f(x+80,y+80); GL11.glVertex2f(x,y+80); GL11.glEnd(); GL11.glPopMatrix(); } /** * Method which makes calculations for movement based on keypresses */ public void moveObject(){ //rotate by x degrees while it is moving; //Left if(Keyboard.isKeyDown(Keyboard.KEY_A)){ x-=0.5f; rotation -= 0.15f; } //Right if(Keyboard.isKeyDown(Keyboard.KEY_D)){ x+=0.5f; rotation += 0.15f; } //Up if(Keyboard.isKeyDown(Keyboard.KEY_W)){ y+=0.5f; rotation += 0.15f; } //Down if(Keyboard.isKeyDown(Keyboard.KEY_S)){ y-=0.5f; rotation -= 0.15f; } } }
mit
henkaku/henkaku
urop/loader.py
3647
#!/usr/bin/env python3 from target_360 import Rop360, G, F from rop import Ret, Load from relocatable import SceWebKit_base, SceLibKernel_base, SceLibc_base, \ SceLibHttp_base, SceNet_base, SceAppMgr_base from sys import argv, exit # Constants stack_size = 6 * 1024 * 1024 max_code_size = stack_size // 2 memblock_size = 1024 * 1024 stack_alloc = 0x1000 def make_rop(henkaku_bin_url, henkaku_bin_len, henkaku_bin_words): r = Rop360() c = r.caller d = r.data bases = [0, -1, SceWebKit_base, SceLibKernel_base, SceLibc_base, SceLibHttp_base, SceNet_base, SceAppMgr_base] r.pre_alloc_data( thread_id=4, thread_info=0x80, stack_base=4, # second thread will pivot here memblock=4, memblock_base=4, stage2_url_base=henkaku_bin_url, http_uid=4, bases=len(bases) * 4, ldm_buf=7*4, ) c.sceKernelCreateThread("", G.ldm_r1_stuff, 0x10000100, stack_size) c.store(Ret, d.thread_id) c.store(0x7C, d.thread_info) c.sceKernelGetThreadInfo(Load(d.thread_id), d.thread_info) # some free space for function calls c.add(Load(d.thread_info + 0x34), stack_alloc) c.store(Ret, d.stack_base) # clean the stack c.memset(Load(d.stack_base), 0, stack_size - stack_alloc) # temp memblock to read henkaku.bin to it and relocate in place # since we can't sceIoRead straight into another thread's stack c.sceKernelAllocMemBlock("", 0x0c20d060, memblock_size, 0) c.store(Ret, d.memblock) c.sceKernelGetMemBlockBase(Load(d.memblock), d.memblock_base) # online loader c.sceHttpInit(0x10000) c.sceHttpCreateTemplate("", 2, 1) c.sceHttpCreateConnectionWithURL(Ret, d.stage2_url_base, 0) c.sceHttpCreateRequestWithURL(Ret, 0, d.stage2_url_base, 0, 0, 0) c.store(Ret, d.http_uid) c.sceHttpSendRequest(Load(d.http_uid), 0, 0) c.sceHttpReadData(Load(d.http_uid), Load(d.memblock_base), memblock_size) # prepare relocation array, same layout as with normal loader, but here relocations are done in rop cur_pbase = d.bases for i, base in enumerate(bases): if i == 1: # Special handling for new data_base c.add(Load(d.stack_base), max_code_size) c.store(Ret, cur_pbase) else: c.store(base, cur_pbase) cur_pbase += 4 # relocate the second stage rop! # Every word is 4 bytes, plus there's relocs at the bottom 1 byte each r.relocate_rop(d.memblock_base, henkaku_bin_words, d.bases) c.memcpy(Load(d.stack_base), Load(d.memblock_base), henkaku_bin_len) # prepare args for LDM gadget c.store(Load(d.stack_base), d.ldm_buf+5*4) c.store(G.pop_pc, d.ldm_buf+6*4) # start second thread c.sceKernelStartThread(Load(d.thread_id), 7 * 4, d.ldm_buf) c.sceKernelWaitThreadEnd(Load(d.thread_id), 0, 0) r.infloop() r.compile() return r tpl = """ payload = [{}]; relocs = [{}]; """ def main(): if len(argv) != 5: print("Usage: loader.py henkaku-bin-url henkaku-bin-file henkaku-bin-words output-js-file") return 1 henkaku_bin_url = argv[1] with open(argv[2], "rb") as fin: henkaku_bin_data = fin.read() henkaku_bin_len = len(henkaku_bin_data) henkaku_bin_words = int(argv[3]) output_file = argv[4] rop = make_rop(henkaku_bin_url, henkaku_bin_len, henkaku_bin_words) with open(output_file, "w") as fout: fout.write(tpl.format(",".join(str(x) for x in rop.compiled_rop), ",".join(str(x) for x in rop.compiled_relocs))) return 0 if __name__ == "__main__": exit(main())
mit
unbornchikken/NOOOCL
lib/clSampler.js
1812
"use strict"; var CLWrapper = require("./clWrapper"); var util = require("util"); var fastcall = require("fastcall"); var ref = fastcall.ref; var clUtils = require("./clUtils"); function createReleaseFunction(cl, handle) { return CLWrapper._releaseFunction(function () { cl.imports.clReleaseSampler(handle); }); } /** * creates a sampler object * * Params: * normalizedCoords= determines if the image coordinates specified are normalized * addressingMode = specifies how out-of-range image coordinates are handled when reading from an image * filterMode = specifies the type of filter that must be applied when reading an image */ function CLSampler(context, normalizedCoords, addressingMode, filterMode) { var cl = context.cl; var err = ref.alloc(cl.types.ErrorCode); var handle = cl.imports.clCreateSampler(clUtils.toHandle(context, "context"), normalizedCoords, addressingMode, filterMode, err); cl.checkError(err); CLWrapper.call(this, cl, handle, createReleaseFunction(cl, handle)); this.context = context; } util.inherits(CLSampler, CLWrapper); Object.defineProperties(CLSampler.prototype, { _classInfoFunction: { get: function () { return "clGetSamplerInfo"; } }, normalizedCoords: { get: function () { return this._getInfo("bool", this.cl.defs.CL_SAMPLER_NORMALIZED_COORDS); } }, addressingMode: { get: function () { return this._getInfo(this.cl.types.AddressingMode, this.cl.defs.CL_SAMPLER_ADDRESSING_MODE); } }, filterMode: { get: function () { return this._getInfo(this.cl.types.FilterMode, this.cl.defs.CL_SAMPLER_FILTER_MODE); } } }); module.exports = CLSampler;
mit
interpunkt/generator-craftskeleton
generators/app/templates/_plugins/retour/migrations/m160426_020311_retour_FixIndexes.php
861
<?php namespace Craft; /** * The class name is the UTC timestamp in the format of mYYMMDD_HHMMSS_pluginHandle_migrationName */ class m160426_020311_retour_FixIndexes extends BaseMigration { /** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { craft()->db->createCommand()->dropIndex('retour_redirects', 'redirectSrcUrl', true); craft()->db->createCommand()->createIndex('retour_redirects', 'redirectSrcUrlParsed', true); craft()->db->createCommand()->dropIndex('retour_static_redirects', 'redirectSrcUrl', true); craft()->db->createCommand()->createIndex('retour_static_redirects', 'redirectSrcUrlParsed', true); RetourPlugin::log("Updated Indexes for retour_redirects & retour_static_redirects", LogLevel::Info, true); return true; } }
mit
ilfeng/hsr
src/js/framework/core/utils/url.js
2675
/** * 地址辅助类。 * * @type {class} * @static */ define(['jquery', 'ns', 'util-string'], function ($, ns, StringUtils) { 'use strict'; return (ns.UrlUtils = { /** * 转换字符串地址为对象。 * * @param {string} url 地址。 * * @return {object} 地址对象。 */ parse: function (url) { if (StringUtils.isBlank(url)) return null; var local = '', ps = null, obj = {}; // 拆分地址:截取"?"前的部分。 var indexSplit = url.indexOf('?'); if (indexSplit != -1) { local = url.substring(0, indexSplit); ps = url.substring(indexSplit); } else if (url.indexOf('&') > 0) { ps = url; } else { local = url; } // 拆分参数。 if (ps) { var params = ps.split("&"); for (var i = 0; i < params.length; i++) { var param = params[i].split('='), key = param[0], value = param[1], objProp = obj[key]; if (objProp) { if (!Array.isArray(objProp)) { obj[key] = [objProp]; } obj[key].push(value); } else { obj[key] = value; } } } return { url: local, params: obj }; }, /** * 生成带参数的地址。 * * @param {string} url 地址。 * @param {object} params 参数对象。 * * @return {string} 转换后的地址。 */ join: function (url, params) { if (StringUtils.isBlank(url)) return ''; var p = []; var indexSplit = url.lastIndexOf('?'); if (!params) return url; var ps = $.param(params); if (StringUtils.isBlank(ps)) return url; // 添加地址。 p.push(url); // 添加连接符。 if (indexSplit == -1) { // 不存在连接符。 p.push('?'); } else if (indexSplit == 0) { // 最后一个字符为连接符。 } else { // 存在连接符。 p.push('&'); } // 添加参数。 p.push(ps); // 拼接地址。 return p.join(''); } }); });
mit
devcycle/devcycle.github.io
vendor/bundle/gems/jekyll-algolia-1.6.0/lib/jekyll/algolia/version.rb
94
# frozen_string_literal: true module Jekyll module Algolia VERSION = '1.6.0' end end
mit
voxie-viewer/voxie
src/Voxie/filter/filterchain3d.cpp
4786
#include "filterchain3d.hpp" #include <cmath> #include <Voxie/ivoxie.hpp> #include <Voxie/plugin/metafilter3d.hpp> #include <Voxie/plugin/voxieplugin.hpp> #include <Voxie/scripting/scriptingexception.hpp> #include <QtWidgets/QMessageBox> using namespace voxie::data; using namespace voxie::filter; using namespace voxie::plugin; FilterChain3D::FilterChain3D(QObject *parent): QObject(parent) { this->filters = QVector<Filter3D*>(); } FilterChain3D::~FilterChain3D() { this->filters.clear(); } void FilterChain3D::applyTo(voxie::data::DataSet* dataSet) { Filter3D* activeFilter; try { dataSet->resetData(); } catch (voxie::scripting::ScriptingException& e) { qCritical() << "Error while applying filters:" << e.message(); QMessageBox(QMessageBox::Critical, "Voxie: Error while applying filters", QString("Error while applying filters: %1").arg(e.message()), QMessageBox::Ok, voxieRoot().mainWindow()).exec(); return; } QSharedPointer<voxie::data::VoxelData> volume = dataSet->filteredData(); for(int x=0; x < this->filters.length(); x++) { activeFilter = this->filters.at(x); if(activeFilter->isEnabled()) { volume = activeFilter->applyTo(volume); } } this->outputVolume = volume; emit volume->changed(); emit this->allFiltersApplied(); // signals that chain has finished work so that application can get output } void FilterChain3D::addFilter(Filter3D* filter) { if(filter != nullptr){ this->filters.append(filter); connect(filter, &Filter3D::filterChanged, this, & FilterChain3D::onFilterChanged); if(this->signalOnChangeEnabled()) emit this->filterListChanged(); } } void FilterChain3D::removeFilter(Filter3D* filter) { //get filter position int filterPos = this->filters.indexOf(filter,0); //check if filter found if(filterPos == -1) { //no matching } this->filters.remove(filterPos); disconnect(filter, &Filter3D::filterChanged, this, & FilterChain3D::onFilterChanged); if(this->signalOnChangeEnabled()) emit this->filterListChanged(); } void FilterChain3D::changePosition(Filter3D* filter, int pos) { //get filter position for deleting int filterPos = this->filters.indexOf(filter,0); if(filterPos == -1) //check if filter found { //no matching } this->filters.remove(filterPos); this->filters.insert(pos, filter); if(this->signalOnChangeEnabled()) emit this->filterListChanged(); } QVector<Filter3D*> FilterChain3D::getFilters() { return this->filters; } Filter3D* FilterChain3D::getFilter(int pos) { return this->filters.at(pos); } QSharedPointer<VoxelData> FilterChain3D::getOutputVolume() { return this->outputVolume; } void FilterChain3D::toXML(QString fileName) { QFile file(fileName); file.open(QIODevice::WriteOnly); QXmlStreamWriter xml; xml.setDevice(&file); xml.setAutoFormatting(true); xml.writeStartDocument(); xml.writeDTD("<!DOCTYPE filterchain>"); xml.writeStartElement("filterchain3d"); xml.writeAttribute("version", "1.0"); for(int i=0; i<this->getFilters().size(); i++) { xml.writeStartElement(this->getFilter(i)->getMetaName()); xml.writeAttribute("type", "filter3d"); xml.writeAttributes(this->getFilter(i)->exportFilterSettingsXML()); xml.writeEndElement(); } xml.writeEndDocument(); file.flush(); file.close(); } void FilterChain3D::fromXML(QString fileName) { QFile file(fileName); file.open(QIODevice::ReadOnly); QXmlStreamReader xml; xml.setDevice(&file); if (xml.readNextStartElement()) { if (!(xml.name() == "filterchain3d" && xml.attributes().value("version") == "1.0")) { xml.raiseError(QObject::tr("The file is no valid filterchain.")); QMessageBox messageBox; messageBox.critical(0,"Error","Invalid filterchain file."); messageBox.setFixedSize(500,200); return; } } this->filters.clear(); while (xml.readNextStartElement()) { if (xml.attributes().value("type").compare(QString("filter3d"))==0) { for(VoxiePlugin* plugin : ::voxie::voxieRoot().plugins()) { for(MetaFilter3D *metaFilter : plugin->filters3D()) { if (metaFilter->objectName().compare(xml.name())==0) { Filter3D* filter = metaFilter->createFilter(); this->addFilter(filter); filter->importFilterSettingsXML(xml.attributes()); } } } } xml.skipCurrentElement(); } emit filterListChanged(); } // Local Variables: // mode: c++ // tab-width: 4 // c-basic-offset: 4 // End:
mit
jpwerka/SistemaSFG
SfgEstoque.cpp
2622
//--------------------------------------------------------------------------- #include <vcl.h> #include <windows.h> #include "uSfgGlobals.h" #include "uSfgTools.h" #pragma hdrstop //--------------------------------------------------------------------------- // Important note about DLL memory management when your DLL uses the // static version of the RunTime Library: // // If your DLL exports any functions that pass String objects (or structs/ // classes containing nested Strings) as parameter or function results, // you will need to add the library MEMMGR.LIB to both the DLL project and // any other projects that use the DLL. You will also need to use MEMMGR.LIB // if any other projects which use the DLL will be performing new or delete // operations on any non-TObject-derived classes which are exported from the // DLL. Adding MEMMGR.LIB to your project will change the DLL and its calling // EXE's to use the BORLNDMM.DLL as their memory manager. In these cases, // the file BORLNDMM.DLL should be deployed along with your DLL. // // To avoid using BORLNDMM.DLL, pass string information using "char *" or // ShortString parameters. // // If your DLL uses the dynamic version of the RTL, you do not need to // explicitly add MEMMGR.LIB as this will be done implicitly for you //--------------------------------------------------------------------------- USEFORM("Produto\uPrd1001.cpp", Prd1001); USEFORM("Produto\uPrd1002.cpp", Prd1002); USEFORM("Produto\uPrd1003.cpp", Prd1003); USEFORM("Produto\uPrd1004.cpp", Prd1004); USEFORM("Produto\uPrd2001.cpp", Prd2001); USEFORM("Produto\uPrd2002.cpp", Prd2002); USEFORM("Produto\uPrd3001.cpp", Prd3001); USEFORM("Produto\uPrd3002.cpp", Prd3002); USEFORM("Produto\uPrd3003.cpp", Prd3003); USEFORM("Produto\uPrd3004.cpp", Prd3004); //--------------------------------------------------------------------------- #pragma link "Utils/uSfgBrowseSup.obj" //--------------------------------------------------------------------------- extern "C" void __declspec(dllexport) WINAPI SfgEstoqueInit(LPARAM lParam); extern "C" void __declspec(dllexport) WINAPI SfgEstoqueFinish(); #pragma argsused BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, LPVOID lpvReserved) { return 1; } //--------------------------------------------------------------------------- void WINAPI SfgEstoqueInit(LPARAM lParam) { //Não faz nada } //--------------------------------------------------------------------------- void WINAPI SfgEstoqueFinish() { //Não faz nada } //---------------------------------------------------------------------------
mit
luanhsd/IFLattes
application/models/Area_model.php
517
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Area_Model extends CI_Model { public function __construct() { parent::__construct(); } public function datalist() { $query = $this->db->query('SELECT grande_area,if(area="","Não Informado",area) as area,if(sub_area="","Não Informado",sub_area) as sub_area,if(espec="","Não Informado",espec) as espec FROM fat_area;'); return $query->result(); } public function count() { } }
mit
Sebubu/BringToAfrica
app/viewmodels/ProjectDetail.java
1440
package viewmodels; import models.Donation; import models.DonationGoal; import models.Project; import models.User; import services.DonationGoalService; import services.ProjectService; import java.util.ArrayList; import java.util.List; import java.util.Set; public class ProjectDetail { private int state; private Project project; public ProjectDetail(models.Project project) { this.state = ProjectService.getStateOfProjectInPercent(project); this.project = project; } public int getState() { return state; } public Project getProject() { return project; } public int getStateOfDonationGoalInPercent(DonationGoal donationGoal) { return DonationGoalService.getStateInPercent(donationGoal); } public int getStateOfDonationGoal(DonationGoal donationGoal) { return DonationGoalService.getState(donationGoal); } public Set<User> getDonators() { return ProjectService.getDonators(this.project); } public List<Donation> getDonationsForUser(User user) { List<Donation> donations = new ArrayList<>(); for (DonationGoal donationGoal : project.getDonationGoals()) { for (Donation donation : donationGoal.getDonations()) { if (donation.getUser().equals(user)) { donations.add(donation); } } } return donations; } }
mit
martinski74/SoftUni
C#_Basic/Задачи/CSharpBasicExam11AprlilEvening2014/05.CatchTheBits/Program.cs
906
using System; class Program { static void Main() { int n = int.Parse(Console.ReadLine()); int step = int.Parse(Console.ReadLine()); int sequence = 0; int bitCount = 0; for (int i = 1, k = 1; i <= n; i++) { byte currentByte = byte.Parse(Console.ReadLine()); for (; k < i * 8; k += step) { int pos = 7 - (k % 8); sequence <<= 1; sequence |= (currentByte & (1 << pos)) >> pos; bitCount++; if (bitCount == 8) { Console.WriteLine(sequence); sequence = 0; bitCount = 0; } } } if (bitCount > 0) { sequence <<= 8 - bitCount; Console.WriteLine(sequence); } } }
mit
Karasiq/scalajs-highcharts
src/main/scala/com/highmaps/config/PlotOptionsIkhMarkerStatesSelect.scala
3967
/** * Automatically generated file. Please do not edit. * @author Highcharts Config Generator by Karasiq * @see [[http://api.highcharts.com/highmaps]] */ package com.highmaps.config import scalajs.js, js.`|` import com.highcharts.CleanJsObject import com.highcharts.HighchartsUtils._ /** * @note JavaScript name: <code>plotOptions-ikh-marker-states-select</code> */ @js.annotation.ScalaJSDefined class PlotOptionsIkhMarkerStatesSelect extends com.highcharts.HighchartsGenericObject { /** * <p>The fill color of the point marker.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-states-select-fillcolor/">Solid red discs for selected points</a> * @since 6.0.0 */ val fillColor: js.UndefOr[String | js.Object] = js.undefined /** * <p>The color of the point marker&#39;s outline. When <code>undefined</code>, * the series&#39; or point&#39;s color is used.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-states-select-linecolor/">Red line color for selected points</a> * @since 6.0.0 */ val lineColor: js.UndefOr[String | js.Object] = js.undefined /** * <p>The width of the point marker&#39;s outline.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-states-select-linewidth/">3px line width for selected points</a> * @since 6.0.0 */ val lineWidth: js.UndefOr[Double] = js.undefined /** * <p>The radius of the point marker. In hover state, it defaults * to the normal state&#39;s radius + 2.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-states-select-radius/">10px radius for selected points</a> * @since 6.0.0 */ val radius: js.UndefOr[Double] = js.undefined /** * <p>Enable or disable visible feedback for selection.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-states-select-enabled/">Disabled select state</a> * @since 6.0.0 */ val enabled: js.UndefOr[Boolean] = js.undefined } object PlotOptionsIkhMarkerStatesSelect { /** * @param fillColor <p>The fill color of the point marker.</p> * @param lineColor <p>The color of the point marker&#39;s outline. When <code>undefined</code>,. the series&#39; or point&#39;s color is used.</p> * @param lineWidth <p>The width of the point marker&#39;s outline.</p> * @param radius <p>The radius of the point marker. In hover state, it defaults. to the normal state&#39;s radius + 2.</p> * @param enabled <p>Enable or disable visible feedback for selection.</p> */ def apply(fillColor: js.UndefOr[String | js.Object] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, radius: js.UndefOr[Double] = js.undefined, enabled: js.UndefOr[Boolean] = js.undefined): PlotOptionsIkhMarkerStatesSelect = { val fillColorOuter: js.UndefOr[String | js.Object] = fillColor val lineColorOuter: js.UndefOr[String | js.Object] = lineColor val lineWidthOuter: js.UndefOr[Double] = lineWidth val radiusOuter: js.UndefOr[Double] = radius val enabledOuter: js.UndefOr[Boolean] = enabled com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsIkhMarkerStatesSelect { override val fillColor: js.UndefOr[String | js.Object] = fillColorOuter override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter override val lineWidth: js.UndefOr[Double] = lineWidthOuter override val radius: js.UndefOr[Double] = radiusOuter override val enabled: js.UndefOr[Boolean] = enabledOuter }) } }
mit
PenguinSquad/Harvest-Festival
src/main/java/joshie/harvest/npcs/gui/GuiNPCGift.java
2253
package joshie.harvest.npcs.gui; import joshie.harvest.api.npc.gift.IGiftHandler.Quality; import joshie.harvest.core.HFTrackers; import joshie.harvest.core.helpers.TextHelper; import joshie.harvest.npcs.NPCHelper; import joshie.harvest.npcs.entity.EntityNPC; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumHand; import java.util.Locale; public class GuiNPCGift extends GuiNPCChat { public static ItemStack GODDESS_GIFT; private final ItemStack gift; private final Quality value; private final EntityNPC npc; public GuiNPCGift(EntityPlayer player, EntityNPC npc, EnumHand hand) { super(new ContainerNPCGift(player, npc, hand, -1), player, npc); this.gift = player.getHeldItem(hand).copy(); this.value = npc.getNPC().getGiftValue(gift); this.npc = npc; } public GuiNPCGift(EntityPlayer player, EntityNPC npc, ItemStack gift) { super(new ContainerNPCGift(player, npc, null, -1), player, npc); this.gift = gift; this.value = npc.getNPC().getGiftValue(gift); this.npc = npc; } @Override public String getScript() { if (NPCHelper.INSTANCE.getGifts().isBlacklisted(player.world, player, gift)) return TextHelper.getSpeech(npc, "gift.no"); //TODO: Reenable in 1.0 when I readd marriage /* if (ToolHelper.isBlueFeather(gift)) { int relationship = HFApi.player.getRelationsForPlayer(player).getRelationship(npc.getNPC().getUUID()); if (relationship >= HFNPCs.MAX_FRIENDSHIP && npc.getNPC().isMarriageCandidate()) { return TextHelper.getSpeech(npc, "marriage.accept"); } else return TextHelper.getSpeech(npc, "marriage.reject"); } else */if (GODDESS_GIFT != null || HFTrackers.getClientPlayerTracker().getRelationships().gift(player, npc.getNPC(), value.getRelationPoints())) { return TextHelper.getSpeech(npc, "gift." + value.name().toLowerCase(Locale.ENGLISH)); } else return TextHelper.getSpeech(npc, "gift.reject"); } @Override public void endChat() { player.closeScreen(); GODDESS_GIFT = null; //Reset npc.setTalking(null); } }
mit
PieterScheffers/ll-protocol
src/utils/FrameHeader.js
1263
'use strict'; // | ID (4) | index (4) | isLast (1) (170 === true) | class FrameHeader { constructor(fields = {}) { this._fields = fields; } // TODO: add frame length to validate length toBuffer() { let buffer = Buffer.alloc(FrameHeader.headerLength()); buffer.writeUInt32LE(this._fields.id, 0); buffer.writeUInt32LE(this._fields.index, 4); let endInt = this._fields.end ? 2 : 1; buffer.writeUInt8(endInt, 8); return buffer; } toObject() { return { id: this._fields.id, index: this._fields.index, end: this._fields.end }; } set id(id) { this._fields.id = id; } get id() { return this._fields.id; } set index(index) { this._fields.index = index; } get index() { return this._fields.index; } set end(end) { this._fields.end = (end ? true : false); } get end() { return this._fields.end; } static headerLength() { return 9; } static removeHeader(buffer) { return buffer.slice(FrameHeader.headerLength()); } static parseBuffer(buffer) { return new FrameHeader({ id: buffer.readUInt32LE(0), index: buffer.readUInt32LE(4), end: buffer.readUInt8(8) === 2 }); } } module.exports = FrameHeader;
mit
zingcoin/zingcoin
src/net.cpp
56641
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2013 Zingcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "db.h" #include "net.h" #include "init.h" #include "addrman.h" #include "ui_interface.h" #include "script.h" #ifdef WIN32 #include <string.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniwget.h> #include <miniupnpc/miniupnpc.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif // period dump peer.dat in second const unsigned int dump_addresses_interval = 900; using namespace std; using namespace boost; static const int MAX_OUTBOUND_CONNECTIONS = 24; bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false); struct LocalServiceInfo { int nScore; int nPort; }; // // Global state variables // bool fDiscover = true; uint64 nLocalServices = NODE_NETWORK; static CCriticalSection cs_mapLocalHost; static map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; static CNode* pnodeSync = NULL; uint64 nLocalHostNonce = 0; static std::vector<SOCKET> vhListenSocket; CAddrMan addrman; int nMaxConnections = 125; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<CInv, CDataStream> mapRelay; deque<pair<int64, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; limitedmap<CInv, int64> mapAlreadyAskedFor(MAX_INV_SZ); static deque<string> vOneShots; CCriticalSection cs_vOneShots; set<CNetAddr> setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; vector<std::string> vAddedNodes; CCriticalSection cs_vAddedNodes; static CSemaphore *semOutbound = NULL; void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", GetDefaultPort())); } void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd) { // Filter out duplicate requests if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd) return; pindexLastGetBlocksBegin = pindexBegin; hashLastGetBlocksEnd = hashEnd; PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr *paddrPeer) { if (fNoListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress CAddress GetLocalAddress(const CNetAddr *paddrPeer) { CAddress ret(CService("0.0.0.0",0),0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); } return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; loop { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { boost::this_thread::interruption_point(); if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { MilliSleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed printf("socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); printf("recv failed: %d\n", nErr); return false; } } } } // used when scores of local addresses may have changed // pushes better local address to peers void static AdvertizeLocal() { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal) { pnode->PushAddress(addrLocal); pnode->addrLocal = addrLocal; } } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo &info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } SetReachable(addr.GetNetwork()); } AdvertizeLocal(); return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr &addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } AdvertizeLocal(); return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { LOCK(cs_mapLocalHost); enum Network net = addr.GetNetwork(); return vfReachable[net] && !vfLimited[net]; } bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet) { SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str()); send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL); string strLine; while (RecvLine(hSocket, strLine)) { if (strLine.empty()) // HTTP response is separated from headers by blank line { loop { if (!RecvLine(hSocket, strLine)) { closesocket(hSocket); return false; } if (pszKeyword == NULL) break; if (strLine.find(pszKeyword) != string::npos) { strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword)); break; } } closesocket(hSocket); if (strLine.find("<") != string::npos) strLine = strLine.substr(0, strLine.find("<")); strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r")); while (strLine.size() > 0 && isspace(strLine[strLine.size()-1])) strLine.resize(strLine.size()-1); CService addr(strLine,0,true); printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str()); if (!addr.IsValid() || !addr.IsRoutable()) return false; ipRet.SetIP(addr); return true; } } closesocket(hSocket); return error("GetMyExternalIP() : connection closed"); } bool GetMyExternalIP(CNetAddr& ipRet) { CService addrConnect; const char* pszGet; const char* pszKeyword; for (int nLookup = 0; nLookup <= 1; nLookup++) for (int nHost = 1; nHost <= 2; nHost++) { // We should be phasing out our use of sites like these. If we need // replacements, we should ask for volunteers to put this simple // php file on their web server that prints the client IP: // <?php echo $_SERVER["REMOTE_ADDR"]; ?> if (nHost == 1) { addrConnect = CService("91.198.22.70", 80); // checkip.dyndns.org if (nLookup == 1) { CService addrIP("checkip.dyndns.org", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET / HTTP/1.1\r\n" "Host: checkip.dyndns.org\r\n" "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = "Address:"; } else if (nHost == 2) { addrConnect = CService("212.117.175.194", 80); // www.showmyip.com if (nLookup == 1) { CService addrIP("www.showmyip.com", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET /simple/ HTTP/1.1\r\n" "Host: www.showmyip.com\r\n" "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = NULL; // Returns just IP address } if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet)) return true; } return false; } void ThreadGetMyExternalIP(void* parg) { // Make this thread recognisable as the external IP detection thread RenameThread("bitcoin-ext-ip"); CNetAddr addrLocalHost; if (GetMyExternalIP(addrLocalHost)) { printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str()); AddLocal(addrLocalHost, LOCAL_HTTP); } } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } CNode* FindNode(const CNetAddr& ip) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); return NULL; } CNode* FindNode(std::string addrName) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CService)pnode->addr == addr) return (pnode); return NULL; } CNode* ConnectNode(CAddress addrConnect, const char *pszDest) { if (pszDest == NULL) { if (IsLocal(addrConnect)) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->AddRef(); return pnode; } } /// debug print printf("trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString().c_str(), pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); // Connect SOCKET hSocket; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket)) { addrman.Attempt(addrConnect); /// debug print printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str()); // Set to non-blocking #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError()); #else if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno); #endif // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); return pnode; } else { return NULL; } } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { printf("disconnecting node %s\n", addrName.c_str()); closesocket(hSocket); hSocket = INVALID_SOCKET; } // in case this fails, we'll empty the recv buffer when the CNode is deleted TRY_LOCK(cs_vRecvMsg, lockRecv); if (lockRecv) vRecvMsg.clear(); // if this was the sync node, we'll need a new one if (this == pnodeSync) pnodeSync = NULL; } void CNode::Cleanup() { } void CNode::PushVersion() { /// when NTP implemented, change to just nTime = GetAdjustedTime() int64 nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0))); CAddress addrMe = GetLocalAddress(&addr); RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str()); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight); } std::map<CNetAddr, int64> CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); std::map<CNetAddr, int64>::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64 t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Misbehaving(int howmuch) { if (addr.IsLocal()) { printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch); return false; } nMisbehavior += howmuch; if (nMisbehavior >= GetArg("-banscore", 100)) { int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior); { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } CloseSocketDisconnect(); return true; } else printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior); return false; } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(addrName); X(nVersion); X(strSubVer); X(fInbound); X(nStartingHeight); X(nMisbehavior); X(nSendBytes); X(nRecvBytes); stats.fSyncNode = (this == pnodeSync); } #undef X // requires LOCK(cs_vRecvMsg) bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes) { while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; pch += handled; nBytes -= handled; } return true; } int CNetMessage::readHeader(const char *pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (std::exception &e) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; vRecv.resize(hdr.nMessageSize); return nCopy; } int CNetMessage::readData(const char *pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } // requires LOCK(cs_vSend) void SocketSendData(CNode *pnode) { std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin(); while (it != pnode->vSendMsg.end()) { const CSerializeData &data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { pnode->nLastSend = GetTime(); pnode->nSendBytes += nBytes; pnode->nSendOffset += nBytes; if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { printf("socket send error %d\n", nErr); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } static list<CNode*> vNodesDisconnected; void ThreadSocketHandler() { unsigned int nPrevNodeCount = 0; loop { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); pnode->Cleanup(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if (vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(vNodes.size()); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) { FD_SET(hListenSocket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket); have_fds = true; } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); have_fds = true; // Implement the following logic: // * If there is data to send, select() for sending data. As this only // happens when optimistic write failed, we choose to first drain the // write buffer in this case before receiving more. This avoids // needlessly queueing received data, if the remote peer is not themselves // receiving data. This means properly utilizing TCP flow control signalling. // * Otherwise, if there is no (complete) message in the receive buffer, // or there is space left in the buffer, select() for receiving data. // * (if neither of the above applies, there is certainly one message // in the receiver buffer ready to be processed). // Together, that means that at least one of the following is always possible, // so we don't deadlock: // * We send some data. // * We wait for data to be received (and disconnect after timeout). // * We process a message in the buffer (message handler thread). { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend && !pnode->vSendMsg.empty()) { FD_SET(pnode->hSocket, &fdsetSend); continue; } } { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv && ( pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() || pnode->GetTotalRecvSize() <= ReceiveFloodSize())) FD_SET(pnode->hSocket, &fdsetRecv); } } } int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); boost::this_thread::interruption_point(); if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); printf("socket select error %d\n", nErr); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec/1000); } // // Accept new connections // BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv)) { #ifdef USE_IPV6 struct sockaddr_storage sockaddr; #else struct sockaddr sockaddr; #endif socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) printf("Warning: Unknown socket family\n"); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) printf("socket error accept failed: %d\n", nErr); } else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) { { LOCK(cs_setservAddNodeAddresses); if (!setservAddNodeAddresses.count(addr)) closesocket(hSocket); } } else if (CNode::IsBanned(addr)) { printf("connection from %s dropped (banned)\n", addr.ToString().c_str()); closesocket(hSocket); } else { printf("accepted connection %s\n", addr.ToString().c_str()); CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } // // Service each socket // vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH(CNode* pnode, vNodesCopy) { boost::this_thread::interruption_point(); // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) pnode->CloseSocketDisconnect(); pnode->nLastRecv = GetTime(); pnode->nRecvBytes += nBytes; } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) printf("socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) printf("socket recv error %d\n", nErr); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SocketSendData(pnode); } // // Inactivity checking // if (pnode->vSendMsg.empty()) pnode->nLastSendEmpty = GetTime(); if (GetTime() - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0); pnode->fDisconnect = true; } else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60) { printf("socket not sending\n"); pnode->fDisconnect = true; } else if (GetTime() - pnode->nLastRecv > 90*60) { printf("socket inactivity timeout\n"); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } MilliSleep(10); } } #ifdef USE_UPNP void ThreadMapPort() { std::string port = strprintf("%u", GetListenPort()); const char * multicastif = 0; const char * minissdpdpath = 0; struct UPNPDev * devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #else /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) printf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if(externalIPAddress[0]) { printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else printf("UPnP: GetExternalIPAddress failed.\n"); } } string strDesc = "Bitcoin " + FormatFullVersion(); try { loop { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if(r!=UPNPCOMMAND_SUCCESS) printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port.c_str(), port.c_str(), lanaddr, r, strupnperror(r)); else printf("UPnP Port Mapping successful.\n");; MilliSleep(20*60*1000); // Refresh every 20 minutes } } catch (boost::thread_interrupted) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); printf("UPNP_DeletePortMapping() returned : %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); throw; } } else { printf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); } } void MapPort(bool fUseUPnP) { static boost::thread* upnp_thread = NULL; if (fUseUPnP) { if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; } upnp_thread = new boost::thread(boost::bind(&TraceThread<boost::function<void()> >, "upnp", &ThreadMapPort)); } else if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; upnp_thread = NULL; } } #else void MapPort(bool) { // Intentionally left blank. } #endif // DNS seeds // Each pair gives a source name and a seed name. // The first name is used as information source for addrman. // The second name should resolve to a list of seed addresses. static const char *strMainNetDNSSeed[][2] = { {"69.10.58.157", "69.10.58.157"}, {NULL, NULL} }; static const char *strTestNetDNSSeed[][2] = { {NULL, NULL} }; void ThreadDNSAddressSeed() { static const char *(*strDNSSeed)[2] = fTestNet ? strTestNetDNSSeed : strMainNetDNSSeed; int found = 0; printf("Loading addresses from DNS seeds (could take a while)\n"); for (unsigned int seed_idx = 0; strDNSSeed[seed_idx][0] != NULL; seed_idx++) { if (HaveNameProxy()) { AddOneShot(strDNSSeed[seed_idx][1]); } else { vector<CNetAddr> vaddr; vector<CAddress> vAdd; if (LookupHost(strDNSSeed[seed_idx][1], vaddr)) { BOOST_FOREACH(CNetAddr& ip, vaddr) { int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true)); } } printf("%d addresses found from DNS seeds\n", found); } unsigned int pnSeed[] = { 0x01020304 }; void DumpAddresses() { int64 nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n", addrman.size(), GetTimeMillis() - nStart); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void ThreadOpenConnections() { // Connect to specific addresses if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64 nLoop = 0;; nLoop++) { ProcessOneShot(); BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { MilliSleep(500); } } MilliSleep(500); } } // Initiate network connections int64 nStart = GetTime(); loop { ProcessOneShot(); MilliSleep(500); CSemaphoreGrant grant(*semOutbound); boost::this_thread::interruption_point(); // Add seed nodes if IRC isn't working if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet) { std::vector<CAddress> vAdd; for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64 nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek; vAdd.push_back(addr); } addrman.Add(vAdd, CNetAddr("127.0.0.1")); } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set<vector<unsigned char> > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64 nANow = GetAdjustedTime(); int nTries = 0; loop { // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections) CAddress addr = addrman.Select(10 + min(nOutbound,8)*10); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections() { { LOCK(cs_vAddedNodes); vAddedNodes = mapMultiArgs["-addnode"]; } if (HaveNameProxy()) { while(true) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } BOOST_FOREACH(string& strAddNode, lAddresses) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } for (unsigned int i = 0; true; i++) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } list<vector<CService> > lservAddressesToAdd(0); BOOST_FOREACH(string& strAddNode, lAddresses) { vector<CService> vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0)) { lservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH(CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) BOOST_FOREACH(CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = lservAddressesToAdd.erase(it); it--; break; } } BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot) { // // Initiate outbound network connection // boost::this_thread::interruption_point(); if (!strDest) if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort().c_str())) return false; if (strDest && FindNode(strDest)) return false; CNode* pnode = ConnectNode(addrConnect, strDest); boost::this_thread::interruption_point(); if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } // for now, use a very simple selection metric: the node from which we received // most recently double static NodeSyncScore(const CNode *pnode) { return -pnode->nLastRecv; } void static StartSync(const vector<CNode*> &vNodes) { CNode *pnodeNewSync = NULL; double dBestScore = 0; // fImporting and fReindex are accessed out of cs_main here, but only // as an optimization - they are checked again in SendMessages. if (fImporting || fReindex) return; // Iterate over all nodes BOOST_FOREACH(CNode* pnode, vNodes) { // check preconditions for allowing a sync if (!pnode->fClient && !pnode->fOneShot && !pnode->fDisconnect && pnode->fSuccessfullyConnected && (pnode->nStartingHeight > (nBestHeight - 144)) && (pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) { // if ok, compare node's score with the best so far double dScore = NodeSyncScore(pnode); if (pnodeNewSync == NULL || dScore > dBestScore) { pnodeNewSync = pnode; dBestScore = dScore; } } } // if a new sync candidate was found, start sync! if (pnodeNewSync) { pnodeNewSync->fStartSync = true; pnodeSync = pnodeNewSync; } } void ThreadMessageHandler() { SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (true) { bool fHaveSyncNode = false; vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { pnode->AddRef(); if (pnode == pnodeSync) fHaveSyncNode = true; } } if (!fHaveSyncNode) StartSync(vNodesCopy); // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) if (!ProcessMessages(pnode)) pnode->CloseSocketDisconnect(); } boost::this_thread::interruption_point(); // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SendMessages(pnode, pnode == pnodeTrickle); } boost::this_thread::interruption_point(); } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } MilliSleep(100); } } bool BindListenPort(const CService &addrBind, string& strError) { strError = ""; int nOne = 1; // Create socket for listening for incoming connections #ifdef USE_IPV6 struct sockaddr_storage sockaddr; #else struct sockaddr sockaddr; #endif socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str()); printf("%s\n", strError.c_str()); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif #ifndef WIN32 // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif #ifdef WIN32 // Set to non-blocking, incoming connections will also inherit this if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR) #else if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) #endif { strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } #ifdef USE_IPV6 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */; int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */; // this call is allowed to fail setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int)); #endif } #endif if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. Bitcoin is probably already running."), addrBind.ToString().c_str()); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr)); printf("%s\n", strError.c_str()); return false; } printf("Bound to %s\n", addrBind.ToString().c_str()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } vhListenSocket.push_back(hListenSocket); if (addrBind.IsRoutable() && fDiscover) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover() { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[1000] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr)) { BOOST_FOREACH (const CNetAddr &addr, vaddr) { AddLocal(addr, LOCAL_IF); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str()); } #ifdef USE_IPV6 else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str()); } #endif } freeifaddrs(myaddrs); } #endif // Don't use external IPv4 discovery, when -onlynet="IPv6" if (!IsLimited(NET_IPV4)) NewThread(ThreadGetMyExternalIP, NULL); } void StartNode(boost::thread_group& threadGroup) { if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(); // // Start threads // if (!GetBoolArg("-dnsseed", true)) printf("DNS seeding disabled\n"); else threadGroup.create_thread(boost::bind(&TraceThread<boost::function<void()> >, "dnsseed", &ThreadDNSAddressSeed)); #ifdef USE_UPNP // Map ports with UPnP MapPort(GetBoolArg("-upnp", USE_UPNP)); #endif // Send and receive from sockets, accept connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler)); // Initiate outbound connections from -addnode threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections)); // Initiate outbound connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections)); // Process messages threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler)); // Dump network addresses threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, 1000 * dump_addresses_interval)); } bool StopNode() { printf("StopNode()\n"); GenerateBitcoins(false, NULL); MapPort(false); nTransactionsUpdated++; if (semOutbound) for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); MilliSleep(50); DumpAddresses(); return true; } class CNetCleanup { public: CNetCleanup() { } ~CNetCleanup() { // Close sockets BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) closesocket(pnode->hSocket); BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET) if (closesocket(hListenSocket) == SOCKET_ERROR) printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError()); // clean up some globals (to help leak detection) BOOST_FOREACH(CNode *pnode, vNodes) delete pnode; BOOST_FOREACH(CNode *pnode, vNodesDisconnected) delete pnode; vNodes.clear(); vNodesDisconnected.clear(); delete semOutbound; semOutbound = NULL; delete pnodeLocalHost; pnodeLocalHost = NULL; #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void RelayTransaction(const CTransaction& tx, const uint256& hash) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(10000); ss << tx; RelayTransaction(tx, hash, ss); } void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss) { CInv inv(MSG_TX, hash); { LOCK(cs_mapRelay); // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } // Save original serialized message so newer versions are preserved mapRelay.insert(std::make_pair(inv, ss)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if(!pnode->fRelayTxes) continue; LOCK(pnode->cs_filter); if (pnode->pfilter) { if (pnode->pfilter->IsRelevantAndUpdate(tx, hash)) pnode->PushInventory(inv); } else pnode->PushInventory(inv); } }
mit
protobi/msexcel-builder
test/numberformat.js
1557
var fs = require('fs'); var assert = require('assert'); var JSZip = require('jszip'); var path = require('path') var compareWorkbooks = require('./util/compareworkbooks.js') var excelbuilder = require('../lib/msexcel-builder'); describe('It generates a simple workbook', function () { it('takes a file name on save rather than in constructor', function (done) { var PATH = './test/out'; var FILENAME = 'numberformat.xlsx'; var OUTFILE = PATH + "/" + FILENAME; var workbook = excelbuilder.createWorkbook(); var sheet1 = workbook.createSheet('sheet1', 10, 12); sheet1.set(1,1,{ fill : { type: "solid", fgColor: "00FFFFFF"}, // font : { name: "Calibri", sz: 8 }, numberFormat: '#,##0', set: 1.61803398875 }); sheet1.set(1,2,{ fill : { type: "solid", fgColor: "00FFFFFF" }, // font : { name: "Calibri", sz: 8 }, numberFormat: "0.00", set: 2.71828182846 }); sheet1.set(1,3,{ fill : { type: "solid", fgColor: "00FFFFFF"}, font : { name: "Calibri", sz: 8 }, numberFormat: "0%", set: 3.14159265459 }); sheet1.set(1,4,{ fill : { type: "solid", fgColor: "00FFFFFF"}, font : { name: "Calibri", sz: 8 }, numberFormat: "$#,###.00", set: 314159.265459 }); // sheet1.set(1,3, 3.14159265459) // sheet1.numberFormat(1,3, "0%") workbook.save(OUTFILE, function (err) { if (err) throw err; else { console.log('open \"' + OUTFILE + "\""); done() } }); }) }) ;
mit
south-coast-science/scs_core
src/scs_core/sys/serial.py
3284
""" Created on 19 Mar 2019 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) https://stackoverflow.com/questions/7266558/pyserial-buffer-wont-flush """ import time from abc import ABC, abstractmethod # -------------------------------------------------------------------------------------------------------------------- class Serial(ABC): """ classdocs """ _DEFAULT_EOL = "\n" # ---------------------------------------------------------------------------------------------------------------- def __init__(self, device_identifier, baud_rate, hard_handshake=False): """ Constructor """ self._device_identifier = device_identifier # string device path or int port number self._baud_rate = baud_rate # int self._hard_handshake = hard_handshake # bool self._ser = None # ---------------------------------------------------------------------------------------------------------------- @abstractmethod def open(self, lock_timeout, comms_timeout): pass @abstractmethod def close(self): pass # ---------------------------------------------------------------------------------------------------------------- def read_lines(self, eol=None, timeout=None): while True: try: yield self.read_line(eol, timeout) except TimeoutError: return def read_line(self, eol=None, timeout=None): terminator = self._DEFAULT_EOL if eol is None else eol end_time = None if timeout is None else time.time() + timeout line = "" while True: if timeout is not None and time.time() > end_time: raise TimeoutError(timeout) char = self._ser.read().decode(errors='ignore') line += char if line.endswith(terminator): break return line.strip() def write_line(self, text, eol=None): terminator = self._DEFAULT_EOL if eol is None else eol text_ln = text.strip() + terminator packet = text_ln.encode() return self._ser.write(packet) # ---------------------------------------------------------------------------------------------------------------- def read(self, count): chars = self._ser.read(count) return chars def write(self, *chars): self._ser.write(bytearray(chars)) def flush_input(self): self._ser.flushInput() def flush_output(self): self._ser.flushOutput() # ---------------------------------------------------------------------------------------------------------------- @property @abstractmethod def device_identifier(self): return None # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): is_open = False if self._ser is None else self._ser.is_open return self.__class__.__name__ + ":{device_identifier:%s, baud_rate=%d, hard_handshake=%s, serial_open:%s}" % \ (self._device_identifier, self._baud_rate, self._hard_handshake, is_open)
mit
ni4ka7a/TelerikAcademyHomeworks
WebServicesAndCloud/02.ASP.NETWebAPI/01.StudentSystem/StudentSystem.Services/Models/Homeworks/HomeworkResponseModel.cs
342
namespace StudentSystem.Services.Models.Homeworks { using System; public class HomeworkResponseModel { public int Id { get; set; } public string Content { get; set; } public int CourseId { get; set; } public int StudentId { get; set; } public DateTime TimeSent { get; set; } } }
mit
cschwebk/mellon
lib/mud.js
2051
'use strict'; var net = require('net'), TelnetInput = require('telnet-stream').TelnetInput, TelnetOutput = require('telnet-stream').TelnetOutput, localSocket = null; module.exports = { connectToMud: function(config, webSocket, logger, debug) { var telnetInput = new TelnetInput(), telnetOutput = new TelnetOutput(); localSocket = webSocket; var socket = net.connect(config, function() { socket.pipe(telnetInput); telnetOutput.pipe(socket); telnetInput.on('do', function(command) { telnetOutput.writeWont(command); }); telnetInput.on('will', function(command) { telnetOutput.writeDont(command); }); telnetInput.on('data', function(buffer) { var data = buffer.toString('utf8'); if (debug) { console.log(data); } logger.log(data); localSocket.emit('message', { type: 'remote', content: data }); }); console.log('socket [' + webSocket.id + '] connected to remote host [' + config.host + ':' + config.port + ']'); }); socket.on('error', function(error) { localSocket.emit('message', { type: 'system', content: 'Error: ' + error.message + '\r\n' }); socket.end(); localSocket.emit('update', { type: 'app', connected: false }); }); socket.on('end', function() { console.log('remote server connection ended'); localSocket.emit('message', { type: 'system', content: 'Disconnected from remote host' + '\r\n' }); localSocket.emit('update', { type: 'app', connected: false }); }); return socket; } };
mit
rinman24/ucsd_ch
coimbra_chamber/utility/plot/contracts.py
1226
"""Data contracts for plot utility.""" from dataclasses import dataclass, field from datetime import datetime from typing import List # ---------------------------------------------------------------------------- # Plot utility DTOs @dataclass(frozen=True) class DataSeries: """DataSeries to plot on a single axis.""" values: List # List of observation values sigma: List = field(default_factory=list) # Error bars not plotted if sum == 0 label: str = '' # Should be an empty string for abscissae @dataclass(frozen=True) class Axis: """Single axis for a two dimensional plot.""" data: List[DataSeries] # Data to plot on the axis y_label: str # y-label for the axis error_type: str = '' # {discrete, continuous} @dataclass(frozen=True) class Plot: """Two dimensional plot.""" abscissa: DataSeries # Independent data series axes: List[Axis] # Axes for dependent data series x_label: str # x-label for the plot legend: bool = True # If True, show legend; else, do not @dataclass(frozen=True) class Layout: """Layout of a figure.""" plots: List[Plot] # List of plots to display (each on its own axis) style: str = '' # valid pyplot.style
mit
j5ik2o/reactive-redis
core/src/main/scala/com/github/j5ik2o/reactive/redis/command/lists/BLPopRequest.scala
2811
package com.github.j5ik2o.reactive.redis.command.lists import java.util.UUID import cats.data.NonEmptyList import com.github.j5ik2o.reactive.redis.RedisIOException import com.github.j5ik2o.reactive.redis.command.{ CommandRequest, CommandResponse, StringParsersSupport } import com.github.j5ik2o.reactive.redis.parser.StringParsers._ import com.github.j5ik2o.reactive.redis.parser.model._ import fastparse.all._ import scala.concurrent.duration.Duration final class BLPopRequest(val id: UUID, val keys: NonEmptyList[String], val timeout: Duration = Duration.Zero) extends CommandRequest with StringParsersSupport { override type Response = BLPopResponse override val isMasterOnly: Boolean = true private def timeoutToSeconds: Long = if (timeout.isFinite()) timeout.toSeconds else 0 override def asString: String = s"BLPOP ${keys.toList.mkString(" ")} $timeoutToSeconds" override protected lazy val responseParser: P[Expr] = fastParse(stringArrayReply | simpleStringReply | errorReply) override protected lazy val parseResponse: Handler = { case (ArrayExpr(values), next) => (BLPopSucceeded(UUID.randomUUID(), id, values.asInstanceOf[Seq[StringExpr]].map(_.value)), next) case (SimpleExpr(QUEUED), next) => (BLPopSuspended(UUID.randomUUID(), id), next) case (ErrorExpr(msg), next) => (BLPopFailed(UUID.randomUUID(), id, RedisIOException(Some(msg))), next) } override def equals(other: Any): Boolean = other match { case that: BLPopRequest => id == that.id && keys == that.keys && timeout == that.timeout case _ => false } @SuppressWarnings(Array("org.wartremover.warts.JavaSerializable")) override def hashCode(): Int = { val state = Seq(id, keys, timeout) state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b) } override def toString: String = s"BLPopRequest($id, $keys, $timeout)" } object BLPopRequest { def apply(id: UUID, key: String, timeout: Duration): BLPopRequest = new BLPopRequest(id, NonEmptyList.one(key), timeout) def apply(id: UUID, keys: NonEmptyList[String], timeout: Duration): BLPopRequest = new BLPopRequest(id, keys, timeout) def unapply(self: BLPopRequest): Option[(UUID, NonEmptyList[String], Duration)] = Some((self.id, self.keys, self.timeout)) def create(id: UUID, key: String, timeout: Duration): BLPopRequest = apply(id, key, timeout) } sealed trait BLPopResponse extends CommandResponse final case class BLPopSuspended(id: UUID, requestId: UUID) extends BLPopResponse final case class BLPopSucceeded(id: UUID, requestId: UUID, values: Seq[String]) extends BLPopResponse final case class BLPopFailed(id: UUID, requestId: UUID, ex: RedisIOException) extends BLPopResponse
mit
qingweibinary/binary-charts
src/parts/rangeSelector.js
644
export default () => ({ buttons: [{ type: 'second', count: 15, text: 'TICK', }, { type: 'minute', count: 1, text: '1M', }, { type: 'minute', count: 15, text: '15M', }, { type: 'hour', count: 1, text: '1H', }, { type: 'hour', count: 6, text: '6H', }, { type: 'day', count: 1, text: '1D', }, { type: 'all', count: 1, text: 'MAX', }], allButtonsEnabled: true, selected: 1, inputEnabled: false, labelStyle: { display: 'none' }, });
mit
oscarotero/Embed
src/Detectors/Keywords.php
1472
<?php declare(strict_types = 1); namespace Embed\Detectors; class Keywords extends Detector { public function detect(): array { $tags = []; $metas = $this->extractor->getMetas(); $ld = $this->extractor->getLinkedData(); $types = [ 'keywords', 'og:video:tag', 'og:article:tag', 'og:video:tag', 'og:book:tag', 'lp.article:section', 'dcterms.subject', ]; foreach ($types as $type) { $value = $metas->strAll($type); if ($value) { $tags = array_merge($tags, self::toArray($value)); } } $value = $ld->strAll('keywords'); if ($value) { $tags = array_merge($tags, self::toArray($value)); } $tags = array_map('mb_strtolower', $tags); $tags = array_unique($tags); $tags = array_filter($tags); $tags = array_values($tags); return $tags; } private static function toArray(array $keywords): array { $all = []; foreach ($keywords as $keyword) { $tags = explode(',', $keyword); $tags = array_map('trim', $tags); $tags = array_filter( $tags, fn ($value) => !empty($value) && substr($value, -3) !== '...' ); $all = array_merge($all, $tags); } return $all; } }
mit
mnahm5/django-estore
src/carts/views.py
8335
import braintree from django.conf import settings from django.contrib import messages from django.contrib.auth.forms import AuthenticationForm from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, Http404, JsonResponse from django.shortcuts import render, get_object_or_404, redirect from django.views.generic.base import View from django.views.generic.detail import SingleObjectMixin, DetailView from django.views.generic.edit import FormMixin # Create your views here. from orders.forms import GuestCheckoutForm from orders.mixins import CartOrderMixin from orders.models import UserCheckout, Order, UserAddress from products.models import Variation from .models import Cart, CartItem if settings.DEBUG: braintree.Configuration.configure( braintree.Environment.Sandbox, merchant_id=settings.BRAINTREE_MERCHANT_ID, public_key=settings.BRAINTREE_PUBLIC, private_key=settings.BRAINTREE_PRIVATE ) class ItemCountView(View): def get(self, request, *args, **kwargs): if request.is_ajax(): cart_id = self.request.session.get("cart_id") if cart_id == None: count = 0 else: cart = Cart.objects.get(id=cart_id) count = cart.items.count() request.session["cart_item_count"] = count return JsonResponse({"count": count}) else: raise Http404 class CartView(SingleObjectMixin, View): model = Cart template_name = "carts/view.html" def get_object(self, *args, **kwargs): self.request.session.set_expiry(0) cart_id = self.request.session.get("cart_id") if cart_id == None: new_cart = Cart() new_cart.save() cart_id = new_cart.id self.request.session["cart_id"] = cart_id cart = Cart.objects.get(id=cart_id) if self.request.user.is_authenticated(): cart.user = self.request.user cart.save() return cart def get(self, request, *args, **kwargs): cart = self.get_object() item_id = request.GET.get("item") delete_item = request.GET.get("delete", False) flash_message = "" item_added = False if item_id: item_instance = get_object_or_404(Variation, id=item_id) qty = request.GET.get("qty", 1) try: if int(qty) < 1: delete_item = True except: raise Http404 cart_item, created = CartItem.objects.get_or_create(cart=cart, item=item_instance) if created: flash_message = "Successfully added to the cart" item_added = True if delete_item: flash_message = "Item removed successfully" cart_item.delete() else: if not created: flash_message = "Quantity has been updated successfully" cart_item.quantity = qty cart_item.save() if not request.is_ajax(): return HttpResponseRedirect(reverse("cart")) if request.is_ajax(): try: line_total = cart_item.line_item_total except: line_total = None try: subtotal = cart_item.cart.subtotal tax_total = cart_item.cart.tax_total total = cart_item.cart.total except: subtotal = None tax_total = None total = None try: total_items = cart_item.cart.items.count() except: total_items = 0 data = JsonResponse({ "deleted": delete_item, "item_added": item_added, "line_total": line_total, "subtotal": subtotal, "tax_total": tax_total, "total": total, "flash_message": flash_message, "total_items": total_items }) return data context = { "object": self.get_object() } template = self.template_name return render(request, template, context) class CheckOutView(CartOrderMixin, DetailView, FormMixin): model = Cart template_name = "carts/checkout_view.html" form_class = GuestCheckoutForm def get_object(self, *args, **kwargs): cart = self.get_cart() if cart == None: return None return cart def get_context_data(self, *args, **kwargs): self.object = self.get_object() context = super(CheckOutView, self).get_context_data(*args, **kwargs) user_can_continue = False user_check_id = self.request.session.get("user_checkout_id") if self.request.user.is_authenticated(): user_can_continue = True user_checkout, created = UserCheckout.objects.get_or_create(email=self.request.user.email) user_checkout.user = self.request.user user_checkout.save() context["client_token"] = user_checkout.get_client_token() self.request.session["user_checkout_id"] = user_checkout.id elif not self.request.user.is_authenticated() and user_check_id == None: context["login_form"] = AuthenticationForm() context["next_url"] = self.request.build_absolute_uri() else: pass if user_check_id != None: user_can_continue = True if not self.request.user.is_authenticated(): user_checkout_2 = UserCheckout.objects.get(id=user_check_id) context["client_token"] = user_checkout_2.get_client_token() if self.get_cart() is not None: context["order"] = self.get_order() context["user_can_continue"] = user_can_continue context["form"] = self.get_form() return context def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): email = form.cleaned_data.get("email") user_checkout, created = UserCheckout.objects.get_or_create(email=email) request.session["user_checkout_id"] = user_checkout.id return self.form_valid(form) else: return self.form_invalid(form) def get_success_url(self): return reverse('checkout') def get(self, request, *args, **kwargs): get_data = super(CheckOutView, self).get(request, *args, **kwargs) cart = self.get_object() if cart is None: return redirect("cart") new_order = self.get_order() user_checkout_id = request.session.get("user_checkout_id") if user_checkout_id != None: user_checkout = UserCheckout.objects.get(id=user_checkout_id) if new_order.billing_address == None or new_order.shipping_address == None: return redirect("order_address") new_order.user = user_checkout new_order.save() return get_data class CheckoutFinalView(CartOrderMixin, View): def post(self, request, *args, **kwargs): order = self.get_order() order_total = order.order_total nonce = request.POST.get("payment_method_nonce") if nonce: result = braintree.Transaction.sale({ "amount" : order_total, "payment_method_nonce": nonce, "billing": { "postal_code": "%s" % (order.billing_address.zipcode) }, "options": { "submit_for_settlement": True } }) if result.is_success: order.mark_completed(order_id=result.transaction.id) messages.success(request, "Thank you for your order") del request.session["cart_id"] del request.session["order_id"] else: messages.success(request, "%s" % (result.message)) return redirect("checkout") return redirect("order_detail", pk=order.pk) def get(self, request, *args, **kwargs): return redirect("checkout")
mit
Roxxik/Evolve5.0
src/field.rs
1457
use std::collections::BTreeMap; use types::*; use organism::OrgRef; #[derive(Debug)] enum Tile { Organism(OrgRef), Corpse(Energy),//the energy contained in the corpse } #[derive(Debug)] pub struct Field{ cols: Coord, rows: Coord, field: BTreeMap<(Coord,Coord),Tile>, } impl Field { pub fn new(cols: Coord, rows: Coord) -> Field { Field{ cols: cols, rows: rows, field: BTreeMap::new(), } } /* pub fn put(&mut self, cell: &Cell) { self.field.insert((cell.x, cell.y), CellState::Living(cell.id)); } */ /* pub fn execute(&mut self, event: Event, cell: &mut Cell) -> Option<CellID> { match event.ty { EventType::Mov { dir: dir } => { self.field.remove((cell.x, cell.y)); //change this to wrapping match self.field.insert((cell.x + dir.get_x(), cell.y + dir.get_y())) { CellState::Living(id) => Some(id) CellState::Dead(nrg) => { cell.nrg += nrg; None } } } EventType::Spawn{ dir: dir, nrg: nrg } => { } _ => panic!("wrong event got executed in Field"), } }*/ /* pub fn zombify(&mut self, mut cell: Cell) { self.field.insert((cell.x, cell.y), CellState::Dead(cell.nrg)); }*/ }
mit
fabiocicerchia/Silex-Setup
src/Tests/ValidateCodingStandardsTest.php
1884
<?php /** * SilexSetup * * PHP version 5 * * @category Framework * @package SilexSetup * @author Fabio Cicerchia <info@fabiocicerchia.it> * @license http://www.opensource.org/licenses/mit-license.php MIT * @link https://github.com/fabiocicerchia/Silex-Setup */ /** * ValidateCodingStandardsTest * * @category Framework * @package SilexSetup * @author Fabio Cicerchia <info@fabiocicerchia.it> * @license http://www.opensource.org/licenses/mit-license.php MIT * @link https://github.com/fabiocicerchia/Silex-Setup **/ class ValidateCodingStandardsTest extends PHPUnit_Framework_TestCase { // {{{ getListOfApplicationFiles /** * getListOfApplicationFiles * * @ignore * @access public * @return array */ public function getListOfApplicationFiles() { $command = 'find "' . __DIR__ . '/../../" -name "*.php" -type f'; $command .= '| egrep -v "' . __DIR__ . '/../../(web|lib|tmp|vendor)/"'; exec($command, $files); $files = array_map('realpath', $files); $files = preg_grep('#/(Configs|Tests)/#', $files, PREG_GREP_INVERT); $data = array(); foreach ($files as $file) { $data[] = array($file); } return $data; } // }}} // {{{ testEachClassIsStrictlyValidated /** * testEachClassIsStrictlyValidated * * @param string $file The file that will be tested * * @ignore * @access public * @return void * @dataProvider getListOfApplicationFiles */ public function testEachClassIsStrictlyValidated($file) { $command = 'phpcs --report=summary --standard=PSR2 '; $command .= '--ignore=Configs/* "' . $file . '"'; exec($command, $report); $this->assertEmpty($report, 'The file doesn\'t respect the PSR2 Coding Standard.'); } }
mit
oligus/jad
tests/e2e/RelationshipsTest.php
4503
<?php declare(strict_types=1); namespace Jad\E2E; use Jad\Jad; use Jad\Database\Manager; use Jad\Map\AnnotationsMapper; use Jad\Tests\TestCase; use Spatie\Snapshots\MatchesSnapshots; /** * Class RelationshipsTest * @package Jad\E2E */ class RelationshipsTest extends TestCase { use MatchesSnapshots; /** * @throws \Doctrine\Common\Annotations\AnnotationException */ public function testCreateRecordOneRelationship() { $_SERVER['REQUEST_URI'] = '/playlists'; $_GET = ['include' => 'tracks']; $_SERVER['REQUEST_METHOD'] = 'POST'; $input = new \stdClass(); $input->data = new \stdClass(); $input->data->type = 'playlists'; $input->data->attributes = new \stdClass(); $input->data->attributes->name = 'New Playlist'; $input->data->relationships = new \stdClass(); $input->data->relationships->tracks = new \stdClass(); $input->data->relationships->tracks->data = new \stdClass(); $input->data->relationships->tracks->data->type = 'tracks'; $input->data->relationships->tracks->data->id = 77; $_POST = ['input' => json_encode($input)]; $mapper = new AnnotationsMapper(Manager::getInstance()->getEm()); $jad = new Jad($mapper); ob_start(); $jad->jsonApiResult(); $output = ob_get_clean(); $this->assertMatchesJsonSnapshot($output); } /** * @throws \Doctrine\Common\Annotations\AnnotationException */ public function testCreateRecordManyRelationships() { $_SERVER['REQUEST_URI'] = '/playlists'; $_GET = ['include' => 'tracks']; $_SERVER['REQUEST_METHOD'] = 'POST'; $input = new \stdClass(); $input->data = new \stdClass(); $input->data->type = 'playlists'; $input->data->attributes = new \stdClass(); $input->data->attributes->name = 'New Playlist'; $input->data->relationships = new \stdClass(); $input->data->relationships->tracks = new \stdClass(); $data = []; $track = new \stdClass(); $track->id = 77; $track->type = 'tracks'; $data[] = $track; $track = new \stdClass(); $track->id = 422; $track->type = 'tracks'; $data[] = $track; $track = new \stdClass(); $track->id = 2014; $track->type = 'tracks'; $data[] = $track; $input->data->relationships->tracks->data = $data; $_POST = ['input' => json_encode($input)]; $mapper = new AnnotationsMapper(Manager::getInstance()->getEm()); $jad = new Jad($mapper); ob_start(); $jad->jsonApiResult(); $output = ob_get_clean(); $this->assertMatchesJsonSnapshot($output); } /** * @throws \Doctrine\Common\Annotations\AnnotationException */ public function testCreateRecordManyUniqueRelationships() { $_SERVER['REQUEST_URI'] = '/invoices'; $_SERVER['REQUEST_METHOD'] = 'POST'; $input = new \stdClass(); $input->data = new \stdClass(); $input->data->type = 'invoices'; $input->data->attributes = new \stdClass(); $input->data->attributes->{'invoice-date'} = '2018-01-01 00:00:00'; $input->data->attributes->{'billing-address'} = 'River street 14'; $input->data->attributes->{'billing-city'} = 'Westham'; $input->data->attributes->{'billing-state'} = null; $input->data->attributes->{'billing-postal-code'} = 'WE345R'; $input->data->attributes->{'total'} = '2.64'; $input->data->relationships = []; $customers = new \stdClass(); $customers->data = new \stdClass(); $customers->data->id = '53'; $customers->data->type = 'customers'; $input->data->relationships['customers'] = $customers; $item = new \stdClass(); $item->data = new \stdClass(); $item->data->id = '10'; $item->data->type = 'invoice-items'; //$input->data->relationships['invoice-items'] = []; $input->data->relationships['invoice-items'] = $item; //print_r(json_encode($input)); die; $_POST = ['input' => json_encode($input)]; $mapper = new AnnotationsMapper(Manager::getInstance()->getEm()); $jad = new Jad($mapper); ob_start(); $jad->jsonApiResult(); $output = ob_get_clean(); $this->assertMatchesJsonSnapshot($output); } }
mit
gz/bespin
kernel/src/prelude.rs
115
#[macro_export] macro_rules! round_up { ($num:expr, $s:expr) => { (($num + $s - 1) / $s) * $s }; }
mit
juliomar/ACBr.Net
ACBr.Net.NFe/Classes/NFe/RefNF.cs
471
using System; using System.Collections.Generic; namespace ACBr.Net.NFe { public sealed class RefNF { #region Constructor public RefNF() { } #endregion Constructor #region Properties public int CUF { get; set; } public string AAMM { get; set; } public string CNPJ { get; set; } public int Modelo { get; set; } public int Serie { get; set; } public int NNF { get; set; } #endregion Properties } }
mit
dinhoarakaki/marariFE
out/artifacts/marariHTML_war_exploded/js/produto.js
4020
var app = new Vue({ el:'#app', data:{ indexUpdate: -1, isActive: false, newProduto:{ id:'', descricao:'', codBarras:'', fornecedor:'', precoCusto:'', precoVenda:'', precoMinVenda:'', precoMaxVenda:'', comissaoVenda:'', qtdEstoque:'', qtdMinEstoque:'', altura:'', peso:'', largura:'', profundidade:'', medidaProduto:'', tipoProduto:'', usuario:'', validade:'' }, produtos:[], fornecedores:[], tiposProduto:[], usuarios:[] }, mounted:function(){ this.findAll(); this.findAllFornecedores(); this.findAllTiposProduto(); this.findAllUsuarios(); }, methods: { findAll: function () { this.$http.get("http://localhost:8080/produto/private/") .then(function (res) { this.produtos = res.body; }, function (res) { console.log(res); }); }, findAllFornecedores:function(){ this.$http.get("http://localhost:8080/fornecedor/private/") .then(function (res) { this.fornecedores = res.body; }, function (res) { console.log(res); }); }, findAllTiposProduto:function(){ this.$http.get("http://localhost:8080/produto/private/") .then(function (res) { this.produtos = res.body; }, function (res) { console.log(res); }); }, findAllUsuarios:function(){ this.$http.get("http://localhost:8080/usuario/private/") .then(function (res) { this.usuarios = res.body; }, function (res) { console.log(res); }); }, updateProduto: function () { this.$http.put("http://localhost:8080/produto/private/edit", this.newProduto) .then(function(res) { this.findAll(); }, function (res){ window.alert(res.body.mensagem); }); }, save:function(){ if(this.newProduto.remoteId==""){ this.add(); }else { this.updateProduto(); } this.clear(); }, add: function () { this.$http.post("http://localhost:8080/produto/private/savenofile", this.newProduto) .then(function(res) { this.findAll(); }, function (res){ window.alert(res.body.mensagem); }); }, deleteProduto: function (i) { this.$http.delete("http://localhost:8080/produto/private/" + (i)) .then(function (res) { this.findAll(); }, function (res) { console.log(res); }); }, prepareUpdate :function(i){ this.newProduto= Vue.util.extend({},this.produtos[i]); }, clear: function () { this.newProduto = { id:'', descricao:'', codBarras:'', fornecedor:'', precoCusto:'', precoVenda:'', precoMinVenda:'', precoMaxVenda:'', comissaoVenda:'', qtdEstoque:'', qtdMinEstoque:'', altura:'', peso:'', largura:'', profundidade:'', medidaProduto:'', tipoProduto:'', usuario:'', validade:'' } } } })
mit
Doshibu/AfkWatch
src/Doshibu/AfkWatchBundle/Controller/NewsController.php
4807
<?php namespace Doshibu\AfkWatchBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpFoundation\Response; use Doshibu\AfkWatchBundle\Entity\Genre; use Doshibu\AfkWatchBundle\Entity\Image; use Doshibu\AfkWatchBundle\Entity\Movie; use Doshibu\AfkWatchBundle\Entity\News; use Doshibu\AfkWatchBundle\Entity\Pays; use Doshibu\AfkWatchBundle\Entity\Serie; use Doshibu\AfkWatchBundle\Entity\Newsletter; use Doshibu\AfkWatchBundle\Form\NewsletterType; use Doshibu\AfkWatchBundle\Entity\Contact; use Doshibu\AfkWatchBundle\Form\ContactType; class NewsController extends Controller { public function newsAction(Request $request, $media, $page=1) { if ($media !== 'movie' && $media !== 'serie') { throw $this->createNotFoundException('La page n\'existe pas ou plus.'); } $em = $this->getDoctrine()->getManager(); $newsRepo = $em->getRepository('DoshibuAfkWatchBundle:News'); $nbPerPage = 16; $listNews = $newsRepo->findRecentsPage($media, $page, $nbPerPage, true); $nbPages = ceil(count($listNews)/$nbPerPage); if ( $page > $nbPages ) { if($page === 1) { throw $this->createNotFoundException('Malheureusement aucune donnée n\'est enregistré avec ce pays en référence.'); } else { throw $this->createNotFoundException('La page '. $page .' n\'existe pas ou plus.'); } } $listMostViewed = $newsRepo->findMostViewed(15); $listMostRecent = $newsRepo->findMostRecent(5); $newsletter = new Newsletter(); $newsletterForm = $this->get('form.factory')->create(NewsletterType::class, $newsletter); $viewParam = array( 'newsletterForm' => $newsletterForm->createView(), 'media' => $media, 'listNews' => $listNews, 'nbPages' => $nbPages, 'page' => $page, 'listMostViewed' => $listMostViewed, 'listMostRecent' => $listMostRecent ); if($newsletterForm->handleRequest($request)->isValid()) { $data = $newsletterForm->getData(); $newsletterRepo = $em->getRepository('DoshibuAfkWatchBundle:Newsletter'); $isKnown = null !== $newsletterRepo->findOneByEmail($newsletter->getEmail()); $alert = array('class' => '', 'message' => ''); if($isKnown) { $alert['class'] = 'warning'; $alert['message'] = 'Cette adresse email a déjà été renseignée.'; } else { $em->persist($newsletter); $em->flush(); $alert['class'] = 'success'; $alert['message'] = 'Votre adresse mail a bien été renseignée. Vous serez avertis des dernières nouveautés.'; } $viewParam['alert'] = $alert; return $this->render('DoshibuAfkWatchBundle:Movie:news.html.twig', $viewParam); } return $this->render('DoshibuAfkWatchBundle:Movie:news.html.twig', $viewParam); } public function newsSingleAction(Request $request, $media, $slug) { $em = $this->getDoctrine()->getManager(); $newsRepo = $em->getRepository('DoshibuAfkWatchBundle:News'); $news = $newsRepo->findUnique($media, $slug); // joined full with genre & pays if($news === null) { throw $this->createNotFoundException('Cette page n\'existe pas ou plus.'); } $newsMedia = $news->getMovie() !== null ? $news->getMovie() : $news->getSerie(); $newsMediaGenders = $newsMedia->getGenders(); $listPopular = $newsRepo->findMostViewedByGender($media, $newsMediaGenders, 15); $listRecent = $newsRepo->findMostRecentByGender($media, $newsMediaGenders, 5); $newsletter = new Newsletter(); $newsletterForm = $this->get('form.factory')->create(NewsletterType::class, $newsletter); $viewParam = array( 'newsletterForm' => $newsletterForm->createView(), 'media' => $media, 'news' => $news, 'listPopular' => $listPopular, 'listRecent' => $listRecent ); if($newsletterForm->handleRequest($request)->isValid()) { $data = $newsletterForm->getData(); $newsletterRepo = $em->getRepository('DoshibuAfkWatchBundle:Newsletter'); $isKnown = null !== $newsletterRepo->findOneByEmail($newsletter->getEmail()); $alert = array('class' => '', 'message' => ''); if($isKnown) { $alert['class'] = 'warning'; $alert['message'] = 'Cette adresse email a déjà été renseignée.'; } else { $em->persist($newsletter); $em->flush(); $alert['class'] = 'success'; $alert['message'] = 'Votre adresse mail a bien été renseignée. Vous serez avertis des dernières nouveautés.'; } $viewParam['alert'] = $alert; return $this->render('DoshibuAfkWatchBundle:Movie:news-single.html.twig', $viewParam); } return $this->render('DoshibuAfkWatchBundle:Movie:news-single.html.twig', $viewParam); } }
mit
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_08_01/models/application_gateway_redirect_configuration_py3.py
3957
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .sub_resource import SubResource class ApplicationGatewayRedirectConfiguration(SubResource): """Redirect configuration of an application gateway. :param id: Resource ID. :type id: str :param redirect_type: Supported http redirection types - Permanent, Temporary, Found, SeeOther. Possible values include: 'Permanent', 'Found', 'SeeOther', 'Temporary' :type redirect_type: str or ~azure.mgmt.network.v2017_08_01.models.ApplicationGatewayRedirectType :param target_listener: Reference to a listener to redirect the request to. :type target_listener: ~azure.mgmt.network.v2017_08_01.models.SubResource :param target_url: Url to redirect the request to. :type target_url: str :param include_path: Include path in the redirected url. :type include_path: bool :param include_query_string: Include query string in the redirected url. :type include_query_string: bool :param request_routing_rules: Request routing specifying redirect configuration. :type request_routing_rules: list[~azure.mgmt.network.v2017_08_01.models.SubResource] :param url_path_maps: Url path maps specifying default redirect configuration. :type url_path_maps: list[~azure.mgmt.network.v2017_08_01.models.SubResource] :param path_rules: Path rules specifying redirect configuration. :type path_rules: list[~azure.mgmt.network.v2017_08_01.models.SubResource] :param name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'redirect_type': {'key': 'properties.redirectType', 'type': 'str'}, 'target_listener': {'key': 'properties.targetListener', 'type': 'SubResource'}, 'target_url': {'key': 'properties.targetUrl', 'type': 'str'}, 'include_path': {'key': 'properties.includePath', 'type': 'bool'}, 'include_query_string': {'key': 'properties.includeQueryString', 'type': 'bool'}, 'request_routing_rules': {'key': 'properties.requestRoutingRules', 'type': '[SubResource]'}, 'url_path_maps': {'key': 'properties.urlPathMaps', 'type': '[SubResource]'}, 'path_rules': {'key': 'properties.pathRules', 'type': '[SubResource]'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, *, id: str=None, redirect_type=None, target_listener=None, target_url: str=None, include_path: bool=None, include_query_string: bool=None, request_routing_rules=None, url_path_maps=None, path_rules=None, name: str=None, etag: str=None, type: str=None, **kwargs) -> None: super(ApplicationGatewayRedirectConfiguration, self).__init__(id=id, **kwargs) self.redirect_type = redirect_type self.target_listener = target_listener self.target_url = target_url self.include_path = include_path self.include_query_string = include_query_string self.request_routing_rules = request_routing_rules self.url_path_maps = url_path_maps self.path_rules = path_rules self.name = name self.etag = etag self.type = type
mit
jbroadway/elefant-quickstart
bootstrap.php
1276
<?php conf ('Database', 'master', array ( 'driver' => 'mysql', 'host' => $_SERVER["DB1_HOST"] . ':' . $_SERVER["DB1_PORT"] , 'name' => $_SERVER["DB1_NAME"], 'user' => $_SERVER["DB1_USER"], 'pass' => $_SERVER["DB1_PASS"] )); // After the first run through, you can comment out or remove // this entire block and redeploy. if (! db_shift ('select count(*) from user')) { // Run the db install $sqldata = sql_split (file_get_contents ('conf/install_mysql.sql')); db_execute ('begin'); foreach ($sqldata as $sql) { if (! db_execute ($sql)) { $err = db_error (); db_execute ('rollback'); die ($err); } } // Create a default admin user $date = gmdate ('Y-m-d H:i:s'); if (! db_execute ( 'insert into `user` (id, email, password, session_id, expires, name, type, signed_up, updated, userdata) values (1, ?, ?, null, ?, ?, "admin", ?, ?, ?)', $_SERVER["DEFAULT_EMAIL"], User::encrypt_pass ($_SERVER["DEFAULT_PASS"]), $date, 'Admin User', $date, $date, json_encode (array ()) )) { $err = db_error (); db_execute ('rollback'); die ($err); } // The initial version history of the default page/blocks $wp = new Webpage ('index'); Versions::add ($wp); $b = new Block ('members'); Versions::add ($b); db_execute ('commit'); } ?>
mit
marlontamo/store-management
application/views/header.php
2555
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html lang="en"> <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>Site title</title> <meta name="description" content=""> <meta name="keywords" content=""> <meta name="author" content=""> <!-- css --> <link href="<?= base_url('assets/css/bootstrap.min.css') ?>" rel="stylesheet"> <link href="<?= base_url('assets/css/style.css') ?>" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <header id="site-header"> <nav class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?= base_url() ?>">Site title</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <?php if (isset( $_SESSION['user_name'] ) && $_SESSION['logged_in'] === true) : ?> <li><a href="<?= base_url('logout') ?>">Logout</a></li> <li> <a href="<?= base_url('home') ?>">mycrud vue app</a></li> <li> <a href="<?= base_url('install') ?>">install</a></li> <?php else : ?> <li><a href="<?= base_url('register') ?>">Register</a></li> <li><a href="<?= base_url('login') ?>">Login</a></li> <li> <a href="<?= base_url('install') ?>">install</a></li> <li> <a href="<?= base_url('home') ?>">add item form</a></li> <?php endif; ?> </ul> </div><!-- .navbar-collapse --> </div><!-- .container-fluid --> </nav><!-- .navbar --> </header><!-- #site-header --> <main id="site-content" role="main"> <?php if (isset($_SESSION)) : ?> <div class="container"> <div class="row"> <div class="col-md-12"> <h1></h1> </div> </div><!-- .row --> </div><!-- .container --> <?php endif; ?> <div class="container">
mit
nassafou/serApp
src/Sdz/CatalogueBundle/Entity/Cproduits.php
2405
<?php namespace Sdz\CatalogueBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Cproduits * * @ORM\Table() * @ORM\Entity(repositoryClass="Sdz\CatalogueBundle\Entity\CproduitsRepository") */ class Cproduits { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="nom", type="string", length=255) */ private $nom; /** * @var string * * @ORM\Column(name="description", type="text") */ private $description; /** * @var float * * @ORM\Column(name="prix", type="float") */ private $prix; /** * @var boolean * * @ORM\Column(name="disponible", type="boolean") */ private $disponible; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nom * * @param string $nom * @return Cproduits */ public function setNom($nom) { $this->nom = $nom; return $this; } /** * Get nom * * @return string */ public function getNom() { return $this->nom; } /** * Set description * * @param string $description * @return Cproduits */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set prix * * @param float $prix * @return Cproduits */ public function setPrix($prix) { $this->prix = $prix; return $this; } /** * Get prix * * @return float */ public function getPrix() { return $this->prix; } /** * Set disponible * * @param boolean $disponible * @return Cproduits */ public function setDisponible($disponible) { $this->disponible = $disponible; return $this; } /** * Get disponible * * @return boolean */ public function getDisponible() { return $this->disponible; } }
mit
tedc/polaris-theme
builder/blog.php
641
<?php $args = array( 'posts_per_page' => 2, 'post__in' => get_sub_field('news') ); $q = new WP_Query($args); $blog = true; if($q->have_posts()) : ?> <div class="news news--shrink news--grow-lg news--grid"> <header class="news__cell news__cell--shrink news__cell--s12"> <h2 class="news__title news__title--big-upper"><a href="<?php echo get_permalink( get_option( 'page_for_posts' )); ?>"><?php _e('Life', 'polaris'); ?></a></h2> </header> <?php while($q->have_posts()) : $q->the_post(); include(locate_template( 'templates/content.php', false, false ) ); endwhile; wp_reset_query(); ?> </div> <?php endif; $blog = false; ?>
mit
portchris/NaturalRemedyCompany
src/lib/Mage/Archive/Helper/File/Bz.php
2412
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Archive * @copyright Copyright (c) 2006-2019 Magento, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Helper class that simplifies bz2 files stream reading and writing * * @category Mage * @package Mage_Archive * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Archive_Helper_File_Bz extends Mage_Archive_Helper_File { /** * Open bz archive file * * @throws Mage_Exception * @param string $mode */ protected function _open($mode) { $this->_fileHandler = @bzopen($this->_filePath, $mode); if (false === $this->_fileHandler) { throw new Mage_Exception('Failed to open file ' . $this->_filePath); } } /** * Write data to bz archive * * @throws Mage_Exception * @param $data */ protected function _write($data) { $result = @bzwrite($this->_fileHandler, $data); if (false === $result) { throw new Mage_Exception('Failed to write data to ' . $this->_filePath); } } /** * Read data from bz archive * * @throws Mage_Exception * @param int $length * @return string */ protected function _read($length) { $data = bzread($this->_fileHandler, $length); if (false === $data) { throw new Mage_Exception('Failed to read data from ' . $this->_filePath); } return $data; } /** * Close bz archive */ protected function _close() { bzclose($this->_fileHandler); } }
mit
H-EAL/vfs
include/vfs/file.hpp
2796
#pragma once #include <memory> #include "vfs/platform.hpp" // File interface #include "vfs/file_interface.hpp" // Platform specific implementations #if VFS_PLATFORM_WIN # include "vfs/win_file.hpp" #elif VFS_PLATFORM_POSIX # include "vfs/posix_file.hpp" #else # error No file implementation defined for the current platform #endif #include "vfs/path.hpp" #include "vfs/file_flags.hpp" #include "vfs/stream_interface.hpp" namespace vfs { //---------------------------------------------------------------------------------------------- using file = file_interface<file_impl>; using file_stream = stream_interface<file>; //---------------------------------------------------------------------------------------------- using file_sptr = std::shared_ptr<file_stream>; using file_wptr = std::weak_ptr<file_stream>; //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- inline auto open_read_only ( const path &fileName, file_creation_options creationOptions, file_flags fileFlags = file_flags::none, file_attributes fileAttributes = file_attributes::normal ) { return file_sptr(new file_stream(fileName, file_access::read_only, creationOptions, fileFlags, fileAttributes)); } //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- inline auto open_write_only ( const path &fileName, file_creation_options creationOptions, file_flags fileFlags = file_flags::none, file_attributes fileAttributes = file_attributes::normal ) { return file_sptr(new file_stream(fileName, file_access::write_only, creationOptions, fileFlags, fileAttributes)); } //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- inline auto open_read_write ( const path &fileName, file_creation_options creationOptions, file_flags fileFlags = file_flags::none, file_attributes fileAttributes = file_attributes::normal ) { return file_sptr(new file_stream(fileName, file_access::read_write, creationOptions, fileFlags, fileAttributes)); } //---------------------------------------------------------------------------------------------- } /*vfs*/
mit
hugojunior/ci-base
ci/application/modules/auth/libraries/Authenticator.php
278
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Authenticator { protected $ci, $user; public function __construct() { $this->ci = &get_instance(); } public function loggedin() { return $this->user; } }
mit
derekgreer/expectedObjects
src/ExpectedObjects.Specs/IgnoreSpecs.cs
2179
using System; using ExpectedObjects.Specs.Extensions; using ExpectedObjects.Specs.Properties; using ExpectedObjects.Specs.TestTypes; using Machine.Specifications; namespace ExpectedObjects.Specs { public class IgnoreSpecs { [Subject("Ignoring Equals Override")] public class when_comparing_unequal_record_types_for_equality_with_equals_override_ignored { static Person _actual; static ExpectedObject _expected; static Exception _exception; Establish context = () => { _expected = new Person {FirstName = "firstName1", LastName = "lastName"} .ToExpectedObject(ctx => ctx.IgnoreEqualsOverride()); _actual = new Person {FirstName = "firstName2", LastName = "lastName"}; }; Because of = () => _exception = Catch.Exception(() => _expected.ShouldMatch(_actual)); It should_throw_a_comparison_exception = () => _exception.ShouldBeOfExactType<ComparisonException>(); It should_report_differences_for_differing_members_only = () => _exception.Message.ShouldEqual(Resources.ExceptionMessage_013); } [Subject("Ignoring Equals Override")] public class when_comparing_unequal_record_types_for_equality_configured_for_value_based_equality { static Person _actual; static ExpectedObject _expected; static Exception _exception; Establish context = () => { _expected = new Person {FirstName = "firstName1", LastName = "lastName"} .ToExpectedObject(ctx => ctx.CompareByValue<Person>()); _actual = new Person {FirstName = "firstName2", LastName = "lastName"}; }; Because of = () => _exception = Catch.Exception(() => _expected.ShouldMatch(_actual)); It should_throw_a_comparison_exception = () => _exception.ShouldBeOfExactType<ComparisonException>(); It should_report_differences_for_differing_members_only = () => _exception.Message.ShouldEqual(Resources.ExceptionMessage_013); } } }
mit
NewEconomyMovement/nem.core
src/test/java/org/nem/core/utils/ByteUtilsTest.java
6934
package org.nem.core.utils; import org.hamcrest.core.IsEqual; import org.junit.*; public class ByteUtilsTest { //region bytesToLong / longToBytes // region bytesToLong @Test public void canConvertBytesToLong() { // Assert: assertBytesToLongConversion(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 0x0102030405060708L); } @Test public void canConvertBytesToLongNegative() { // Assert: assertBytesToLongConversion(new byte[] { (byte)0x80, 2, 3, 4, 5, 6, 7, 8 }, 0x8002030405060708L); } @Test public void conversionToLongIgnoresExcessiveData() { // Assert: assertBytesToLongConversion(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9 }, 0x0102030405060708L); } private static void assertBytesToLongConversion(final byte[] input, final long expected) { // Act: final long result = ByteUtils.bytesToLong(input); // Assert: Assert.assertThat(result, IsEqual.equalTo(expected)); } @Test(expected = IndexOutOfBoundsException.class) public void conversionToLongFailsOnDataUnderflow() { // Arrange: final byte[] data = { 1, 2, 3, 4, 5, 6 }; // Act: ByteUtils.bytesToLong(data); } //endregion //region longToBytes @Test public void canConvertLongToBytes() { // Assert: assertLongToBytesConversion(0x0807060504030201L, new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }); } @Test public void canConvertLongNegativeToBytes() { // Arrange: assertLongToBytesConversion(0x8070605040302010L, new byte[] { (byte)0x80, 0x70, 0x60, 0x50, 0x40, 0x30, 0x20, 0x10 }); } private static void assertLongToBytesConversion(final long input, final byte[] expected) { // Act: final byte[] result = ByteUtils.longToBytes(input); // Assert: Assert.assertThat(result, IsEqual.equalTo(expected)); } //endregion //region roundtrip @Test public void canRoundtripLongViaBytes() { // Arrange: final long input = 0x8070605040302010L; // Act: final long result = ByteUtils.bytesToLong(ByteUtils.longToBytes(input)); // Assert: Assert.assertThat(result, IsEqual.equalTo(input)); } @Test public void canRoundtripBytesViaLong() { // Arrange: final byte[] input = { (byte)0x80, 2, 3, 4, 5, 6, 7, 8 }; // Act: final byte[] result = ByteUtils.longToBytes(ByteUtils.bytesToLong(input)); // Assert: Assert.assertThat(result, IsEqual.equalTo(input)); } //endregion //endregion //region bytesToInt / intToBytes // region bytesToInt @Test public void canConvertBytesToInt() { // Assert: assertBytesToIntConversion(new byte[] { 1, 2, 3, 4 }, 0x01020304); } @Test public void canConvertBytesToIntNegative() { // Assert: assertBytesToIntConversion(new byte[] { (byte)0x80, 2, 3, 4 }, 0x80020304); } @Test public void conversionToIntIgnoresExcessiveData() { // Assert: assertBytesToIntConversion(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9 }, 0x01020304); } private static void assertBytesToIntConversion(final byte[] input, final int expected) { // Act: final int result = ByteUtils.bytesToInt(input); // Assert: Assert.assertThat(result, IsEqual.equalTo(expected)); } @Test(expected = IndexOutOfBoundsException.class) public void conversionToIntFailsOnDataUnderflow() { // Arrange: final byte[] data = { 1, 2, 3 }; // Act: ByteUtils.bytesToInt(data); } //endregion //region intToBytes @Test public void canConvertIntToBytes() { // Assert: assertIntToBytesConversion(0x08070605, new byte[] { 8, 7, 6, 5 }); } @Test public void canConvertIntNegativeToBytes() { // Arrange: assertIntToBytesConversion(0x80706050, new byte[] { (byte)0x80, 0x70, 0x60, 0x50 }); } private static void assertIntToBytesConversion(final int input, final byte[] expected) { // Act: final byte[] result = ByteUtils.intToBytes(input); // Assert: Assert.assertThat(result, IsEqual.equalTo(expected)); } //endregion //region roundtrip @Test public void canRoundtripIntViaBytes() { // Arrange: final int input = 0x80706050; // Act: final int result = ByteUtils.bytesToInt(ByteUtils.intToBytes(input)); // Assert: Assert.assertThat(result, IsEqual.equalTo(input)); } @Test public void canRoundtripBytesViaInt() { // Arrange: final byte[] input = { (byte)0x80, 2, 3, 4 }; // Act: final byte[] result = ByteUtils.intToBytes(ByteUtils.bytesToInt(input)); // Assert: Assert.assertThat(result, IsEqual.equalTo(input)); } //endregion //endregion //region isEqual @Test public void isEqualReturnsOneIfBytesAreEqual() { // Assert: Assert.assertThat(ByteUtils.isEqualConstantTime(0, 0), IsEqual.equalTo(1)); Assert.assertThat(ByteUtils.isEqualConstantTime(7, 7), IsEqual.equalTo(1)); Assert.assertThat(ByteUtils.isEqualConstantTime(64, 64), IsEqual.equalTo(1)); Assert.assertThat(ByteUtils.isEqualConstantTime(255, 255), IsEqual.equalTo(1)); } @Test public void isEqualReturnsOneIfLoBytesAreEqualButHiBytesAreNot() { // Assert: Assert.assertThat(ByteUtils.isEqualConstantTime(75 + 256, 75 + 256 * 2), IsEqual.equalTo(1)); } @Test public void isEqualReturnsZeroIfBytesAreNotEqual() { // Assert: Assert.assertThat(ByteUtils.isEqualConstantTime(0, 1), IsEqual.equalTo(0)); Assert.assertThat(ByteUtils.isEqualConstantTime(7, -7), IsEqual.equalTo(0)); Assert.assertThat(ByteUtils.isEqualConstantTime(64, 63), IsEqual.equalTo(0)); Assert.assertThat(ByteUtils.isEqualConstantTime(254, 255), IsEqual.equalTo(0)); } //endregion // region isNegative @Test public void isNegativeReturnsOneIfByteIsNegative() { // Assert: Assert.assertThat(ByteUtils.isNegativeConstantTime(-1), IsEqual.equalTo(1)); Assert.assertThat(ByteUtils.isNegativeConstantTime(-100), IsEqual.equalTo(1)); Assert.assertThat(ByteUtils.isNegativeConstantTime(-255), IsEqual.equalTo(1)); } @Test public void isNegativeReturnsZeroIfByteIsZeroOrPositive() { // Assert: Assert.assertThat(ByteUtils.isNegativeConstantTime(0), IsEqual.equalTo(0)); Assert.assertThat(ByteUtils.isNegativeConstantTime(1), IsEqual.equalTo(0)); Assert.assertThat(ByteUtils.isNegativeConstantTime(32), IsEqual.equalTo(0)); Assert.assertThat(ByteUtils.isNegativeConstantTime(127), IsEqual.equalTo(0)); } //endregion //region toString @Test public void toStringCreatesCorrectRepresentationForEmptyBytes() { // Act: final String result = ByteUtils.toString(new byte[] {}); // Assert: Assert.assertThat(result, IsEqual.equalTo("{ }")); } @Test public void toStringCreatesCorrectRepresentationForNonEmptyBytes() { // Act: final String result = ByteUtils.toString(new byte[] { 0x12, (byte)0x8A, 0x00, 0x07 }); // Assert: Assert.assertThat(result, IsEqual.equalTo("{ 12 8A 00 07 }")); } //endregion }
mit
hengkx/note
packages/web/webpack.config.dev.js
1735
import webpack from 'webpack'; import path from 'path'; import webpackMerge from 'webpack-merge'; import pxtorem from 'postcss-pxtorem'; import ip from 'ip'; import baseConfig from './webpack.config.base'; import theme from './themes/theme'; const host = ip.address(); const port = 5005; export default webpackMerge(baseConfig, { devtool: 'cheap-module-source-map', devServer: { host, port, hot: true, historyApiFallback: true, compress: true, }, entry: [ 'react-hot-loader/patch', 'babel-polyfill', `webpack-dev-server/client?http://${host}:${port}`, 'webpack/hot/only-dev-server', './src/index.js', ], module: { rules: [ // { // enforce: 'pre', // test: /\.(js|jsx)$/, // loader: 'eslint-loader', // include: path.join(__dirname, 'src') // }, { test: /\.css$/i, include: /node_modules/, loader: 'style-loader!css-loader!postcss-loader' }, { test: /\.less/i, use: [ { loader: 'style-loader', options: { sourceMap: true } }, { loader: 'css-loader', options: { sourceMap: true } }, { loader: 'postcss-loader', options: { sourceMap: true } }, { loader: 'less-loader', options: { sourceMap: true, modifyVars: theme } } ] } ] }, plugins: [ new webpack.LoaderOptionsPlugin({ options: { postcss: () => ([ pxtorem({ rootValue: 100, propWhiteList: [], }) ]) } }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), new webpack.DefinePlugin({ __DEV__: true, __DEBUG__: false, }), ], });
mit
DPOH-VAR/PowerNBT
src/main/java/me/dpohvar/powernbt/command/action/Action.java
404
package me.dpohvar.powernbt.command.action; import me.dpohvar.powernbt.exception.NBTTagNotFound; import me.dpohvar.powernbt.nbt.*; import org.bukkit.ChatColor; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Map; import static me.dpohvar.powernbt.PowerNBT.plugin; public abstract class Action { abstract public void execute() throws Exception; }
mit
mt830813/code
Lib/ADOUtility/ADOUtility.Model/SampleDbDataStructureListExt.cs
1246
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ADOUtility.Model { public static class SampleDbDataStructureListExt { public static int InsertOrUpdateMulti(this List<SampleDBDataStructure> list) { int returnValue = 0; foreach (var obj in list) { try { obj.InsertOrUpdate(); returnValue++; } catch (Exception) { } } return returnValue; } public static string ToJsonString(this List<SampleDBDataStructure> list) { StringBuilder returnValue = new StringBuilder(); returnValue.Append("["); foreach (var obj in list) { returnValue.Append(obj.ToJsonString() + ","); } if (list.Count > 0) { returnValue = returnValue.Remove(returnValue.Length - 1, 1); } returnValue.Append("]"); return returnValue.ToString(); } } }
mit
googlecreativelab/three.js
src/Three.Legacy.js
39188
/** * @author mrdoob / http://mrdoob.com/ */ import { Audio } from './audio/Audio.js'; import { AudioAnalyser } from './audio/AudioAnalyser.js'; import { PerspectiveCamera } from './cameras/PerspectiveCamera.js'; import { CullFaceFront, CullFaceBack, FlatShading } from './constants.js'; import { Float64BufferAttribute, Float32BufferAttribute, Uint32BufferAttribute, Int32BufferAttribute, Uint16BufferAttribute, Int16BufferAttribute, Uint8ClampedBufferAttribute, Uint8BufferAttribute, Int8BufferAttribute, BufferAttribute } from './core/BufferAttribute.js'; import { BufferGeometry } from './core/BufferGeometry.js'; import { Face3 } from './core/Face3.js'; import { Geometry } from './core/Geometry.js'; import { Object3D } from './core/Object3D.js'; import { Uniform } from './core/Uniform.js'; import { Curve } from './extras/core/Curve.js'; import { CatmullRomCurve3 } from './extras/curves/CatmullRomCurve3.js'; import { BoxHelper } from './helpers/BoxHelper.js'; import { GridHelper } from './helpers/GridHelper.js'; import { SkeletonHelper } from './helpers/SkeletonHelper.js'; import { BoxGeometry } from './geometries/BoxGeometry.js'; import { EdgesGeometry } from './geometries/EdgesGeometry.js'; import { ExtrudeGeometry } from './geometries/ExtrudeGeometry.js'; import { ShapeGeometry } from './geometries/ShapeGeometry.js'; import { WireframeGeometry } from './geometries/WireframeGeometry.js'; import { Light } from './lights/Light.js'; import { FileLoader } from './loaders/FileLoader.js'; import { AudioLoader } from './loaders/AudioLoader.js'; import { CubeTextureLoader } from './loaders/CubeTextureLoader.js'; import { DataTextureLoader } from './loaders/DataTextureLoader.js'; import { TextureLoader } from './loaders/TextureLoader.js'; import { Material } from './materials/Material.js'; import { LineBasicMaterial } from './materials/LineBasicMaterial.js'; import { MeshPhongMaterial } from './materials/MeshPhongMaterial.js'; import { PointsMaterial } from './materials/PointsMaterial.js'; import { ShaderMaterial } from './materials/ShaderMaterial.js'; import { Box2 } from './math/Box2.js'; import { Box3 } from './math/Box3.js'; import { Color } from './math/Color.js'; import { Line3 } from './math/Line3.js'; import { _Math } from './math/Math.js'; import { Matrix3 } from './math/Matrix3.js'; import { Matrix4 } from './math/Matrix4.js'; import { Plane } from './math/Plane.js'; import { Quaternion } from './math/Quaternion.js'; import { Ray } from './math/Ray.js'; import { Vector2 } from './math/Vector2.js'; import { Vector3 } from './math/Vector3.js'; import { Vector4 } from './math/Vector4.js'; import { LineSegments } from './objects/LineSegments.js'; import { LOD } from './objects/LOD.js'; import { Points } from './objects/Points.js'; import { Sprite } from './objects/Sprite.js'; import { Skeleton } from './objects/Skeleton.js'; import { WebGLRenderer } from './renderers/WebGLRenderer.js'; import { WebGLRenderTarget } from './renderers/WebGLRenderTarget.js'; import { WebGLShadowMap } from './renderers/webgl/WebGLShadowMap.js'; import { Shape } from './extras/core/Shape.js'; import { CubeCamera } from './cameras/CubeCamera.js'; export { BoxGeometry as CubeGeometry }; export function Face4( a, b, c, d, normal, color, materialIndex ) { console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ); return new Face3( a, b, c, normal, color, materialIndex ); } export var LineStrip = 0; export var LinePieces = 1; export function MeshFaceMaterial( materials ) { console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' ); return materials; } export function MultiMaterial( materials ) { if ( materials === undefined ) materials = []; console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' ); materials.isMultiMaterial = true; materials.materials = materials; materials.clone = function () { return materials.slice(); }; return materials; } export function PointCloud( geometry, material ) { console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); return new Points( geometry, material ); } export function Particle( material ) { console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' ); return new Sprite( material ); } export function ParticleSystem( geometry, material ) { console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); return new Points( geometry, material ); } export function PointCloudMaterial( parameters ) { console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); return new PointsMaterial( parameters ); } export function ParticleBasicMaterial( parameters ) { console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); return new PointsMaterial( parameters ); } export function ParticleSystemMaterial( parameters ) { console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); return new PointsMaterial( parameters ); } export function Vertex( x, y, z ) { console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' ); return new Vector3( x, y, z ); } // export function DynamicBufferAttribute( array, itemSize ) { console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' ); return new BufferAttribute( array, itemSize ).setDynamic( true ); } export function Int8Attribute( array, itemSize ) { console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' ); return new Int8BufferAttribute( array, itemSize ); } export function Uint8Attribute( array, itemSize ) { console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' ); return new Uint8BufferAttribute( array, itemSize ); } export function Uint8ClampedAttribute( array, itemSize ) { console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' ); return new Uint8ClampedBufferAttribute( array, itemSize ); } export function Int16Attribute( array, itemSize ) { console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' ); return new Int16BufferAttribute( array, itemSize ); } export function Uint16Attribute( array, itemSize ) { console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' ); return new Uint16BufferAttribute( array, itemSize ); } export function Int32Attribute( array, itemSize ) { console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' ); return new Int32BufferAttribute( array, itemSize ); } export function Uint32Attribute( array, itemSize ) { console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' ); return new Uint32BufferAttribute( array, itemSize ); } export function Float32Attribute( array, itemSize ) { console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' ); return new Float32BufferAttribute( array, itemSize ); } export function Float64Attribute( array, itemSize ) { console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' ); return new Float64BufferAttribute( array, itemSize ); } // Curve.create = function ( construct, getPoint ) { console.log( 'THREE.Curve.create() has been deprecated' ); construct.prototype = Object.create( Curve.prototype ); construct.prototype.constructor = construct; construct.prototype.getPoint = getPoint; return construct; }; // export function ClosedSplineCurve3( points ) { console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' ); CatmullRomCurve3.call( this, points ); this.type = 'catmullrom'; this.closed = true; } ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype ); // export function SplineCurve3( points ) { console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' ); CatmullRomCurve3.call( this, points ); this.type = 'catmullrom'; } SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype ); // export function Spline( points ) { console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' ); CatmullRomCurve3.call( this, points ); this.type = 'catmullrom'; } Spline.prototype = Object.create( CatmullRomCurve3.prototype ); Object.assign( Spline.prototype, { initFromArray: function ( /* a */ ) { console.error( 'THREE.Spline: .initFromArray() has been removed.' ); }, getControlPointsArray: function ( /* optionalTarget */ ) { console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' ); }, reparametrizeByArcLength: function ( /* samplingCoef */ ) { console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' ); } } ); // export function BoundingBoxHelper( object, color ) { console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' ); return new BoxHelper( object, color ); } export function EdgesHelper( object, hex ) { console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' ); return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); } GridHelper.prototype.setColors = function () { console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); }; SkeletonHelper.prototype.update = function () { console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' ); }; export function WireframeHelper( object, hex ) { console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' ); return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); } // export function XHRLoader( manager ) { console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' ); return new FileLoader( manager ); } export function BinaryTextureLoader( manager ) { console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' ); return new DataTextureLoader( manager ); } // Object.assign( Box2.prototype, { center: function ( optionalTarget ) { console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' ); return this.getCenter( optionalTarget ); }, empty: function () { console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' ); return this.isEmpty(); }, isIntersectionBox: function ( box ) { console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' ); return this.intersectsBox( box ); }, size: function ( optionalTarget ) { console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' ); return this.getSize( optionalTarget ); } } ); Object.assign( Box3.prototype, { center: function ( optionalTarget ) { console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' ); return this.getCenter( optionalTarget ); }, empty: function () { console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' ); return this.isEmpty(); }, isIntersectionBox: function ( box ) { console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' ); return this.intersectsBox( box ); }, isIntersectionSphere: function ( sphere ) { console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); return this.intersectsSphere( sphere ); }, size: function ( optionalTarget ) { console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' ); return this.getSize( optionalTarget ); } } ); Line3.prototype.center = function ( optionalTarget ) { console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' ); return this.getCenter( optionalTarget ); }; Object.assign( _Math, { random16: function () { console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' ); return Math.random(); }, nearestPowerOfTwo: function ( value ) { console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' ); return _Math.floorPowerOfTwo( value ); }, nextPowerOfTwo: function ( value ) { console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' ); return _Math.ceilPowerOfTwo( value ); } } ); Object.assign( Matrix3.prototype, { flattenToArrayOffset: function ( array, offset ) { console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." ); return this.toArray( array, offset ); }, multiplyVector3: function ( vector ) { console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); return vector.applyMatrix3( this ); }, multiplyVector3Array: function ( /* a */ ) { console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' ); }, applyToBuffer: function ( buffer /*, offset, length */ ) { console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' ); return this.applyToBufferAttribute( buffer ); }, applyToVector3Array: function ( /* array, offset, length */ ) { console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' ); } } ); Object.assign( Matrix4.prototype, { extractPosition: function ( m ) { console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); return this.copyPosition( m ); }, flattenToArrayOffset: function ( array, offset ) { console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." ); return this.toArray( array, offset ); }, getPosition: function () { var v1; return function getPosition() { if ( v1 === undefined ) v1 = new Vector3(); console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); return v1.setFromMatrixColumn( this, 3 ); }; }(), setRotationFromQuaternion: function ( q ) { console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); return this.makeRotationFromQuaternion( q ); }, multiplyToArray: function () { console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' ); }, multiplyVector3: function ( vector ) { console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); return vector.applyMatrix4( this ); }, multiplyVector4: function ( vector ) { console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); return vector.applyMatrix4( this ); }, multiplyVector3Array: function ( /* a */ ) { console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' ); }, rotateAxis: function ( v ) { console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); v.transformDirection( this ); }, crossVector: function ( vector ) { console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); return vector.applyMatrix4( this ); }, translate: function () { console.error( 'THREE.Matrix4: .translate() has been removed.' ); }, rotateX: function () { console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); }, rotateY: function () { console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); }, rotateZ: function () { console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); }, rotateByAxis: function () { console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); }, applyToBuffer: function ( buffer /*, offset, length */ ) { console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' ); return this.applyToBufferAttribute( buffer ); }, applyToVector3Array: function ( /* array, offset, length */ ) { console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' ); }, makeFrustum: function ( left, right, bottom, top, near, far ) { console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' ); return this.makePerspective( left, right, top, bottom, near, far ); } } ); Plane.prototype.isIntersectionLine = function ( line ) { console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' ); return this.intersectsLine( line ); }; Quaternion.prototype.multiplyVector3 = function ( vector ) { console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); return vector.applyQuaternion( this ); }; Object.assign( Ray.prototype, { isIntersectionBox: function ( box ) { console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' ); return this.intersectsBox( box ); }, isIntersectionPlane: function ( plane ) { console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' ); return this.intersectsPlane( plane ); }, isIntersectionSphere: function ( sphere ) { console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); return this.intersectsSphere( sphere ); } } ); Object.assign( Shape.prototype, { extrude: function ( options ) { console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' ); return new ExtrudeGeometry( this, options ); }, makeGeometry: function ( options ) { console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' ); return new ShapeGeometry( this, options ); } } ); Object.assign( Vector2.prototype, { fromAttribute: function ( attribute, index, offset ) { console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' ); return this.fromBufferAttribute( attribute, index, offset ); } } ); Object.assign( Vector3.prototype, { setEulerFromRotationMatrix: function () { console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); }, setEulerFromQuaternion: function () { console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); }, getPositionFromMatrix: function ( m ) { console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); return this.setFromMatrixPosition( m ); }, getScaleFromMatrix: function ( m ) { console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); return this.setFromMatrixScale( m ); }, getColumnFromMatrix: function ( index, matrix ) { console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); return this.setFromMatrixColumn( matrix, index ); }, applyProjection: function ( m ) { console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' ); return this.applyMatrix4( m ); }, fromAttribute: function ( attribute, index, offset ) { console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' ); return this.fromBufferAttribute( attribute, index, offset ); } } ); Object.assign( Vector4.prototype, { fromAttribute: function ( attribute, index, offset ) { console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' ); return this.fromBufferAttribute( attribute, index, offset ); } } ); // Geometry.prototype.computeTangents = function () { console.warn( 'THREE.Geometry: .computeTangents() has been removed.' ); }; Object.assign( Object3D.prototype, { getChildByName: function ( name ) { console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); return this.getObjectByName( name ); }, renderDepth: function () { console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); }, translate: function ( distance, axis ) { console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); return this.translateOnAxis( axis, distance ); } } ); Object.defineProperties( Object3D.prototype, { eulerOrder: { get: function () { console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); return this.rotation.order; }, set: function ( value ) { console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); this.rotation.order = value; } }, useQuaternion: { get: function () { console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); }, set: function () { console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); } } } ); Object.defineProperties( LOD.prototype, { objects: { get: function () { console.warn( 'THREE.LOD: .objects has been renamed to .levels.' ); return this.levels; } } } ); Object.defineProperty( Skeleton.prototype, 'useVertexTexture', { get: function () { console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' ); }, set: function () { console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' ); } } ); Object.defineProperty( Curve.prototype, '__arcLengthDivisions', { get: function () { console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' ); return this.arcLengthDivisions; }, set: function ( value ) { console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' ); this.arcLengthDivisions = value; } } ); // PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) { console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup." ); if ( filmGauge !== undefined ) this.filmGauge = filmGauge; this.setFocalLength( focalLength ); }; // Object.defineProperties( Light.prototype, { onlyShadow: { set: function () { console.warn( 'THREE.Light: .onlyShadow has been removed.' ); } }, shadowCameraFov: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' ); this.shadow.camera.fov = value; } }, shadowCameraLeft: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' ); this.shadow.camera.left = value; } }, shadowCameraRight: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' ); this.shadow.camera.right = value; } }, shadowCameraTop: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' ); this.shadow.camera.top = value; } }, shadowCameraBottom: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' ); this.shadow.camera.bottom = value; } }, shadowCameraNear: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' ); this.shadow.camera.near = value; } }, shadowCameraFar: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' ); this.shadow.camera.far = value; } }, shadowCameraVisible: { set: function () { console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' ); } }, shadowBias: { set: function ( value ) { console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' ); this.shadow.bias = value; } }, shadowDarkness: { set: function () { console.warn( 'THREE.Light: .shadowDarkness has been removed.' ); } }, shadowMapWidth: { set: function ( value ) { console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' ); this.shadow.mapSize.width = value; } }, shadowMapHeight: { set: function ( value ) { console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' ); this.shadow.mapSize.height = value; } } } ); // Object.defineProperties( BufferAttribute.prototype, { length: { get: function () { console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' ); return this.array.length; } } } ); Object.assign( BufferGeometry.prototype, { addIndex: function ( index ) { console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); this.setIndex( index ); }, addDrawCall: function ( start, count, indexOffset ) { if ( indexOffset !== undefined ) { console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); } console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); this.addGroup( start, count ); }, clearDrawCalls: function () { console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); this.clearGroups(); }, computeTangents: function () { console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' ); }, computeOffsets: function () { console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' ); } } ); Object.defineProperties( BufferGeometry.prototype, { drawcalls: { get: function () { console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); return this.groups; } }, offsets: { get: function () { console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); return this.groups; } } } ); // Object.defineProperties( Uniform.prototype, { dynamic: { set: function () { console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' ); } }, onUpdate: { value: function () { console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' ); return this; } } } ); // Object.defineProperties( Material.prototype, { wrapAround: { get: function () { console.warn( 'THREE.Material: .wrapAround has been removed.' ); }, set: function () { console.warn( 'THREE.Material: .wrapAround has been removed.' ); } }, wrapRGB: { get: function () { console.warn( 'THREE.Material: .wrapRGB has been removed.' ); return new Color(); } }, shading: { get: function () { console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); }, set: function ( value ) { console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); this.flatShading = ( value === FlatShading ); } } } ); Object.defineProperties( MeshPhongMaterial.prototype, { metal: { get: function () { console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' ); return false; }, set: function () { console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' ); } } } ); Object.defineProperties( ShaderMaterial.prototype, { derivatives: { get: function () { console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); return this.extensions.derivatives; }, set: function ( value ) { console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); this.extensions.derivatives = value; } } } ); // Object.assign( WebGLRenderer.prototype, { getCurrentRenderTarget: function () { console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' ); return this.getRenderTarget(); }, getMaxAnisotropy: function () { console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' ); return this.capabilities.getMaxAnisotropy(); }, getPrecision: function () { console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' ); return this.capabilities.precision; }, resetGLState: function () { console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' ); return this.state.reset(); }, supportsFloatTextures: function () { console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); return this.extensions.get( 'OES_texture_float' ); }, supportsHalfFloatTextures: function () { console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' ); return this.extensions.get( 'OES_texture_half_float' ); }, supportsStandardDerivatives: function () { console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' ); return this.extensions.get( 'OES_standard_derivatives' ); }, supportsCompressedTextureS3TC: function () { console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' ); return this.extensions.get( 'WEBGL_compressed_texture_s3tc' ); }, supportsCompressedTexturePVRTC: function () { console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' ); return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' ); }, supportsBlendMinMax: function () { console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' ); return this.extensions.get( 'EXT_blend_minmax' ); }, supportsVertexTextures: function () { console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' ); return this.capabilities.vertexTextures; }, supportsInstancedArrays: function () { console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' ); return this.extensions.get( 'ANGLE_instanced_arrays' ); }, enableScissorTest: function ( boolean ) { console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' ); this.setScissorTest( boolean ); }, initMaterial: function () { console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' ); }, addPrePlugin: function () { console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' ); }, addPostPlugin: function () { console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' ); }, updateShadowMap: function () { console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); } } ); Object.defineProperties( WebGLRenderer.prototype, { shadowMapEnabled: { get: function () { return this.shadowMap.enabled; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' ); this.shadowMap.enabled = value; } }, shadowMapType: { get: function () { return this.shadowMap.type; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' ); this.shadowMap.type = value; } }, shadowMapCullFace: { get: function () { return this.shadowMap.cullFace; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' ); this.shadowMap.cullFace = value; } } } ); Object.defineProperties( WebGLShadowMap.prototype, { cullFace: { get: function () { return this.renderReverseSided ? CullFaceFront : CullFaceBack; }, set: function ( cullFace ) { var value = ( cullFace !== CullFaceBack ); console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." ); this.renderReverseSided = value; } } } ); // Object.defineProperties( WebGLRenderTarget.prototype, { wrapS: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); return this.texture.wrapS; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); this.texture.wrapS = value; } }, wrapT: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); return this.texture.wrapT; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); this.texture.wrapT = value; } }, magFilter: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); return this.texture.magFilter; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); this.texture.magFilter = value; } }, minFilter: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); return this.texture.minFilter; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); this.texture.minFilter = value; } }, anisotropy: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); return this.texture.anisotropy; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); this.texture.anisotropy = value; } }, offset: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); return this.texture.offset; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); this.texture.offset = value; } }, repeat: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); return this.texture.repeat; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); this.texture.repeat = value; } }, format: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); return this.texture.format; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); this.texture.format = value; } }, type: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); return this.texture.type; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); this.texture.type = value; } }, generateMipmaps: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); return this.texture.generateMipmaps; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); this.texture.generateMipmaps = value; } } } ); // Audio.prototype.load = function ( file ) { console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' ); var scope = this; var audioLoader = new AudioLoader(); audioLoader.load( file, function ( buffer ) { scope.setBuffer( buffer ); } ); return this; }; AudioAnalyser.prototype.getData = function () { console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' ); return this.getFrequencyData(); }; // CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) { console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' ); return this.update( renderer, scene ); }; // export var GeometryUtils = { merge: function ( geometry1, geometry2, materialIndexOffset ) { console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' ); var matrix; if ( geometry2.isMesh ) { geometry2.matrixAutoUpdate && geometry2.updateMatrix(); matrix = geometry2.matrix; geometry2 = geometry2.geometry; } geometry1.merge( geometry2, matrix, materialIndexOffset ); }, center: function ( geometry ) { console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' ); return geometry.center(); } }; export var ImageUtils = { crossOrigin: undefined, loadTexture: function ( url, mapping, onLoad, onError ) { console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' ); var loader = new TextureLoader(); loader.setCrossOrigin( this.crossOrigin ); var texture = loader.load( url, onLoad, undefined, onError ); if ( mapping ) texture.mapping = mapping; return texture; }, loadTextureCube: function ( urls, mapping, onLoad, onError ) { console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' ); var loader = new CubeTextureLoader(); loader.setCrossOrigin( this.crossOrigin ); var texture = loader.load( urls, onLoad, undefined, onError ); if ( mapping ) texture.mapping = mapping; return texture; }, loadCompressedTexture: function () { console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ); }, loadCompressedTextureCube: function () { console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ); } }; // export function Projector() { console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' ); this.projectVector = function ( vector, camera ) { console.warn( 'THREE.Projector: .projectVector() is now vector.project().' ); vector.project( camera ); }; this.unprojectVector = function ( vector, camera ) { console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' ); vector.unproject( camera ); }; this.pickingRay = function () { console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' ); }; } // export function CanvasRenderer() { console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' ); this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); this.clear = function () {}; this.render = function () {}; this.setClearColor = function () {}; this.setSize = function () {}; }
mit
zzjkf2009/Midterm_Astar
opencv/modules/imgproc/src/undistort.avx2.cpp
10014
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" #include "undistort.hpp" namespace cv { int initUndistortRectifyMapLine_AVX(float* m1f, float* m2f, short* m1, ushort* m2, double* matTilt, const double* ir, double& _x, double& _y, double& _w, int width, int m1type, double& k1, double& k2, double& k3, double& k4, double& k5, double& k6, double& p1, double& p2, double& s1, double& s2, double& s3, double& s4, double& u0, double& v0, double& fx, double& fy) { int j = 0; static const __m256d __one = _mm256_set1_pd(1.0); static const __m256d __two = _mm256_set1_pd(2.0); const __m256d __matTilt_00 = _mm256_set1_pd(matTilt[0]); const __m256d __matTilt_10 = _mm256_set1_pd(matTilt[3]); const __m256d __matTilt_20 = _mm256_set1_pd(matTilt[6]); const __m256d __matTilt_01 = _mm256_set1_pd(matTilt[1]); const __m256d __matTilt_11 = _mm256_set1_pd(matTilt[4]); const __m256d __matTilt_21 = _mm256_set1_pd(matTilt[7]); const __m256d __matTilt_02 = _mm256_set1_pd(matTilt[2]); const __m256d __matTilt_12 = _mm256_set1_pd(matTilt[5]); const __m256d __matTilt_22 = _mm256_set1_pd(matTilt[8]); for (; j <= width - 4; j += 4, _x += 4 * ir[0], _y += 4 * ir[3], _w += 4 * ir[6]) { // Question: Should we load the constants first? __m256d __w = _mm256_div_pd(__one, _mm256_set_pd(_w + 3 * ir[6], _w + 2 * ir[6], _w + ir[6], _w)); __m256d __x = _mm256_mul_pd(_mm256_set_pd(_x + 3 * ir[0], _x + 2 * ir[0], _x + ir[0], _x), __w); __m256d __y = _mm256_mul_pd(_mm256_set_pd(_y + 3 * ir[3], _y + 2 * ir[3], _y + ir[3], _y), __w); __m256d __x2 = _mm256_mul_pd(__x, __x); __m256d __y2 = _mm256_mul_pd(__y, __y); __m256d __r2 = _mm256_add_pd(__x2, __y2); __m256d __2xy = _mm256_mul_pd(__two, _mm256_mul_pd(__x, __y)); __m256d __kr = _mm256_div_pd( #if CV_FMA3 _mm256_fmadd_pd(_mm256_fmadd_pd(_mm256_fmadd_pd(_mm256_set1_pd(k3), __r2, _mm256_set1_pd(k2)), __r2, _mm256_set1_pd(k1)), __r2, __one), _mm256_fmadd_pd(_mm256_fmadd_pd(_mm256_fmadd_pd(_mm256_set1_pd(k6), __r2, _mm256_set1_pd(k5)), __r2, _mm256_set1_pd(k4)), __r2, __one) #else _mm256_add_pd(__one, _mm256_mul_pd(_mm256_add_pd(_mm256_mul_pd(_mm256_add_pd(_mm256_mul_pd(_mm256_set1_pd(k3), __r2), _mm256_set1_pd(k2)), __r2), _mm256_set1_pd(k1)), __r2)), _mm256_add_pd(__one, _mm256_mul_pd(_mm256_add_pd(_mm256_mul_pd(_mm256_add_pd(_mm256_mul_pd(_mm256_set1_pd(k6), __r2), _mm256_set1_pd(k5)), __r2), _mm256_set1_pd(k4)), __r2)) #endif ); __m256d __r22 = _mm256_mul_pd(__r2, __r2); #if CV_FMA3 __m256d __xd = _mm256_fmadd_pd(__x, __kr, _mm256_add_pd( _mm256_fmadd_pd(_mm256_set1_pd(p1), __2xy, _mm256_mul_pd(_mm256_set1_pd(p2), _mm256_fmadd_pd(__two, __x2, __r2))), _mm256_fmadd_pd(_mm256_set1_pd(s1), __r2, _mm256_mul_pd(_mm256_set1_pd(s2), __r22)))); __m256d __yd = _mm256_fmadd_pd(__y, __kr, _mm256_add_pd( _mm256_fmadd_pd(_mm256_set1_pd(p1), _mm256_fmadd_pd(__two, __y2, __r2), _mm256_mul_pd(_mm256_set1_pd(p2), __2xy)), _mm256_fmadd_pd(_mm256_set1_pd(s3), __r2, _mm256_mul_pd(_mm256_set1_pd(s4), __r22)))); __m256d __vecTilt2 = _mm256_fmadd_pd(__matTilt_20, __xd, _mm256_fmadd_pd(__matTilt_21, __yd, __matTilt_22)); #else __m256d __xd = _mm256_add_pd( _mm256_mul_pd(__x, __kr), _mm256_add_pd( _mm256_add_pd( _mm256_mul_pd(_mm256_set1_pd(p1), __2xy), _mm256_mul_pd(_mm256_set1_pd(p2), _mm256_add_pd(__r2, _mm256_mul_pd(__two, __x2)))), _mm256_add_pd( _mm256_mul_pd(_mm256_set1_pd(s1), __r2), _mm256_mul_pd(_mm256_set1_pd(s2), __r22)))); __m256d __yd = _mm256_add_pd( _mm256_mul_pd(__y, __kr), _mm256_add_pd( _mm256_add_pd( _mm256_mul_pd(_mm256_set1_pd(p1), _mm256_add_pd(__r2, _mm256_mul_pd(__two, __y2))), _mm256_mul_pd(_mm256_set1_pd(p2), __2xy)), _mm256_add_pd( _mm256_mul_pd(_mm256_set1_pd(s3), __r2), _mm256_mul_pd(_mm256_set1_pd(s4), __r22)))); __m256d __vecTilt2 = _mm256_add_pd(_mm256_add_pd( _mm256_mul_pd(__matTilt_20, __xd), _mm256_mul_pd(__matTilt_21, __yd)), __matTilt_22); #endif __m256d __invProj = _mm256_blendv_pd( __one, _mm256_div_pd(__one, __vecTilt2), _mm256_cmp_pd(__vecTilt2, _mm256_setzero_pd(), _CMP_EQ_OQ)); #if CV_FMA3 __m256d __u = _mm256_fmadd_pd(__matTilt_00, __xd, _mm256_fmadd_pd(__matTilt_01, __yd, __matTilt_02)); __u = _mm256_fmadd_pd(_mm256_mul_pd(_mm256_set1_pd(fx), __invProj), __u, _mm256_set1_pd(u0)); __m256d __v = _mm256_fmadd_pd(__matTilt_10, __xd, _mm256_fmadd_pd(__matTilt_11, __yd, __matTilt_12)); __v = _mm256_fmadd_pd(_mm256_mul_pd(_mm256_set1_pd(fy), __invProj), __v, _mm256_set1_pd(v0)); #else __m256d __u = _mm256_add_pd(_mm256_add_pd( _mm256_mul_pd(__matTilt_00, __xd), _mm256_mul_pd(__matTilt_01, __yd)), __matTilt_02); __u = _mm256_add_pd(_mm256_mul_pd(_mm256_mul_pd(_mm256_set1_pd(fx), __invProj), __u), _mm256_set1_pd(u0)); __m256d __v = _mm256_add_pd(_mm256_add_pd( _mm256_mul_pd(__matTilt_10, __xd), _mm256_mul_pd(__matTilt_11, __yd)), __matTilt_12); __v = _mm256_add_pd(_mm256_mul_pd(_mm256_mul_pd(_mm256_set1_pd(fy), __invProj), __v), _mm256_set1_pd(v0)); #endif if (m1type == CV_32FC1) { _mm_storeu_ps(&m1f[j], _mm256_cvtpd_ps(__u)); _mm_storeu_ps(&m2f[j], _mm256_cvtpd_ps(__v)); } else if (m1type == CV_32FC2) { __m128 __u_float = _mm256_cvtpd_ps(__u); __m128 __v_float = _mm256_cvtpd_ps(__v); _mm_storeu_ps(&m1f[j * 2], _mm_unpacklo_ps(__u_float, __v_float)); _mm_storeu_ps(&m1f[j * 2 + 4], _mm_unpackhi_ps(__u_float, __v_float)); } else // m1type == CV_16SC2 { __u = _mm256_mul_pd(__u, _mm256_set1_pd(INTER_TAB_SIZE)); __v = _mm256_mul_pd(__v, _mm256_set1_pd(INTER_TAB_SIZE)); __m128i __iu = _mm256_cvtpd_epi32(__u); __m128i __iv = _mm256_cvtpd_epi32(__v); static const __m128i __INTER_TAB_SIZE_m1 = _mm_set1_epi32(INTER_TAB_SIZE - 1); __m128i __m2 = _mm_add_epi32( _mm_mullo_epi32(_mm_and_si128(__iv, __INTER_TAB_SIZE_m1), _mm_set1_epi32(INTER_TAB_SIZE)), _mm_and_si128(__iu, __INTER_TAB_SIZE_m1)); __m2 = _mm_packus_epi32(__m2, __m2); _mm_maskstore_epi64((long long int*) &m2[j], _mm_set_epi32(0, 0, 0xFFFFFFFF, 0xFFFFFFFF), __m2); // gcc4.9 does not support _mm256_set_m128 // __m256i __m1 = _mm256_set_m128i(__iv, __iu); __m256i __m1 = _mm256_setzero_si256(); __m1 = _mm256_inserti128_si256(__m1, __iu, 0); __m1 = _mm256_inserti128_si256(__m1, __iv, 1); __m1 = _mm256_srai_epi32(__m1, INTER_BITS); // v3 v2 v1 v0 u3 u2 u1 u0 (int32_t) static const __m256i __permute_mask = _mm256_set_epi32(7, 3, 6, 2, 5, 1, 4, 0); __m1 = _mm256_permutevar8x32_epi32(__m1, __permute_mask); // v3 u3 v2 u2 v1 u1 v0 u0 (int32_t) __m1 = _mm256_packs_epi32(__m1, __m1); // x x x x v3 u3 v2 u2 x x x x v1 u1 v0 u0 (int16_t) _mm_storeu_si128((__m128i*) &m1[j * 2], _mm256_extracti128_si256(_mm256_permute4x64_epi64(__m1, (2 << 2) + 0), 0)); } } _mm256_zeroupper(); return j; } } /* End of file */
mit
lsjroberts/node-tfl
lib/bus.js
25
var bus = function() { };
mit
TrayboonBucks/Trayboon_Bucks
src/qt/guiutil.cpp
13561
#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include "base58.h" #include <QString> #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { if(uri.scheme() != QString("trayboonbucks")) return false; // check if the address is valid CBitcoinAddress addressFromUri(uri.path().toStdString()); if (!addressFromUri.IsValid()) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert TrayboonBucks:// to TrayboonBucks: // // Cannot handle this later, because trayboonbucks:// will cause Qt to see the part after // as host, // which will lowercase it (and thus invalidate the address). if(uri.startsWith("trayboonbucks://")) { uri.replace(0, 11, "trayboonbucks:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt/>" + HtmlEscape(tooltip, true); widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "TrayboonBucks.lnk"; } bool GetStartOnSystemStartup() { // check for TrayboonBucks.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "trayboonbucks.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a trayboonbucks.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=TrayboonBucks\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("trayboonbucks-qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " trayboonbucks-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("trayboonbucks-qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in nonbreaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stderr, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
mit
misterhaan/track7.org
comments.php
3818
<?php define('MAX_COMMENT_GET', 24); require_once $_SERVER['DOCUMENT_ROOT'] . '/etc/class/t7.php'; $u = FindUser(); $html = new t7html(['vue' => true]); if($u) { $html->Open(htmlspecialchars($u->displayname) . '’s comments'); ?> <h1 data-user=<?=$u->id; ?>> <a href="/user/<?=$u->username; ?>/"> <img class="inline avatar" src="<?=$u->avatar; ?>"> <?=htmlspecialchars($u->displayname); ?></a>’s comments </h1> <?php } else { $html->Open('comments'); ?> <h1 data-user=all> comments <a class=feed href="<?=str_replace('.php', '.rss', $_SERVER['PHP_SELF']); ?>" title="rss feed of comments"></a> </h1> <?php } ?> <div id=comments> <p class=error v-if="error">{{error}}</p> <p class=info v-if="!loading && !error && comments.length == 0">no comments found</p> <template v-for="comment in comments"> <h3><a :href=comment.url>{{comment.title}}</a></h3> <section class=comment> <div class=userinfo> <div class=username v-if=comment.username :class="{friend: comment.friend}" :title="comment.friend ? (comment.displayname || comment.username) + ' is your friend' : null"> <a :href="'/user/' + comment.username + '/'">{{comment.displayname || comment.username}}</a> </div> <a v-if="comment.username && comment.avatar" :href="'/user/' + comment.username + '/'"><img class=avatar alt="" :src=comment.avatar></a> <div class=userlevel v-if="comment.username && comment.level">{{comment.level}}</div> <div class=username v-if="!comment.username && comment.contacturl"><a :href=comment.contacturl>{{comment.name}}</a></div> <div class=username v-if="!comment.username && !comment.contacturl">{{comment.name}}</div> </div> <div class=comment> <header>posted <time :datetime=comment.posted.datetime>{{comment.posted.display}}</time></header> <div class=content v-if=!comment.editing v-html=comment.html></div> <div class="content edit" v-if=comment.editing> <textarea v-model=comment.markdown></textarea> </div> <footer v-if=comment.canchange> <a class="okay action" v-if=comment.editing v-on:click.prevent=Save(comment) href="/api/comments/save">save</a> <a class="cancel action" v-if=comment.editing v-on:click.prevent=Unedit(comment) href="#cancelEdit">cancel</a> <a class="edit action" v-if=!comment.editing v-on:click.prevent=Edit(comment) href="#edit">edit</a> <a class="del action" v-if=!comment.editing v-on:click.prevent=Delete(comment) href="/api/comments/delete">delete</a> </footer> </div> </section> </template> <p class=loading v-if=loading>loading comments . . .</p> <p class=calltoaction v-if=hasMore v-on:click.prevent=Load><a class="get action" href="/api/comments/keyed">load more comments</a></p> </div> <?php $html->Close(); /** * Find the user whose comments are being displayed (if not all users). Will * redirect to the list of users if unable to find the user. * @param string $_GET['username'] username to display comments from (unset for all users) * @return object user object with id, username, displayname, and avatar */ function FindUser() { global $db; if(isset($_GET['username'])) { if($u = $db->prepare('select id, username, displayname, avatar from users where username=? limit 1')) if($u->bind_param('s', $_GET['username'])) if($u->execute()) if($u->bind_result($id, $username, $displayname, $avatar)) if($u->fetch()) return (object)['id' => $id, 'username' => $username, 'displayname' => $displayname ? $displayname : $username, 'avatar' => $avatar ? $avatar : t7user::DEFAULT_AVATAR]; if(substr($_SERVER['REQUEST_URI'], 0, 6) == '/user/') { header('Location: ' . t7format::FullUrl($_SERVER['PHP_SELF'])); die; } } return false; }
mit
paydirt/delayable_km
lib/delayable_km/km.rb
2336
# The main delayable_km class, containing methods for initializing a KISSmetrics API client and making API calls class KM # The default KISSmetrics API endpoint that all requests are sent to DEFAULT_API_ENDPOINT = 'http://trk.kissmetrics.com' # Create a KISSmetrics API client. # # @param [String] :api_key Your site's KISSmetrics API key def initialize(api_key, options = {}) @api_key = api_key @api_endpoint = DEFAULT_API_ENDPOINT end # Set the identity of a person using your site # @see http://support.kissmetrics.com/apis/common-methods#identify # # @param [String] :id A unique identifier for a person (email address, user id, or login are common choices) def identify(id) @id = id end # Record a KISSmetrics event # @see http://support.kissmetrics.com/apis/common-methods#record # # @param [String] event # @param [Hash] params # @option options [String] :_p (@id) The identity of the person you are setting properties on. You can also set this by calling #identify. def record(event, params = {}) defaults = { :_n => event, :_p => @id } params = defaults.merge(params) request('e', params) end # Associate one KISSmetrics identity with another # @see http://support.kissmetrics.com/apis/common-methods#alias # @note The order of arguments to this method doesn't actually matter. You can call it with the existing identifier first or second. # # @param [String] name An existing identifier for a user # @param [String] alias_to A new identifier to associate with the user def alias(name, alias_to) params = { :_n => alias_to, :_p => name } request('a', params) end # Set properties on a person without recording a named event # @see http://support.kissmetrics.com/apis/common-methods#set # # @param [Hash] params An arbitrary hash of properties to associate with a person # @option options [String] :_p (@id) The identity of the person you are setting properties on. You can also set this by calling #identify. def set(params) defaults = { :_p => @id } params = defaults.merge(params) request('s', params) end private def request(path, params) params = { :_t => Time.now.utc.to_i.to_s, :_d => 1, :_k => @api_key }.merge(params) HTTParty.get("#{@api_endpoint}/#{path}", :query => params) end end
mit
Canadensys/canadensys-data-access
src/main/java/net/canadensys/dataportal/occurrence/model/ResourceContactModel.java
2693
package net.canadensys.dataportal.occurrence.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "resource_contact") @SequenceGenerator(name = "resource_contact_id_seq", sequenceName = "resource_contact_id_seq", allocationSize=1) public class ResourceContactModel { @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "resource_contact_id_seq") private Integer id; private String sourcefileid; private String resource_name; private String name; private String position_name; private String organization_name; private String address; private String city; private String administrative_area; private String country; private String postal_code; private String phone; private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSourcefileid() { return sourcefileid; } public void setSourcefileid(String sourcefileid) { this.sourcefileid = sourcefileid; } public String getResource_name() { return resource_name; } public void setResource_name(String resource_name) { this.resource_name = resource_name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPosition_name() { return position_name; } public void setPosition_name(String position_name) { this.position_name = position_name; } public String getOrganization_name() { return organization_name; } public void setOrganization_name(String organization_name) { this.organization_name = organization_name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getAdministrative_area() { return administrative_area; } public void setAdministrative_area(String administrative_area) { this.administrative_area = administrative_area; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getPostal_code() { return postal_code; } public void setPostal_code(String postal_code) { this.postal_code = postal_code; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
mit
ysden123/ys-pnodejs
modules/pmocha/lib/config.js
207
// Defines list of the automation tests. 'use strict'; module.exports = function () { return { tests: [ "google_adwords/test/auth_test.js", "ppc/test/*" ] }; }
mit
negrinho/deep_architect
dev/google_communicator/worker.py
5680
import argparse import pickle import json import time import threading import pprint import deep_architect.utils as ut from google.cloud import pubsub_v1 from deep_architect.contrib.misc.datasets.loaders import (load_cifar10, load_mnist) from deep_architect.contrib.misc.datasets.dataset import InMemoryDataset from deep_architect.searchers import common as se from deep_architect.contrib.misc import gpu_utils from deep_architect import search_logging as sl from deep_architect import utils as ut from dev.google_communicator.search_space_factory import name_to_search_space_factory_fn from deep_architect.contrib.misc.evaluators.tensorflow.tpu_estimator_classification import TPUEstimatorEvaluator from deep_architect.contrib.communicators.communicator import get_communicator import logging logging.basicConfig() publisher = pubsub_v1.PublisherClient() subscriber = pubsub_v1.SubscriberClient() results_topic = None arch_subscription = None specified = False evaluated = False arch_data = None started = False def retrieve_message(message): global specified global evaluated global arch_data global started # print(type(message.data)) # print(message.data) # print(message.data.decode('utf-8')) # print(json.loads(message.data.decode('utf-8'))) started = True data = json.loads(message.data.decode('utf-8')) if data == 'kill': arch_data = None specified = True message.nack() else: arch_data = data evaluated = False specified = True last_refresh = 0 while not evaluated: if last_refresh > 300: message.modify_ack_deadline(600) last_refresh = 0 time.sleep(5) last_refresh += 5 message.ack() def main(): global specified global evaluated global results_topic, arch_subscription configs = ut.read_jsonfile( "/deep_architect/dev/google_communicator/experiment_config.json") parser = argparse.ArgumentParser("MPI Job for architecture search") parser.add_argument('--config', '-c', action='store', dest='config_name', default='search_evol') # Other arguments parser.add_argument('--display-output', '-o', action='store_true', dest='display_output', default=False) parser.add_argument('--project-id', action='store', dest='project_id', default='deep-architect') parser.add_argument('--bucket', '-b', action='store', dest='bucket', default='normal') parser.add_argument('--resume', '-r', action='store_true', dest='resume', default=False) options = parser.parse_args() config = configs[options.config_name] PROJECT_ID = options.project_id BUCKET_NAME = options.bucket results_topic = publisher.topic_path(PROJECT_ID, 'results') arch_subscription = subscriber.subscription_path(PROJECT_ID, 'architectures-sub') datasets = { 'cifar10': ('/data/cifar10/', 10), } data_dir, num_classes = datasets[config['dataset']] search_space_factory = name_to_search_space_factory_fn[ config['search_space']](num_classes) save_every = 1 if 'save_every' not in config else config['save_every'] evaluators = { 'tpu_classification': lambda: TPUEstimatorEvaluator( 'gs://' + BUCKET_NAME + data_dir, max_num_training_epochs=config['eval_epochs'], log_output_to_terminal=options.display_output, base_dir='gs://' + BUCKET_NAME + '/scratch_dir'), } evaluator = evaluators[config['evaluator']]() search_data_folder = sl.get_search_data_folderpath(config['search_folder'], config['search_name']) subscription = subscriber.subscribe(arch_subscription, callback=retrieve_message) thread = threading.Thread(target=nudge_master) thread.start() step = 0 while True: while not specified: time.sleep(5) if arch_data: vs, evaluation_id, searcher_eval_token = arch_data inputs, outputs = search_space_factory.get_search_space() se.specify(outputs, vs) print('Evaluating architecture') results = evaluator.eval(inputs, outputs) print('Evaluated architecture') step += 1 if step % save_every == 0: evaluator.save_state(search_data_folder) encoded_results = json.dumps((results, vs, evaluation_id, searcher_eval_token)).encode('utf-8') future = publisher.publish(results_topic, encoded_results) future.result() evaluated = True specified = False else: break thread.join() subscription.cancel() def nudge_master(): global started time.sleep(10) if not started: encoded_results = json.dumps('publish').encode('utf-8') future = publisher.publish(results_topic, encoded_results) future.result() if __name__ == "__main__": main()
mit
marcusfcbarbosa/myPortfolio
MyPortFolio.WebUI/Controllers/AccountController.cs
15926
using System; using System.Collections.Generic; using System.Linq; using System.Transactions; using System.Web; using System.Web.Mvc; using System.Web.Security; using DotNetOpenAuth.AspNet; using Microsoft.Web.WebPages.OAuth; using WebMatrix.WebData; using MyPortFolio.WebUI.Filters; using MyPortFolio.WebUI.Models; namespace MyPortFolio.WebUI.Controllers { [Authorize] [InitializeSimpleMembership] public class AccountController : Controller { // // GET: /Account/Login [AllowAnonymous] public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Login(LoginModel model, string returnUrl) { if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)) { return RedirectToLocal(returnUrl); } // If we got this far, something failed, redisplay form ModelState.AddModelError("", "The user name or password provided is incorrect."); return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { WebSecurity.Logout(); return RedirectToAction("Index", "Home"); } // // GET: /Account/Register [AllowAnonymous] public ActionResult Register() { return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the user try { WebSecurity.CreateUserAndAccount(model.UserName, model.Password); WebSecurity.Login(model.UserName, model.Password); return RedirectToAction("Index", "Home"); } catch (MembershipCreateUserException e) { ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); } } // If we got this far, something failed, redisplay form return View(model); } // // POST: /Account/Disassociate [HttpPost] [ValidateAntiForgeryToken] public ActionResult Disassociate(string provider, string providerUserId) { string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId); ManageMessageId? message = null; // Only disassociate the account if the currently logged in user is the owner if (ownerAccount == User.Identity.Name) { // Use a transaction to prevent the user from deleting their last login credential using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable })) { bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)); if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1) { OAuthWebSecurity.DeleteAccount(provider, providerUserId); scope.Complete(); message = ManageMessageId.RemoveLoginSuccess; } } } return RedirectToAction("Manage", new { Message = message }); } // // GET: /Account/Manage public ActionResult Manage(ManageMessageId? message) { ViewBag.StatusMessage = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : ""; ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)); ViewBag.ReturnUrl = Url.Action("Manage"); return View(); } // // POST: /Account/Manage [HttpPost] [ValidateAntiForgeryToken] public ActionResult Manage(LocalPasswordModel model) { bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)); ViewBag.HasLocalPassword = hasLocalAccount; ViewBag.ReturnUrl = Url.Action("Manage"); if (hasLocalAccount) { if (ModelState.IsValid) { // ChangePassword will throw an exception rather than return false in certain failure scenarios. bool changePasswordSucceeded; try { changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword); } catch (Exception) { changePasswordSucceeded = false; } if (changePasswordSucceeded) { return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess }); } else { ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); } } } else { // User does not have a local password so remove any validation errors caused by a missing // OldPassword field ModelState state = ModelState["OldPassword"]; if (state != null) { state.Errors.Clear(); } if (ModelState.IsValid) { try { WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword); return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess }); } catch (Exception) { ModelState.AddModelError("", String.Format("Unable to create local account. An account with the name \"{0}\" may already exist.", User.Identity.Name)); } } } // If we got this far, something failed, redisplay form return View(model); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult ExternalLogin(string provider, string returnUrl) { return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl })); } // // GET: /Account/ExternalLoginCallback [AllowAnonymous] public ActionResult ExternalLoginCallback(string returnUrl) { AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl })); if (!result.IsSuccessful) { return RedirectToAction("ExternalLoginFailure"); } if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false)) { return RedirectToLocal(returnUrl); } if (User.Identity.IsAuthenticated) { // If the current user is logged in add the new account OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name); return RedirectToLocal(returnUrl); } else { // User is new, ask for their desired membership name string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId); ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName; ViewBag.ReturnUrl = returnUrl; return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl) { string provider = null; string providerUserId = null; if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId)) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { // Insert a new user into the database using (UsersContext db = new UsersContext()) { UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower()); // Check if user already exists if (user == null) { // Insert name into the profile table db.UserProfiles.Add(new UserProfile { UserName = model.UserName }); db.SaveChanges(); OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName); OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false); return RedirectToLocal(returnUrl); } else { ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name."); } } } ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName; ViewBag.ReturnUrl = returnUrl; return View(model); } // // GET: /Account/ExternalLoginFailure [AllowAnonymous] public ActionResult ExternalLoginFailure() { return View(); } [AllowAnonymous] [ChildActionOnly] public ActionResult ExternalLoginsList(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData); } [ChildActionOnly] public ActionResult RemoveExternalLogins() { ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name); List<ExternalLogin> externalLogins = new List<ExternalLogin>(); foreach (OAuthAccount account in accounts) { AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider); externalLogins.Add(new ExternalLogin { Provider = account.Provider, ProviderDisplayName = clientData.DisplayName, ProviderUserId = account.ProviderUserId, }); } ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)); return PartialView("_RemoveExternalLoginsPartial", externalLogins); } #region Helpers private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } public enum ManageMessageId { ChangePasswordSuccess, SetPasswordSuccess, RemoveLoginSuccess, } internal class ExternalLoginResult : ActionResult { public ExternalLoginResult(string provider, string returnUrl) { Provider = provider; ReturnUrl = returnUrl; } public string Provider { get; private set; } public string ReturnUrl { get; private set; } public override void ExecuteResult(ControllerContext context) { OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl); } } private static string ErrorCodeToString(MembershipCreateStatus createStatus) { // See http://go.microsoft.com/fwlink/?LinkID=177550 for // a full list of status codes. switch (createStatus) { case MembershipCreateStatus.DuplicateUserName: return "User name already exists. Please enter a different user name."; case MembershipCreateStatus.DuplicateEmail: return "A user name for that e-mail address already exists. Please enter a different e-mail address."; case MembershipCreateStatus.InvalidPassword: return "The password provided is invalid. Please enter a valid password value."; case MembershipCreateStatus.InvalidEmail: return "The e-mail address provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidAnswer: return "The password retrieval answer provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidQuestion: return "The password retrieval question provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidUserName: return "The user name provided is invalid. Please check the value and try again."; case MembershipCreateStatus.ProviderError: return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."; case MembershipCreateStatus.UserRejected: return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."; default: return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."; } } #endregion } }
mit
anitagraham/refinerycms-testimonials
spec/models/testimonial_spec.rb
1319
require 'spec_helper' module Refinery module Testimonials describe Testimonial, type: :model do let(:good_testimonial) { FactoryBot.create(:testimonial)} let(:no_name_testimonial) { FactoryBot.create(:testimonial, name: "") } let(:no_quote_testimonial) { FactoryBot.create(:testimonial, quote: "")} describe 'validations' do context "with all required attributes" do it "has no errors" do expect(good_testimonial.errors).to be_empty end it "has a name" do expect(testimonial.name).to eq('Person Name') end it "has a quote" do expect(testimonial.quote).to eq('Like your work') end end context "without required attribute name" do it 'fails validation' do expect(no_name_testimonial).not_to be_valid end it "has errors" do expect(no_name_testimonial.errors).not_to be_empty end end context "without required attribute quote" do it 'fails validation' do expect(no_quote_testimonial).not_to be_valid end it "has errors" do expect(no_name_testimonial.errors).not_to be_empty end end end end end end
mit
QuincyWork/AllCodes
Cpp/Codes/Practice/LeetCode/205 Isomorphic Strings.cpp
730
#include <gtest\gtest.h> #include <map> using namespace std; bool isIsomorphic(string s, string t) { const int lengthS = s.length(); const int lengthT = t.length(); if (lengthS != lengthT) { return false; } map<int, int> deltaS; map<int, int> deltaT; for (int i = 0; i < lengthS; ++i) { int m = s[i]; int n = t[i]; if (deltaS.find(m) != deltaS.end()) { if (m + deltaS[m] != n) return false; } else { deltaS[m] = n - m; } if (deltaT.find(n) != deltaT.end()) { if (m != n + deltaT[n]) return false; } else { deltaT[n] = m - n; } } return true; } TEST(Pratices, tIsIsomorphic) { ASSERT_TRUE(isIsomorphic("egg", "add")); ASSERT_FALSE(isIsomorphic("ab", "aa")); }
mit
xinton/exercicio-vox
src/VoxSocioBundle/VoxSocioBundle.php
123
<?php namespace VoxSocioBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class VoxSocioBundle extends Bundle { }
mit
ksonbol/portfolio
public/js/bootstrap.js
67347
/*! * Bootstrap v3.3.1 (http://getbootstrap.com) * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ /*! * Generated using the Bootstrap Customizer (http://getbootstrap.com/customize/?id=4d95e0409bc83a676390) * Config saved to config.json and https://gist.github.com/4d95e0409bc83a676390 */ if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') } +function ($) { var version = $.fn.jquery.split(' ')[0].split('.') if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1)) { throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher') } }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.3.1 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.3.1' Alert.TRANSITION_DURATION = 150 Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.3.1 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.3.1' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) // push to event loop to allow forms to submit setTimeout($.proxy(function () { $el[val](data[state] == null ? this.options[state] : data[state]) if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) } if (changed) this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') Plugin.call($btn, 'toggle') e.preventDefault() }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.3.1 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.3.1' Carousel.TRANSITION_DURATION = 600 Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } Carousel.prototype.keydown = function (e) { if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.getItemForDirection = function (direction, active) { var delta = direction == 'prev' ? -1 : 1 var activeIndex = this.getItemIndex(active) var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var fallback = type == 'next' ? 'first' : 'last' var that = this if (!$next.length) { if (!this.options.wrap) return $next = this.$element.find('.item')[fallback]() } if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= var clickHandler = function (e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.3.1 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle="dropdown"]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.VERSION = '3.3.1' Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this .trigger('focus') .attr('aria-expanded', 'true') $parent .toggleClass('open') .trigger('shown.bs.dropdown', relatedTarget) } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if ((!isActive && e.which != 27) || (isActive && e.which == 27)) { if (e.which == 27) $parent.find(toggle).trigger('focus') return $this.trigger('click') } var desc = ' li:not(.divider):visible a' var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc) if (!$items.length) return var index = $items.index(e.target) if (e.which == 38 && index > 0) index-- // up if (e.which == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).trigger('focus') } function clearMenus(e) { if (e && e.which === 3) return $(backdrop).remove() $(toggle).each(function () { var $this = $(this) var $parent = getParent($this) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this.attr('aria-expanded', 'false') $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget) }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown $.fn.dropdown = Plugin $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '[role="menu"]', Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '[role="listbox"]', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.3.1 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$backdrop = this.isShown = null this.scrollbarWidth = 0 if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.3.1' Modal.TRANSITION_DURATION = 300 Modal.BACKDROP_TRANSITION_DURATION = 150 Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.setScrollbar() this.$body.addClass('modal-open') this.escape() this.resize() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) // don't move modals dom position } that.$element .show() .scrollTop(0) if (that.options.backdrop) that.adjustBackdrop() that.adjustDialog() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() this.resize() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } } Modal.prototype.resize = function () { if (this.isShown) { $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) } else { $(window).off('resize.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.$body.removeClass('modal-open') that.resetAdjustments() that.resetScrollbar() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .prependTo(this.$element) .on('click.dismiss.bs.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function () { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove() } else if (callback) { callback() } } // these following methods are used to handle overflowing modals Modal.prototype.handleUpdate = function () { if (this.options.backdrop) this.adjustBackdrop() this.adjustDialog() } Modal.prototype.adjustBackdrop = function () { this.$backdrop .css('height', 0) .css('height', this.$element[0].scrollHeight) } Modal.prototype.adjustDialog = function () { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) } Modal.prototype.resetAdjustments = function () { this.$element.css({ paddingLeft: '', paddingRight: '' }) } Modal.prototype.checkScrollbar = function () { this.bodyIsOverflowing = document.body.scrollHeight > document.documentElement.clientHeight this.scrollbarWidth = this.measureScrollbar() } Modal.prototype.setScrollbar = function () { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function () { this.$body.css('padding-right', '') } Modal.prototype.measureScrollbar = function () { // thx walsh var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function (showEvent) { if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function () { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.3.1 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.3.1' Tooltip.TRANSITION_DURATION = 150 Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (self && self.$tip && self.$tip.is(':visible')) { self.hoverState = 'in' return } if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) this.$element.attr('aria-describedby', tipId) if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var $container = this.options.container ? $(this.options.container) : this.$element.parent() var containerDim = this.getPosition($container) placement = placement == 'bottom' && pos.bottom + actualHeight > containerDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < containerDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > containerDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < containerDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function () { var prevHoverState = that.hoverState that.$element.trigger('shown.bs.' + that.type) that.hoverState = null if (prevHoverState == 'out') that.leave(that) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) if (delta.left) offset.left += delta.left else offset.top += delta.top var isVertical = /top|bottom/.test(placement) var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) } Tooltip.prototype.replaceArrow = function (delta, dimension, isHorizontal) { this.arrow() .css(isHorizontal ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isHorizontal ? 'top' : 'left', '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function (callback) { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) callback && callback() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function ($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' var elRect = el.getBoundingClientRect() if (elRect.width == null) { // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top }) } var elOffset = isBody ? { top: 0, left: 0 } : $element.offset() var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() } var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null return $.extend({}, elRect, scroll, outerDims, elOffset) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) { var delta = { top: 0, left: 0 } if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var viewportDimensions = this.getPosition(this.$viewport) if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding var rightEdgeOffset = pos.left + viewportPadding + actualWidth if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.width) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function (prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function () { return (this.$tip = this.$tip || $(this.options.template)) } Tooltip.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { var that = this clearTimeout(this.timeout) this.hide(function () { that.$element.off('.' + that.type).removeData('bs.' + that.type) }) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option var selector = options && options.selector if (!data && option == 'destroy') return if (selector) { if (!data) $this.data('bs.tooltip', (data = {})) if (!data[selector]) data[selector] = new Tooltip(this, options) } else { if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) } if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.3.1 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.VERSION = '3.3.1' Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option var selector = options && options.selector if (!data && option == 'destroy') return if (selector) { if (!data) $this.data('bs.popover', (data = {})) if (!data[selector]) data[selector] = new Popover(this, options) } else { if (!data) $this.data('bs.popover', (data = new Popover(this, options))) } if (typeof option == 'string') data[option]() }) } var old = $.fn.popover $.fn.popover = Plugin $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.3.1 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.VERSION = '3.3.1' Tab.TRANSITION_DURATION = 150 Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } if ($this.parent('li').hasClass('active')) return var $previous = $ul.find('.active:last a') var hideEvent = $.Event('hide.bs.tab', { relatedTarget: $this[0] }) var showEvent = $.Event('show.bs.tab', { relatedTarget: $previous[0] }) $previous.trigger(hideEvent) $this.trigger(showEvent) if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return var $target = $(selector) this.activate($this.closest('li'), $ul) this.activate($target, $target.parent(), function () { $previous.trigger({ type: 'hidden.bs.tab', relatedTarget: $this[0] }) $this.trigger({ type: 'shown.bs.tab', relatedTarget: $previous[0] }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && (($active.length && $active.hasClass('fade')) || !!container.find('> .fade').length) function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', false) element .addClass('active') .find('[data-toggle="tab"]') .attr('aria-expanded', true) if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element .closest('li.dropdown') .addClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', true) } callback && callback() } $active.length && transition ? $active .one('bsTransitionEnd', next) .emulateTransitionEnd(Tab.TRANSITION_DURATION) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tab $.fn.tab = Plugin $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ var clickHandler = function (e) { e.preventDefault() Plugin.call($(this), 'show') } $(document) .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.3.1 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$target = $(this.options.target) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = this.pinnedOffset = null this.checkPosition() } Affix.VERSION = '3.3.1' Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0, target: window } Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) { var scrollTop = this.$target.scrollTop() var position = this.$element.offset() var targetHeight = this.$target.height() if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false if (this.affixed == 'bottom') { if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom' return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom' } var initializing = this.affixed == null var colliderTop = initializing ? scrollTop : position.top var colliderHeight = initializing ? targetHeight : height if (offsetTop != null && colliderTop <= offsetTop) return 'top' if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom' return false } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$target.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var height = this.$element.height() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom var scrollHeight = $('body').height() if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom) if (this.affixed != affix) { if (this.unpin != null) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger(affixType.replace('affix', 'affixed') + '.bs.affix') } if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - height - offsetBottom }) } } // AFFIX PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.affix $.fn.affix = Plugin $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom if (data.offsetTop != null) data.offset.top = data.offsetTop Plugin.call($spy, data) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.3.1 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.$trigger = $(this.options.trigger).filter('[href="#' + element.id + '"], [data-target="#' + element.id + '"]') this.transitioning = null if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.3.1' Collapse.TRANSITION_DURATION = 350 Collapse.DEFAULTS = { toggle: true, trigger: '[data-toggle="collapse"]' } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var activesData var actives = this.$parent && this.$parent.find('> .panel').children('.in, .collapsing') if (actives && actives.length) { activesData = actives.data('bs.collapse') if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (actives && actives.length) { Plugin.call(actives, 'hide') activesData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true) this.$trigger .removeClass('collapsed') .attr('aria-expanded', true) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false) this.$trigger .addClass('collapsed') .attr('aria-expanded', false) this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } Collapse.prototype.getParent = function () { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function (i, element) { var $element = $(element) this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() } Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) { var isOpen = $element.hasClass('in') $element.attr('aria-expanded', isOpen) $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) } function getTargetFromTrigger($trigger) { var href var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && option == 'show') options.toggle = false if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var $this = $(this) if (!$this.attr('data-target')) e.preventDefault() var $target = getTargetFromTrigger($this) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $.extend({}, $this.data(), { trigger: this }) Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.3.1 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var process = $.proxy(this.process, this) this.$body = $('body') this.$scrollElement = $(element).is('body') ? $(window) : $(element) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || '') + ' .nav li > a' this.offsets = [] this.targets = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', process) this.refresh() this.process() } ScrollSpy.VERSION = '3.3.1' ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) } ScrollSpy.prototype.refresh = function () { var offsetMethod = 'offset' var offsetBase = 0 if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position' offsetBase = this.$scrollElement.scrollTop() } this.offsets = [] this.targets = [] this.scrollHeight = this.getScrollHeight() var self = this this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[$href[offsetMethod]().top + offsetBase, href]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.getScrollHeight() var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop < offsets[0]) { this.activeTarget = null return this.clear() } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target this.clear() var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } ScrollSpy.prototype.clear = function () { $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') } // SCROLLSPY PLUGIN DEFINITION // =========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy $.fn.scrollspy = Plugin $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load.bs.scrollspy.data-api', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) Plugin.call($spy, $spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.3.1 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition : 'webkitTransitionEnd', MozTransition : 'transitionend', OTransition : 'oTransitionEnd otransitionend', transition : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function (e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery);
mit
UKHomeOffice/removals_integration
api/controllers/CentresController.js
1099
'use strict'; const findOneAction = require('sails/lib/hooks/blueprints/actions/findOne'); const findAction = require('sails/lib/hooks/blueprints/actions/find'); const BedCountService = require('../services/BedCountService'); /** * CentreController * * @description :: Server-side logic for managing centres * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ module.exports = { _config: { populate: true }, find: function (req, res) { const oldOk = res.ok; res.ok = (matchingRecords) => { Promise.all( matchingRecords.map((matchingRecord) => { return BedCountService.performConfiguredReconciliation(matchingRecord); }) ).then(() => { oldOk(matchingRecords); }); }; return findAction(req, res); }, findOne: function (req, res) { const oldOk = res.ok; res.ok = (matchingRecord) => { BedCountService.performConfiguredReconciliation(matchingRecord) .then(() => { oldOk(matchingRecord); }); }; return findOneAction(req, res); } };
mit
OpenESDH/OpenESDH-UI
app/src/shared/filters/oeParametersFilter.js
295
angular .module('openeApp') .filter('oeParam', oeParametersFilterFactory); function oeParametersFilterFactory(oeParametersService) { function oeParamFilter(oeParameterName) { return oeParametersService.getParameter(oeParameterName); } return oeParamFilter; }
mit
gameofbombs/pixi-super-atlas
src/core/AtlasNode.ts
1726
namespace pixi_atlas { import Rectangle = PIXI.Rectangle; const INF = 1 << 20; //TODO: add some padding export class AtlasNode<T> { public childs: Array<AtlasNode<T>> = []; public rect = new Rectangle(0, 0, INF, INF); public data: T = null; public insert(atlasWidth: number, atlasHeight: number, width: number, height: number, data: T): AtlasNode<T> { if (this.childs.length > 0) { const newNode: AtlasNode<T> = this.childs[0].insert( atlasWidth, atlasHeight, width, height, data); if (newNode != null) { return newNode; } return this.childs[1].insert(atlasWidth, atlasHeight, width, height, data); } else { let rect: Rectangle = this.rect; if (this.data != null) return null; const w = Math.min(rect.width, atlasWidth - rect.x); if (width > rect.width || width > atlasWidth - rect.x || height > rect.height || height > atlasHeight - rect.y) return null; if (width == rect.width && height == rect.height) { this.data = data; return this; } this.childs.push(new AtlasNode<T>()); this.childs.push(new AtlasNode<T>()); const dw: Number = rect.width - width; const dh: Number = rect.height - height; if (dw > dh) { this.childs[0].rect = new Rectangle(rect.x, rect.y, width, rect.height); this.childs[1].rect = new Rectangle(rect.x + width, rect.y, rect.width - width, rect.height); } else { this.childs[0].rect = new Rectangle(rect.x, rect.y, rect.width, height); this.childs[1].rect = new Rectangle(rect.x, rect.y + height, rect.width, rect.height - height); } return this.childs[0].insert(atlasWidth, atlasHeight, width, height, data); } } } }
mit
akiellor/gemjars-deux
lib/gemjars/deux/http.rb
816
require 'gemjars/deux/streams' module Gemjars module Deux class Http def self.default new end def initialize connection_manager = Java::OrgApacheHttpImplConn::PoolingClientConnectionManager.new @client = Java::org.apache.http.impl.client.DefaultHttpClient.new(connection_manager) end def get uri request = Java::org.apache.http.client.methods.HttpGet.new uri raise "No block given" unless block_given? response = @client.execute(request) io = response.entity.content out = Java::JavaIo::ByteArrayOutputStream.new Streams.copy_channel Streams.to_channel(io), Streams.to_channel(out) yield Streams.to_channel(Java::JavaIo::ByteArrayInputStream.new(out.to_byte_array)) end end end end
mit
rusinikita/recipies-app
app/src/androidTest/java/com/nikita/recipiesapp/RecyclerViewMatcher.java
2590
package com.nikita.recipiesapp; import android.content.res.Resources; import android.support.test.espresso.Espresso; import android.support.test.espresso.contrib.RecyclerViewActions; import android.support.test.espresso.matcher.ViewMatchers; import android.support.v7.widget.RecyclerView; import android.view.View; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class RecyclerViewMatcher { private final int recyclerViewId; private RecyclerViewMatcher(int recyclerViewId) { this.recyclerViewId = recyclerViewId; } public static RecyclerViewMatcher withRecyclerView(int recyclerViewId) { return new RecyclerViewMatcher(recyclerViewId); } public Matcher<View> atPosition(final int position) { return atPositionOnView(position, -1); } public Matcher<View> atPositionWithScroll(final int position) { Espresso.onView(ViewMatchers.withId(recyclerViewId)).perform(RecyclerViewActions.scrollToPosition(position)); return atPosition(position); } public Matcher<View> atPositionOnView(final int position, final int targetViewId) { return new TypeSafeMatcher<View>() { Resources resources = null; View childView; public void describeTo(Description description) { String idDescription = Integer.toString(recyclerViewId); if (this.resources != null) { try { idDescription = this.resources.getResourceName(recyclerViewId); } catch (Resources.NotFoundException var4) { idDescription = String.format("%s (resource name not found)", recyclerViewId); } } description.appendText("RecyclerView with id: " + idDescription + " at position: " + position); } public boolean matchesSafely(View view) { this.resources = view.getResources(); if (childView == null) { RecyclerView recyclerView = (RecyclerView) view.getRootView().findViewById(recyclerViewId); if (recyclerView != null && recyclerView.getId() == recyclerViewId) { RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(position); if (viewHolder != null) { childView = viewHolder.itemView; } } else { return false; } } if (targetViewId == -1) { return view == childView; } else { View targetView = childView.findViewById(targetViewId); return view == targetView; } } }; } }
mit
metalvarez/tonada-prototype
src/Tonada/ApplicationBundle/Resources/skeleton/crud/tests/test.php
397
<?php namespace {{ namespace }}\Tests\Controller{{ entity_namespace ? '\\' ~ entity_namespace : '' }}; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class {{ entity_class }}ControllerTest extends WebTestCase { /* {%- if 'new' in actions %} {%- include 'tests/others/full_scenario.php' -%} {%- else %} {%- include 'tests/others/short_scenario.php' -%} {%- endif %} */ }
mit
mitjajez/SONCE
imports/ui/test-helpers.js
756
// TODO -- this should probably be some kind of test package that people use import { _ } from 'meteor/underscore'; import { Template } from 'meteor/peerlibrary:blaze-components'; import { Blaze } from 'meteor/blaze'; import { Tracker } from 'meteor/tracker'; const withDiv = function withDiv(callback) { const el = document.createElement('div'); document.body.appendChild(el); try { callback(el); } finally { document.body.removeChild(el); } }; export const withRenderedTemplate = function withRenderedTemplate(template, data, callback) { withDiv((el) => { const ourTemplate = _.isString(template) ? Template[template] : template; Blaze.renderWithData(ourTemplate, data, el); Tracker.flush(); callback(el); }); };
mit
bgotink/libdoorman
doorman/parser.hpp
312
#ifndef __parser_h #define __parser_h namespace doorman { void initParser(); struct state_t; class parser_t { state_t *state; public: unsigned int bits[12]; unsigned int length; parser_t(); void reset(); bool consume(unsigned int); bool is_ready() const; }; } #endif
mit
makandra/katapult
lib/generators/katapult/model/model_generator.rb
2203
# Generate a Rails model, including migration and spec. require 'katapult/generator' require 'generators/katapult/model_specs/model_specs_generator' module Katapult module Generators class ModelGenerator < Katapult::Generator desc 'Generate a Rails Model' check_class_collision source_root File.expand_path('../templates', __FILE__) def create_migration_file migration_name = "create_#{table_name}" migration_attributes = model.db_fields.map(&:for_migration) args = [migration_name] + migration_attributes options = { timestamps: true, force: true } invoke 'active_record:migration', args, options end def create_model_file template 'model.rb', File.join('app', 'models', "#{file_name}.rb") end def write_traits template 'app/models/shared/does_flag.rb' if flag_attrs.any? end def write_factory factory = " factory #{ model.name(:symbol) }" factories_file = 'spec/factories/factories.rb' # Can happen in multiple transformation runs with authentication return if file_contains?(factories_file, factory) factory_attrs = model.required_attrs.map do |a| " #{ a.name(:human) } #{ a.test_value.inspect }" end if factory_attrs.any? factory << " do\n#{ factory_attrs.join "\n" }\n end" end insert_into_file factories_file, factory + "\n\n", before: /end\n\z/ end def generate_unit_tests Generators::ModelSpecsGenerator.new(model, options).invoke_all end no_commands do def belongs_tos model.application_model.get_belongs_tos_for model.name end def has_manys model.application_model.get_has_manys_for model.name end def flag_attrs model.attrs.select(&:flag?) end def defaults {}.tap do |defaults| model.attrs.select(&:has_defaults?).each do |attr| defaults[attr.name.to_sym] = attr.default end end end end private def model @element end end end end
mit
huntie/laravel-simple-jsonapi
src/Routing/Router.php
944
<?php namespace Huntie\JsonApi\Routing; class Router extends \Illuminate\Routing\Router { /** * Register an array of JSON API resource controllers. * * @param array $resources */ public function jsonApiResources(array $resources) { foreach ($resources as $name => $controller) { $this->resource($name, $controller); } } /** * Route a JSON API resource to a controller. * * @param string $name * @param string $controller * @param array $options */ public function jsonApiResource($name, $controller, array $options = []) { if ($this->container && $this->container->bound(ResourceRegistrar::class)) { $registrar = $this->container->make(ResourceRegistrar::class); } else { $registrar = new ResourceRegistrar($this); } $registrar->register($name, $controller, $options); } }
mit
jking6884/ember-cli-table-pagination
addon/components/bs-table-pagination/table-content.js
5063
import Ember from 'ember'; import layout from '../../templates/components/bs-table-pagination/table-content'; import ResizeAware from 'ember-resize/mixins/resize-aware'; const { Component, computed, observer, on, run} = Ember; const { reads } = computed; export default Component.extend(ResizeAware, { layout, resizeHeightSensitive: true, resizeWidthSensitive: true, classNames: ['ember-cli-table-content'], // tagName: '', showFilter: false, scrollMode: reads('contentParams.scrollMode'), mainScroll: reads('contentParams.mainScroll'), bodyHeight: reads('contentParams.bodyHeight'), actionWidth: undefined, onInit: on('didInsertElement', function () { if (this.get('scrollMode')) { this.adjustTableDimensions(); } }), showFilterObserver: observer('showFilter', function () { if (this.get('scrollMode')) { this.adjustTableDimensions(); } }), currentContentSizeObserver: observer('currentContentSize', function () { // let size = this.get('currentContentSize'); if (this.get('scrollMode')) { this.adjustTableDimensions(); } }), didResize(width, height) { if (this.get('scrollMode')) { this.adjustTableDimensions(); } }, adjustTableDimensions() { //if we need to resize the table's height if (this.get('mainScroll')) { this.adjustBodyHeight(); } let columns = this.get('columns'); run.later(() => { this.set('actionWidth', 0); columns.forEach((col) => { col.set('width', 0); }); let self = this; run.later(() => { //in anycase, we need to check the width of each cell in the table's body let showFilter = self.get('showFilter'); let firstRow = self.$('tbody > tr:nth-of-type(2) > td'); let headerRow = self.$('thead > tr:first-of-type > th'); let footerRow = self.$('tfoot > tr:first-of-type > th'); let columnWidths = []; let contentWidths = []; let headerWidths = []; let footerWidths = []; let actionWidth; firstRow.each((idx, cell) => { contentWidths[idx] = self.$(cell).innerWidth(); if (idx === columns.length) { actionWidth = self.$(cell).innerWidth(); } }); headerRow.each((idx, cell) => { headerWidths[idx] = self.$(cell).innerWidth(); }); footerRow.each((idx, cell) => { footerWidths[idx] = self.$(cell).innerWidth(); }); let maxWidth; let sum = 0; let delta = 0; for (let i = 0; i < columns.length; i ++) { maxWidth = Math.max(headerWidths[i], contentWidths[i] - 0, footerWidths[i]); // console.log(`headerWidth[${i}] vs contentWidth[${i}] -> `, headerWidths[i], contentWidths[i]); // console.log(`footerWidths[${i}] -> `, footerWidths[i]); // console.log(`contentWidth[${i}] - delta -> `, contentWidths[i] - delta); // console.log(`maxWidth[${i}] -> `, maxWidth); if (showFilter) { // the delta business is only for when we show the filters if (maxWidth === contentWidths[i] - delta) { // if we applied the delta we need to reset it. delta = 0; } else if (maxWidth === headerWidths[i]) { // if we didn't we need to add him delta += headerWidths[i] - contentWidths[i]; // console.log('delta -> ', delta); } } columnWidths[i] = maxWidth; sum += maxWidth; } maxWidth = Math.max(headerWidths[columns.length], contentWidths[columns.length], footerWidths[columns.length]); self.set('actionWidth', maxWidth); sum += maxWidth; // now check if there is some extra space let tableWidth = self.$().innerWidth(); let extra = tableWidth - sum; extra = (extra > 0) ? extra: 0; extra = extra / columns.length; // console.log('we have ', extra, ' extra px / col'); for (let i = 0; i < columns.length; i ++) { columns[i].set('width', columnWidths[i] + extra); // columns[i].set('width', tableWidth / columns.length); } run.later(() => { // console.log('second pass'); actionWidth = self.$('thead').outerWidth() + self.$('thead').offset().left - self.$('tbody > tr:nth-of-type(2) > td:last-of-type').offset().left; self.set('actionWidth', actionWidth); }); }); }); }, adjustBodyHeight() { // let documentHeight = document.body.clientHeight; let above = this.$('tbody').offset().top; let height = this.$('tbody').outerHeight(); let mainContent = this.$().parents('section.content'); let under = (mainContent.offset().top + mainContent.outerHeight()) - (above + height); // let under = documentHeight - (above + height); let bodyHeight = `${window.innerHeight - above - under}px`; this.set('bodyHeight', bodyHeight); } });
mit
andyw8/mutant
meta/match_current_line.rb
283
# encoding: utf-8 Mutant::Meta::Example.add do source 'true if /foo/' singleton_mutations mutation 'false if /foo/' mutation 'true if //' mutation 'nil if /foo/' mutation 'true if true' mutation 'true if false' mutation 'true if nil' mutation 'true if /a\A/' end
mit
onajphi/CmsSitioAdministrador
src/Cms/CmsBundle/Controller/EstadoCivilesController.php
6337
<?php namespace Cms\CmsBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Cms\CmsBundle\Entity\EstadoCiviles; use Cms\CmsBundle\Form\EstadoCivilesType; /** * EstadoCiviles controller. * */ class EstadoCivilesController extends Controller { /** * Lists all EstadoCiviles entities. * */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('CmsBundle:EstadoCiviles')->findAll(); return $this->render('CmsBundle:EstadoCiviles:index.html.twig', array( 'entities' => $entities, )); } /** * Creates a new EstadoCiviles entity. * */ public function createAction(Request $request) { $entity = new EstadoCiviles(); $form = $this->createCreateForm($entity); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('estadociviles_show', array('id' => $entity->getId()))); } return $this->render('CmsBundle:EstadoCiviles:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); } /** * Creates a form to create a EstadoCiviles entity. * * @param EstadoCiviles $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createCreateForm(EstadoCiviles $entity) { $form = $this->createForm(new EstadoCivilesType(), $entity, array( 'action' => $this->generateUrl('estadociviles_create'), 'method' => 'POST', )); $form->add('submit', 'submit', array('label' => 'Create')); return $form; } /** * Displays a form to create a new EstadoCiviles entity. * */ public function newAction() { $entity = new EstadoCiviles(); $form = $this->createCreateForm($entity); return $this->render('CmsBundle:EstadoCiviles:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); } /** * Finds and displays a EstadoCiviles entity. * */ public function showAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('CmsBundle:EstadoCiviles')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find EstadoCiviles entity.'); } $deleteForm = $this->createDeleteForm($id); return $this->render('CmsBundle:EstadoCiviles:show.html.twig', array( 'entity' => $entity, 'delete_form' => $deleteForm->createView(), )); } /** * Displays a form to edit an existing EstadoCiviles entity. * */ public function editAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('CmsBundle:EstadoCiviles')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find EstadoCiviles entity.'); } $editForm = $this->createEditForm($entity); $deleteForm = $this->createDeleteForm($id); return $this->render('CmsBundle:EstadoCiviles:edit.html.twig', array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * Creates a form to edit a EstadoCiviles entity. * * @param EstadoCiviles $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createEditForm(EstadoCiviles $entity) { $form = $this->createForm(new EstadoCivilesType(), $entity, array( 'action' => $this->generateUrl('estadociviles_update', array('id' => $entity->getId())), 'method' => 'PUT', )); $form->add('submit', 'submit', array('label' => 'Update')); return $form; } /** * Edits an existing EstadoCiviles entity. * */ public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('CmsBundle:EstadoCiviles')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find EstadoCiviles entity.'); } $deleteForm = $this->createDeleteForm($id); $editForm = $this->createEditForm($entity); $editForm->handleRequest($request); if ($editForm->isValid()) { $em->flush(); return $this->redirect($this->generateUrl('estadociviles_edit', array('id' => $id))); } return $this->render('CmsBundle:EstadoCiviles:edit.html.twig', array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * Deletes a EstadoCiviles entity. * */ public function deleteAction(Request $request, $id) { $form = $this->createDeleteForm($id); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('CmsBundle:EstadoCiviles')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find EstadoCiviles entity.'); } $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('estadociviles')); } /** * Creates a form to delete a EstadoCiviles entity by id. * * @param mixed $id The entity id * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('estadociviles_delete', array('id' => $id))) ->setMethod('DELETE') ->add('submit', 'submit', array('label' => 'Delete')) ->getForm() ; } }
mit
websoftwares/adr
src/Action/Page/ReadAction.php
740
<?php namespace Websoftwares\Adr\Action\Page; use Websoftwares\Adr\Action\ActionInterface, Symfony\Component\HttpFoundation\Request, Websoftwares\Adr\IoCInterface as Domain, Websoftwares\Adr\Responder\Page\ReadResponder as Responder; class ReadAction implements ActionInterface { public function __construct( Request $request, Domain $domain, Responder $responder ) { $this->request = $request; $this->domain = $domain; $this->responder = $responder; } public function send(array $params) { $this->responder->setVariables("data", $this->domain->resolve("pages")[$params["id"]]); return $this->responder->send($params["format"]); } }
mit
vanatka/auth0client
Auth0Client/src/main/java/com/helloworldlab/auth0client/core/utils/DeviceId.java
985
package com.helloworldlab.auth0client.core.utils; import android.os.Build; /** * @author Ivan Aläxkin (ivan.alyakskin@gmail.com) */ public class DeviceId { /** * @return pseudo unique id */ public static String getDeviceId( ) { StringBuilder sb = new StringBuilder(); return sb.append( "35" ) .append(Build.BOARD.length() % 10) .append(Build.BRAND.length() % 10) .append(Build.CPU_ABI.length() % 10) .append(Build.DEVICE.length() % 10) .append(Build.DISPLAY.length() % 10) .append(Build.HOST.length() % 10) .append(Build.ID.length() % 10) .append(Build.MANUFACTURER.length() % 10) .append(Build.MODEL.length() % 10) .append(Build.PRODUCT.length() % 10) .append(Build.TAGS.length() % 10) .append(Build.TYPE.length() % 10) .append(Build.USER.length() % 10) .toString( ); } }
mit