code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace NutritionRecommendationEngine { public static class MyRandom { private static Random random = new Random(); public static int Next(int max) { return random.Next(max); } public static double Next(double min, double max) { return min + (random.NextDouble() * (max - min)); } } public static class Ext { public static T GetRandomMember<T>(this IEnumerable<T> list) { return list.ElementAt(MyRandom.Next(list.Count())); } } }
tsvgeorgieva/AmAm
AmAm/NutritionRecommendationEngine/MyRandom.cs
C#
mit
670
beforeEach(function () { jasmine.Clock.useMock(); jasmine.Clock.reset(); $.fx.off = true; if ($('.fake_dom').length) { $('.fake_dom').empty(); } this.addMatchers(new CustomMatchers()); }); afterEach(function () { $.fx.off = false; }); function printNode(node, depth, renderer) { renderer = renderer || _.identity; if (node === null) { return ''; } if (depth === 0) { return node.data ? renderer(node.data) + '@' + node.level.toString() : ''; } return '(' + ([printNode(node.left, depth - 1, renderer), printNode(node, 0, renderer), printNode(node.right, depth - 1, renderer)].join('-')) + ')'; } function printStack(stack) { return _.map(stack, function(node){ return node.data; }); } jasmine.fixture = function () { if (!$('.fake_dom').length) { $("body", document).prepend($('<div></div>').attr("style", "position: fixed; left: 100%").addClass('fake_dom')); } return $('.fake_dom'); }; function _helper_isObject(arg) { return arg != null && typeof(arg) == 'object'; } function _helper_isArray(arg) { return _helper_isObject(arg) && Object.prototype.toString.apply(arg) == '[object Array]'; } function decodeParams(string_or_object) { if(typeof string_or_object !== 'string') { return string_or_object; } var keyValuePairs = string_or_object.replace(/\+/g, "%20").split("&"); var hash = {}; $(keyValuePairs).each(function () { var equalSplit = this.split("="); var key = decodeURIComponent(equalSplit[0]); if (hash[key] == null) { hash[key] = decodeURIComponent(equalSplit[1]); } else if (jQuery.isArray(hash[key])) { hash[key].push(decodeURIComponent(equalSplit[1])); } else { hash[key] = [hash[key]]; hash[key].push(decodeURIComponent(equalSplit[1])); } }); return hash; } CustomMatchers = function() {}; CustomMatchers.prototype = { toBeEmpty: function() { this.message = function() { return 'Expected ' + jasmine.pp(this.actual) + (this.isNot ? ' not' : '') + ' to be empty'; }; if (this.actual instanceof jQuery) { return this.actual.size() == 0 } else if (_helper_isArray(this.actual)) { return this.actual.length == 0; } else if (_helper_isObject(this.actual)) { // any property means not empty for(var property in this.actual) { return false; } return true; } return false; }, toHaveAjaxData: function(expected) { this.message = function() { return 'Expected ' + jasmine.pp(decodeParams(this.actual)) + (this.isNot ? ' not' : '') + ' to match ' + jasmine.pp(expected); } return this.env.equals_(decodeParams(this.actual), expected); } };
ohrite/view_zoo
spec/javascripts/helpers/spec_helper.js
JavaScript
mit
2,675
package reborncore.api.power; /** * Created by modmuss50 on 08/03/2016. */ public enum EnumPowerTier { MICRO(8, 8, 0), LOW(32, 32, 1), MEDIUM(128, 128, 2), HIGH(512, 512, 3), EXTREME(2048, 2048, 4), INSANE(8192, 8192, 5), INFINITE(Integer.MAX_VALUE, Integer.MAX_VALUE, 6); private final int maxInput; private final int maxOutput; private final int ic2Tier; EnumPowerTier(int maxInput, int maxOutput, int ic2Tier) { this.maxInput = maxInput; this.maxOutput = maxOutput; this.ic2Tier = ic2Tier; } public int getMaxInput() { return maxInput; } public int getMaxOutput() { return maxOutput; } public int getIC2Tier() { return ic2Tier; } }
Szewek/Minecraft-Flux
src/api/java/reborncore/api/power/EnumPowerTier.java
Java
mit
673
class CreateTables < ActiveRecord::Migration def self.up create_table :users do |t| t.string :username t.string :facebook_token ## Database authenticatable t.string :email, :null => false, :default => "" t.string :encrypted_password, :null => false, :default => "" ## Inactivatable t.datetime :inactivated_at ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at ## Rememberable t.datetime :remember_created_at ## Trackable t.integer :sign_in_count, :default => 0 t.datetime :current_sign_in_at t.datetime :last_sign_in_at t.string :current_sign_in_ip t.string :last_sign_in_ip ## Encryptable # t.string :password_salt ## Confirmable t.string :confirmation_token t.datetime :confirmed_at t.datetime :confirmation_sent_at # t.string :unconfirmed_email # Only if using reconfirmable ## Lockable t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts t.string :unlock_token # Only if unlock strategy is :email or :both t.datetime :locked_at ## Token authenticatable t.string :authentication_token t.timestamps end create_table :admins do |t| ## Database authenticatable t.string :email, :null => true t.string :encrypted_password, :null => true ## Inactivatable t.datetime :inactivated_at ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at ## Rememberable t.datetime :remember_created_at ## Confirmable t.string :confirmation_token t.datetime :confirmed_at t.datetime :confirmation_sent_at t.string :unconfirmed_email # Only if using reconfirmable ## Encryptable t.string :password_salt ## Lockable t.datetime :locked_at t.timestamps end end def self.down drop_table :users drop_table :admins end end
jonathanccalixto/devise_inactivatable
test/rails_app/db/migrate/20120508165529_create_tables.rb
Ruby
mit
2,095
package net.meisen.general.sbconfigurator.config; import java.util.Map; import java.util.Properties; /** * A bean used to inject properties within the {@code SpringPropertyHolder} * during the configuration loading. * * @author pmeisen * */ public class PropertyInjectorBean { private final Properties properties = new Properties(); /** * Gets the set properties. * * @return the set properties */ public Properties getProperties() { return this.properties; } /** * Sets some properties. * * @param properties * the final properties to be set */ public void setProperties(final Properties properties) { this.properties.putAll(properties); } /** * Sets some properties. * * @param properties * the final properties to be set */ public void setProperties(final Map<String, String> properties) { this.properties.putAll(properties); } /** * Sets a property. * * @param key * the key of the property * @param value * the value of the property * */ public void setProperty(final String key, final String value) { this.properties.setProperty(key, value); } }
pmeisen/gen-sbconfigurator
src/net/meisen/general/sbconfigurator/config/PropertyInjectorBean.java
Java
mit
1,181
var path = require('path'); module.exports = { entry: { entry:path.join(__dirname, 'src', 'entry.js'), toggle:path.join(__dirname, 'src', 'toggle.js'), }, output: { path: path.join(__dirname, 'dist'), publicPath: '/static/', filename: '[name].js' }, module: { loaders: [{ test: /\.js(x)?$/, loader: 'babel' }, { test: /.css$/, loader: 'style-loader!css-loader' },{ test : /\.(json|ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/, loader : 'file-loader', query:{ name:'[name]-[md5:hash:8].[ext]' } }] } }
wyvernnot/react-datatables-example
webpack.config.js
JavaScript
mit
599
import merge from 'webpack-merge'; import chalk from 'chalk'; import pkgInfo from './package.json'; import BabiliPlugin from 'babili-webpack-plugin'; import WebpackShellPlugin from '@slightlytyler/webpack-shell-plugin'; import webpackConfigBase from './webpack.config.base'; const webpackConfigProd = { plugins: [ new BabiliPlugin({}), new WebpackShellPlugin({ onBuildStart: [], // need to bump version first before files copied etc onBuildExit: ['bash scripts/clean-production.sh']}) ] }; export default merge(webpackConfigBase, webpackConfigProd);
mikeerickson/cd-messenger
webpack.config.prod.js
JavaScript
mit
584
<?xml version="1.0" ?><!DOCTYPE TS><TS language="hu" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="14"/> <source>About Bitcoin</source> <translation>A Bitcoinról</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="53"/> <source>&lt;b&gt;Bitcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Bitcoin&lt;/b&gt; verzió</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="97"/> <source>Copyright © 2009-2012 Bitcoin Developers This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file license.txt or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="14"/> <source>Address Book</source> <translation>Címjegyzék</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="20"/> <source>These are your Bitcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Ezekkel a Bitcoin-címekkel fogadhatod kifizetéseket. Érdemes lehet minden egyes kifizető számára külön címet létrehozni, hogy könnyebben nyomon követhesd, kitől kaptál már pénzt.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="36"/> <source>Double-click to edit address or label</source> <translation>Dupla-katt a cím vagy a címke szerkesztéséhez</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="63"/> <source>Create a new address</source> <translation>Új cím létrehozása</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="77"/> <source>Copy the currently selected address to the system clipboard</source> <translation>A kiválasztott cím másolása a vágólapra</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="66"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="80"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="91"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="102"/> <source>Sign a message to prove you own this address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="105"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="116"/> <source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source> <translation>A kiválasztott cím törlése a listáról. Csak a küldő címek törölhetőek.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="119"/> <source>&amp;Delete</source> <translation>&amp;Törlés</translation> </message> <message> <location filename="../addressbookpage.cpp" line="63"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="65"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="292"/> <source>Export Address Book Data</source> <translation>Címjegyzék adatainak exportálása</translation> </message> <message> <location filename="../addressbookpage.cpp" line="293"/> <source>Comma separated file (*.csv)</source> <translation>Vesszővel elválasztott fájl (*. csv)</translation> </message> <message> <location filename="../addressbookpage.cpp" line="306"/> <source>Error exporting</source> <translation>Hiba exportálás közben</translation> </message> <message> <location filename="../addressbookpage.cpp" line="306"/> <source>Could not write to file %1.</source> <translation>%1 nevű fájl nem írható.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="142"/> <source>Label</source> <translation>Címke</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="142"/> <source>Address</source> <translation>Cím</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="178"/> <source>(no label)</source> <translation>(nincs címke)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="47"/> <source>Enter passphrase</source> <translation>Add meg a jelszót</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="61"/> <source>New passphrase</source> <translation>Új jelszó</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="75"/> <source>Repeat new passphrase</source> <translation>Új jelszó újra</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Írd be az új jelszót a tárcához.&lt;br/&gt;Használj legalább 10&lt;br/&gt;véletlenszerű karaktert&lt;/b&gt; vagy &lt;b&gt;legalább nyolc szót&lt;/b&gt;.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="34"/> <source>Encrypt wallet</source> <translation>Tárca kódolása</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="37"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>A tárcád megnyitásához a műveletnek szüksége van a tárcád jelszavára.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="42"/> <source>Unlock wallet</source> <translation>Tárca megnyitása</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="45"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>A tárcád dekódolásához a műveletnek szüksége van a tárcád jelszavára.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="50"/> <source>Decrypt wallet</source> <translation>Tárca dekódolása</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="53"/> <source>Change passphrase</source> <translation>Jelszó megváltoztatása</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="54"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Írd be a tárca régi és új jelszavát.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="100"/> <source>Confirm wallet encryption</source> <translation>Biztosan kódolni akarod a tárcát?</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="101"/> <source>WARNING: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR GOODBYECOINS&lt;/b&gt;! Are you sure you wish to encrypt your wallet?</source> <translation>FIGYELEM: Ha kódolod a tárcát, és elveszíted a jelszavad, akkor &lt;b&gt;AZ ÖSSZES BITCOINODAT IS EL FOGOD VESZÍTENI!&lt;/b&gt; Biztosan kódolni akarod a tárcát?</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="110"/> <location filename="../askpassphrasedialog.cpp" line="159"/> <source>Wallet encrypted</source> <translation>Tárca kódolva</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="111"/> <source>Bitcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="207"/> <location filename="../askpassphrasedialog.cpp" line="231"/> <source>Warning: The Caps Lock key is on.</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="116"/> <location filename="../askpassphrasedialog.cpp" line="123"/> <location filename="../askpassphrasedialog.cpp" line="165"/> <location filename="../askpassphrasedialog.cpp" line="171"/> <source>Wallet encryption failed</source> <translation>Tárca kódolása sikertelen.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="117"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Tárca kódolása belső hiba miatt sikertelen. A tárcád nem lett kódolva.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="124"/> <location filename="../askpassphrasedialog.cpp" line="172"/> <source>The supplied passphrases do not match.</source> <translation>A megadott jelszavak nem egyeznek.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="135"/> <source>Wallet unlock failed</source> <translation>Tárca megnyitása sikertelen</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="136"/> <location filename="../askpassphrasedialog.cpp" line="147"/> <location filename="../askpassphrasedialog.cpp" line="166"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Hibás jelszó.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="146"/> <source>Wallet decryption failed</source> <translation>Dekódolás sikertelen.</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="160"/> <source>Wallet passphrase was succesfully changed.</source> <translation>Jelszó megváltoztatva.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="73"/> <source>Bitcoin Wallet</source> <translation>Bitcoin-tárca</translation> </message> <message> <location filename="../bitcoingui.cpp" line="215"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="248"/> <source>Show/Hide &amp;Bitcoin</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="515"/> <source>Synchronizing with network...</source> <translation>Szinkronizálás a hálózattal...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="185"/> <source>&amp;Overview</source> <translation>&amp;Áttekintés</translation> </message> <message> <location filename="../bitcoingui.cpp" line="186"/> <source>Show general overview of wallet</source> <translation>Tárca általános áttekintése</translation> </message> <message> <location filename="../bitcoingui.cpp" line="191"/> <source>&amp;Transactions</source> <translation>&amp;Tranzakciók</translation> </message> <message> <location filename="../bitcoingui.cpp" line="192"/> <source>Browse transaction history</source> <translation>Tranzakciótörténet megtekintése</translation> </message> <message> <location filename="../bitcoingui.cpp" line="197"/> <source>&amp;Address Book</source> <translation>Cím&amp;jegyzék</translation> </message> <message> <location filename="../bitcoingui.cpp" line="198"/> <source>Edit the list of stored addresses and labels</source> <translation>Tárolt címek és címkék listájának szerkesztése</translation> </message> <message> <location filename="../bitcoingui.cpp" line="203"/> <source>&amp;Receive coins</source> <translation>Érmék &amp;fogadása</translation> </message> <message> <location filename="../bitcoingui.cpp" line="204"/> <source>Show the list of addresses for receiving payments</source> <translation>Kiizetést fogadó címek listája</translation> </message> <message> <location filename="../bitcoingui.cpp" line="209"/> <source>&amp;Send coins</source> <translation>Érmék &amp;küldése</translation> </message> <message> <location filename="../bitcoingui.cpp" line="216"/> <source>Prove you control an address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="235"/> <source>E&amp;xit</source> <translation>&amp;Kilépés</translation> </message> <message> <location filename="../bitcoingui.cpp" line="236"/> <source>Quit application</source> <translation>Kilépés</translation> </message> <message> <location filename="../bitcoingui.cpp" line="239"/> <source>&amp;About %1</source> <translation>&amp;A %1-ról</translation> </message> <message> <location filename="../bitcoingui.cpp" line="240"/> <source>Show information about Bitcoin</source> <translation>Információk a Bitcoinról</translation> </message> <message> <location filename="../bitcoingui.cpp" line="242"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="243"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="245"/> <source>&amp;Options...</source> <translation>&amp;Opciók...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="252"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="255"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="257"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="517"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="528"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="250"/> <source>&amp;Export...</source> <translation>&amp;Exportálás...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="210"/> <source>Send coins to a Bitcoin address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="246"/> <source>Modify configuration options for Bitcoin</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="249"/> <source>Show or hide the Bitcoin window</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="251"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="253"/> <source>Encrypt or decrypt wallet</source> <translation>Tárca kódolása vagy dekódolása</translation> </message> <message> <location filename="../bitcoingui.cpp" line="256"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="258"/> <source>Change the passphrase used for wallet encryption</source> <translation>Tárcakódoló jelszó megváltoztatása</translation> </message> <message> <location filename="../bitcoingui.cpp" line="259"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="260"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="261"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="262"/> <source>Verify a message signature</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="286"/> <source>&amp;File</source> <translation>&amp;Fájl</translation> </message> <message> <location filename="../bitcoingui.cpp" line="296"/> <source>&amp;Settings</source> <translation>&amp;Beállítások</translation> </message> <message> <location filename="../bitcoingui.cpp" line="302"/> <source>&amp;Help</source> <translation>&amp;Súgó</translation> </message> <message> <location filename="../bitcoingui.cpp" line="311"/> <source>Tabs toolbar</source> <translation>Fül eszköztár</translation> </message> <message> <location filename="../bitcoingui.cpp" line="322"/> <source>Actions toolbar</source> <translation>Parancsok eszköztár</translation> </message> <message> <location filename="../bitcoingui.cpp" line="334"/> <location filename="../bitcoingui.cpp" line="343"/> <source>[testnet]</source> <translation>[teszthálózat]</translation> </message> <message> <location filename="../bitcoingui.cpp" line="343"/> <location filename="../bitcoingui.cpp" line="399"/> <source>Bitcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="492"/> <source>%n active connection(s) to Bitcoin network</source> <translation><numerusform>%n aktív kapcsolat a Bitcoin-hálózattal</numerusform><numerusform>%n aktív kapcsolat a Bitcoin-hálózattal</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="540"/> <source>Downloaded %1 blocks of transaction history.</source> <translation>%1 blokk letöltve a tranzakciótörténetből.</translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="555"/> <source>%n second(s) ago</source> <translation><numerusform>%n másodperccel ezelőtt</numerusform><numerusform>%n másodperccel ezelőtt</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="559"/> <source>%n minute(s) ago</source> <translation><numerusform>%n perccel ezelőtt</numerusform><numerusform>%n perccel ezelőtt</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="563"/> <source>%n hour(s) ago</source> <translation><numerusform>%n órával ezelőtt</numerusform><numerusform>%n órával ezelőtt</numerusform></translation> </message> <message numerus="yes"> <location filename="../bitcoingui.cpp" line="567"/> <source>%n day(s) ago</source> <translation><numerusform>%n nappal ezelőtt</numerusform><numerusform>%n nappal ezelőtt</numerusform></translation> </message> <message> <location filename="../bitcoingui.cpp" line="573"/> <source>Up to date</source> <translation>Naprakész</translation> </message> <message> <location filename="../bitcoingui.cpp" line="580"/> <source>Catching up...</source> <translation>Frissítés...</translation> </message> <message> <location filename="../bitcoingui.cpp" line="590"/> <source>Last received block was generated %1.</source> <translation>Az utolsóként kapott blokk generálva: %1.</translation> </message> <message> <location filename="../bitcoingui.cpp" line="649"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Ez a tranzakció túllépi a mérethatárt, de %1 tranzakciós díj ellenében így is elküldheted. Ezt a plusz összeget a tranzakcióidat feldolgozó csomópontok kapják, így magát a hálózatot támogatod vele. Hajlandó vagy megfizetni a díjat?</translation> </message> <message> <location filename="../bitcoingui.cpp" line="654"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="681"/> <source>Sent transaction</source> <translation>Tranzakció elküldve.</translation> </message> <message> <location filename="../bitcoingui.cpp" line="682"/> <source>Incoming transaction</source> <translation>Beérkező tranzakció</translation> </message> <message> <location filename="../bitcoingui.cpp" line="683"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Dátum: %1 Összeg: %2 Típus: %3 Cím: %4 </translation> </message> <message> <location filename="../bitcoingui.cpp" line="804"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Tárca &lt;b&gt;kódolva&lt;/b&gt; és jelenleg &lt;b&gt;nyitva&lt;/b&gt;.</translation> </message> <message> <location filename="../bitcoingui.cpp" line="812"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Tárca &lt;b&gt;kódolva&lt;/b&gt; és jelenleg &lt;b&gt;zárva&lt;/b&gt;.</translation> </message> <message> <location filename="../bitcoingui.cpp" line="835"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="835"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="838"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoingui.cpp" line="838"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="112"/> <source>A fatal error occured. Bitcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="84"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>DisplayOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="246"/> <source>Display</source> <translation>Megjelenítés</translation> </message> <message> <location filename="../optionsdialog.cpp" line="257"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="263"/> <source>The user interface language can be set here. This setting will only take effect after restarting Bitcoin.</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="252"/> <source>User Interface &amp;Language:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="273"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="277"/> <source>Choose the default subdivision unit to show in the interface, and when sending coins</source> <translation>Válaszd ki az interfészen és érmék küldésekor megjelenítendő alapértelmezett alegységet.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="284"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="285"/> <source>Whether to show Bitcoin addresses in the transaction list</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="303"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="303"/> <source>This setting will take effect after restarting Bitcoin.</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="14"/> <source>Edit Address</source> <translation>Cím szerkesztése</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="25"/> <source>&amp;Label</source> <translation>Cím&amp;ke</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="35"/> <source>The label associated with this address book entry</source> <translation>A címhez tartozó címke</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="42"/> <source>&amp;Address</source> <translation>&amp;Cím</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="52"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Az ehhez a címjegyzék-bejegyzéshez tartozó cím. Ez csak a küldő címeknél módosítható.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="20"/> <source>New receiving address</source> <translation>Új fogadó cím</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="24"/> <source>New sending address</source> <translation>Új küldő cím</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="27"/> <source>Edit receiving address</source> <translation>Fogadó cím szerkesztése</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="31"/> <source>Edit sending address</source> <translation>Küldő cím szerkesztése</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="91"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>A megadott &quot;%1&quot; cím már szerepel a címjegyzékben.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="96"/> <source>The entered address &quot;%1&quot; is not a valid Bitcoin address.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="101"/> <source>Could not unlock wallet.</source> <translation>Tárca feloldása sikertelen</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="106"/> <source>New key generation failed.</source> <translation>Új kulcs generálása sikertelen</translation> </message> </context> <context> <name>HelpMessageBox</name> <message> <location filename="../bitcoin.cpp" line="133"/> <location filename="../bitcoin.cpp" line="143"/> <source>Bitcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="133"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="135"/> <source>Usage:</source> <translation>Használat:</translation> </message> <message> <location filename="../bitcoin.cpp" line="136"/> <source>options</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="138"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="139"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="140"/> <source>Start minimized</source> <translation>Indítás lekicsinyítve </translation> </message> <message> <location filename="../bitcoin.cpp" line="141"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>MainOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="227"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="212"/> <source>Pay transaction &amp;fee</source> <translation>Tranzakciós &amp;díj fizetése</translation> </message> <message> <location filename="../optionsdialog.cpp" line="204"/> <source>Main</source> <translation>Fő</translation> </message> <message> <location filename="../optionsdialog.cpp" line="206"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="222"/> <source>&amp;Start Bitcoin on system login</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="223"/> <source>Automatically start Bitcoin after logging in to the system</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="226"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> </context> <context> <name>MessagePage</name> <message> <location filename="../forms/messagepage.ui" line="14"/> <source>Sign Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="20"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="38"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="48"/> <source>Choose adress from address book</source> <translation>Válassz egy címet a címjegyzékből</translation> </message> <message> <location filename="../forms/messagepage.ui" line="58"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/messagepage.ui" line="71"/> <source>Paste address from clipboard</source> <translation>Cím beillesztése a vágólapról</translation> </message> <message> <location filename="../forms/messagepage.ui" line="81"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location filename="../forms/messagepage.ui" line="93"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="128"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="131"/> <source>&amp;Copy Signature</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="142"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="145"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="31"/> <source>Click &quot;Sign Message&quot; to get signature</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="114"/> <source>Sign a message to prove you own this address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/messagepage.ui" line="117"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="30"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adj meg egy Bitcoin-címet (pl.: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L )</translation> </message> <message> <location filename="../messagepage.cpp" line="83"/> <location filename="../messagepage.cpp" line="90"/> <location filename="../messagepage.cpp" line="105"/> <location filename="../messagepage.cpp" line="117"/> <source>Error signing</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="83"/> <source>%1 is not a valid address.</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="90"/> <source>%1 does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="105"/> <source>Private key for %1 is not available.</source> <translation type="unfinished"/> </message> <message> <location filename="../messagepage.cpp" line="117"/> <source>Sign failed</source> <translation type="unfinished"/> </message> </context> <context> <name>NetworkOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="345"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="347"/> <source>Map port using &amp;UPnP</source> <translation>&amp;UPnP port-feltérképezés</translation> </message> <message> <location filename="../optionsdialog.cpp" line="348"/> <source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>A Bitcoin-kliens portjának automatikus megnyitása a routeren. Ez csak akkor működik, ha a routered támogatja az UPnP-t és az engedélyezve is van rajta.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="351"/> <source>&amp;Connect through SOCKS4 proxy:</source> <translation>&amp;Csatlakozás SOCKS4 proxyn keresztül:</translation> </message> <message> <location filename="../optionsdialog.cpp" line="352"/> <source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source> <translation>SOCKS4 proxyn keresztüli csatlakozás a Bitcoin hálózatához (pl. Tor-on keresztüli csatlakozás esetén)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="357"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="366"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="363"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Proxy IP címe (pl.: 127.0.0.1)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="372"/> <source>Port of the proxy (e.g. 1234)</source> <translation>Proxy portja (pl.: 1234)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../optionsdialog.cpp" line="135"/> <source>Options</source> <translation>Opciók</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="14"/> <source>Form</source> <translation>Űrlap</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="47"/> <location filename="../forms/overviewpage.ui" line="204"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Bitcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/overviewpage.ui" line="89"/> <source>Balance:</source> <translation>Egyenleg:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="147"/> <source>Number of transactions:</source> <translation>Tranzakciók száma:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="118"/> <source>Unconfirmed:</source> <translation>Megerősítetlen:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="40"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/overviewpage.ui" line="197"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Legutóbbi tranzakciók&lt;/b&gt;</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="105"/> <source>Your current balance</source> <translation>Aktuális egyenleged</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="134"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Még megerősítésre váró, a jelenlegi egyenlegbe be nem számított tranzakciók</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="154"/> <source>Total number of transactions in wallet</source> <translation>Tárca összes tranzakcióinak száma</translation> </message> <message> <location filename="../overviewpage.cpp" line="110"/> <location filename="../overviewpage.cpp" line="111"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="32"/> <source>QR Code</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="55"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="70"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="105"/> <source>BTC</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="121"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/qrcodedialog.ui" line="144"/> <source>Message:</source> <translation>Üzenet:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="186"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="45"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="63"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="120"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="120"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="14"/> <source>Bitcoin debug window</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="56"/> <location filename="../forms/rpcconsole.ui" line="79"/> <location filename="../forms/rpcconsole.ui" line="102"/> <location filename="../forms/rpcconsole.ui" line="125"/> <location filename="../forms/rpcconsole.ui" line="161"/> <location filename="../forms/rpcconsole.ui" line="214"/> <location filename="../forms/rpcconsole.ui" line="237"/> <location filename="../forms/rpcconsole.ui" line="260"/> <location filename="../rpcconsole.cpp" line="245"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="69"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="24"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="39"/> <source>Client</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="115"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="144"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="151"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="174"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="197"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="204"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="227"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="250"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="292"/> <source>Debug logfile</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="299"/> <source>Open the Bitcoin debug logfile from the current data directory. This can take a few seconds for large logfiles.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="302"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="323"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="92"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/rpcconsole.ui" line="372"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="212"/> <source>Welcome to the Bitcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="213"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="214"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="14"/> <location filename="../sendcoinsdialog.cpp" line="122"/> <location filename="../sendcoinsdialog.cpp" line="127"/> <location filename="../sendcoinsdialog.cpp" line="132"/> <location filename="../sendcoinsdialog.cpp" line="137"/> <location filename="../sendcoinsdialog.cpp" line="143"/> <location filename="../sendcoinsdialog.cpp" line="148"/> <location filename="../sendcoinsdialog.cpp" line="153"/> <source>Send Coins</source> <translation>Érmék küldése</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="64"/> <source>Send to multiple recipients at once</source> <translation>Küldés több címzettnek egyszerre</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="67"/> <source>&amp;Add Recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="84"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="87"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="106"/> <source>Balance:</source> <translation>Egyenleg:</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="113"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="144"/> <source>Confirm the send action</source> <translation>Küldés megerősítése</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="147"/> <source>&amp;Send</source> <translation>&amp;Küldés</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="94"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; %2-re (%3)</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="99"/> <source>Confirm send coins</source> <translation>Küldés megerősítése</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source>Are you sure you want to send %1?</source> <translation>Valóban el akarsz küldeni %1-t?</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source> and </source> <translation> és</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="123"/> <source>The recepient address is not valid, please recheck.</source> <translation>A címzett címe érvénytelen, kérlek, ellenőrizd.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="128"/> <source>The amount to pay must be larger than 0.</source> <translation>A fizetendő összegnek nagyobbnak kell lennie 0-nál.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="133"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="138"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="144"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="149"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="154"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="14"/> <source>Form</source> <translation>Űrlap</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="29"/> <source>A&amp;mount:</source> <translation>Összeg:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="42"/> <source>Pay &amp;To:</source> <translation>Címzett:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="66"/> <location filename="../sendcoinsentry.cpp" line="25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Milyen címkével kerüljön be ez a cím a címtáradba? </translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="75"/> <source>&amp;Label:</source> <translation>Címke:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="93"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Címzett címe (pl.: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L )</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="103"/> <source>Choose address from address book</source> <translation>Válassz egy címet a címjegyzékből</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="113"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="120"/> <source>Paste address from clipboard</source> <translation>Cím beillesztése a vágólapról</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="130"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="137"/> <source>Remove this recipient</source> <translation>Címzett eltávolítása</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="26"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adj meg egy Bitcoin-címet (pl.: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L )</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="21"/> <source>Open for %1 blocks</source> <translation>Megnyitva %1 blokkra</translation> </message> <message> <location filename="../transactiondesc.cpp" line="23"/> <source>Open until %1</source> <translation>Megnyitva %1-ig</translation> </message> <message> <location filename="../transactiondesc.cpp" line="29"/> <source>%1/offline?</source> <translation>%1/offline?</translation> </message> <message> <location filename="../transactiondesc.cpp" line="31"/> <source>%1/unconfirmed</source> <translation>%1/megerősítetlen</translation> </message> <message> <location filename="../transactiondesc.cpp" line="33"/> <source>%1 confirmations</source> <translation>%1 megerősítés</translation> </message> <message> <location filename="../transactiondesc.cpp" line="51"/> <source>&lt;b&gt;Status:&lt;/b&gt; </source> <translation>&lt;b&gt;Állapot:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="56"/> <source>, has not been successfully broadcast yet</source> <translation>, még nem sikerült elküldeni.</translation> </message> <message> <location filename="../transactiondesc.cpp" line="58"/> <source>, broadcast through %1 node</source> <translation>, %1 csomóponton keresztül elküldve.</translation> </message> <message> <location filename="../transactiondesc.cpp" line="60"/> <source>, broadcast through %1 nodes</source> <translation>, elküldve %1 csomóponton keresztül.</translation> </message> <message> <location filename="../transactiondesc.cpp" line="64"/> <source>&lt;b&gt;Date:&lt;/b&gt; </source> <translation>&lt;b&gt;Dátum:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="71"/> <source>&lt;b&gt;Source:&lt;/b&gt; Generated&lt;br&gt;</source> <translation>&lt;b&gt;Forrás:&lt;/b&gt; Generálva &lt;br&gt;</translation> </message> <message> <location filename="../transactiondesc.cpp" line="77"/> <location filename="../transactiondesc.cpp" line="94"/> <source>&lt;b&gt;From:&lt;/b&gt; </source> <translation>&lt;b&gt;Űrlap:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="94"/> <source>unknown</source> <translation>ismeretlen</translation> </message> <message> <location filename="../transactiondesc.cpp" line="95"/> <location filename="../transactiondesc.cpp" line="118"/> <location filename="../transactiondesc.cpp" line="178"/> <source>&lt;b&gt;To:&lt;/b&gt; </source> <translation>&lt;b&gt;Címzett:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="98"/> <source> (yours, label: </source> <translation> (tiéd, címke: </translation> </message> <message> <location filename="../transactiondesc.cpp" line="100"/> <source> (yours)</source> <translation> (tiéd)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="136"/> <location filename="../transactiondesc.cpp" line="150"/> <location filename="../transactiondesc.cpp" line="195"/> <location filename="../transactiondesc.cpp" line="212"/> <source>&lt;b&gt;Credit:&lt;/b&gt; </source> <translation>&lt;b&gt;Jóváírás&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="138"/> <source>(%1 matures in %2 more blocks)</source> <translation>(%1, %2 múlva készül el)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="142"/> <source>(not accepted)</source> <translation>(elutasítva)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="186"/> <location filename="../transactiondesc.cpp" line="194"/> <location filename="../transactiondesc.cpp" line="209"/> <source>&lt;b&gt;Debit:&lt;/b&gt; </source> <translation>&lt;b&gt;Terhelés&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="200"/> <source>&lt;b&gt;Transaction fee:&lt;/b&gt; </source> <translation>&lt;b&gt;Tranzakciós díj:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="216"/> <source>&lt;b&gt;Net amount:&lt;/b&gt; </source> <translation>&lt;b&gt;Nettó összeg:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="222"/> <source>Message:</source> <translation>Üzenet:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="224"/> <source>Comment:</source> <translation>Megjegyzés:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="226"/> <source>Transaction ID:</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiondesc.cpp" line="229"/> <source>Generated coins must wait 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to &quot;not accepted&quot; and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>A frissen generált érméket csak 120 blokkal később tudod elkölteni. Ez a blokk nyomban szétküldésre került a hálózatba, amint legeneráltad, hogy hozzáadhassák a blokklánchoz. Ha nem kerül be a láncba, úgy az állapota &quot;elutasítva&quot;-ra módosul, és nem költheted el az érméket. Ez akkor következhet be időnként, ha egy másik csomópont mindössze néhány másodperc különbséggel generált le egy blokkot a tiédhez képest.</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="14"/> <source>Transaction details</source> <translation>Tranzakció részletei</translation> </message> <message> <location filename="../forms/transactiondescdialog.ui" line="20"/> <source>This pane shows a detailed description of the transaction</source> <translation>Ez a mező a tranzakció részleteit mutatja</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Date</source> <translation>Dátum</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Type</source> <translation>Típus</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Address</source> <translation>Cím</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="226"/> <source>Amount</source> <translation>Összeg</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="281"/> <source>Open for %n block(s)</source> <translation><numerusform>%n blokkra megnyitva</numerusform><numerusform>%n blokkra megnyitva</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="284"/> <source>Open until %1</source> <translation>%1-ig megnyitva</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="287"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 megerősítés)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="290"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Megerősítetlen (%1 %2 megerősítésből)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="293"/> <source>Confirmed (%1 confirmations)</source> <translation>Megerősítve (%1 megerősítés)</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="301"/> <source>Mined balance will be available in %n more blocks</source> <translation><numerusform>%n blokk múlva lesz elérhető a bányászott egyenleg.</numerusform><numerusform>%n blokk múlva lesz elérhető a bányászott egyenleg.</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="307"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Ezt a blokkot egyetlen másik csomópont sem kapta meg, így valószínűleg nem lesz elfogadva!</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="310"/> <source>Generated but not accepted</source> <translation>Legenerálva, de még el nem fogadva.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="353"/> <source>Received with</source> <translation>Erre a címre</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="355"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location filename="../transactiontablemodel.cpp" line="358"/> <source>Sent to</source> <translation>Erre a címre</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="360"/> <source>Payment to yourself</source> <translation>Magadnak kifizetve</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="362"/> <source>Mined</source> <translation>Kibányászva</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="400"/> <source>(n/a)</source> <translation>(nincs)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="599"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Tranzakció állapota. Húzd ide a kurzort, hogy lásd a megerősítések számát.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="601"/> <source>Date and time that the transaction was received.</source> <translation>Tranzakció fogadásának dátuma és időpontja.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="603"/> <source>Type of transaction.</source> <translation>Tranzakció típusa.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="605"/> <source>Destination address of transaction.</source> <translation>A tranzakció címzettjének címe.</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="607"/> <source>Amount removed from or added to balance.</source> <translation>Az egyenleghez jóváírt vagy ráterhelt összeg.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="55"/> <location filename="../transactionview.cpp" line="71"/> <source>All</source> <translation>Mind</translation> </message> <message> <location filename="../transactionview.cpp" line="56"/> <source>Today</source> <translation>Mai</translation> </message> <message> <location filename="../transactionview.cpp" line="57"/> <source>This week</source> <translation>Ezen a héten</translation> </message> <message> <location filename="../transactionview.cpp" line="58"/> <source>This month</source> <translation>Ebben a hónapban</translation> </message> <message> <location filename="../transactionview.cpp" line="59"/> <source>Last month</source> <translation>Múlt hónapban</translation> </message> <message> <location filename="../transactionview.cpp" line="60"/> <source>This year</source> <translation>Ebben az évben</translation> </message> <message> <location filename="../transactionview.cpp" line="61"/> <source>Range...</source> <translation>Tartomány ...</translation> </message> <message> <location filename="../transactionview.cpp" line="72"/> <source>Received with</source> <translation>Erre a címre</translation> </message> <message> <location filename="../transactionview.cpp" line="74"/> <source>Sent to</source> <translation>Erre a címre</translation> </message> <message> <location filename="../transactionview.cpp" line="76"/> <source>To yourself</source> <translation>Magadnak</translation> </message> <message> <location filename="../transactionview.cpp" line="77"/> <source>Mined</source> <translation>Kibányászva</translation> </message> <message> <location filename="../transactionview.cpp" line="78"/> <source>Other</source> <translation>Más</translation> </message> <message> <location filename="../transactionview.cpp" line="85"/> <source>Enter address or label to search</source> <translation>Írd be a keresendő címet vagy címkét</translation> </message> <message> <location filename="../transactionview.cpp" line="92"/> <source>Min amount</source> <translation>Minimális összeg</translation> </message> <message> <location filename="../transactionview.cpp" line="126"/> <source>Copy address</source> <translation>Cím másolása</translation> </message> <message> <location filename="../transactionview.cpp" line="127"/> <source>Copy label</source> <translation>Címke másolása</translation> </message> <message> <location filename="../transactionview.cpp" line="128"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="129"/> <source>Edit label</source> <translation>Címke szerkesztése</translation> </message> <message> <location filename="../transactionview.cpp" line="130"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location filename="../transactionview.cpp" line="270"/> <source>Export Transaction Data</source> <translation>Tranzakció adatainak exportálása</translation> </message> <message> <location filename="../transactionview.cpp" line="271"/> <source>Comma separated file (*.csv)</source> <translation>Vesszővel elválasztott fájl (*.csv)</translation> </message> <message> <location filename="../transactionview.cpp" line="279"/> <source>Confirmed</source> <translation>Megerősítve</translation> </message> <message> <location filename="../transactionview.cpp" line="280"/> <source>Date</source> <translation>Dátum</translation> </message> <message> <location filename="../transactionview.cpp" line="281"/> <source>Type</source> <translation>Típus</translation> </message> <message> <location filename="../transactionview.cpp" line="282"/> <source>Label</source> <translation>Címke</translation> </message> <message> <location filename="../transactionview.cpp" line="283"/> <source>Address</source> <translation>Cím</translation> </message> <message> <location filename="../transactionview.cpp" line="284"/> <source>Amount</source> <translation>Összeg</translation> </message> <message> <location filename="../transactionview.cpp" line="285"/> <source>ID</source> <translation>Azonosító</translation> </message> <message> <location filename="../transactionview.cpp" line="289"/> <source>Error exporting</source> <translation>Hiba lépett fel exportálás közben</translation> </message> <message> <location filename="../transactionview.cpp" line="289"/> <source>Could not write to file %1.</source> <translation>%1 fájlba való kiírás sikertelen.</translation> </message> <message> <location filename="../transactionview.cpp" line="384"/> <source>Range:</source> <translation>Tartomány:</translation> </message> <message> <location filename="../transactionview.cpp" line="392"/> <source>to</source> <translation>meddig</translation> </message> </context> <context> <name>VerifyMessageDialog</name> <message> <location filename="../forms/verifymessagedialog.ui" line="14"/> <source>Verify Signed Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="20"/> <source>Enter the message and signature below (be careful to correctly copy newlines, spaces, tabs and other invisible characters) to obtain the Bitcoin address used to sign the message.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="62"/> <source>Verify a message and obtain the Bitcoin address used to sign the message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="65"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="79"/> <source>Copy the currently selected address to the system clipboard</source> <translation>A kiválasztott cím másolása a vágólapra</translation> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="82"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="93"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/verifymessagedialog.ui" line="96"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="28"/> <source>Enter Bitcoin signature</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="29"/> <source>Click &quot;Verify Message&quot; to obtain address</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="55"/> <location filename="../verifymessagedialog.cpp" line="62"/> <source>Invalid Signature</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="55"/> <source>The signature could not be decoded. Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="62"/> <source>The signature did not match the message digest. Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="72"/> <source>Address not found in address book.</source> <translation type="unfinished"/> </message> <message> <location filename="../verifymessagedialog.cpp" line="72"/> <source>Address found in address book: %1</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="158"/> <source>Sending...</source> <translation>Küldés ...</translation> </message> </context> <context> <name>WindowOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="313"/> <source>Window</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="316"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Kicsinyítés a tálcára az eszköztár helyett</translation> </message> <message> <location filename="../optionsdialog.cpp" line="317"/> <source>Show only a tray icon after minimizing the window</source> <translation>Kicsinyítés után csak eszköztár-ikont mutass</translation> </message> <message> <location filename="../optionsdialog.cpp" line="320"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="321"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Az alkalmazásból való kilépés helyett az eszköztárba kicsinyíti az alkalmazást az ablak bezárásakor. Ez esetben az alkalmazás csak a Kilépés menüponttal zárható be.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="43"/> <source>Bitcoin version</source> <translation>Bitcoin verzió</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="44"/> <source>Usage:</source> <translation>Használat:</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="45"/> <source>Send command to -server or bitcoind</source> <translation>Parancs küldése a -serverhez vagy a bitcoindhez </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="46"/> <source>List commands</source> <translation>Parancsok kilistázása </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="47"/> <source>Get help for a command</source> <translation>Segítség egy parancsról </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="49"/> <source>Options:</source> <translation>Opciók </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="50"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation>Konfigurációs fájl (alapértelmezett: bitcoin.conf) </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="51"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation>pid-fájl (alapértelmezett: bitcoind.pid) </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="52"/> <source>Generate coins</source> <translation>Érmék generálása </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="53"/> <source>Don&apos;t generate coins</source> <translation>Bitcoin-generálás leállítása </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="54"/> <source>Specify data directory</source> <translation>Adatkönyvtár </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="55"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="56"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="57"/> <source>Specify connection timeout (in milliseconds)</source> <translation>Csatlakozás időkerete (milliszekundumban) </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="63"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="64"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="66"/> <source>Connect only to the specified node</source> <translation>Csatlakozás csak a megadott csomóponthoz </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="67"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="68"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="69"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4 or IPv6)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="70"/> <source>Try to discover public IP address (default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="73"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="75"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="76"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="79"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="80"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="83"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="86"/> <source>Accept command line and JSON-RPC commands</source> <translation>Parancssoros és JSON-RPC parancsok elfogadása </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="87"/> <source>Run in the background as a daemon and accept commands</source> <translation>Háttérben futtatás daemonként és parancsok elfogadása </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="88"/> <source>Use the test network</source> <translation>Teszthálózat használata </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="89"/> <source>Output extra debugging information</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="90"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="91"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="92"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="93"/> <source>Username for JSON-RPC connections</source> <translation>Felhasználói név JSON-RPC csatlakozásokhoz </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="94"/> <source>Password for JSON-RPC connections</source> <translation>Jelszó JSON-RPC csatlakozásokhoz </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="95"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332)</source> <translation>JSON-RPC csatlakozásokhoz figyelendő &lt;port&gt; (alapértelmezett: 8332) </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="96"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>JSON-RPC csatlakozások engedélyezése meghatározott IP-címről </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="97"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Parancsok küldése &lt;ip&gt; címen működő csomóponthoz (alapértelmezett: 127.0.0.1) </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="98"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="101"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="102"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Kulcskarika mérete &lt;n&gt; (alapértelmezett: 100) </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="103"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Blokklánc újraszkennelése hiányzó tárca-tranzakciók után </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="104"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="105"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="106"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="108"/> <source> SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation> SSL-opciók: (lásd a Bitcoin Wiki SSL-beállítási instrukcióit) </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="111"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>OpenSSL (https) használata JSON-RPC csatalkozásokhoz </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="112"/> <source>Server certificate file (default: server.cert)</source> <translation>Szervertanúsítvány-fájl (alapértelmezett: server.cert) </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="113"/> <source>Server private key (default: server.pem)</source> <translation>Szerver titkos kulcsa (alapértelmezett: server.pem) </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="114"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Elfogadható rejtjelkulcsok (alapértelmezett: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH ) </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="145"/> <source>Warning: Disk space is low</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="107"/> <source>This help message</source> <translation>Ez a súgó-üzenet </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="121"/> <source>Cannot obtain a lock on data directory %s. Bitcoin is probably already running.</source> <translation>Az %s adatkönyvtár nem zárható. A Bitcoin valószínűleg fut már.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="48"/> <source>Bitcoin</source> <translation>Bitcoin</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="30"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="58"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="59"/> <source>Select the version of socks proxy to use (4 or 5, 5 is default)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="60"/> <source>Do not use proxy for connections to network &lt;net&gt; (IPv4 or IPv6)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="61"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="62"/> <source>Pass DNS requests to (SOCKS5) proxy</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="142"/> <source>Loading addresses...</source> <translation>Címek betöltése...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="132"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="134"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="135"/> <source>Error loading wallet.dat: Wallet requires newer version of Bitcoin</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="136"/> <source>Wallet needed to be rewritten: restart Bitcoin to complete</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="137"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="124"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="125"/> <source>Unknown network specified in -noproxy: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="127"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="126"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="128"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="129"/> <source>Not listening on any port</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="130"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="117"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="143"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="31"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="32"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="35"/> <source>Error: Transaction creation failed </source> <translation>Hiba: nem sikerült létrehozni a tranzakciót </translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="36"/> <source>Sending...</source> <translation>Küldés...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="37"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Hiba: a tranzakciót elutasították. Ezt az okozhatja, ha már elköltöttél valamennyi érmét a tárcádból - például ha a wallet.dat-od egy másolatát használtad, és így az elköltés csak abban lett jelölve, de itt nem.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="41"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="42"/> <source>Insufficient funds</source> <translation>Nincs elég bitcoinod.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="131"/> <source>Loading block index...</source> <translation>Blokkindex betöltése...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="65"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="28"/> <source>Unable to bind to %s on this computer. Bitcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="71"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="72"/> <source>Accept connections from outside (default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="74"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="81"/> <source>Use Universal Plug and Play to map the listening port (default: 1)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="82"/> <source>Use Universal Plug and Play to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="85"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="118"/> <source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="133"/> <source>Loading wallet...</source> <translation>Tárca betöltése...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="138"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="139"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="140"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="141"/> <source>Rescanning...</source> <translation>Újraszkennelés...</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="144"/> <source>Done loading</source> <translation>Betöltés befejezve.</translation> </message> <message> <location filename="../bitcoinstrings.cpp" line="8"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="9"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=%s (you do not need to remember this password) If the file does not exist, create it with owner-readable-only file permissions. </source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="18"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="19"/> <source>An error occured while setting up the RPC port %i for listening: %s</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="20"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoinstrings.cpp" line="25"/> <source>Warning: Please check that your computer&apos;s date and time are correct. If your clock is wrong Bitcoin will not work properly.</source> <translation>Figyelem: Ellenőrizd, hogy helyesen van-e beállítva a gépeden a dátum és az idő. A Bitcoin nem fog megfelelően működni, ha rosszul van beállítvaaz órád.</translation> </message> </context> </TS>
goodbyecoin/goodbyecoin
src/qt/locale/bitcoin_hu.ts
TypeScript
mit
106,091
/** * This file is where you define your application routes and controllers. * * Start by including the middleware you want to run for every request; * you can attach middleware to the pre('routes') and pre('render') events. * * For simplicity, the default setup for route controllers is for each to be * in its own file, and we import all the files in the /routes/views directory. * * Each of these files is a route controller, and is responsible for all the * processing that needs to happen for the route (e.g. loading data, handling * form submissions, rendering the view template, etc). * * Bind each route pattern your application should respond to in the function * that is exported from this module, following the examples below. * * See the Express application routing documentation for more information: * http://expressjs.com/api.html#app.VERB */ var keystone = require('keystone'); var middleware = require('./middleware'); var importRoutes = keystone.importer(__dirname); var sitemap = require('keystone-express-sitemap'); var https = require('https'); // Common Middleware keystone.pre('routes', middleware.initLocals); keystone.pre('render', middleware.flashMessages); // Import Route Controllers var routes = { views: importRoutes('./views') }; // Setup Route Bindings exports = module.exports = function(app) { // Views app.get('/', routes.views.index); app.get('/blog/:category?', routes.views.blog); app.get('/blog/post/:post', routes.views.post); app.get('/buy/:category?', routes.views.buy); app.get('/buy/post/:post', routes.views.post); app.get('/sell/:category?', routes.views.sell); app.get('/sell/post/:post', routes.views.post); app.get('/testimonial/:category?', routes.views.testimonial); app.get('/testimonial/post/:post', routes.views.post); app.get('/gallery', routes.views.gallery); //app.get('/listing/:category?', routes.views.listing); app.get('/listing2', routes.views.listing2); //app.get('/listing/post/:post', routes.views.post); app.all('/search2', routes.views.search2); app.get('/mls', routes.views.mls); app.all('/contact', routes.views.contact); app.all('/coverage', routes.views.coverage); app.all('/legal', routes.views.legal); app.all('/location', routes.views.location); app.get('/sitemap.xml', function(req, res) { sitemap.create(keystone, req, res); }); // NOTE: To protect a route so that only admins can see it, use the requireUser middleware: // app.get('/protected', middleware.requireUser, routes.views.protected); };
briviere/keystone-realestate-template
routes/index.js
JavaScript
mit
2,560
/** * @license Copyright (c) {{year}}, {{author}} All Rights Reserved. * Available via MIT license. */ /** * A client {{page}} {{request}} handler. */ define([ 'framework/request/base_request_handler', '../{{request}}_request', 'framework/core/deferred/deferred', 'domain/request/{{page}}/{{requestServer}}_request' ], function(BaseRequestHandler, {{toPascal request}}Request, Deferred, {{toPascal requestServer}}Request) { var {{toPascal request}}Handler = BaseRequestHandler.create({{toPascal request}}Request); // @override {{toPascal request}}Handler.prototype.execute = function(requestContext, request, response) { // TODO: Add in the handler method. return Deferred.resolvedPromise(requestContext); // OR /* var _this = this, remoteRequest = new {{toPascal requestServer}}Request(request); this._dispatcher.trigger('message', [ 'Doing Something', request.getSomething() ]); return this._remoteRequest(requestContext, remoteRequest).then(function(remoteResponse) { _this._dispatcher.trigger('message', [ 'Something Done', request.getSomething() ]); return Deferred.resolvedPromise(requestContext); }); */ }; return {{toPascal request}}Handler; });
DragonDTG/vex
lib/generator/request/public/static/scripts/pages/page/handler/request_handler.js
JavaScript
mit
1,223
// A cross-browser javascript shim for html5 audio (function(audiojs, audiojsInstance, container) { // Use the path to the audio.js file to create relative paths to the swf and player graphics // Remember that some systems (e.g. ruby on rails) append strings like '?1301478336' to asset paths var path = (function() { var re = new RegExp('audio(\.min)?\.js.*'), scripts = document.getElementsByTagName('script'); for (var i = 0, ii = scripts.length; i < ii; i++) { var path = scripts[i].getAttribute('src'); if(re.test(path)) return path.replace(re, ''); } })(); // ##The audiojs interface // This is the global object which provides an interface for creating new `audiojs` instances. // It also stores all of the construction helper methods and variables. container[audiojs] = { instanceCount: 0, instances: {}, // The markup for the swf. It is injected into the page if there is not support for the `<audio>` element. The `$n`s are placeholders. // `$1` The name of the flash movie // `$2` The path to the swf // `$3` Cache invalidation flashSource: '\ <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="$1" width="1" height="1" name="$1" style="position: absolute; left: -1px;"> \ <param name="movie" value="$2?playerInstance='+audiojs+'.instances[\'$1\']&datetime=$3"> \ <param name="allowscriptaccess" value="always"> \ <embed name="$1" src="$2?playerInstance='+audiojs+'.instances[\'$1\']&datetime=$3" width="1" height="1" allowscriptaccess="always"> \ </object>', // ### The main settings object // Where all the default settings are stored. Each of these variables and methods can be overwritten by the user-provided `options` object. settings: { autoplay: false, loop: false, preload: false, imageLocation: path + 'player-graphics.gif', swfLocation: path + 'audiojs.swf', useFlash: (function() { var a = document.createElement('audio'); return !(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, '')); })(), hasFlash: (function() { if (navigator.plugins && navigator.plugins.length && navigator.plugins['Shockwave Flash']) { return true; } else if (navigator.mimeTypes && navigator.mimeTypes.length) { var mimeType = navigator.mimeTypes['application/x-shockwave-flash']; return mimeType && mimeType.enabledPlugin; } else { try { var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); return true; } catch (e) {} } return false; })(), // The default markup and classes for creating the player: createPlayer: { markup: '\ <div class="play-pause"> \ <p class="play"></p> \ <p class="pause"></p> \ <p class="loading"></p> \ <p class="error"></p> \ </div> \ <div class="scrubber"> \ <div class="progress"></div> \ <div class="loaded"></div> \ </div> \ <div class="time"> \ <em class="played">00:00</em>/<strong class="duration">00:00</strong> \ </div> \ <div class="error-message"></div>', playPauseClass: 'play-pause', scrubberClass: 'scrubber', progressClass: 'progress', loaderClass: 'loaded', timeClass: 'time', durationClass: 'duration', playedClass: 'played', errorMessageClass: 'error-message', playingClass: 'playing', loadingClass: 'loading', errorClass: 'error' }, // The css used by the default player. This is is dynamically injected into a `<style>` tag in the top of the head. css: '\ .audiojs audio { position: absolute; left: -1px; } \ .audiojs { width: 460px; height: 36px; background: #404040; overflow: hidden; font-family: monospace; font-size: 12px; \ background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #444), color-stop(0.5, #555), color-stop(0.51, #444), color-stop(1, #444)); \ background-image: -moz-linear-gradient(center top, #444 0%, #555 50%, #444 51%, #444 100%); \ -webkit-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.3); -moz-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.3); \ -o-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.3); box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.3); } \ .audiojs .play-pause { width: 25px; height: 40px; padding: 4px 6px; margin: 0px; float: left; overflow: hidden; border-right: 1px solid #000; } \ .audiojs p { display: none; width: 25px; height: 40px; margin: 0px; cursor: pointer; } \ .audiojs .play { display: block; } \ .audiojs .scrubber { position: relative; float: left; width: 280px; background: #5a5a5a; height: 14px; margin: 10px; border-top: 1px solid #3f3f3f; border-left: 0px; border-bottom: 0px; overflow: hidden; } \ .audiojs .progress { position: absolute; top: 0px; left: 0px; height: 14px; width: 0px; background: #ccc; z-index: 1; \ background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #ccc), color-stop(0.5, #ddd), color-stop(0.51, #ccc), color-stop(1, #ccc)); \ background-image: -moz-linear-gradient(center top, #ccc 0%, #ddd 50%, #ccc 51%, #ccc 100%); } \ .audiojs .loaded { position: absolute; top: 0px; left: 0px; height: 14px; width: 0px; background: #000; \ background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #222), color-stop(0.5, #333), color-stop(0.51, #222), color-stop(1, #222)); \ background-image: -moz-linear-gradient(center top, #222 0%, #333 50%, #222 51%, #222 100%); } \ .audiojs .time { float: left; height: 36px; line-height: 36px; margin: 0px 0px 0px 6px; padding: 0px 6px 0px 12px; border-left: 1px solid #000; color: #ddd; text-shadow: 1px 1px 0px rgba(0, 0, 0, 0.5); } \ .audiojs .time em { padding: 0px 2px 0px 0px; color: #f9f9f9; font-style: normal; } \ .audiojs .time strong { padding: 0px 0px 0px 2px; font-weight: normal; } \ .audiojs .error-message { float: left; display: none; margin: 0px 10px; height: 36px; width: 400px; overflow: hidden; line-height: 36px; white-space: nowrap; color: #fff; \ text-overflow: ellipsis; -o-text-overflow: ellipsis; -icab-text-overflow: ellipsis; -khtml-text-overflow: ellipsis; -moz-text-overflow: ellipsis; -webkit-text-overflow: ellipsis; } \ .audiojs .error-message a { color: #eee; text-decoration: none; padding-bottom: 1px; border-bottom: 1px solid #999; white-space: wrap; } \ \ .audiojs .play { background: url("$1") -2px -1px no-repeat; } \ .audiojs .loading { background: url("$1") -2px -31px no-repeat; } \ .audiojs .error { background: url("$1") -2px -61px no-repeat; } \ .audiojs .pause { background: url("$1") -2px -91px no-repeat; } \ \ .playing .play, .playing .loading, .playing .error { display: none; } \ .playing .pause { display: block; } \ \ .loading .play, .loading .pause, .loading .error { display: none; } \ .loading .loading { display: block; } \ \ .error .time, .error .play, .error .pause, .error .scrubber, .error .loading { display: none; } \ .error .error { display: block; } \ .error .play-pause p { cursor: auto; } \ .error .error-message { display: block; }', // The default event callbacks: trackEnded: function(e) {}, flashError: function() { var player = this.settings.createPlayer, errorMessage = getByClass(player.errorMessageClass, this.wrapper), html = 'Missing <a href="http://get.adobe.com/flashplayer/">flash player</a> plugin.'; if (this.mp3) html += ' <a href="'+this.mp3+'">Download audio file</a>.'; container[audiojs].helpers.removeClass(this.wrapper, player.loadingClass); container[audiojs].helpers.addClass(this.wrapper, player.errorClass); errorMessage.innerHTML = html; }, loadError: function(e) { var player = this.settings.createPlayer, errorMessage = getByClass(player.errorMessageClass, this.wrapper); container[audiojs].helpers.removeClass(this.wrapper, player.loadingClass); container[audiojs].helpers.addClass(this.wrapper, player.errorClass); errorMessage.innerHTML = 'Error loading: "'+this.mp3+'"'; }, init: function() { var player = this.settings.createPlayer; container[audiojs].helpers.addClass(this.wrapper, player.loadingClass); }, loadStarted: function() { var player = this.settings.createPlayer, duration = getByClass(player.durationClass, this.wrapper), m = Math.floor(this.duration / 60), s = Math.floor(this.duration % 60); container[audiojs].helpers.removeClass(this.wrapper, player.loadingClass); duration.innerHTML = ((m<10?'0':'')+m+':'+(s<10?'0':'')+s); }, loadProgress: function(percent) { var player = this.settings.createPlayer, scrubber = getByClass(player.scrubberClass, this.wrapper), loaded = getByClass(player.loaderClass, this.wrapper); loaded.style.width = (scrubber.offsetWidth * percent) + 'px'; }, playPause: function() { if (this.playing) this.settings.play(); else this.settings.pause(); }, play: function() { var player = this.settings.createPlayer; container[audiojs].helpers.addClass(this.wrapper, player.playingClass); }, pause: function() { var player = this.settings.createPlayer; container[audiojs].helpers.removeClass(this.wrapper, player.playingClass); }, updatePlayhead: function(percent) { var player = this.settings.createPlayer, scrubber = getByClass(player.scrubberClass, this.wrapper), progress = getByClass(player.progressClass, this.wrapper); progress.style.width = (scrubber.offsetWidth * percent) + 'px'; var played = getByClass(player.playedClass, this.wrapper), p = this.duration * percent, m = Math.floor(p / 60), s = Math.floor(p % 60); played.innerHTML = ((m<10?'0':'')+m+':'+(s<10?'0':'')+s); } }, // ### Contructor functions // `create()` // Used to create a single `audiojs` instance. // If an array is passed then it calls back to `createAll()`. // Otherwise, it creates a single instance and returns it. create: function(element, options) { var options = options || {} if (element.length) { return this.createAll(options, element); } else { return this.newInstance(element, options); } }, // `createAll()` // Creates multiple `audiojs` instances. // If `elements` is `null`, then automatically find any `<audio>` tags on the page and create `audiojs` instances for them. createAll: function(options, elements) { var audioElements = elements || document.getElementsByTagName('audio'), instances = [] options = options || {}; for (var i = 0, ii = audioElements.length; i < ii; i++) { instances.push(this.newInstance(audioElements[i], options)); } return instances; }, // ### Creating and returning a new instance // This goes through all the steps required to build out a usable `audiojs` instance. newInstance: function(element, options) { var element = element, s = this.helpers.clone(this.settings), id = 'audiojs'+this.instanceCount, wrapperId = 'audiojs_wrapper'+this.instanceCount, instanceCount = this.instanceCount++; // Check for `autoplay`, `loop` and `preload` attributes and write them into the settings. if (element.getAttribute('autoplay') != null) s.autoplay = true; if (element.getAttribute('loop') != null) s.loop = true; if (element.getAttribute('preload') == 'none') s.preload = false; // Merge the default settings with the user-defined `options`. if (options) this.helpers.merge(s, options); // Inject the player html if required. if (s.createPlayer.markup) element = this.createPlayer(element, s.createPlayer, wrapperId); else element.parentNode.setAttribute('id', wrapperId); // Return a new `audiojs` instance. var audio = new container[audiojsInstance](element, s); // If css has been passed in, dynamically inject it into the `<head>`. if (s.css) this.helpers.injectCss(audio, s.css); // If `<audio>` or mp3 playback isn't supported, insert the swf & attach the required events for it. if (s.useFlash && s.hasFlash) { this.injectFlash(audio, id); this.attachFlashEvents(audio.wrapper, audio); } else if (s.useFlash && !s.hasFlash) { this.settings.flashError.apply(audio); } // Attach event callbacks to the new audiojs instance. if (!s.useFlash || (s.useFlash && s.hasFlash)) this.attachEvents(audio.wrapper, audio); // Store the newly-created `audiojs` instance. this.instances[id] = audio; return audio; }, // ### Helper methods for constructing a working player // Inject a wrapping div and the markup for the html player. createPlayer: function(element, player, id) { var wrapper = document.createElement('div'), newElement = element.cloneNode(true); wrapper.setAttribute('class', 'audiojs'); wrapper.setAttribute('className', 'audiojs'); wrapper.setAttribute('id', id); // Fix IE's broken implementation of `innerHTML` & `cloneNode` for HTML5 elements. if (newElement.outerHTML && !document.createElement('audio').canPlayType) { newElement = this.helpers.cloneHtml5Node(element); wrapper.innerHTML = player.markup; wrapper.appendChild(newElement); element.outerHTML = wrapper.outerHTML; wrapper = document.getElementById(id); } else { wrapper.appendChild(newElement); wrapper.innerHTML = wrapper.innerHTML + player.markup; element.parentNode.replaceChild(wrapper, element); } return wrapper.getElementsByTagName('audio')[0]; }, // Attaches useful event callbacks to an `audiojs` instance. attachEvents: function(wrapper, audio) { if (!audio.settings.createPlayer) return; var player = audio.settings.createPlayer, playPause = getByClass(player.playPauseClass, wrapper), scrubber = getByClass(player.scrubberClass, wrapper), leftPos = function(elem) { var curleft = 0; if (elem.offsetParent) { do { curleft += elem.offsetLeft; } while (elem = elem.offsetParent); } return curleft; }; container[audiojs].events.addListener(playPause, 'click', function(e) { audio.playPause.apply(audio); }); container[audiojs].events.addListener(scrubber, 'click', function(e) { var relativeLeft = e.clientX - leftPos(this); audio.skipTo(relativeLeft / scrubber.offsetWidth); }); // _If flash is being used, then the following handlers don't need to be registered._ if (audio.settings.useFlash) return; // Start tracking the load progress of the track. container[audiojs].events.trackLoadProgress(audio); container[audiojs].events.addListener(audio.element, 'timeupdate', function(e) { audio.updatePlayhead.apply(audio); }); container[audiojs].events.addListener(audio.element, 'ended', function(e) { audio.trackEnded.apply(audio); }); container[audiojs].events.addListener(audio.source, 'error', function(e) { // on error, cancel any load timers that are running. clearInterval(audio.readyTimer); clearInterval(audio.loadTimer); audio.settings.loadError.apply(audio); }); }, // Flash requires a slightly different API to the `<audio>` element, so this method is used to overwrite the standard event handlers. attachFlashEvents: function(element, audio) { audio['swfReady'] = false; audio['load'] = function(mp3) { // If the swf isn't ready yet then just set `audio.mp3`. `init()` will load it in once the swf is ready. audio.mp3 = mp3; if (audio.swfReady) audio.element.load(mp3); } audio['loadProgress'] = function(percent, duration) { audio.loadedPercent = percent; audio.duration = duration; audio.settings.loadStarted.apply(audio); audio.settings.loadProgress.apply(audio, [percent]); } audio['skipTo'] = function(percent) { if (percent > audio.loadedPercent) return; audio.updatePlayhead.call(audio, [percent]) audio.element.skipTo(percent); } audio['updatePlayhead'] = function(percent) { audio.settings.updatePlayhead.apply(audio, [percent]); } audio['play'] = function() { // If the audio hasn't started preloading, then start it now. // Then set `preload` to `true`, so that any tracks loaded in subsequently are loaded straight away. if (!audio.settings.preload) { audio.settings.preload = true; audio.element.init(audio.mp3); } audio.playing = true; // IE doesn't allow a method named `play()` to be exposed through `ExternalInterface`, so lets go with `pplay()`. // <http://dev.nuclearrooster.com/2008/07/27/externalinterfaceaddcallback-can-cause-ie-js-errors-with-certain-keyworkds/> audio.element.pplay(); audio.settings.play.apply(audio); } audio['pause'] = function() { audio.playing = false; // Use `ppause()` for consistency with `pplay()`, even though it isn't really required. audio.element.ppause(); audio.settings.pause.apply(audio); } audio['setVolume'] = function(v) { audio.element.setVolume(v); } audio['loadStarted'] = function() { // Load the mp3 specified by the audio element into the swf. audio.swfReady = true; if (audio.settings.preload) audio.element.init(audio.mp3); if (audio.settings.autoplay) audio.play.apply(audio); } }, // ### Injecting an swf from a string // Build up the swf source by replacing the `$keys` and then inject the markup into the page. injectFlash: function(audio, id) { var flashSource = this.flashSource.replace(/\$1/g, id); flashSource = flashSource.replace(/\$2/g, audio.settings.swfLocation); // `(+new Date)` ensures the swf is not pulled out of cache. The fixes an issue with Firefox running multiple players on the same page. flashSource = flashSource.replace(/\$3/g, (+new Date + Math.random())); // Inject the player markup using a more verbose `innerHTML` insertion technique that works with IE. var html = audio.wrapper.innerHTML, div = document.createElement('div'); div.innerHTML = flashSource + html; audio.wrapper.innerHTML = div.innerHTML; audio.element = this.helpers.getSwf(id); }, // ## Helper functions helpers: { // **Merge two objects, with `obj2` overwriting `obj1`** // The merge is shallow, but that's all that is required for our purposes. merge: function(obj1, obj2) { for (attr in obj2) { if (obj1.hasOwnProperty(attr) || obj2.hasOwnProperty(attr)) { obj1[attr] = obj2[attr]; } } }, // **Clone a javascript object (recursively)** clone: function(obj){ if (obj == null || typeof(obj) !== 'object') return obj; var temp = new obj.constructor(); for (var key in obj) temp[key] = arguments.callee(obj[key]); return temp; }, // **Adding/removing classnames from elements** addClass: function(element, className) { var re = new RegExp('(\\s|^)'+className+'(\\s|$)'); if (re.test(element.className)) return; element.className += ' ' + className; }, removeClass: function(element, className) { var re = new RegExp('(\\s|^)'+className+'(\\s|$)'); element.className = element.className.replace(re,' '); }, // **Dynamic CSS injection** // Takes a string of css, inserts it into a `<style>`, then injects it in at the very top of the `<head>`. This ensures any user-defined styles will take precedence. injectCss: function(audio, string) { // If an `audiojs` `<style>` tag already exists, then append to it rather than creating a whole new `<style>`. var prepend = '', styles = document.getElementsByTagName('style'), css = string.replace(/\$1/g, audio.settings.imageLocation); for (var i = 0, ii = styles.length; i < ii; i++) { var title = styles[i].getAttribute('title'); if (title && ~title.indexOf('audiojs')) { style = styles[i]; if (style.innerHTML === css) return; prepend = style.innerHTML; break; } }; var head = document.getElementsByTagName('head')[0], firstchild = head.firstChild, style = document.createElement('style'); if (!head) return; style.setAttribute('type', 'text/css'); style.setAttribute('title', 'audiojs'); if (style.styleSheet) style.styleSheet.cssText = prepend + css; else style.appendChild(document.createTextNode(prepend + css)); if (firstchild) head.insertBefore(style, firstchild); else head.appendChild(styleElement); }, // **Handle all the IE6+7 requirements for cloning `<audio>` nodes** // Create a html5-safe document fragment by injecting an `<audio>` element into the document fragment. cloneHtml5Node: function(audioTag) { var fragment = document.createDocumentFragment(), doc = fragment.createElement ? fragment : document; doc.createElement('audio'); var div = doc.createElement('div'); fragment.appendChild(div); div.innerHTML = audioTag.outerHTML; return div.firstChild; }, // **Cross-browser `<object>` / `<embed>` element selection** getSwf: function(name) { var swf = document[name] || window[name]; return swf.length > 1 ? swf[swf.length - 1] : swf; } }, // ## Event-handling events: { memoryLeaking: false, listeners: [], // **A simple cross-browser event handler abstraction** addListener: function(element, eventName, func) { // For modern browsers use the standard DOM-compliant `addEventListener`. if (element.addEventListener) { element.addEventListener(eventName, func, false); // For older versions of Internet Explorer, use `attachEvent`. // Also provide a fix for scoping `this` to the calling element and register each listener so the containing elements can be purged on page unload. } else if (element.attachEvent) { this.listeners.push(element); if (!this.memoryLeaking) { window.attachEvent('onunload', function() { if(this.listeners) { for (var i = 0, ii = this.listeners.length; i < ii; i++) { container[audiojs].events.purge(this.listeners[i]); } } }); this.memoryLeaking = true; } element.attachEvent('on' + eventName, function() { func.call(element, window.event); }); } }, trackLoadProgress: function(audio) { // If `preload` has been set to `none`, then we don't want to start loading the track yet. if (!audio.settings.preload) return; var readyTimer, loadTimer, audio = audio, ios = (/(ipod|iphone|ipad)/i).test(navigator.userAgent); // Use timers here rather than the official `progress` event, as Chrome has issues calling `progress` when loading mp3 files from cache. readyTimer = setInterval(function() { if (audio.element.readyState > -1) { // iOS doesn't start preloading the mp3 until the user interacts manually, so this stops the loader being displayed prematurely. if (!ios) audio.init.apply(audio); } if (audio.element.readyState > 1) { if (audio.settings.autoplay) audio.play.apply(audio); clearInterval(readyTimer); // Once we have data, start tracking the load progress. loadTimer = setInterval(function() { audio.loadProgress.apply(audio); if (audio.loadedPercent >= 1) clearInterval(loadTimer); }); } }, 10); audio.readyTimer = readyTimer; audio.loadTimer = loadTimer; }, // **Douglas Crockford's IE6 memory leak fix** // <http://javascript.crockford.com/memory/leak.html> // This is used to release the memory leak created by the circular references created when fixing `this` scoping for IE. It is called on page unload. purge: function(d) { var a = d.attributes, i; if (a) { for (i = 0; i < a.length; i += 1) { if (typeof d[a[i].name] === 'function') d[a[i].name] = null; } } a = d.childNodes; if (a) { for (i = 0; i < a.length; i += 1) purge(d.childNodes[i]); } }, // **DOMready function** // As seen here: <https://github.com/dperini/ContentLoaded/>. ready: (function() { return function(fn) { var win = window, done = false, top = true, doc = win.document, root = doc.documentElement, add = doc.addEventListener ? 'addEventListener' : 'attachEvent', rem = doc.addEventListener ? 'removeEventListener' : 'detachEvent', pre = doc.addEventListener ? '' : 'on', init = function(e) { if (e.type == 'readystatechange' && doc.readyState != 'complete') return; (e.type == 'load' ? win : doc)[rem](pre + e.type, init, false); if (!done && (done = true)) fn.call(win, e.type || e); }, poll = function() { try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; } init('poll'); }; if (doc.readyState == 'complete') fn.call(win, 'lazy'); else { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch(e) { } if (top) poll(); } doc[add](pre + 'DOMContentLoaded', init, false); doc[add](pre + 'readystatechange', init, false); win[add](pre + 'load', init, false); } } })() } } // ## The audiojs class // We create one of these per `<audio>` and then push them into `audiojs['instances']`. container[audiojsInstance] = function(element, settings) { // Each audio instance returns an object which contains an API back into the `<audio>` element. this.element = element; this.wrapper = element.parentNode; this.source = element.getElementsByTagName('source')[0] || element; // First check the `<audio>` element directly for a src and if one is not found, look for a `<source>` element. this.mp3 = (function(element) { var source = element.getElementsByTagName('source')[0]; return element.getAttribute('src') || (source ? source.getAttribute('src') : null); })(element); this.settings = settings; this.loadStartedCalled = false; this.loadedPercent = 0; this.duration = 1; this.playing = false; } container[audiojsInstance].prototype = { // API access events: // Each of these do what they need do and then call the matching methods defined in the settings object. updatePlayhead: function() { var percent = this.element.currentTime / this.duration; this.settings.updatePlayhead.apply(this, [percent]); }, skipTo: function(percent) { if (percent > this.loadedPercent) return; this.element.currentTime = this.duration * percent; this.updatePlayhead(); }, load: function(mp3) { this.loadStartedCalled = false; this.source.setAttribute('src', mp3); // The now outdated `load()` method is required for Safari 4 this.element.load(); this.mp3 = mp3; container[audiojs].events.trackLoadProgress(this); }, loadError: function() { this.settings.loadError.apply(this); }, init: function() { this.settings.init.apply(this); }, loadStarted: function() { // Wait until `element.duration` exists before setting up the audio player. if (!this.element.duration) return false; this.duration = this.element.duration; this.updatePlayhead(); this.settings.loadStarted.apply(this); }, loadProgress: function() { if (this.element.buffered != null && this.element.buffered.length) { // Ensure `loadStarted()` is only called once. if (!this.loadStartedCalled) { this.loadStartedCalled = this.loadStarted(); } var durationLoaded = this.element.buffered.end(this.element.buffered.length - 1); this.loadedPercent = durationLoaded / this.duration; this.settings.loadProgress.apply(this, [this.loadedPercent]); } }, playPause: function() { if (this.playing) this.pause(); else this.play(); }, play: function() { var ios = (/(ipod|iphone|ipad)/i).test(navigator.userAgent); // On iOS this interaction will trigger loading the mp3, so run `init()`. if (ios && this.element.readyState == 0) this.init.apply(this); // If the audio hasn't started preloading, then start it now. // Then set `preload` to `true`, so that any tracks loaded in subsequently are loaded straight away. if (!this.settings.preload) { this.settings.preload = true; this.element.setAttribute('preload', 'auto'); container[audiojs].events.trackLoadProgress(this); } this.playing = true; this.element.play(); this.settings.play.apply(this); }, pause: function() { this.playing = false; this.element.pause(); this.settings.pause.apply(this); }, setVolume: function(v) { this.element.volume = v; }, trackEnded: function(e) { this.skipTo.apply(this, [0]); if (!this.settings.loop) this.pause.apply(this); this.settings.trackEnded.apply(this); } } // **getElementsByClassName** // Having to rely on `getElementsByTagName` is pretty inflexible internally, so a modified version of Dustin Diaz's `getElementsByClassName` has been included. // This version cleans things up and prefers the native DOM method if it's available. var getByClass = function(searchClass, node) { var matches = []; node = node || document; if (node.getElementsByClassName) { matches = node.getElementsByClassName(searchClass); } else { var i, l, els = node.getElementsByTagName("*"), pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"); for (i = 0, l = els.length; i < l; i++) { if (pattern.test(els[i].className)) { matches.push(els[i]); } } } return matches.length > 1 ? matches : matches[0]; }; // The global variable names are passed in here and can be changed if they conflict with anything else. })('audiojs', 'audiojsInstance', this);
OdeArmasSR/scsofficials.com
public/js/lib/audio.js
JavaScript
mit
31,933
/*----------------------------------------------------------------------------*\ MODULE NAME: math.cpp PROJECT: F3DB AUTHOR: Evert Bauwens DATE: september 8 2003 DESCRIPTION: \*----------------------------------------------------------------------------*/ #include "math.h" #include <stdlib.h> #include <time.h> #include <math.h> #include <stdio.h> namespace F3DB { void InitMath() { int32 seed; FILE *fp = fopen("randseed", "rb"); if(fp) { fread((void*)&seed, 2, 1, fp); fclose(fp); } else { seed = time(null); } srand(seed); fp = fopen("randseed", "wb"); if(fp) { seed = Random((int32)0, (int32)INT32_MAX); fwrite((void*)&seed, 2, 1, fp); fclose(fp); } } int32 Random(int32 min, int32 max) { return (int32)floor((double)min + ((double)max - (double)min)*(double)rand()/(double)RAND_MAX + 0.5); } float Random(float min, float max) { return (float)floor((double)min + ((double)max - (double)min)*(double)rand()/(double)RAND_MAX + 0.5); } }
everbuild/f3db
src/math.cpp
C++
mit
1,020
/* * Cloud Foundry API module * Service connection module helper */ var app = require("./properties"); function ServiceClient () { } exports.ServiceClient = ServiceClient; ServiceClient.prototype.create = function () { if (!this.type) return false; var svcNames = app.serviceNamesOfType[this.type]; if (!svcNames) return false; if (svcNames.length !== 1) { throw new Error("Expected 1 service of " + this.type + " type, " + "but found " + svcNames.length + ". " + "Consider using createFromSvc(name) instead."); } var args = Array.prototype.slice.call(arguments); args.unshift(svcNames[0]); return this.createFromSvc.apply(this, args); }; ServiceClient.prototype.createFromSvc = function (name) { var handler = this._create; if (!handler) return false; var props = app.serviceProps[name]; if (!props) return false; switch (arguments.length) { case 2: return handler.call(this, props, arguments[1]); case 3: return handler.call(this, props, arguments[1], arguments[2]); default: return handler.call(this, props); } };
chinshr/foundry-node
node_modules/cf-autoconfig/node_modules/cf-runtime/lib/service.js
JavaScript
mit
1,115
import string import random def random_secret(n=45): chars = string.ascii_letters + string.digits return ''.join(random.choice(chars) for _ in range(n))
Wiredcraft/pipelines
pipelines/pipeline/utils.py
Python
mit
162
<?php namespace Ociosos\UsuarioBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('usuario'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
jorgemunoz8807/ociosos
src/Ociosos/UsuarioBundle/DependencyInjection/Configuration.php
PHP
mit
877
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Log_monitoring extends MY_Controller { public function __construct() { parent::__construct(); $this->load->model(array("Log_monitoring_model")); $this->data['html_css'] = ''; $this->data['html_js'] = ' <script> $(document).ready(function() { App.init(); }); </script>'; $this->data['csrf'] = array( 'name' => $this->security->get_csrf_token_name(), 'hash' => $this->security->get_csrf_hash() ); $this->data['error_message'] = $this->session->flashdata("error_message"); } public function index() { $this->data['title'] = "Log Monitoring"; $this->load->view('admin/header',$this->data); $this->load->view('log_monitoring_view',$this->data); $this->load->view('admin/footer',$this->data); } public function page_list_rest() { $query = $this->Log_monitoring_model->get_all_items(); $json_object = new stdClass(); $json_object->total = @$query->num_rows(); $json_object->rows = @$query->result(); header('Content-Type: application/json'); echo json_encode($json_object); } }
fajarlabs/sucofindo
application/admin/log_monitoring/controllers/Log_monitoring.php
PHP
mit
1,129
package com.birdbraintechnologies.birdblox.httpservice.RequestHandlers; import android.app.AlertDialog; import android.bluetooth.BluetoothGatt; import android.bluetooth.le.ScanFilter; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Handler; import android.os.ParcelUuid; import android.util.Log; import android.widget.Toast; import com.birdbraintechnologies.birdblox.Bluetooth.BluetoothHelper; import com.birdbraintechnologies.birdblox.Bluetooth.UARTConnection; import com.birdbraintechnologies.birdblox.Bluetooth.UARTSettings; import com.birdbraintechnologies.birdblox.Robots.Hummingbird; import com.birdbraintechnologies.birdblox.Robots.Hummingbit; import com.birdbraintechnologies.birdblox.Robots.Microbit; import com.birdbraintechnologies.birdblox.Robots.Robot; import com.birdbraintechnologies.birdblox.Robots.RobotType; import com.birdbraintechnologies.birdblox.httpservice.HttpService; import com.birdbraintechnologies.birdblox.httpservice.RequestHandler; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.UUID; import fi.iki.elonen.NanoHTTPD; import static com.birdbraintechnologies.birdblox.MainWebView.bbxEncode; import static com.birdbraintechnologies.birdblox.MainWebView.mainWebViewContext; import static com.birdbraintechnologies.birdblox.MainWebView.runJavascript; import static com.birdbraintechnologies.birdblox.Robots.RobotType.robotTypeFromString; import static fi.iki.elonen.NanoHTTPD.MIME_PLAINTEXT; /** * @author AppyFizz (Shreyan Bakshi) * @author Zhendong Yuan (yzd1998111) */ public class RobotRequestHandler implements RequestHandler { private final String TAG = this.getClass().getName(); private static final String FIRMWARE_UPDATE_URL = "http://www.hummingbirdkit.com/learning/installing-birdblox#BurnFirmware"; /* UUIDs for different Hummingbird features */ private static final String DEVICE_UUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"; private static final UUID HB_UART_UUID = UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"); private static final UUID HB_TX_UUID = UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"); private static final UUID HB_RX_UUID = UUID.fromString("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"); // TODO: Remove this, it is the same across devices private static final UUID RX_CONFIG_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); public static HashSet<String> hummingbirdsToConnect = new HashSet<>(); public static HashSet<String> hummingbitsToConnect = new HashSet<>(); public static HashSet<String> microbitsToConnect = new HashSet<>(); HttpService service; private static BluetoothHelper btHelper; private static HashMap<String, Thread> threadMap; private static UARTSettings HBUARTSettings; private static HashMap<String, Hummingbird> connectedHummingbirds; private static UARTSettings HBitUARTSettings; private static HashMap<String, Hummingbit> connectedHummingbits; private static UARTSettings MBitUARTSettings; private static HashMap<String, Microbit> connectedMicrobits; private AlertDialog.Builder builder; private AlertDialog robotInfoDialog; public static HashMap<String, BluetoothGatt> deviceGatt; public RobotRequestHandler(HttpService service) { this.service = service; btHelper = service.getBluetoothHelper(); threadMap = new HashMap<>(); connectedHummingbirds = new HashMap<>(); connectedHummingbits = new HashMap<>(); connectedMicrobits = new HashMap<>(); deviceGatt = new HashMap<>(); // Build Hummingbird UART settings HBUARTSettings = (new UARTSettings.Builder()) .setUARTServiceUUID(HB_UART_UUID) .setRxCharacteristicUUID(HB_RX_UUID) .setTxCharacteristicUUID(HB_TX_UUID) .setRxConfigUUID(RX_CONFIG_UUID) .build(); HBitUARTSettings = (new UARTSettings.Builder()) .setUARTServiceUUID(HB_UART_UUID) .setRxCharacteristicUUID(HB_RX_UUID) .setTxCharacteristicUUID(HB_TX_UUID) .setRxConfigUUID(RX_CONFIG_UUID) .build(); MBitUARTSettings = (new UARTSettings.Builder()) .setUARTServiceUUID(HB_UART_UUID) .setRxCharacteristicUUID(HB_RX_UUID) .setTxCharacteristicUUID(HB_TX_UUID) .setRxConfigUUID(RX_CONFIG_UUID) .build(); } @Override public NanoHTTPD.Response handleRequest(NanoHTTPD.IHTTPSession session, List<String> args) { String[] path = args.get(0).split("/"); Map<String, List<String>> m = session.getParameters(); // Generate response body String responseBody = ""; Robot robot; switch (path[0]) { case "startDiscover": responseBody = startScan(); break; case "stopDiscover": responseBody = stopDiscover(); break; case "totalStatus": responseBody = getTotalStatus(robotTypeFromString(m.get("type").get(0))); break; case "connect": responseBody = connectToRobot(robotTypeFromString(m.get("type").get(0)), m.get("id").get(0)); break; case "disconnect": responseBody = disconnectFromRobot(robotTypeFromString(m.get("type").get(0)), m.get("id").get(0)); break; case "out": robot = getRobotFromId(robotTypeFromString(m.get("type").get(0)), m.get("id").get(0)); if (robot == null) { runJavascript("CallbackManager.robot.updateStatus('" + m.get("id").get(0) + "', false);"); return NanoHTTPD.newFixedLengthResponse( NanoHTTPD.Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Robot " + m.get("id").get(0) + " was not found."); } else if (!robot.setOutput(path[1], m)) { //TODO: Is it really true that when you fail to set output it always means not connected? runJavascript("CallbackManager.robot.updateStatus('" + m.get("id").get(0) + "', false);"); return NanoHTTPD.newFixedLengthResponse( NanoHTTPD.Response.Status.EXPECTATION_FAILED, MIME_PLAINTEXT, "Failed to send to robot " + m.get("id").get(0) + "."); } else { runJavascript("CallbackManager.robot.updateStatus('" + m.get("id").get(0) + "', true);"); responseBody = "Sent to robot " + m.get("type").get(0) + " successfully."; } break; case "in": robot = getRobotFromId(robotTypeFromString(m.get("type").get(0)), m.get("id").get(0)); if (robot == null) { runJavascript("CallbackManager.robot.updateStatus('" + m.get("id").get(0) + "', false);"); return NanoHTTPD.newFixedLengthResponse( NanoHTTPD.Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Robot " + m.get("id").get(0) + " was not found."); } else { String sensorPort = null; String sensorAxis = null; if (m.get("port") != null) { sensorPort = m.get("port").get(0); } if (m.get("axis") != null) { sensorAxis = m.get("axis").get(0); } String sensorValue = robot.readSensor(m.get("sensor").get(0), sensorPort, sensorAxis); if (sensorValue == null) { runJavascript("CallbackManager.robot.updateStatus('" + m.get("id").get(0) + "', false);"); return NanoHTTPD.newFixedLengthResponse( NanoHTTPD.Response.Status.NO_CONTENT, MIME_PLAINTEXT, "Failed to read sensors from robot " + m.get("id").get(0) + "."); } else { runJavascript("CallbackManager.robot.updateStatus('" + m.get("id").get(0) + "', true);"); responseBody = sensorValue; } } break; case "showInfo": responseBody = showRobotInfo(robotTypeFromString(m.get("type").get(0)), m.get("id").get(0)); break; case "showUpdateInstructions": showFirmwareUpdateInstructions(); break; case "stopAll": stopAll(); break; } return NanoHTTPD.newFixedLengthResponse( NanoHTTPD.Response.Status.OK, MIME_PLAINTEXT, responseBody); } // TODO: Properly define Robot Object // TODO: Synchronization of below functions // TODO: Finish implementing new Robot commands and callbacks private static String startScan() { final List deviceFilter = generateDeviceFilter(); if (BluetoothHelper.currentlyScanning) { return ""; } if (BluetoothHelper.currentlyScanning) { stopDiscover(); } new Thread() { @Override public void run() { btHelper.scanDevices(deviceFilter); } }.start(); return ""; } /** * Finds a robotId in the list of connected robots. Null if it does not exist. * * @param robotType The type of the robot to be found. Must be 'hummingbird' or 'hummingbit' or 'microbit'. * @param robotId Robot ID to find. * @return The connected Robot if it exists, null otherwise. */ private static Robot getRobotFromId(RobotType robotType, String robotId) { if (robotType == RobotType.Hummingbird) { return connectedHummingbirds.get(robotId); } else if (robotType == RobotType.Hummingbit) { return connectedHummingbits.get(robotId); } else { return connectedMicrobits.get(robotId); } } /** * Creates a Bluetooth scan Robot filter that only matches the required 'type' of Robot. * * @return List of scan filters. */ private static List<ScanFilter> generateDeviceFilter() { String ROBOT_UUID = DEVICE_UUID; ScanFilter scanFilter = (new ScanFilter.Builder()) .setServiceUuid(ParcelUuid.fromString(ROBOT_UUID)) .build(); List<ScanFilter> robotFilters = new ArrayList<>(); robotFilters.add(scanFilter); return robotFilters; } /** * @param robotType * @param robotId * @return */ public static String connectToRobot(RobotType robotType, String robotId) { if (robotType == RobotType.Hummingbird) { connectToHummingbird(robotId); } else if (robotType == RobotType.Hummingbit) { connectToHummingbit(robotId); } else { connectToMicrobit(robotId); } return ""; } private static void connectToHummingbird(final String hummingbirdId) { if (connectedHummingbirds.containsKey(hummingbirdId) == false) { final UARTSettings HBUART = HBUARTSettings; if (hummingbirdsToConnect.contains(hummingbirdId)) { hummingbirdsToConnect.remove(hummingbirdId); } try { Thread hbConnectionThread = new Thread() { @Override public void run() { UARTConnection hbConn = btHelper.connectToDeviceUART(hummingbirdId, HBUART); if (hbConn != null && hbConn.isConnected() && connectedHummingbirds != null) { Hummingbird hummingbird = new Hummingbird(hbConn); connectedHummingbirds.put(hummingbirdId, hummingbird); hummingbird.setConnected(); } } }; hbConnectionThread.start(); final Thread oldThread = threadMap.put(hummingbirdId, hbConnectionThread); if (oldThread != null) { new Thread() { @Override public void run() { super.run(); oldThread.interrupt(); } }.start(); } } catch (Exception e) { Log.e("ConnectHB", " Error while connecting to HB " + e.getMessage()); } } } private static void connectToHummingbit(final String hummingbitId) { if (connectedHummingbits.containsKey(hummingbitId) == false) { final UARTSettings HBitUART = HBitUARTSettings; if (hummingbitsToConnect.contains(hummingbitId)) { hummingbitsToConnect.remove(hummingbitId); } try { Thread hbitConnectionThread = new Thread() { @Override public void run() { UARTConnection hbitConn = btHelper.connectToDeviceUART(hummingbitId, HBitUART); if (hbitConn != null && hbitConn.isConnected() && connectedHummingbits != null) { Hummingbit hummingbit = new Hummingbit(hbitConn); connectedHummingbits.put(hummingbitId, hummingbit); hummingbit.setConnected(); } } }; hbitConnectionThread.start(); final Thread oldThread = threadMap.put(hummingbitId, hbitConnectionThread); if (oldThread != null) { new Thread() { @Override public void run() { super.run(); oldThread.interrupt(); } }.start(); } } catch (Exception e) { Log.e("ConnectHBit", " Error while connecting to HBit " + e.getMessage()); } } } private static void connectToMicrobit(final String microbitId) { if (connectedMicrobits.containsKey(microbitId) == false) { final UARTSettings MBitUART = MBitUARTSettings; if (microbitsToConnect.contains(microbitId)) { microbitsToConnect.remove(microbitId); } try { Thread mbitConnectionThread = new Thread() { @Override public void run() { UARTConnection mbitConn = btHelper.connectToDeviceUART(microbitId, MBitUART); if (mbitConn != null && mbitConn.isConnected() && connectedMicrobits != null) { Microbit microbit = new Microbit(mbitConn); connectedMicrobits.put(microbitId, microbit); microbit.setConnected(); } } }; mbitConnectionThread.start(); final Thread oldThread = threadMap.put(microbitId, mbitConnectionThread); if (oldThread != null) { new Thread() { @Override public void run() { super.run(); oldThread.interrupt(); } }.start(); } } catch (Exception e) { Log.e("ConnectHBit", " Error while connecting to HBit " + e.getMessage()); } } } /** * @param robotType * @param robotId * @return */ private String disconnectFromRobot(RobotType robotType, final String robotId) { new Thread() { @Override public void run() { super.run(); Thread connThread = threadMap.get(robotId); if (connThread != null) connThread.interrupt(); } }.start(); if (robotType == RobotType.Hummingbird) { disconnectFromHummingbird(robotId); } else if (robotType == RobotType.Hummingbit) { disconnectFromHummingbit(robotId); } else { disconnectFromMicrobit(robotId); } hummingbirdsToConnect = new HashSet<>(); hummingbitsToConnect = new HashSet<>(); microbitsToConnect = new HashSet<>(); btHelper.stopScan(); runJavascript("CallbackManager.robot.updateStatus('" + bbxEncode(robotId) + "', false);"); Log.d("TotStat", "Connected Hummingbirds: " + connectedHummingbirds.toString()); Log.d("TotStat", "Connected Hummingbits: " + connectedHummingbits.toString()); Log.d("TotStat", "Connected Hummingbits: " + connectedMicrobits.toString()); return robotType.toString() + " disconnected successfully."; } /** * @param hummingbirdId */ public static void disconnectFromHummingbird(String hummingbirdId) { try { Hummingbird hummingbird = (Hummingbird) getRobotFromId(RobotType.Hummingbird, hummingbirdId); if (hummingbird != null) { hummingbird.disconnect(); if (hummingbird.getDisconnected()) { connectedHummingbirds.remove(hummingbirdId); } Log.d("TotStat", "Removing hummingbird: " + hummingbirdId); } else { BluetoothGatt curDeviceGatt = deviceGatt.get(hummingbirdId); if (curDeviceGatt != null) { curDeviceGatt.disconnect(); curDeviceGatt.close(); curDeviceGatt = null; if (deviceGatt.containsKey(hummingbirdId)) { deviceGatt.remove(hummingbirdId); } } } } catch (Exception e) { Log.e("ConnectHB", " Error while disconnecting from HB " + e.getMessage()); } } /** * @param hummingbitId */ public static void disconnectFromHummingbit(String hummingbitId) { try { Hummingbit hummingbit = (Hummingbit) getRobotFromId(RobotType.Hummingbit, hummingbitId); if (hummingbit != null) { hummingbit.disconnect(); if (hummingbit.getDisconnected()) { connectedHummingbits.remove(hummingbitId); } Log.d("TotStat", "Removing hummingbit: " + hummingbitId); } else { BluetoothGatt curDeviceGatt = deviceGatt.get(hummingbitId); if (curDeviceGatt != null) { curDeviceGatt.disconnect(); curDeviceGatt.close(); curDeviceGatt = null; if (deviceGatt.containsKey(hummingbitId)) { deviceGatt.remove(hummingbitId); } } } } catch (Exception e) { Log.e("ConnectHB", " Error while disconnecting from HB " + e.getMessage()); } } /** * @param microbitId */ public static void disconnectFromMicrobit(String microbitId) { try { Microbit microbit = (Microbit) getRobotFromId(RobotType.Microbit, microbitId); if (microbit != null) { microbit.disconnect(); if (microbit.getDisconnected()) { connectedMicrobits.remove(microbitId); } Log.d("TotStat", "Removing microbit: " + microbitId); } else { BluetoothGatt curDeviceGatt = deviceGatt.get(microbitId); if (curDeviceGatt != null) { curDeviceGatt.disconnect(); curDeviceGatt.close(); curDeviceGatt = null; if (deviceGatt.containsKey(microbitId)) { deviceGatt.remove(microbitId); } } } } catch (Exception e) { Log.e("ConnectHB", " Error while disconnecting from MB " + e.getMessage()); } } public static void disconnectAll() { hummingbirdsToConnect = null; hummingbitsToConnect = null; microbitsToConnect = null; if (connectedHummingbirds != null) { for (String individualHummingBird : connectedHummingbirds.keySet()) { disconnectFromHummingbird(individualHummingBird); } } if (connectedHummingbits != null) { for (String individualHummingBit : connectedHummingbits.keySet()) { disconnectFromHummingbit(individualHummingBit); } } if (connectedMicrobits != null) { for (String individualMicroBit : connectedMicrobits.keySet()) { disconnectFromMicrobit(individualMicroBit); } } } /** * @param robotType * @return */ private String getTotalStatus(RobotType robotType) { if (robotType == RobotType.Hummingbird) { return getTotalHBStatus(); } else if (robotType == RobotType.Hummingbit) { return getTotalHBitStatus(); } else { return getTotalMBitStatus(); } } /** * @return */ private String getTotalHBStatus() { Log.d("TotStat", "Connected Hummingbirds: " + connectedHummingbirds.toString()); if (connectedHummingbirds.size() == 0) { return "2"; // No hummingbirds connected } for (Hummingbird hummingbird : connectedHummingbirds.values()) { if (!hummingbird.isConnected()) { return "0"; // Some hummingbird is disconnected } } return "1"; // All hummingbirds are OK } /** * @return */ private String getTotalHBitStatus() { Log.d("TotStat", "Connected Hummingbits: " + connectedHummingbits.toString()); if (connectedHummingbits.size() == 0) { return "2"; // No hummingbits connected } for (Hummingbit hummingbit : connectedHummingbits.values()) { if (!hummingbit.isConnected()) { return "0"; // Some hummingbit is disconnected } } return "1"; // All hummingbits are OK } /** * @return */ private String getTotalMBitStatus() { Log.d("TotStat", "Connected Microbits: " + connectedMicrobits.toString()); if (connectedMicrobits.size() == 0) { return "2"; // No hummingbits connected } for (Microbit microbit : connectedMicrobits.values()) { if (!microbit.isConnected()) { return "0"; // Some hummingbit is disconnected } } return "1"; // All hummingbits are OK } private static String stopDiscover() { if (btHelper != null) btHelper.stopScan(); runJavascript("CallbackManager.robot.stopDiscover();"); return "Bluetooth discovery stopped."; } private String showRobotInfo(RobotType robotType, String robotId) { builder = new AlertDialog.Builder(mainWebViewContext); // Get details Robot robot = getRobotFromId(robotType, robotId); String name = robot.getName(); String macAddress = robot.getMacAddress(); String gapName = robot.getGAPName(); String hardwareVersion = ""; String firmwareVersion = ""; if (robotType == RobotType.Hummingbird) { hardwareVersion = ((Hummingbird) robot).getHardwareVersion(); firmwareVersion = ((Hummingbird) robot).getFirmwareVersion(); } else if (robotType == RobotType.Hummingbit) { hardwareVersion = ((Hummingbit) robot).getHardwareVersion(); firmwareVersion = "microBit: " + ((Hummingbit) robot).getMicroBitVersion() + "SMD: " + ((Hummingbit) robot).getSMDVersion(); } else if (robotType == RobotType.Microbit) { hardwareVersion = ((Microbit) robot).getHardwareVersion(); firmwareVersion = "microBit: " + ((Microbit) robot).getMicroBitVersion(); } builder.setTitle(robotType.toString() + " Peripheral"); String message = ""; if (name != null) message += ("Name: " + name + "\n"); if (macAddress != null) message += ("MAC Address: " + macAddress + "\n"); if (gapName != null) message += ("Bluetooth Name: " + gapName + "\n"); if (hardwareVersion != null) message += ("Hardware Version: " + hardwareVersion + "\n"); if (firmwareVersion != null) message += ("Firmware Version: " + firmwareVersion + "\n"); if (!robot.hasLatestFirmware()) message += ("\nFirmware update available."); builder.setMessage(message); builder.setCancelable(true); if (!robot.hasLatestFirmware()) { builder.setPositiveButton( "Update Firmware", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); showFirmwareUpdateInstructions(); } }); builder.setNegativeButton( "Dismiss", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); } else { builder.setNeutralButton( "Dismiss", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); } new Thread() { @Override public void run() { super.run(); new Handler(mainWebViewContext.getMainLooper()).post(new Runnable() { @Override public void run() { robotInfoDialog = builder.create(); robotInfoDialog.show(); } }); } }.start(); return "Successfully showed robot info."; } private static void showFirmwareUpdateInstructions() { mainWebViewContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(FIRMWARE_UPDATE_URL))); } /** * Resets the values of the peripherals of all connected hummingbirds * and microbits and hummingbits to their default values. */ private void stopAll() { for (Hummingbird hummingbird : connectedHummingbirds.values()) hummingbird.stopAll(); for (Hummingbit hummingbit : connectedHummingbits.values()) hummingbit.stopAll(); for (Microbit microbit : connectedMicrobits.values()) microbit.stopAll(); } }
BirdBrainTechnologies/BirdBlox-Android-Support
app/src/main/java/com/birdbraintechnologies/birdblox/httpservice/RequestHandlers/RobotRequestHandler.java
Java
mit
27,668
package org.xdevs23.management.config; public class SharedPreferenceArray { public static String getPreferenceString(String[] array) { if(array == null) return ""; if(array.length == 0) return ""; StringBuilder sb = new StringBuilder(); for ( String s : array) { String aps; if(s == null) return ""; else aps = s; if(s.contains(":")) aps = s.replace(":", "::"); if(s.contains("|")) aps = aps.replace("|", "||"); sb.append(aps).append("|:|"); } sb.delete(sb.length() - 3, sb.length()); return sb.toString(); } public static String[] getStringArray(String preferenceString) { if(preferenceString == null || preferenceString.isEmpty()) return new String[] {""}; String[] array = preferenceString.split("([|][:][|])"); for ( int i = 0; i < array.length; i++ ) { String aps = array[i]; if(aps.contains(":")) aps = aps.replace("::", ":"); if(aps.contains("|")) aps = aps.replace("||", "|"); array[i] = aps; } return array; } }
xdevs23/Cornowser
app/src/main/java/org/xdevs23/management/config/SharedPreferenceArray.java
Java
mit
1,173
package com.github.ddth.djs.message.queue; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import com.fasterxml.jackson.annotation.JsonIgnore; import com.github.ddth.djs.message.BaseJobMessage; import com.github.ddth.djs.utils.DjsConstants; /** * This message is put to queue when a job task is finished. * * @author Thanh Nguyen <btnguyen2k@gmail.com> * @since 0.1.3 */ public class TaskFinishMessage extends BaseJobMessage { private static final long serialVersionUID = 1L; public final long finishTimestamp = System.currentTimeMillis(); public final int status; public final String message, error; public final byte[] output; public TaskFinishMessage() { super(null); status = DjsConstants.TASK_STATUS_FINISHED_OK; message = null; error = null; output = null; } public TaskFinishMessage(TaskFireoffMessage taskFireoffMessage, int status, String message, String error, byte[] output) { super(taskFireoffMessage.id, taskFireoffMessage.jobInfo); this.status = status; this.message = message; this.error = error; this.output = output; } /** * {@inheritDoc} */ @Override public int hashCode() { HashCodeBuilder hcb = new HashCodeBuilder(19, 81); hcb.append(finishTimestamp).append(status).append(message).append(error).append(output) .appendSuper(super.hashCode()); return hcb.hashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof TaskFinishMessage) { TaskFinishMessage another = (TaskFinishMessage) obj; EqualsBuilder eq = new EqualsBuilder(); eq.appendSuper(super.equals(obj)).append(finishTimestamp, another.finishTimestamp) .append(status, another.status).append(message, another.message) .append(error, another.error).append(output, another.output); } return false; } protected final static String ATTR_FINISH_TIMESTAMP = "finish_timestamp"; protected final static String ATTR_STATUS = "status"; protected final static String ATTR_MESSAGE = "message"; protected final static String ATTR_ERROR = "error"; protected final static String ATTR_OUTPUT = "output"; @JsonIgnore private Lock LOCK = new ReentrantLock(); @JsonIgnore private Map<String, Object> dataAsMap = null; /** * Serializes mesage's attributes as a {@link Map}. * * @return */ public Map<String, Object> toMap() { if (dataAsMap == null) { LOCK.lock(); if (dataAsMap == null) { try { dataAsMap = new HashMap<>(); dataAsMap.putAll(super.toMap()); dataAsMap.put(ATTR_FINISH_TIMESTAMP, finishTimestamp); dataAsMap.put(ATTR_STATUS, status); dataAsMap.put(ATTR_MESSAGE, message); dataAsMap.put(ATTR_ERROR, error); dataAsMap.put(ATTR_OUTPUT, output); } finally { LOCK.unlock(); } } } return dataAsMap; } }
DDTH/djs-commons
src/main/java/com/github/ddth/djs/message/queue/TaskFinishMessage.java
Java
mit
3,552
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.gradle.tooling; import java.util.Set; public interface McpModelFG2 extends McpModel { String getMinecraftVersion(); Set<String> getMappingFiles(); }
DemonWav/MinecraftDevIntelliJ
src/gradle-tooling-extension/java/com/demonwav/mcdev/platform/mcp/gradle/tooling/McpModelFG2.java
Java
mit
325
#!/usr/bin/env python # coding=utf-8 __author__ = 'Jayin Ton' from flask import Flask, request, session, redirect, url_for app = Flask(__name__) host = '127.0.0.1' port = 8000 # 使用session 必须设置secret_key # set the secret key. keep this really secret: app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' @app.route('/') def index(): print session.__dict__ print session if 'username' in session: return 'Logged in as %s' % session['username'] return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return ''' <form action="" method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app.route('/see',methods=['GET']) def see(): print session.__dict__ print session return "see" @app.route('/logout') def logout(): if 'username' in session: # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) else: return ''' <p> Not logint yet</p> <p> Click</p><a href="./login">Here</a> to login! ''' if __name__ == '__main__': app.run(host=host, port=port, debug=True)
jayinton/FlaskDemo
simple/sessionTest.py
Python
mit
1,407
using StankinsInterfaces; using System; using System.Collections.Generic; using System.Text; namespace StanskinsImplementation { public class CommonData : ICommonData { public CommonData() { this.UTCDateReceived = DateTime.UtcNow; this.LocalDateReceived = DateTime.Now; this.DeviceName = Environment.MachineName; //this.UserName = Environment.UserDomainName; } public DateTime UTCDateReceived { get; protected set; } public DateTime LocalDateReceived { get; protected set; } public string UserName { get; protected set; } public string DeviceName { get; protected set; } public string DeviceType { get; protected set; } } }
ignatandrei/stankins
stankinsV1/StanskinsImplementation/CommonData.cs
C#
mit
768
class TrueClass def present? true end def blank? false end end
joshwetzel/existence
lib/existence/true_class.rb
Ruby
mit
80
<?php namespace ac\DataBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction($name) { return $this->render('acDataBundle:Default:index.html.twig', array('name' => $name)); } }
Codeperitus/cms
src/ac/DataBundle/Controller/DefaultController.php
PHP
mit
295
import {combineReducers} from 'redux'; import postValuesReducer from './post_values'; import ListReducer from './list_reducer'; import ForeignListReducer from './foreign_list_reducer'; import FuelReducer from './fuel_reducer'; import {reducer as formReducer} from 'redux-form'; const rootReducer = combineReducers({ postValues: postValuesReducer, routePoints: ListReducer, routeForeignPoints: ForeignListReducer, fuel: FuelReducer, form: formReducer }); export default rootReducer;
nadzins/riepas-react-redux
src/reducers/index.js
JavaScript
mit
504
require 'spec_helper' describe HolidayList::Params do before(:all) do Time.zone = 'Central Time (US & Canada)' new_time = Time.zone.local(2014, 1, 29, 12, 0, 0) Timecop.freeze(new_time) end after(:all) do Timecop.return end subject { HolidayList::Params.new('12345', options) } let(:options) { Hash.new } describe '#to_s' do before do subject.should_receive(:params_hash).and_return Hash.new end it 'calls #params_hash' do subject.to_s end end describe '#params_hash' do let(:params_hash) { subject.params_hash } it 'uses the passed in key' do expect(params_hash[:key]).to eq '12345' end it 'orders by startTime' do expect(params_hash[:orderBy]).to eq 'startTime' end it 'uses single events' do expect(params_hash[:singleEvents]).to be true end describe 'time ranges' do shared_examples 'customizable start and stop dates' do it 'uses a default start date of today' do expect(params_hash[:timeMin]).to eq start end it 'uses a default stop date of 1 year from now' do expect(params_hash[:timeMax]).to eq stop end end context 'with default start and stop dates' do let(:start) { DateTime.new(2014, 1, 29, 12, 0, 0, '-6') } let(:stop) { DateTime.new(2015, 1, 29, 12, 0, 0, '-6') } it_behaves_like 'customizable start and stop dates' end context 'with custom start and stop dates' do let(:start) { DateTime.new(2014, 2, 1) } let(:stop) { DateTime.new(2014, 2, 15) } let(:options) do { 'start' => start, 'stop' => stop } end it_behaves_like 'customizable start and stop dates' end context 'with invalid dates' do let(:start) { 'foo' } let(:stop) { 'bar' } let(:options) do { 'start' => start, 'stop' => stop } end it 'throws an error' do expect { params_hash[:timeMin] }.to raise_error ArgumentError end end context 'with stop date after start date' do let(:start) { DateTime.new(2014, 1, 29, 12, 0, 0, '-6') } let(:stop) { DateTime.new(2014, 1, 28, 18, 5, 10, '-6') } let(:options) do { 'start' => start, 'stop' => stop } end it 'throws an error' do expect { params_hash[:timeMin] }.to raise_error ArgumentError end end end end end
bhicks/holiday_list
spec/holiday_list/params_spec.rb
Ruby
mit
2,599
unless defined?(NameAndEmailValidator) class NameAndEmailValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) unless value =~ /\A(.+)?\s<([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})?>\Z/i record.errors[attribute] << (options[:message] || "is not a valid email address. Proper format is 'Name First <email@second.com>' separated by commas ") end end end end
AnnArborTees/acts_as_warnable
app/validators/name_and_email_validator.rb
Ruby
mit
413
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License #include "mxtest/control/CompileControl.h" #ifdef MX_COMPILE_CORE_TESTS #include "cpul/cpulTestHarness.h" #include "mxtest/core/HelperFunctions.h" #include "mxtest/core/SystemLayoutTest.h" #include "mxtest/core/SystemMarginsTest.h" #include "mxtest/core/SystemDividersTest.h" using namespace mx::core; using namespace std; using namespace mxtest; TEST( Test01, SystemLayout ) { TestMode v = TestMode::one; SystemLayoutPtr object = tgenSystemLayout( v ); stringstream expected; tgenSystemLayoutExpected( expected, 1, v ); stringstream actual; // object->toStream( std::cout, 1 ); object->toStream( actual, 1 ); CHECK_EQUAL( expected.str(), actual.str() ) CHECK( ! object->hasAttributes() ) CHECK( ! object->hasContents() ) } TEST( Test02, SystemLayout ) { TestMode v = TestMode::two; SystemLayoutPtr object = tgenSystemLayout( v ); stringstream expected; tgenSystemLayoutExpected( expected, 1, v ); stringstream actual; // object->toStream( std::cout, 1 ); object->toStream( actual, 1 ); CHECK_EQUAL( expected.str(), actual.str() ) CHECK( ! object->hasAttributes() ) CHECK( object->hasContents() ) } TEST( Test03, SystemLayout ) { TestMode v = TestMode::three; SystemLayoutPtr object = tgenSystemLayout( v ); stringstream expected; tgenSystemLayoutExpected( expected, 1, v ); stringstream actual; // object->toStream( std::cout, 1 ); object->toStream( actual, 1 ); CHECK_EQUAL( expected.str(), actual.str() ) CHECK( ! object->hasAttributes() ) CHECK( object->hasContents() ) } namespace mxtest { SystemLayoutPtr tgenSystemLayout( TestMode v ) { SystemLayoutPtr o = makeSystemLayout(); switch ( v ) { case TestMode::one: { } break; case TestMode::two: { o->setHasSystemMargins( true ); o->setSystemMargins( tgenSystemMargins( v ) ); o->setHasTopSystemDistance( true ); o->getTopSystemDistance()->setValue( TenthsValue( 1.1 ) ); o->setHasSystemDistance( true ); o->getSystemDistance()->setValue( TenthsValue( 2.2 ) ); o->setHasSystemDividers( true ); o->setSystemDividers( tgenSystemDividers( v ) ); } break; case TestMode::three: { o->setHasSystemMargins( true ); o->setSystemMargins( tgenSystemMargins( v ) ); o->setHasTopSystemDistance( true ); o->getTopSystemDistance()->setValue( TenthsValue( 3.3 ) ); o->setHasSystemDistance( true ); o->getSystemDistance()->setValue( TenthsValue( 4.4 ) ); } break; default: break; } return o; } void tgenSystemLayoutExpected(std::ostream& os, int i, TestMode v ) { switch ( v ) { case TestMode::one: { streamLine( os, i, R"(<system-layout/>)", false ); } break; case TestMode::two: { streamLine( os, i, R"(<system-layout>)" ); tgenSystemMarginsExpected( os, i+1, v ); os << std::endl; streamLine( os, i+1, R"(<system-distance>2.2</system-distance>)" ); streamLine( os, i+1, R"(<top-system-distance>1.1</top-system-distance>)" ); tgenSystemDividersExpected( os, i+1, v ); os << std::endl; streamLine( os, i, R"(</system-layout>)", false ); } break; case TestMode::three: { streamLine( os, i, R"(<system-layout>)" ); tgenSystemMarginsExpected( os, i+1, v ); os << std::endl; streamLine( os, i+1, R"(<system-distance>4.4</system-distance>)" ); streamLine( os, i+1, R"(<top-system-distance>3.3</top-system-distance>)" ); streamLine( os, i, R"(</system-layout>)", false ); } break; default: break; } } } #endif
Webern/MusicXML-Class-Library
Sourcecode/private/mxtest/core/SystemLayoutTest.cpp
C++
mit
4,339
#pragma once #include <QWidget> #include <QListWidget> #include <QMainWindow> #include <QMenu> #include "../data/array.hpp" #include "../data/data_source.hpp" #include "../json/json.hpp" #include <list> namespace datavis { using std::list; using nlohmann::json; class DataSet; class PlotView; class PlotGridView; class Plot; class LinePlot; class DataLibrary; class DataLibraryView; class PlotDataSettingsView; class MainWindow : public QMainWindow { public: MainWindow(QWidget * parent = 0); void openFile(const QString & path); void openData(); void openDataFile(const QString & file_path); void saveProject(); void saveProjectAs(); void saveProjectFile(const QString & path); void openProject(); void openProjectFile(const QString & file_path); bool closeProject(); protected: virtual void dragEnterEvent(QDragEnterEvent *event); virtual void dropEvent(QDropEvent *event); virtual void closeEvent(QCloseEvent *event); private: void makeMenu(); void onOpenFailed(const QString & path, const QString & reason); void onSelectedDataChanged(); bool hasSelectedObject(); void plotSelectedObject(); PlotGridView * addPlotView(); void removePlotView(PlotGridView*); void plot(DataSource *, const string & id); Plot * makePlot(DataSource *, const string & datasetId); void restorePlot(PlotGridView *, const json & state); void removeSelectedPlot(); void onDatasetDroppedOnPlotView(const QVariant &); bool eventFilter(QObject*, QEvent*) override; void showPlotContextMenu(Plot*, const QPoint & pos); QString m_project_file_path; DataLibrary * m_lib = nullptr; DataLibraryView * m_lib_view = nullptr; list<PlotGridView*> m_plot_views; PlotGridView * m_selected_plot_view = nullptr; Plot * m_selected_plot = nullptr; QMenu * m_plot_context_menu = nullptr; }; }
jleben/datavis
app/main_window.hpp
C++
mit
1,907
// File generated from our OpenAPI spec package com.stripe.param; import com.google.gson.annotations.SerializedName; import com.stripe.net.ApiRequestParams; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.Getter; @Getter public class InvoiceItemListParams extends ApiRequestParams { @SerializedName("created") Object created; /** * The identifier of the customer whose invoice items to return. If none is provided, all invoice * items will be returned. */ @SerializedName("customer") String customer; /** * A cursor for use in pagination. {@code ending_before} is an object ID that defines your place * in the list. For instance, if you make a list request and receive 100 objects, starting with * {@code obj_bar}, your subsequent call can include {@code ending_before=obj_bar} in order to * fetch the previous page of the list. */ @SerializedName("ending_before") String endingBefore; /** Specifies which fields in the response should be expanded. */ @SerializedName("expand") List<String> expand; /** * Map of extra parameters for custom features not available in this client library. The content * in this map is not serialized under this field's {@code @SerializedName} value. Instead, each * key/value pair is serialized as if the key is a root-level field (serialized) name in this * param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; /** * Only return invoice items belonging to this invoice. If none is provided, all invoice items * will be returned. If specifying an invoice, no customer identifier is needed. */ @SerializedName("invoice") String invoice; /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the * default is 10. */ @SerializedName("limit") Long limit; /** * Set to {@code true} to only show pending invoice items, which are not yet attached to any * invoices. Set to {@code false} to only show invoice items already attached to invoices. If * unspecified, no filter is applied. */ @SerializedName("pending") Boolean pending; /** * A cursor for use in pagination. {@code starting_after} is an object ID that defines your place * in the list. For instance, if you make a list request and receive 100 objects, ending with * {@code obj_foo}, your subsequent call can include {@code starting_after=obj_foo} in order to * fetch the next page of the list. */ @SerializedName("starting_after") String startingAfter; private InvoiceItemListParams( Object created, String customer, String endingBefore, List<String> expand, Map<String, Object> extraParams, String invoice, Long limit, Boolean pending, String startingAfter) { this.created = created; this.customer = customer; this.endingBefore = endingBefore; this.expand = expand; this.extraParams = extraParams; this.invoice = invoice; this.limit = limit; this.pending = pending; this.startingAfter = startingAfter; } public static Builder builder() { return new Builder(); } public static class Builder { private Object created; private String customer; private String endingBefore; private List<String> expand; private Map<String, Object> extraParams; private String invoice; private Long limit; private Boolean pending; private String startingAfter; /** Finalize and obtain parameter instance from this builder. */ public InvoiceItemListParams build() { return new InvoiceItemListParams( this.created, this.customer, this.endingBefore, this.expand, this.extraParams, this.invoice, this.limit, this.pending, this.startingAfter); } public Builder setCreated(Created created) { this.created = created; return this; } public Builder setCreated(Long created) { this.created = created; return this; } /** * The identifier of the customer whose invoice items to return. If none is provided, all * invoice items will be returned. */ public Builder setCustomer(String customer) { this.customer = customer; return this; } /** * A cursor for use in pagination. {@code ending_before} is an object ID that defines your place * in the list. For instance, if you make a list request and receive 100 objects, starting with * {@code obj_bar}, your subsequent call can include {@code ending_before=obj_bar} in order to * fetch the previous page of the list. */ public Builder setEndingBefore(String endingBefore) { this.endingBefore = endingBefore; return this; } /** * Add an element to `expand` list. A list is initialized for the first `add/addAll` call, and * subsequent calls adds additional elements to the original list. See {@link * InvoiceItemListParams#expand} for the field documentation. */ public Builder addExpand(String element) { if (this.expand == null) { this.expand = new ArrayList<>(); } this.expand.add(element); return this; } /** * Add all elements to `expand` list. A list is initialized for the first `add/addAll` call, and * subsequent calls adds additional elements to the original list. See {@link * InvoiceItemListParams#expand} for the field documentation. */ public Builder addAllExpand(List<String> elements) { if (this.expand == null) { this.expand = new ArrayList<>(); } this.expand.addAll(elements); return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * InvoiceItemListParams#extraParams} for the field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link InvoiceItemListParams#extraParams} for the field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** * Only return invoice items belonging to this invoice. If none is provided, all invoice items * will be returned. If specifying an invoice, no customer identifier is needed. */ public Builder setInvoice(String invoice) { this.invoice = invoice; return this; } /** * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the * default is 10. */ public Builder setLimit(Long limit) { this.limit = limit; return this; } /** * Set to {@code true} to only show pending invoice items, which are not yet attached to any * invoices. Set to {@code false} to only show invoice items already attached to invoices. If * unspecified, no filter is applied. */ public Builder setPending(Boolean pending) { this.pending = pending; return this; } /** * A cursor for use in pagination. {@code starting_after} is an object ID that defines your * place in the list. For instance, if you make a list request and receive 100 objects, ending * with {@code obj_foo}, your subsequent call can include {@code starting_after=obj_foo} in * order to fetch the next page of the list. */ public Builder setStartingAfter(String startingAfter) { this.startingAfter = startingAfter; return this; } } @Getter public static class Created { /** * Map of extra parameters for custom features not available in this client library. The content * in this map is not serialized under this field's {@code @SerializedName} value. Instead, each * key/value pair is serialized as if the key is a root-level field (serialized) name in this * param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; /** Minimum value to filter by (exclusive). */ @SerializedName("gt") Long gt; /** Minimum value to filter by (inclusive). */ @SerializedName("gte") Long gte; /** Maximum value to filter by (exclusive). */ @SerializedName("lt") Long lt; /** Maximum value to filter by (inclusive). */ @SerializedName("lte") Long lte; private Created(Map<String, Object> extraParams, Long gt, Long gte, Long lt, Long lte) { this.extraParams = extraParams; this.gt = gt; this.gte = gte; this.lt = lt; this.lte = lte; } public static Builder builder() { return new Builder(); } public static class Builder { private Map<String, Object> extraParams; private Long gt; private Long gte; private Long lt; private Long lte; /** Finalize and obtain parameter instance from this builder. */ public Created build() { return new Created(this.extraParams, this.gt, this.gte, this.lt, this.lte); } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * InvoiceItemListParams.Created#extraParams} for the field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link InvoiceItemListParams.Created#extraParams} for the field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** Minimum value to filter by (exclusive). */ public Builder setGt(Long gt) { this.gt = gt; return this; } /** Minimum value to filter by (inclusive). */ public Builder setGte(Long gte) { this.gte = gte; return this; } /** Maximum value to filter by (exclusive). */ public Builder setLt(Long lt) { this.lt = lt; return this; } /** Maximum value to filter by (inclusive). */ public Builder setLte(Long lte) { this.lte = lte; return this; } } } }
stripe/stripe-java
src/main/java/com/stripe/param/InvoiceItemListParams.java
Java
mit
11,499
#region License // Pomona is open source software released under the terms of the LICENSE specified in the // project's repository, or alternatively at http://pomona.io/ #endregion namespace Pomona.Common.Serialization { public enum DeserializerNodeOperation { Default, Post, Patch, Delete, Put } }
Pomona/Pomona
app/Pomona.Common/Serialization/DeserializerNodeOperation.cs
C#
mit
353
<?php namespace Hotfix\Datatables; use DateTime; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Str; use Illuminate\View\Compilers\BladeCompiler; class Helper { /** * Places item of extra columns into results by care of their order. * * @param $item * @param $array * @return array */ public static function includeInArray($item, $array) { if ($item['order'] === false) { return array_merge($array, [$item['name'] => $item['content']]); } else { $count = 0; $last = $array; $first = []; foreach ($array as $key => $value) { if ($count == $item['order']) { return array_merge($first, [$item['name'] => $item['content']], $last); } unset($last[$key]); $first[$key] = $value; $count++; } } } /** * Determines if content is callable or blade string, processes and returns. * * @param string|callable $content Pre-processed content * @param array $data data to use with blade template * @param mixed $param parameter to call with callable * @return string Processed content */ public static function compileContent($content, array $data, $param) { if (is_string($content)) { return static::compileBlade($content, static::getMixedValue($data, $param)); } elseif (is_callable($content)) { return $content($param); } return $content; } /** * Parses and compiles strings by using Blade Template System. * * @param string $str * @param array $data * @return string * @throws \Exception */ public static function compileBlade($str, $data = []) { if (view()->exists($str)) { return view($str, $data)->render(); } $empty_filesystem_instance = new Filesystem(); $blade = new BladeCompiler($empty_filesystem_instance, 'datatables'); $parsed_string = $blade->compileString($str); ob_start() && extract($data, EXTR_SKIP); try { eval('?>' . $parsed_string); } catch (\Exception $e) { ob_end_clean(); throw $e; } $str = ob_get_contents(); ob_end_clean(); return $str; } /** * @param array $data * @param mixed $param * @return array */ public static function getMixedValue(array $data, $param) { $param = self::castToArray($param); foreach ($data as $key => $value) { if (isset($param[$key])) { $data[$key] = $param[$key]; } } return $data; } /** * @param $param * @return array */ public static function castToArray($param) { if ($param instanceof \stdClass) { $param = (array) $param; return $param; } return $param; } /** * Get equivalent or method of query builder. * * @param string $method * @return string */ public static function getOrMethod($method) { if (! Str::contains(Str::lower($method), 'or')) { return 'or' . ucfirst($method); } return $method; } /** * Wrap value depending on database type. * * @param string $database * @param string $value * @return string */ public static function wrapDatabaseValue($database, $value) { $parts = explode('.', $value); $column = ''; foreach ($parts as $key) { $column = static::wrapDatabaseColumn($database, $key, $column); } return substr($column, 0, strlen($column) - 1); } /** * Database column wrapper * * @param string $database * @param string $key * @param string $column * @return string */ public static function wrapDatabaseColumn($database, $key, $column) { switch ($database) { case 'mysql': $column .= '`' . str_replace('`', '``', $key) . '`' . '.'; break; case 'sqlsrv': $column .= '[' . str_replace(']', ']]', $key) . ']' . '.'; break; case 'pgsql': case 'sqlite': $column .= '"' . str_replace('"', '""', $key) . '"' . '.'; break; default: $column .= $key . '.'; } return $column; } /** * Converts array object values to associative array. * * @param mixed $row * @return array */ public static function convertToArray($row) { $data = $row instanceof Arrayable ? $row->toArray() : (array) $row; foreach (array_keys($data) as $key) { if (is_object($data[$key]) || is_array($data[$key])) { $data[$key] = self::convertToArray($data[$key]); } } return $data; } /** * @param array $data * @return array */ public static function transform(array $data) { return array_map(function ($row) { return self::transformRow($row); }, $data); } /** * @param $row * @return mixed */ protected static function transformRow($row) { foreach ($row as $key => $value) { if ($value instanceof DateTime) { $row[$key] = $value->format('Y-m-d H:i:s'); } else { if (is_string($value)) { $row[$key] = (string) $value; } else { $row[$key] = $value; } } } return $row; } /** * Build parameters depending on # of arguments passed. * * @param array $args * @return array */ public static function buildParameters(array $args) { $parameters = []; if (count($args) > 2) { $parameters[] = $args[0]; foreach ($args[1] as $param) { $parameters[] = $param; } } else { foreach ($args[0] as $param) { $parameters[] = $param; } } return $parameters; } /** * Replace all pattern occurrences with keyword * * @param array $subject * @param string $keyword * @param string $pattern * @return array */ public static function replacePatternWithKeyword(array $subject, $keyword, $pattern = '$1') { $parameters = []; foreach ($subject as $param) { if (is_array($param)) { $parameters[] = self::replacePatternWithKeyword($param, $keyword, $pattern); } else { $parameters[] = str_replace($pattern, $keyword, $param); } } return $parameters; } }
hotfix31/lumen-datatables
src/Helper.php
PHP
mit
7,124
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using BolfTracker.Models; namespace BolfTracker.Infrastructure.EntityFramework { public class PlayerGameStatisticsConfiguration : EntityTypeConfiguration<PlayerGameStatistics> { public PlayerGameStatisticsConfiguration() { HasKey(pgs => pgs.Id); Property(pgs => pgs.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); Property(pgs => pgs.ShootingPercentage).HasPrecision(18, 3); HasRequired(pgs => pgs.Game).WithMany(g => g.PlayerGameStatistics).Map(pgs => pgs.MapKey("GameId")); HasRequired(pgs => pgs.Player).WithMany(p => p.PlayerGameStatistics).Map(pgs => pgs.MapKey("PlayerId")); ToTable("PlayerGameStatistics"); } } }
mkchandler/bolf-tracker-mvc
src/BolfTracker.Infrastructure.EntityFramework/Configuration/PlayerGameStatisticsConfiguration.cs
C#
mit
874
<?php /** * Author: Nil Portugués Calderó <contact@nilportugues.com> * Date: 29/03/16 * Time: 23:03. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace NilPortugues\Tests\MessageBus\EventBus; use NilPortugues\MessageBus\EventBus\EventBusMiddleware; use NilPortugues\MessageBus\EventBus\Resolver\SimpleArrayResolver; use NilPortugues\MessageBus\EventBus\Translator\EventFullyQualifiedClassNameStrategy; class EventBusMiddlewareTest extends \PHPUnit_Framework_TestCase { /** @var EventBusMiddleware */ protected $eventBus; public function setUp() { $handlers = [ DummyEventHandler::class => function () { return new DummyEventHandler(); }, ]; $this->eventBus = new EventBusMiddleware( new EventFullyQualifiedClassNameStrategy([DummyEventHandler::class]), new SimpleArrayResolver($handlers) ); } public function testItCanHandle() { $this->eventBus->__invoke(new DummyEvent(), function () { return; }); $this->assertTrue(true); } }
PHPMessageBus/messagebus
tests/EventBus/EventBusMiddlewareTest.php
PHP
mit
1,196
<?php namespace Pingpp; /** * 结算账户对象 * Class SettleAccount * @package Pingpp */ class SettleAccount extends UserBase { public static function classUrlWithUserId($user_id) { return User::instanceUrlWithId($user_id) . '/settle_accounts'; } public static function instanceUrlWithSettleAccountId($user_id, $settle_account_id) { $user_id = Util\Util::utf8($user_id); $base = static::classUrlWithUserId($user_id); $settle_account_id = urlencode($settle_account_id); return $base . '/' . $settle_account_id; } /** * 创建结算账户对象 * @param $user_id * @param $params * @param $options * @return SettleAccount */ public static function create($user_id, $params, $options = null) { $url = static::classUrlWithUserId($user_id); return static::_directRequest('post', $url, $params, $options); } /** * 查询结算账户对象 * @param $user_id * @param $settle_account_id * @param null $params * @return SettleAccount */ public static function retrieve($user_id, $settle_account_id, $params = null, $options = null) { $url = static::instanceUrlWithSettleAccountId($user_id, $settle_account_id); return static::_directRequest('get', $url, $params, $options); } /** * 删除结算账户对象 * @param $user_id * @param $settle_account_id * @param $params * @return SettleAccount */ public static function delete($user_id, $settle_account_id) { $url = static::instanceUrlWithSettleAccountId($user_id, $settle_account_id); return static::_directRequest('delete', $url); } /** * 查询结算账户对象列表 * @param $user_id * @param null $params * @return SettleAccount */ public static function all($user_id, $params = null) { $url = static::classUrlWithUserId($user_id); return static::_directRequest('get', $url, $params); } /** * 更新结算账户对象(存管相关) * * @param string $user_id 用户 ID * @param string $settle_account_id 结算账户 ID * @param array $params 需要更新的数据 * @return SettleAccount */ public static function update($user_id, $settle_account_id, $params, $options = null) { $url = static::instanceUrlWithSettleAccountId($user_id, $settle_account_id); return static::_directRequest('put', $url, $params, $options); } /** * 更新手机号(存管相关) * * @param string $user_id 用户 ID * @param string $settle_account_id 结算账户 ID * @param array $params 手机号数据 * @return SettleAccount */ public static function updateMobile($user_id, $settle_account_id, $params, $options = null) { $url = static::instanceUrlWithSettleAccountId($user_id, $settle_account_id) . "/mobile"; return static::_directRequest('put', $url, $params, $options); } /** * 打款验证(存管相关) * * @param string $user_id 用户 ID * @param string $settle_account_id 结算账户 ID * @param array $params 验证数据 * @return SettleAccount */ public static function verify($user_id, $settle_account_id, $params, $options = null) { $url = static::instanceUrlWithSettleAccountId($user_id, $settle_account_id) . "/verify"; return static::_directRequest('post', $url, $params, $options); } }
PingPlusPlus/pingpp-php
lib/SettleAccount.php
PHP
mit
3,574
// 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. namespace Fixtures.Azure.AcceptanceTestsHead { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestHeadTestService : ServiceClient<AutoRestHeadTestService>, IAutoRestHeadTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IHttpSuccessOperations. /// </summary> public virtual IHttpSuccessOperations HttpSuccess { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestHeadTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestHeadTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestHeadTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestHeadTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestHeadTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestHeadTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestHeadTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestHeadTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.HttpSuccess = new HttpSuccessOperations(this); this.BaseUri = new Uri("http://localhost"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
John-Hart/autorest
src/generator/AutoRest.CSharp.Azure.Tests/Expected/AcceptanceTests/Head/AutoRestHeadTestService.cs
C#
mit
12,059
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var angular2_1 = require("angular2/angular2"); var GdgHeader = (function () { function GdgHeader() { } GdgHeader = __decorate([ angular2_1.Component({ selector: "gdg-header", properties: ["title"] }), angular2_1.View({ templateUrl: "./app/components/header/header.html" }), __metadata('design:paramtypes', []) ], GdgHeader); return GdgHeader; })(); exports.GdgHeader = GdgHeader;
GDGAracaju/gdg.ninjas
src/app/components/header/header.js
JavaScript
mit
1,252
using UnityEngine; public interface IDamageable { void TakeHit(float damage, Vector3 hitPoint, Vector3 hitDirection); void TakeDamage(float damage); }
daltonbr/TopDownShooter
Assets/Scripts/IDamageable.cs
C#
mit
161
module Houdini module PostbackProcessor EnvironmentMismatchError = Class.new RuntimeError APIKeyMistmatchError = Class.new RuntimeError def self.process(class_name, model_id, params) task_manager = params.delete(:task_manager) || TaskManager if params[:environment] != Houdini.environment raise EnvironmentMismatchError, "Environment received does not match Houdini.environment" end if params[:api_key] != Houdini.api_key raise APIKeyMistmatchError, "API key received doesn't match our API key." end task_manager.process class_name, model_id, params[:blueprint], params[:output], params[:verbose_output] end end end
chrisconley/houdini-gem
lib/houdini/postback_processor.rb
Ruby
mit
696
<?php namespace AppBundle\Entity; use PUGX\MultiUserBundle\Validator\Constraints\UniqueEntity; use Symfony\Component\Validator\Constraints as Assert; use Vich\UploaderBundle\Mapping\Annotation as Vich; use Doctrine\Common\Collections\ArrayCollection; use Symfony\Component\HttpFoundation\File\File; use Doctrine\ORM\Mapping as ORM; use DateTime; /** * @ORM\Entity * @ORM\Table(name="user_employer") * @ORM\Entity(repositoryClass="AppBundle\Repository\UserEmployerRepository") * @UniqueEntity(fields = "username", targetClass = "AppBundle\Entity\User", message="fos_user.username.already_used") * @UniqueEntity(fields = "email", targetClass = "AppBundle\Entity\User", message="Vartotojas su tokiu adresu jau yra") * @Vich\Uploadable */ class UserEmployer extends User { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string") * @Assert\NotBlank(message = "Įrašykite įmonės pavadinimą") * @Assert\Length(max=55) */ private $title; /** * @ORM\Column(type="text", nullable=true) */ private $description; /** * Many UserEmployer has One Sector. * @ORM\ManyToOne(targetEntity="Sector") * @ORM\JoinColumn(name="sector", referencedColumnName="id") */ private $sector; /** * @ORM\Column(type="string", nullable=true) * @Assert\Length(max=12) */ private $phone; /** * NOTE: This is not a mapped field of entity metadata, just a simple property. * @Vich\UploadableField(mapping="employer_logo", fileNameProperty="photo") * @var File * * @Assert\Image( * maxSize = "1660Ki" * ) */ private $imageFile; /** * @ORM\Column(type="string", nullable=true) */ private $photo; /** * @ORM\Column(type="string", nullable=true) * @Assert\Length(max=55) */ private $city; /** * @ORM\Column(type="datetime", nullable=true) * * @var \DateTime */ private $updatedAt; /** * One UserEmployer has Many JobAd. * @ORM\OneToMany(targetEntity="JobAd", mappedBy="employer") * * @var ArrayCollection|JobAd[] */ private $jobAds; /** * @ORM\Column(name="legal_code", type="string") * @Assert\NotBlank() * @Assert\Length( * min=7, * max=9 * ) */ private $legalEntitysCode; public function __construct() { parent::__construct(); $this->jobAds = new ArrayCollection(); } // *** Getters and setters *** /** * @return int */ public function getId() { return $this->id; } /** * @return string */ public function getTitle() { return $this->title; } /** * @param string $title * @return UserEmployer */ public function setTitle($title) { $this->title = $title; return $this; } /** * @return string */ public function getDescription() { return $this->description; } /** * @param string $description * @return UserEmployer */ public function setDescription($description) { $this->description = $description; return $this; } /** * @return string */ public function getSector() { return $this->sector; } /** * @param string $sector * @return UserEmployer */ public function setSector($sector) { $this->sector = $sector; return $this; } /** * @return string */ public function getPhone() { return $this->phone; } /** * @param string $phone * @return UserEmployer */ public function setPhone($phone) { $this->phone = $phone; return $this; } /** * @return string */ public function getPhoto() { return $this->photo; } /** * @param string $photo * @return UserEmployer */ public function setPhoto($photo) { $this->photo = $photo; return $this; } /** * @return string */ public function getCity() { return $this->city; } /** * @param string $city * @return UserEmployer */ public function setCity($city) { $this->city = $city; return $this; } // File upload /** * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image * * @return UserEmployer */ public function setImageFile(File $image = null) { $this->imageFile = $image; if ($image) { // It is required that at least one field changes if you are using doctrine // otherwise the event listeners won't be called and the file is lost $this->updatedAt = new \DateTimeImmutable(); } return $this; } /** * @return File|null */ public function getImageFile() { return $this->imageFile; } /** * @return DateTime */ public function getUpdatedAt() { return $this->updatedAt; } /** * @param DateTime $updatedAt * @return UserEmployer */ public function setUpdatedAt($updatedAt) { $this->updatedAt = $updatedAt; return $this; } /** * @return ArrayCollection */ public function getJobAd() { return $this->jobAds; } /** * @param JobAd $jobAd * @return UserEmployer */ public function setJobAd($jobAd) { $this->jobAds = $jobAd; return $this; } /** * @param string $legalEntitysCode * @return UserEmployer */ public function setlegalEntitysCode($legalEntitysCode) { $this->legalEntitysCode = $legalEntitysCode; return $this; } /** * @return string */ public function getlegalEntitysCode() { return $this->legalEntitysCode; } }
arvyjaar/cv
src/AppBundle/Entity/UserEmployer.php
PHP
mit
6,131
<br> <br> <?php $deporte[]='Deporte*'; foreach ($datos as $dato) { $deporte[$dato->nombre]=$dato->nombre; } foreach ($usuarios as $usuario){ $nombre=(isset($nombre)) ? $nombre=$nombre : $nombre= $usuario->nombre; $apellidos=(isset($apellidos)) ? $apellidos=$apellidos : $apellidos=$usuario->apellidos; $ciudad=(isset($ciudad)) ? $ciudad=$ciudad : $ciudad=$usuario->ciudad; $correo=(isset($correo)) ? $correo=$correo : $correo=$usuario->correo; $nombre_usuario=(isset($nombre_usuario)) ? $nombre_usuario=$nombre_usuario : $nombre_usuario=$usuario->nombre_usuario; $contraseña=(isset($contraseña)) ? $contraseña=$contraseña : $contraseña=$usuario->contraseña; $repetir_contraseña=(isset($repetir_contraseña)) ? $repetir_contraseña=$repetir_contraseña : $repetir_contraseña=$usuario->contraseña; $deporte1=(isset($deporte1)) ? $deporte1=$deporte1 : $deporte1=$usuario->deporte; } $nom = array( 'name' => 'nombre', 'value' => $nombre, 'placeholder' =>'Nombre*', 'class' => 'form-control', ); $ape = array( 'name' => 'apellidos', 'value' => $apellidos, 'placeholder' =>'Apellidos*', 'class' => 'form-control', ); $ciu = array( 'name' => 'ciudad', 'value' => $ciudad, 'placeholder' =>'Ciudad*', 'class' => 'form-control', ); $cor = array( 'name' => 'correo', 'value' => $correo, 'placeholder' =>'Correo electrónico*', 'class' => 'form-control', ); $nomU = array( 'name' => 'nombre_usuario', 'value' => $nombre_usuario, 'placeholder' =>'Nombre de Usuario*', 'class' => 'form-control', ); $cont = array( 'name' => 'contraseña', 'value' => $contraseña, 'placeholder' =>'Contraseña*', 'class' => 'form-control', ); $rcont = array( 'name' => 'repetir_contrasena', 'value' => $repetir_contraseña, 'placeholder' =>'Repetir Contraseña*', 'class' => 'form-control', ); ?> <div class='container'> <div class="row" style="background: rgba(255, 255, 255, .8)"> <div class="col-md-7"> <p><h1>Editar Perfil</h1></p> <?= form_open('ControladorUsuario/guardar_cambios'); ?> <?php echo validation_errors(); ?> <table border="0"> <tr> <td><?= form_input($nom, ['id'=>'nombre']); ?></td> <td><?= form_input($ape, ['id'=>'apellidos']); ?></td> </tr> <tr> <td><?= form_input($ciu, ['id'=>'ciudad']); ?></td> <td><?= form_dropdown('deporte', $deporte, $deporte1, 'class="form-control"', ['id'=>'deporte']) ?> </td> </tr> <tr> <td><?= form_input($cor, ['id'=>'correo']); ?></td> <td><?= form_input($nomU,['id'=>'nombre_usuario']); ?></td> </tr> <tr> <td><?= form_password($cont, ['id'=>'contraseña']); ?></td> <td><?= form_password($rcont, ['id'=>'repetir_contrasena']); ?></td> </tr> </table> <br> <p class="help-block"> La contraseña debe tener por lo menos 1 letra en mayúscula, <br> 1 en minúscula, 1 digito y 1 caracter especial y tener una longitud mayor o igual a 7</p> <?= form_submit('sbm', 'Guardar', 'class="btn btn-primary"'); ?> <?= form_close(); ?> <?php if(isset($mensaje)): echo $mensaje; endif; ?> </div> </div> </div>
albeiroep/sportremind
application/views/editar_perfil_vista.php
PHP
mit
3,710
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; /* |-------------------------------------------------------------------------- | API (Client Credentials) Routes |-------------------------------------------------------------------------- | | For API requests that use a token from the OAuth client_credentials flow | -- Important: All requests to these routes must include a HTTP header | -- X-Api-UsesClientCredentials = 1 | */ Route::get('version', function () { return response()->json(['version' => 'Flares API (client credentials) v2'], 200); }); Route::group(['middleware' => 'clientCredentials:manage-sso'], function() { Route::post('usersso/{userId}/link', 'UserSSOController@provisionSSO')->name('link'); Route::resource('usersso', 'UserSSOController', ['only' => ['store', 'destroy']]); }); Route::group(['middleware' => 'clientCredentials:submit-decorations'], function() { Route::resource('approval', 'DecorationApprovalController', ['only' => ['index', 'store']]); }); Route::group(['middleware' => 'clientCredentials:sync-members'], function() { Route::post('membersync', 'MemberSyncController@sync'); Route::post('membersync/presync', 'MemberSyncController@presync'); });
alansfyeung/FLARES
routes/api-clientcred.php
PHP
mit
1,239
/*(function() { 'use strict'; angular.module('myApp', []).controller('VideoListController', function($http, $log) { var ctrl = this; ctrl.query = 'Rick Astley'; ctrl.search = function() { return $http.get('https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=20&type=video&q=' + ctrl.query + '&key=AIzaSyD4YJITOWdfQdFbcxHc6TgeCKmVS9yRuQ8') .then(function(res) { $log.info(res.data.items); ctrl.videos = res.data.items.map(function (v) { var snip = v.snippet; return { title: snip.title, description: snip.description, thumb: snip.thumbnails.medium.url, link: 'https://www.youtube.com/watch?v=' + v.id.videoId }; }); }); } ctrl.search(); }); })();*/
rasmusvhansen/angularjs-foundation-course
exercises/03Controllers/app2.js
JavaScript
mit
884
import React, { PropTypes } from 'react'; import CSSModules from 'react-css-modules'; // Styles import styles from './index.scss'; const propTypes = { crises: PropTypes.array.isRequired, }; const CrisisArchiveList = ({ crises }) => ( <div styleName='CrisisArchiveList'> <h1> All Crises </h1> <ul> {crises.map((crisis, i) => { const crisisStatusText = crisis.status === 'ARC' ? 'archived' : 'active'; return ( <li styleName={crisisStatusText} key={i} > <div styleName='header'> {crisis.title} </div> <div styleName='body'> <span>{crisis.incidents.length} incidents</span> {crisis.description && <div styleName='description'> Description: {crisis.description} </div> } </div> <div styleName='footer'> <span styleName='tag'> {crisis.status === 'ARC' ? <i className='ion-ios-box-outline' /> : <i className='ion-ios-pulse' /> } {crisisStatusText} </span> </div> </li> ); })} </ul> </div> ); CrisisArchiveList.propTypes = propTypes; export default CSSModules(CrisisArchiveList, styles);
Temzasse/ntu-crysis
client/components/crisis/CrisisArchiveList/index.js
JavaScript
mit
1,416
/** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v25.0.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** Provides sync access to async component. Date component can be lazy created - this class encapsulates * this by keeping value locally until DateComp has loaded, then passing DateComp the value. */ var DateCompWrapper = /** @class */ (function () { function DateCompWrapper(context, userComponentFactory, dateComponentParams, eParent) { var _this = this; this.alive = true; this.context = context; userComponentFactory.newDateComponent(dateComponentParams).then(function (dateComp) { // because async, check the filter still exists after component comes back if (!_this.alive) { context.destroyBean(dateComp); return; } _this.dateComp = dateComp; eParent.appendChild(dateComp.getGui()); if (dateComp.afterGuiAttached) { dateComp.afterGuiAttached(); } if (_this.tempValue) { dateComp.setDate(_this.tempValue); } }); } DateCompWrapper.prototype.destroy = function () { this.alive = false; this.dateComp = this.context.destroyBean(this.dateComp); }; DateCompWrapper.prototype.getDate = function () { return this.dateComp ? this.dateComp.getDate() : this.tempValue; }; DateCompWrapper.prototype.setDate = function (value) { if (this.dateComp) { this.dateComp.setDate(value); } else { this.tempValue = value; } }; DateCompWrapper.prototype.setInputPlaceholder = function (placeholder) { if (this.dateComp && this.dateComp.setInputPlaceholder) { this.dateComp.setInputPlaceholder(placeholder); } }; DateCompWrapper.prototype.setInputAriaLabel = function (label) { if (this.dateComp && this.dateComp.setInputAriaLabel) { this.dateComp.setInputAriaLabel(label); } }; DateCompWrapper.prototype.afterGuiAttached = function (params) { if (this.dateComp && typeof this.dateComp.afterGuiAttached === 'function') { this.dateComp.afterGuiAttached(params); } }; return DateCompWrapper; }()); exports.DateCompWrapper = DateCompWrapper; //# sourceMappingURL=dateCompWrapper.js.map
ceolter/angular-grid
community-modules/core/dist/cjs/filter/provided/date/dateCompWrapper.js
JavaScript
mit
2,578
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class MakePatientInfoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('patient_info', function(Blueprint $table) { $table->bigincrements('file_number'); $table->char('name' , 90); $table->biginteger('id_number'); $table->text('residents'); $table->string('sex'); $table->integer('age'); $table->text('marital_status'); $table->char('next_of_keen' ,90); $table->biginteger('keen_phone_number'); $table->text('postal address'); $table->biginteger('phone_number'); $table->string('email'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('patient_info'); } }
Meritei/MOI-TEACHING-AND-REFERAL-HOSPITALONLINE-HOSPITAL-MANAGEMENT-SYSTEMS
app/database/migrations/2015_02_25_123444_make_patient_info_table.php
PHP
mit
856
package laatikot; import java.util.ArrayList; import java.util.List; public class YhdenTavaranLaatikko extends Laatikko { private List<Tavara> laatikko; public YhdenTavaranLaatikko(){ this.laatikko = new ArrayList<Tavara>(); } @Override public void lisaa(Tavara tavara) { if(this.laatikko.isEmpty()){ this.laatikko.add(tavara); } } @Override public boolean onkoLaatikossa(Tavara tavara) { if(this.laatikko.contains(tavara)){ return true; }else{ return false; } } }
Vahtix/Ohjelmoinnin-MOOC-2017-nodl
Osa10/Osa10_07.ErilaisiaLaatikoita/src/laatikot/YhdenTavaranLaatikko.java
Java
mit
507
from flask_bcrypt import check_password_hash from project.user.services.create_user_service import CreateUserService from project.user.services.login_user_service import LoginUserService from project.user.services.logout_user_service import LogoutUserService from project.user.finders.user_finder import UserFinder from project.utils import flash class UserHandler: @classmethod def login(cls, form): """ Login user by giving "LoginForm" form and validate if username+password pair is valid """ if not form.validate_on_submit(): flash.danger(u'Form is not valid.') return False user = UserFinder.by_username(form.username.data) if not user: flash.danger(u'User {} does not exists.'.format(form.username.data)) return False if not check_password_hash(user.password, form.password.data): flash.warning(u'Invalid Credentials. Please try again.') return False LoginUserService(user).call() return user @classmethod def logout(cls): """ Delete user session """ return LogoutUserService().call() @classmethod def register(cls, form): """ Create new user by given "RegisterForm" """ if not form.validate_on_submit(): flash.danger(u'Form is not valid.') return False user = CreateUserService(form.username.data, form.password.data).call() return LoginUserService(user).call()
andreffs18/flask-template-project
project/user/handlers/user_handler.py
Python
mit
1,551
'use strict'; import './index.html'; import 'babel-core/polyfill'; import PIXI from 'pixi.js'; import TWEEN from 'tween.js'; import Renderer from './Renderer/Renderer'; import App from './displayobjects/App/App.js'; var renderer = new Renderer(); var stage = new PIXI.Stage(0x333333); var app = new App(1920, 1080); function animate() { renderer.render(stage); window.requestAnimationFrame(animate); TWEEN.update(); } document.body.appendChild(renderer.view); stage.addChild(app); animate();
edwinwebb/dashboard-playground
app/app.js
JavaScript
mit
506
// File generated from our OpenAPI spec package com.stripe.model; public class SubscriptionCollection extends StripeCollection<Subscription> {}
stripe/stripe-java
src/main/java/com/stripe/model/SubscriptionCollection.java
Java
mit
145
package com.mindscapehq.raygun4java.core; import com.mindscapehq.raygun4java.core.messages.RaygunMessage; public interface IRaygunOnAfterSend extends IRaygunSentEvent { RaygunMessage onAfterSend(RaygunClient client, RaygunMessage message); }
MindscapeHQ/raygun4java
core/src/main/java/com/mindscapehq/raygun4java/core/IRaygunOnAfterSend.java
Java
mit
247
using UnityEngine; using System.Collections; using UnityEngine.UI; #if UNITY_5_3 using UnityEngine.SceneManagement; #endif public class vChangeScenes : MonoBehaviour { public void LoadThirdPersonScene() { #if UNITY_5_3 SceneManager.LoadScene("3rdPersonController-Demo"); #else Application.LoadLevel("3rdPersonController-Demo"); #endif } public void LoadTopDownScene() { #if UNITY_5_3 SceneManager.LoadScene("TopDownController-Demo"); #else Application.LoadLevel("TopDownController-Demo"); #endif } public void LoadPlatformScene() { #if UNITY_5_3 SceneManager.LoadScene("2.5DController-Demo"); #else Application.LoadLevel("2.5DController-Demo"); #endif } public void LoadIsometricScene() { #if UNITY_5_3 SceneManager.LoadScene("IsometricController-Demo"); #else Application.LoadLevel("IsometricController-Demo"); #endif } public void LoadVMansion() { #if UNITY_5_3 SceneManager.LoadScene("V-Mansion"); #else Application.LoadLevel("V-Mansion"); #endif } public void LoadCompanionAI() { #if UNITY_5_3 SceneManager.LoadScene("BeatnUp@CompanionAI-Demo"); #else Application.LoadLevel("BeatnUp@CompanionAI-Demo"); #endif } public void LoadPuzzleBox() { #if UNITY_5_3 SceneManager.LoadScene("PuzzleBoxes"); #else Application.LoadLevel("PuzzleBoxes"); #endif } }
Sugarfooot/VeggyBot
Assets/Invector-3rdPersonController/Scripts/Generic/vChangeScenes.cs
C#
mit
1,697
/** * @author mrdoob / http://mrdoob.com/ * @author *kile / http://kile.stravaganza.org/ * @author philogb / http://blog.thejit.org/ * @author mikael emtinger / http://gomo.se/ * @author egraether / http://egraether.com/ * @author WestLangley / http://github.com/WestLangley */ THREE.Vector3 = function ( x, y, z ) { this.x = x || 0; this.y = y || 0; this.z = z || 0; }; THREE.Vector3.prototype = { constructor: THREE.Vector3, set: function ( x, y, z ) { this.x = x; this.y = y; this.z = z; return this; }, setX: function ( x ) { this.x = x; return this; }, setY: function ( y ) { this.y = y; return this; }, setZ: function ( z ) { this.z = z; return this; }, setComponent: function ( index, value ) { switch ( index ) { case 0: this.x = value; break; case 1: this.y = value; break; case 2: this.z = value; break; default: throw new Error( 'index is out of range: ' + index ); } }, getComponent: function ( index ) { switch ( index ) { case 0: return this.x; case 1: return this.y; case 2: return this.z; default: throw new Error( 'index is out of range: ' + index ); } }, copy: function ( v ) { this.x = v.x; this.y = v.y; this.z = v.z; return this; }, add: function ( v, w ) { this.x += v.x; this.y += v.y; this.z += v.z; return this; }, addScalar: function ( s ) { this.x += s; this.y += s; this.z += s; return this; }, addVectors: function ( a, b ) { this.x = a.x + b.x; this.y = a.y + b.y; this.z = a.z + b.z; return this; }, sub: function ( v, w ) { this.x -= v.x; this.y -= v.y; this.z -= v.z; return this; }, subScalar: function ( s ) { this.x -= s; this.y -= s; this.z -= s; return this; }, subVectors: function ( a, b ) { this.x = a.x - b.x; this.y = a.y - b.y; this.z = a.z - b.z; return this; }, multiply: function ( v, w ) { if ( w !== undefined ) { THREE.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); return this.multiplyVectors( v, w ); } this.x *= v.x; this.y *= v.y; this.z *= v.z; return this; }, multiplyScalar: function ( scalar ) { this.x *= scalar; this.y *= scalar; this.z *= scalar; return this; }, multiplyVectors: function ( a, b ) { this.x = a.x * b.x; this.y = a.y * b.y; this.z = a.z * b.z; return this; }, applyEuler: function () { var quaternion; return function ( euler ) { if ( euler instanceof THREE.Euler === false ) { THREE.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' ); } if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); this.applyQuaternion( quaternion.setFromEuler( euler ) ); return this; }; }(), applyAxisAngle: function () { var quaternion; return function ( axis, angle ) { if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); return this; }; }(), applyMatrix3: function ( m ) { var x = this.x; var y = this.y; var z = this.z; var e = m.elements; this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; return this; }, applyMatrix4: function ( m ) { // input: THREE.Matrix4 affine matrix var x = this.x, y = this.y, z = this.z; var e = m.elements; this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ]; this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ]; this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ]; return this; }, applyProjection: function ( m ) { // input: THREE.Matrix4 projection matrix var x = this.x, y = this.y, z = this.z; var e = m.elements; var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d; this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d; this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d; return this; }, applyQuaternion: function ( q ) { var x = this.x; var y = this.y; var z = this.z; var qx = q.x; var qy = q.y; var qz = q.z; var qw = q.w; // calculate quat * vector var ix = qw * x + qy * z - qz * y; var iy = qw * y + qz * x - qx * z; var iz = qw * z + qx * y - qy * x; var iw = - qx * x - qy * y - qz * z; // calculate result * inverse quat this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; return this; }, project: function () { var matrix; return function ( camera ) { if ( matrix === undefined ) matrix = new THREE.Matrix4(); matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); return this.applyProjection( matrix ); }; }(), unproject: function () { var matrix; return function ( camera ) { if ( matrix === undefined ) matrix = new THREE.Matrix4(); matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); return this.applyProjection( matrix ); }; }(), transformDirection: function ( m ) { // input: THREE.Matrix4 affine matrix // vector interpreted as a direction var x = this.x, y = this.y, z = this.z; var e = m.elements; this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; this.normalize(); return this; }, divide: function ( v ) { this.x /= v.x; this.y /= v.y; this.z /= v.z; return this; }, divideScalar: function ( scalar ) { if ( scalar !== 0 ) { var invScalar = 1 / scalar; this.x *= invScalar; this.y *= invScalar; this.z *= invScalar; } else { this.x = 0; this.y = 0; this.z = 0; } return this; }, min: function ( v ) { if ( this.x > v.x ) { this.x = v.x; } if ( this.y > v.y ) { this.y = v.y; } if ( this.z > v.z ) { this.z = v.z; } return this; }, max: function ( v ) { if ( this.x < v.x ) { this.x = v.x; } if ( this.y < v.y ) { this.y = v.y; } if ( this.z < v.z ) { this.z = v.z; } return this; }, clamp: function ( min, max ) { // This function assumes min < max, if this assumption isn't true it will not operate correctly if ( this.x < min.x ) { this.x = min.x; } else if ( this.x > max.x ) { this.x = max.x; } if ( this.y < min.y ) { this.y = min.y; } else if ( this.y > max.y ) { this.y = max.y; } if ( this.z < min.z ) { this.z = min.z; } else if ( this.z > max.z ) { this.z = max.z; } return this; }, clampScalar: ( function () { var min, max; return function ( minVal, maxVal ) { if ( min === undefined ) { min = new THREE.Vector3(); max = new THREE.Vector3(); } min.set( minVal, minVal, minVal ); max.set( maxVal, maxVal, maxVal ); return this.clamp( min, max ); }; } )(), floor: function () { this.x = Math.floor( this.x ); this.y = Math.floor( this.y ); this.z = Math.floor( this.z ); return this; }, ceil: function () { this.x = Math.ceil( this.x ); this.y = Math.ceil( this.y ); this.z = Math.ceil( this.z ); return this; }, round: function () { this.x = Math.round( this.x ); this.y = Math.round( this.y ); this.z = Math.round( this.z ); return this; }, roundToZero: function () { this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); return this; }, negate: function () { this.x = - this.x; this.y = - this.y; this.z = - this.z; return this; }, dot: function ( v ) { return this.x * v.x + this.y * v.y + this.z * v.z; }, lengthSq: function () { return this.x * this.x + this.y * this.y + this.z * this.z; }, length: function () { return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); }, lengthManhattan: function () { return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); }, normalize: function () { return this.divideScalar( this.length() ); }, setLength: function ( l ) { var oldLength = this.length(); if ( oldLength !== 0 && l !== oldLength ) { this.multiplyScalar( l / oldLength ); } return this; }, lerp: function ( v, alpha ) { this.x += ( v.x - this.x ) * alpha; this.y += ( v.y - this.y ) * alpha; this.z += ( v.z - this.z ) * alpha; return this; }, lerpVectors: function ( v1, v2, alpha ) { this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); return this; }, cross: function ( v, w ) { if ( w !== undefined ) { THREE.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); return this.crossVectors( v, w ); } var x = this.x, y = this.y, z = this.z; this.x = y * v.z - z * v.y; this.y = z * v.x - x * v.z; this.z = x * v.y - y * v.x; return this; }, crossVectors: function ( a, b ) { var ax = a.x, ay = a.y, az = a.z; var bx = b.x, by = b.y, bz = b.z; this.x = ay * bz - az * by; this.y = az * bx - ax * bz; this.z = ax * by - ay * bx; return this; }, projectOnVector: function () { var v1, dot; return function ( vector ) { if ( v1 === undefined ) v1 = new THREE.Vector3(); v1.copy( vector ).normalize(); dot = this.dot( v1 ); return this.copy( v1 ).multiplyScalar( dot ); }; }(), projectOnPlane: function () { var v1; return function ( planeNormal ) { if ( v1 === undefined ) v1 = new THREE.Vector3(); v1.copy( this ).projectOnVector( planeNormal ); return this.sub( v1 ); } }(), reflect: function () { // reflect incident vector off plane orthogonal to normal // normal is assumed to have unit length var v1; return function ( normal ) { if ( v1 === undefined ) v1 = new THREE.Vector3(); return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); } }(), angleTo: function ( v ) { var theta = this.dot( v ) / ( this.length() * v.length() ); // clamp, to handle numerical problems return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) ); }, distanceTo: function ( v ) { return Math.sqrt( this.distanceToSquared( v ) ); }, distanceToSquared: function ( v ) { var dx = this.x - v.x; var dy = this.y - v.y; var dz = this.z - v.z; return dx * dx + dy * dy + dz * dz; }, setEulerFromRotationMatrix: function ( m, order ) { THREE.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); }, setEulerFromQuaternion: function ( q, order ) { THREE.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); }, getPositionFromMatrix: function ( m ) { THREE.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); return this.setFromMatrixPosition( m ); }, getScaleFromMatrix: function ( m ) { THREE.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); return this.setFromMatrixScale( m ); }, getColumnFromMatrix: function ( index, matrix ) { THREE.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); return this.setFromMatrixColumn( index, matrix ); }, setFromMatrixPosition: function ( m ) { this.x = m.elements[ 12 ]; this.y = m.elements[ 13 ]; this.z = m.elements[ 14 ]; return this; }, setFromMatrixScale: function ( m ) { var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length(); var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length(); var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length(); this.x = sx; this.y = sy; this.z = sz; return this; }, setFromMatrixColumn: function ( index, matrix ) { var offset = index * 4; var me = matrix.elements; this.x = me[ offset ]; this.y = me[ offset + 1 ]; this.z = me[ offset + 2 ]; return this; }, equals: function ( v ) { return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); }, fromArray: function ( array, offset ) { if ( offset === undefined ) offset = 0; this.x = array[ offset ]; this.y = array[ offset + 1 ]; this.z = array[ offset + 2 ]; return this; }, toArray: function ( array, offset ) { if ( array === undefined ) array = []; if ( offset === undefined ) offset = 0; array[ offset ] = this.x; array[ offset + 1 ] = this.y; array[ offset + 2 ] = this.z; return array; }, fromAttribute: function ( attribute, index, offset ) { if ( offset === undefined ) offset = 0; index = index * attribute.itemSize + offset; this.x = attribute.array[ index ]; this.y = attribute.array[ index + 1 ]; this.z = attribute.array[ index + 2 ]; return this; }, clone: function () { return new THREE.Vector3( this.x, this.y, this.z ); } };
strandedcity/makeItZoom
src/threejs_files/Vector3.js
JavaScript
mit
13,436
class Ability include CanCan::Ability def initialize(user) user ||= User.new if user.role == 'admin' can :manage, :all elsif !user.id.blank? [Clothing, ClothingLog, Context, ClothingMatch, CsaFood, DecisionLog, Decision, Food, LibraryItem, LocationHistory, MeasurementLog, Measurement, Stuff, TimeRecord, TorontoLibrary, Memory, TapLogRecord, RecordCategory, Goal, ReceiptItem, ReceiptItemType, ReceiptItemCategory].each do |item| can :manage, item, user_id: user.id can :create, item end can :manage, GroceryList do |o| o.user_id == user.id || GroceryListUser.find_by(grocery_list_id: o.id, user_id: user.id) end can :create, GroceryList can :manage, GroceryListItem do |o| can? :manage, o.grocery_list end can :view_food, User, id: user.id can :manage_account, User, id: user.id can :delete, User, id: user.id can :view_tap_log_records, User, id: user.id can :view_time, User can :send_feedback, User do |o| !o.demo? end end can :view, LibraryItem do |o| o.public? and o.user.demo? end can :view, Memory do |o| o.public? and o.user.demo? end [:view_contexts, :view_locations, :view_dashboard, :view_clothing, :view_clothing_logs, :view_time, :view_library_items, :view_memories, :view_tap_log_records].each do |sym| can sym, User do |u| u.demo? || u.id == user.id end end can :view, Clothing do |o| o.user.demo? end can :view, TapLogRecord do |o| o.user.demo? and o.public? end can :view_note, TapLogRecord do |o| (!o.private? and o.user.demo?) || (o.user_id == user.id) end can :view_site, User end end
sachac/quantified
app/models/ability.rb
Ruby
mit
1,714
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.Dropbox = {})); }(this, (function (exports) { 'use strict'; // Auto-generated by Stone, do not modify. var routes = {}; /** * Sets a user's profile photo. * @function Dropbox#accountSetProfilePhoto * @arg {AccountSetProfilePhotoArg} arg - The request parameters. * @returns {Promise.<AccountSetProfilePhotoResult, Error.<AccountSetProfilePhotoError>>} */ routes.accountSetProfilePhoto = function (arg) { return this.request('account/set_profile_photo', arg, 'user', 'api', 'rpc'); }; /** * Creates an OAuth 2.0 access token from the supplied OAuth 1.0 access token. * @function Dropbox#authTokenFromOauth1 * @arg {AuthTokenFromOAuth1Arg} arg - The request parameters. * @returns {Promise.<AuthTokenFromOAuth1Result, Error.<AuthTokenFromOAuth1Error>>} */ routes.authTokenFromOauth1 = function (arg) { return this.request('auth/token/from_oauth1', arg, 'app', 'api', 'rpc'); }; /** * Disables the access token used to authenticate the call. * @function Dropbox#authTokenRevoke * @arg {void} arg - The request parameters. * @returns {Promise.<void, Error.<void>>} */ routes.authTokenRevoke = function (arg) { return this.request('auth/token/revoke', arg, 'user', 'api', 'rpc'); }; /** * This endpoint performs App Authentication, validating the supplied app key * and secret, and returns the supplied string, to allow you to test your code * and connection to the Dropbox API. It has no other effect. If you receive an * HTTP 200 response with the supplied query, it indicates at least part of the * Dropbox API infrastructure is working and that the app key and secret valid. * @function Dropbox#checkApp * @arg {CheckEchoArg} arg - The request parameters. * @returns {Promise.<CheckEchoResult, Error.<void>>} */ routes.checkApp = function (arg) { return this.request('check/app', arg, 'app', 'api', 'rpc'); }; /** * This endpoint performs User Authentication, validating the supplied access * token, and returns the supplied string, to allow you to test your code and * connection to the Dropbox API. It has no other effect. If you receive an HTTP * 200 response with the supplied query, it indicates at least part of the * Dropbox API infrastructure is working and that the access token is valid. * @function Dropbox#checkUser * @arg {CheckEchoArg} arg - The request parameters. * @returns {Promise.<CheckEchoResult, Error.<void>>} */ routes.checkUser = function (arg) { return this.request('check/user', arg, 'user', 'api', 'rpc'); }; /** * Fetch the binary content of the requested document. This route requires Cloud * Docs auth. Please make a request to cloud_docs/authorize and supply that * token in the Authorization header. * @function Dropbox#cloudDocsGetContent * @arg {CloudDocsGetContentArg} arg - The request parameters. * @returns {Promise.<void, Error.<CloudDocsCloudDocsAccessError>>} */ routes.cloudDocsGetContent = function (arg) { return this.request('cloud_docs/get_content', arg, 'user', 'content', 'download'); }; /** * Fetches metadata associated with a Cloud Doc and user. This route requires * Cloud Docs auth. Please make a request to cloud_docs/authorize and supply * that token in the Authorization header. * @function Dropbox#cloudDocsGetMetadata * @arg {CloudDocsGetMetadataArg} arg - The request parameters. * @returns {Promise.<CloudDocsGetMetadataResult, Error.<CloudDocsGetMetadataError>>} */ routes.cloudDocsGetMetadata = function (arg) { return this.request('cloud_docs/get_metadata', arg, 'user', 'api', 'rpc'); }; /** * Lock a Cloud Doc. This route requires Cloud Docs auth. Please make a request * to cloud_docs/authorize and supply that token in the Authorization header. * @function Dropbox#cloudDocsLock * @arg {CloudDocsLockArg} arg - The request parameters. * @returns {Promise.<CloudDocsLockResult, Error.<CloudDocsLockingError>>} */ routes.cloudDocsLock = function (arg) { return this.request('cloud_docs/lock', arg, 'user', 'api', 'rpc'); }; /** * Update the title of a Cloud Doc. This route requires Cloud Docs auth. Please * make a request to cloud_docs/authorize and supply that token in the * Authorization header. * @function Dropbox#cloudDocsRename * @arg {CloudDocsRenameArg} arg - The request parameters. * @returns {Promise.<CloudDocsRenameResult, Error.<CloudDocsRenameError>>} */ routes.cloudDocsRename = function (arg) { return this.request('cloud_docs/rename', arg, 'user', 'api', 'rpc'); }; /** * Unlock a Cloud Doc. This route requires Cloud Docs auth. Please make a * request to cloud_docs/authorize and supply that token in the Authorization * header. * @function Dropbox#cloudDocsUnlock * @arg {CloudDocsUnlockArg} arg - The request parameters. * @returns {Promise.<CloudDocsUnlockResult, Error.<CloudDocsLockingError>>} */ routes.cloudDocsUnlock = function (arg) { return this.request('cloud_docs/unlock', arg, 'user', 'api', 'rpc'); }; /** * Update the contents of a Cloud Doc. This should be called for files with a * max size of 150MB. This route requires Cloud Docs auth. Please make a request * to cloud_docs/authorize and supply that token in the Authorization header. * @function Dropbox#cloudDocsUpdateContent * @arg {CloudDocsUpdateContentArg} arg - The request parameters. * @returns {Promise.<CloudDocsUpdateContentResult, Error.<CloudDocsUpdateContentError>>} */ routes.cloudDocsUpdateContent = function (arg) { return this.request('cloud_docs/update_content', arg, 'user', 'content', 'upload'); }; /** * Removes all manually added contacts. You'll still keep contacts who are on * your team or who you imported. New contacts will be added when you share. * @function Dropbox#contactsDeleteManualContacts * @arg {void} arg - The request parameters. * @returns {Promise.<void, Error.<void>>} */ routes.contactsDeleteManualContacts = function (arg) { return this.request('contacts/delete_manual_contacts', arg, 'user', 'api', 'rpc'); }; /** * Removes manually added contacts from the given list. * @function Dropbox#contactsDeleteManualContactsBatch * @arg {ContactsDeleteManualContactsArg} arg - The request parameters. * @returns {Promise.<void, Error.<ContactsDeleteManualContactsError>>} */ routes.contactsDeleteManualContactsBatch = function (arg) { return this.request('contacts/delete_manual_contacts_batch', arg, 'user', 'api', 'rpc'); }; /** * Add property groups to a Dropbox file. See templates/add_for_user or * templates/add_for_team to create new templates. * @function Dropbox#filePropertiesPropertiesAdd * @arg {FilePropertiesAddPropertiesArg} arg - The request parameters. * @returns {Promise.<void, Error.<FilePropertiesAddPropertiesError>>} */ routes.filePropertiesPropertiesAdd = function (arg) { return this.request('file_properties/properties/add', arg, 'user', 'api', 'rpc'); }; /** * Overwrite property groups associated with a file. This endpoint should be * used instead of properties/update when property groups are being updated via * a "snapshot" instead of via a "delta". In other words, this endpoint will * delete all omitted fields from a property group, whereas properties/update * will only delete fields that are explicitly marked for deletion. * @function Dropbox#filePropertiesPropertiesOverwrite * @arg {FilePropertiesOverwritePropertyGroupArg} arg - The request parameters. * @returns {Promise.<void, Error.<FilePropertiesInvalidPropertyGroupError>>} */ routes.filePropertiesPropertiesOverwrite = function (arg) { return this.request('file_properties/properties/overwrite', arg, 'user', 'api', 'rpc'); }; /** * Permanently removes the specified property group from the file. To remove * specific property field key value pairs, see properties/update. To update a * template, see templates/update_for_user or templates/update_for_team. To * remove a template, see templates/remove_for_user or * templates/remove_for_team. * @function Dropbox#filePropertiesPropertiesRemove * @arg {FilePropertiesRemovePropertiesArg} arg - The request parameters. * @returns {Promise.<void, Error.<FilePropertiesRemovePropertiesError>>} */ routes.filePropertiesPropertiesRemove = function (arg) { return this.request('file_properties/properties/remove', arg, 'user', 'api', 'rpc'); }; /** * Search across property templates for particular property field values. * @function Dropbox#filePropertiesPropertiesSearch * @arg {FilePropertiesPropertiesSearchArg} arg - The request parameters. * @returns {Promise.<FilePropertiesPropertiesSearchResult, Error.<FilePropertiesPropertiesSearchError>>} */ routes.filePropertiesPropertiesSearch = function (arg) { return this.request('file_properties/properties/search', arg, 'user', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from properties/search, use this to paginate * through all search results. * @function Dropbox#filePropertiesPropertiesSearchContinue * @arg {FilePropertiesPropertiesSearchContinueArg} arg - The request parameters. * @returns {Promise.<FilePropertiesPropertiesSearchResult, Error.<FilePropertiesPropertiesSearchContinueError>>} */ routes.filePropertiesPropertiesSearchContinue = function (arg) { return this.request('file_properties/properties/search/continue', arg, 'user', 'api', 'rpc'); }; /** * Add, update or remove properties associated with the supplied file and * templates. This endpoint should be used instead of properties/overwrite when * property groups are being updated via a "delta" instead of via a "snapshot" . * In other words, this endpoint will not delete any omitted fields from a * property group, whereas properties/overwrite will delete any fields that are * omitted from a property group. * @function Dropbox#filePropertiesPropertiesUpdate * @arg {FilePropertiesUpdatePropertiesArg} arg - The request parameters. * @returns {Promise.<void, Error.<FilePropertiesUpdatePropertiesError>>} */ routes.filePropertiesPropertiesUpdate = function (arg) { return this.request('file_properties/properties/update', arg, 'user', 'api', 'rpc'); }; /** * Add a template associated with a team. See properties/add to add properties * to a file or folder. Note: this endpoint will create team-owned templates. * @function Dropbox#filePropertiesTemplatesAddForTeam * @arg {FilePropertiesAddTemplateArg} arg - The request parameters. * @returns {Promise.<FilePropertiesAddTemplateResult, Error.<FilePropertiesModifyTemplateError>>} */ routes.filePropertiesTemplatesAddForTeam = function (arg) { return this.request('file_properties/templates/add_for_team', arg, 'team', 'api', 'rpc'); }; /** * Add a template associated with a user. See properties/add to add properties * to a file. This endpoint can't be called on a team member or admin's behalf. * @function Dropbox#filePropertiesTemplatesAddForUser * @arg {FilePropertiesAddTemplateArg} arg - The request parameters. * @returns {Promise.<FilePropertiesAddTemplateResult, Error.<FilePropertiesModifyTemplateError>>} */ routes.filePropertiesTemplatesAddForUser = function (arg) { return this.request('file_properties/templates/add_for_user', arg, 'user', 'api', 'rpc'); }; /** * Get the schema for a specified template. * @function Dropbox#filePropertiesTemplatesGetForTeam * @arg {FilePropertiesGetTemplateArg} arg - The request parameters. * @returns {Promise.<FilePropertiesGetTemplateResult, Error.<FilePropertiesTemplateError>>} */ routes.filePropertiesTemplatesGetForTeam = function (arg) { return this.request('file_properties/templates/get_for_team', arg, 'team', 'api', 'rpc'); }; /** * Get the schema for a specified template. This endpoint can't be called on a * team member or admin's behalf. * @function Dropbox#filePropertiesTemplatesGetForUser * @arg {FilePropertiesGetTemplateArg} arg - The request parameters. * @returns {Promise.<FilePropertiesGetTemplateResult, Error.<FilePropertiesTemplateError>>} */ routes.filePropertiesTemplatesGetForUser = function (arg) { return this.request('file_properties/templates/get_for_user', arg, 'user', 'api', 'rpc'); }; /** * Get the template identifiers for a team. To get the schema of each template * use templates/get_for_team. * @function Dropbox#filePropertiesTemplatesListForTeam * @arg {void} arg - The request parameters. * @returns {Promise.<FilePropertiesListTemplateResult, Error.<FilePropertiesTemplateError>>} */ routes.filePropertiesTemplatesListForTeam = function (arg) { return this.request('file_properties/templates/list_for_team', arg, 'team', 'api', 'rpc'); }; /** * Get the template identifiers for a team. To get the schema of each template * use templates/get_for_user. This endpoint can't be called on a team member or * admin's behalf. * @function Dropbox#filePropertiesTemplatesListForUser * @arg {void} arg - The request parameters. * @returns {Promise.<FilePropertiesListTemplateResult, Error.<FilePropertiesTemplateError>>} */ routes.filePropertiesTemplatesListForUser = function (arg) { return this.request('file_properties/templates/list_for_user', arg, 'user', 'api', 'rpc'); }; /** * Permanently removes the specified template created from * templates/add_for_user. All properties associated with the template will also * be removed. This action cannot be undone. * @function Dropbox#filePropertiesTemplatesRemoveForTeam * @arg {FilePropertiesRemoveTemplateArg} arg - The request parameters. * @returns {Promise.<void, Error.<FilePropertiesTemplateError>>} */ routes.filePropertiesTemplatesRemoveForTeam = function (arg) { return this.request('file_properties/templates/remove_for_team', arg, 'team', 'api', 'rpc'); }; /** * Permanently removes the specified template created from * templates/add_for_user. All properties associated with the template will also * be removed. This action cannot be undone. * @function Dropbox#filePropertiesTemplatesRemoveForUser * @arg {FilePropertiesRemoveTemplateArg} arg - The request parameters. * @returns {Promise.<void, Error.<FilePropertiesTemplateError>>} */ routes.filePropertiesTemplatesRemoveForUser = function (arg) { return this.request('file_properties/templates/remove_for_user', arg, 'user', 'api', 'rpc'); }; /** * Update a template associated with a team. This route can update the template * name, the template description and add optional properties to templates. * @function Dropbox#filePropertiesTemplatesUpdateForTeam * @arg {FilePropertiesUpdateTemplateArg} arg - The request parameters. * @returns {Promise.<FilePropertiesUpdateTemplateResult, Error.<FilePropertiesModifyTemplateError>>} */ routes.filePropertiesTemplatesUpdateForTeam = function (arg) { return this.request('file_properties/templates/update_for_team', arg, 'team', 'api', 'rpc'); }; /** * Update a template associated with a user. This route can update the template * name, the template description and add optional properties to templates. This * endpoint can't be called on a team member or admin's behalf. * @function Dropbox#filePropertiesTemplatesUpdateForUser * @arg {FilePropertiesUpdateTemplateArg} arg - The request parameters. * @returns {Promise.<FilePropertiesUpdateTemplateResult, Error.<FilePropertiesModifyTemplateError>>} */ routes.filePropertiesTemplatesUpdateForUser = function (arg) { return this.request('file_properties/templates/update_for_user', arg, 'user', 'api', 'rpc'); }; /** * Returns the total number of file requests owned by this user. Includes both * open and closed file requests. * @function Dropbox#fileRequestsCount * @arg {void} arg - The request parameters. * @returns {Promise.<FileRequestsCountFileRequestsResult, Error.<FileRequestsCountFileRequestsError>>} */ routes.fileRequestsCount = function (arg) { return this.request('file_requests/count', arg, 'user', 'api', 'rpc'); }; /** * Creates a file request for this user. * @function Dropbox#fileRequestsCreate * @arg {FileRequestsCreateFileRequestArgs} arg - The request parameters. * @returns {Promise.<FileRequestsFileRequest, Error.<FileRequestsCreateFileRequestError>>} */ routes.fileRequestsCreate = function (arg) { return this.request('file_requests/create', arg, 'user', 'api', 'rpc'); }; /** * Delete a batch of closed file requests. * @function Dropbox#fileRequestsDelete * @arg {FileRequestsDeleteFileRequestArgs} arg - The request parameters. * @returns {Promise.<FileRequestsDeleteFileRequestsResult, Error.<FileRequestsDeleteFileRequestError>>} */ routes.fileRequestsDelete = function (arg) { return this.request('file_requests/delete', arg, 'user', 'api', 'rpc'); }; /** * Delete all closed file requests owned by this user. * @function Dropbox#fileRequestsDeleteAllClosed * @arg {void} arg - The request parameters. * @returns {Promise.<FileRequestsDeleteAllClosedFileRequestsResult, Error.<FileRequestsDeleteAllClosedFileRequestsError>>} */ routes.fileRequestsDeleteAllClosed = function (arg) { return this.request('file_requests/delete_all_closed', arg, 'user', 'api', 'rpc'); }; /** * Returns the specified file request. * @function Dropbox#fileRequestsGet * @arg {FileRequestsGetFileRequestArgs} arg - The request parameters. * @returns {Promise.<FileRequestsFileRequest, Error.<FileRequestsGetFileRequestError>>} */ routes.fileRequestsGet = function (arg) { return this.request('file_requests/get', arg, 'user', 'api', 'rpc'); }; /** * Returns a list of file requests owned by this user. For apps with the app * folder permission, this will only return file requests with destinations in * the app folder. * @function Dropbox#fileRequestsListV2 * @arg {FileRequestsListFileRequestsArg} arg - The request parameters. * @returns {Promise.<FileRequestsListFileRequestsV2Result, Error.<FileRequestsListFileRequestsError>>} */ routes.fileRequestsListV2 = function (arg) { return this.request('file_requests/list_v2', arg, 'user', 'api', 'rpc'); }; /** * Returns a list of file requests owned by this user. For apps with the app * folder permission, this will only return file requests with destinations in * the app folder. * @function Dropbox#fileRequestsList * @arg {void} arg - The request parameters. * @returns {Promise.<FileRequestsListFileRequestsResult, Error.<FileRequestsListFileRequestsError>>} */ routes.fileRequestsList = function (arg) { return this.request('file_requests/list', arg, 'user', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from list_v2, use this to paginate through * all file requests. The cursor must come from a previous call to list_v2 or * list/continue. * @function Dropbox#fileRequestsListContinue * @arg {FileRequestsListFileRequestsContinueArg} arg - The request parameters. * @returns {Promise.<FileRequestsListFileRequestsV2Result, Error.<FileRequestsListFileRequestsContinueError>>} */ routes.fileRequestsListContinue = function (arg) { return this.request('file_requests/list/continue', arg, 'user', 'api', 'rpc'); }; /** * Update a file request. * @function Dropbox#fileRequestsUpdate * @arg {FileRequestsUpdateFileRequestArgs} arg - The request parameters. * @returns {Promise.<FileRequestsFileRequest, Error.<FileRequestsUpdateFileRequestError>>} */ routes.fileRequestsUpdate = function (arg) { return this.request('file_requests/update', arg, 'user', 'api', 'rpc'); }; /** * Returns the metadata for a file or folder. This is an alpha endpoint * compatible with the properties API. Note: Metadata for the root folder is * unsupported. * @function Dropbox#filesAlphaGetMetadata * @deprecated * @arg {FilesAlphaGetMetadataArg} arg - The request parameters. * @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.<FilesAlphaGetMetadataError>>} */ routes.filesAlphaGetMetadata = function (arg) { return this.request('files/alpha/get_metadata', arg, 'user', 'api', 'rpc'); }; /** * Create a new file with the contents provided in the request. Note that this * endpoint is part of the properties API alpha and is slightly different from * upload. Do not use this to upload a file larger than 150 MB. Instead, create * an upload session with upload_session/start. * @function Dropbox#filesAlphaUpload * @deprecated * @arg {FilesCommitInfoWithProperties} arg - The request parameters. * @returns {Promise.<FilesFileMetadata, Error.<FilesUploadErrorWithProperties>>} */ routes.filesAlphaUpload = function (arg) { return this.request('files/alpha/upload', arg, 'user', 'content', 'upload'); }; /** * Copy a file or folder to a different location in the user's Dropbox. If the * source path is a folder all its contents will be copied. * @function Dropbox#filesCopyV2 * @arg {FilesRelocationArg} arg - The request parameters. * @returns {Promise.<FilesRelocationResult, Error.<FilesRelocationError>>} */ routes.filesCopyV2 = function (arg) { return this.request('files/copy_v2', arg, 'user', 'api', 'rpc'); }; /** * Copy a file or folder to a different location in the user's Dropbox. If the * source path is a folder all its contents will be copied. * @function Dropbox#filesCopy * @deprecated * @arg {FilesRelocationArg} arg - The request parameters. * @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.<FilesRelocationError>>} */ routes.filesCopy = function (arg) { return this.request('files/copy', arg, 'user', 'api', 'rpc'); }; /** * Copy multiple files or folders to different locations at once in the user's * Dropbox. This route will replace copy_batch. The main difference is this * route will return status for each entry, while copy_batch raises failure if * any entry fails. This route will either finish synchronously, or return a job * ID and do the async copy job in background. Please use copy_batch/check_v2 to * check the job status. * @function Dropbox#filesCopyBatchV2 * @arg {Object} arg - The request parameters. * @returns {Promise.<FilesRelocationBatchV2Launch, Error.<void>>} */ routes.filesCopyBatchV2 = function (arg) { return this.request('files/copy_batch_v2', arg, 'user', 'api', 'rpc'); }; /** * Copy multiple files or folders to different locations at once in the user's * Dropbox. If RelocationBatchArg.allow_shared_folder is false, this route is * atomic. If one entry fails, the whole transaction will abort. If * RelocationBatchArg.allow_shared_folder is true, atomicity is not guaranteed, * but it allows you to copy the contents of shared folders to new locations. * This route will return job ID immediately and do the async copy job in * background. Please use copy_batch/check to check the job status. * @function Dropbox#filesCopyBatch * @deprecated * @arg {FilesRelocationBatchArg} arg - The request parameters. * @returns {Promise.<FilesRelocationBatchLaunch, Error.<void>>} */ routes.filesCopyBatch = function (arg) { return this.request('files/copy_batch', arg, 'user', 'api', 'rpc'); }; /** * Returns the status of an asynchronous job for copy_batch_v2. It returns list * of results for each entry. * @function Dropbox#filesCopyBatchCheckV2 * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<FilesRelocationBatchV2JobStatus, Error.<AsyncPollError>>} */ routes.filesCopyBatchCheckV2 = function (arg) { return this.request('files/copy_batch/check_v2', arg, 'user', 'api', 'rpc'); }; /** * Returns the status of an asynchronous job for copy_batch. If success, it * returns list of results for each entry. * @function Dropbox#filesCopyBatchCheck * @deprecated * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<FilesRelocationBatchJobStatus, Error.<AsyncPollError>>} */ routes.filesCopyBatchCheck = function (arg) { return this.request('files/copy_batch/check', arg, 'user', 'api', 'rpc'); }; /** * Get a copy reference to a file or folder. This reference string can be used * to save that file or folder to another user's Dropbox by passing it to * copy_reference/save. * @function Dropbox#filesCopyReferenceGet * @arg {FilesGetCopyReferenceArg} arg - The request parameters. * @returns {Promise.<FilesGetCopyReferenceResult, Error.<FilesGetCopyReferenceError>>} */ routes.filesCopyReferenceGet = function (arg) { return this.request('files/copy_reference/get', arg, 'user', 'api', 'rpc'); }; /** * Save a copy reference returned by copy_reference/get to the user's Dropbox. * @function Dropbox#filesCopyReferenceSave * @arg {FilesSaveCopyReferenceArg} arg - The request parameters. * @returns {Promise.<FilesSaveCopyReferenceResult, Error.<FilesSaveCopyReferenceError>>} */ routes.filesCopyReferenceSave = function (arg) { return this.request('files/copy_reference/save', arg, 'user', 'api', 'rpc'); }; /** * Create a folder at a given path. * @function Dropbox#filesCreateFolderV2 * @arg {FilesCreateFolderArg} arg - The request parameters. * @returns {Promise.<FilesCreateFolderResult, Error.<FilesCreateFolderError>>} */ routes.filesCreateFolderV2 = function (arg) { return this.request('files/create_folder_v2', arg, 'user', 'api', 'rpc'); }; /** * Create a folder at a given path. * @function Dropbox#filesCreateFolder * @deprecated * @arg {FilesCreateFolderArg} arg - The request parameters. * @returns {Promise.<FilesFolderMetadata, Error.<FilesCreateFolderError>>} */ routes.filesCreateFolder = function (arg) { return this.request('files/create_folder', arg, 'user', 'api', 'rpc'); }; /** * Create multiple folders at once. This route is asynchronous for large * batches, which returns a job ID immediately and runs the create folder batch * asynchronously. Otherwise, creates the folders and returns the result * synchronously for smaller inputs. You can force asynchronous behaviour by * using the CreateFolderBatchArg.force_async flag. Use * create_folder_batch/check to check the job status. * @function Dropbox#filesCreateFolderBatch * @arg {FilesCreateFolderBatchArg} arg - The request parameters. * @returns {Promise.<FilesCreateFolderBatchLaunch, Error.<void>>} */ routes.filesCreateFolderBatch = function (arg) { return this.request('files/create_folder_batch', arg, 'user', 'api', 'rpc'); }; /** * Returns the status of an asynchronous job for create_folder_batch. If * success, it returns list of result for each entry. * @function Dropbox#filesCreateFolderBatchCheck * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<FilesCreateFolderBatchJobStatus, Error.<AsyncPollError>>} */ routes.filesCreateFolderBatchCheck = function (arg) { return this.request('files/create_folder_batch/check', arg, 'user', 'api', 'rpc'); }; /** * Delete the file or folder at a given path. If the path is a folder, all its * contents will be deleted too. A successful response indicates that the file * or folder was deleted. The returned metadata will be the corresponding * FileMetadata or FolderMetadata for the item at time of deletion, and not a * DeletedMetadata object. * @function Dropbox#filesDeleteV2 * @arg {FilesDeleteArg} arg - The request parameters. * @returns {Promise.<FilesDeleteResult, Error.<FilesDeleteError>>} */ routes.filesDeleteV2 = function (arg) { return this.request('files/delete_v2', arg, 'user', 'api', 'rpc'); }; /** * Delete the file or folder at a given path. If the path is a folder, all its * contents will be deleted too. A successful response indicates that the file * or folder was deleted. The returned metadata will be the corresponding * FileMetadata or FolderMetadata for the item at time of deletion, and not a * DeletedMetadata object. * @function Dropbox#filesDelete * @deprecated * @arg {FilesDeleteArg} arg - The request parameters. * @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.<FilesDeleteError>>} */ routes.filesDelete = function (arg) { return this.request('files/delete', arg, 'user', 'api', 'rpc'); }; /** * Delete multiple files/folders at once. This route is asynchronous, which * returns a job ID immediately and runs the delete batch asynchronously. Use * delete_batch/check to check the job status. * @function Dropbox#filesDeleteBatch * @arg {FilesDeleteBatchArg} arg - The request parameters. * @returns {Promise.<FilesDeleteBatchLaunch, Error.<void>>} */ routes.filesDeleteBatch = function (arg) { return this.request('files/delete_batch', arg, 'user', 'api', 'rpc'); }; /** * Returns the status of an asynchronous job for delete_batch. If success, it * returns list of result for each entry. * @function Dropbox#filesDeleteBatchCheck * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<FilesDeleteBatchJobStatus, Error.<AsyncPollError>>} */ routes.filesDeleteBatchCheck = function (arg) { return this.request('files/delete_batch/check', arg, 'user', 'api', 'rpc'); }; /** * Download a file from a user's Dropbox. * @function Dropbox#filesDownload * @arg {FilesDownloadArg} arg - The request parameters. * @returns {Promise.<FilesFileMetadata, Error.<FilesDownloadError>>} */ routes.filesDownload = function (arg) { return this.request('files/download', arg, 'user', 'content', 'download'); }; /** * Download a folder from the user's Dropbox, as a zip file. The folder must be * less than 20 GB in size and have fewer than 10,000 total files. The input * cannot be a single file. Any single file must be less than 4GB in size. * @function Dropbox#filesDownloadZip * @arg {FilesDownloadZipArg} arg - The request parameters. * @returns {Promise.<FilesDownloadZipResult, Error.<FilesDownloadZipError>>} */ routes.filesDownloadZip = function (arg) { return this.request('files/download_zip', arg, 'user', 'content', 'download'); }; /** * Export a file from a user's Dropbox. This route only supports exporting files * that cannot be downloaded directly and whose ExportResult.file_metadata has * ExportInfo.export_as populated. * @function Dropbox#filesExport * @arg {FilesExportArg} arg - The request parameters. * @returns {Promise.<FilesExportResult, Error.<FilesExportError>>} */ routes.filesExport = function (arg) { return this.request('files/export', arg, 'user', 'content', 'download'); }; /** * Return the lock metadata for the given list of paths. * @function Dropbox#filesGetFileLockBatch * @arg {FilesLockFileBatchArg} arg - The request parameters. * @returns {Promise.<FilesLockFileBatchResult, Error.<FilesLockFileError>>} */ routes.filesGetFileLockBatch = function (arg) { return this.request('files/get_file_lock_batch', arg, 'user', 'api', 'rpc'); }; /** * Returns the metadata for a file or folder. Note: Metadata for the root folder * is unsupported. * @function Dropbox#filesGetMetadata * @arg {FilesGetMetadataArg} arg - The request parameters. * @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.<FilesGetMetadataError>>} */ routes.filesGetMetadata = function (arg) { return this.request('files/get_metadata', arg, 'user', 'api', 'rpc'); }; /** * Get a preview for a file. Currently, PDF previews are generated for files * with the following extensions: .ai, .doc, .docm, .docx, .eps, .gdoc, * .gslides, .odp, .odt, .pps, .ppsm, .ppsx, .ppt, .pptm, .pptx, .rtf. HTML * previews are generated for files with the following extensions: .csv, .ods, * .xls, .xlsm, .gsheet, .xlsx. Other formats will return an unsupported * extension error. * @function Dropbox#filesGetPreview * @arg {FilesPreviewArg} arg - The request parameters. * @returns {Promise.<FilesFileMetadata, Error.<FilesPreviewError>>} */ routes.filesGetPreview = function (arg) { return this.request('files/get_preview', arg, 'user', 'content', 'download'); }; /** * Get a temporary link to stream content of a file. This link will expire in * four hours and afterwards you will get 410 Gone. This URL should not be used * to display content directly in the browser. The Content-Type of the link is * determined automatically by the file's mime type. * @function Dropbox#filesGetTemporaryLink * @arg {FilesGetTemporaryLinkArg} arg - The request parameters. * @returns {Promise.<FilesGetTemporaryLinkResult, Error.<FilesGetTemporaryLinkError>>} */ routes.filesGetTemporaryLink = function (arg) { return this.request('files/get_temporary_link', arg, 'user', 'api', 'rpc'); }; /** * Get a one-time use temporary upload link to upload a file to a Dropbox * location. This endpoint acts as a delayed upload. The returned temporary * upload link may be used to make a POST request with the data to be uploaded. * The upload will then be perfomed with the CommitInfo previously provided to * get_temporary_upload_link but evaluated only upon consumption. Hence, errors * stemming from invalid CommitInfo with respect to the state of the user's * Dropbox will only be communicated at consumption time. Additionally, these * errors are surfaced as generic HTTP 409 Conflict responses, potentially * hiding issue details. The maximum temporary upload link duration is 4 hours. * Upon consumption or expiration, a new link will have to be generated. * Multiple links may exist for a specific upload path at any given time. The * POST request on the temporary upload link must have its Content-Type set to * "application/octet-stream". Example temporary upload link consumption * request: curl -X POST * https://dl.dropboxusercontent.com/apitul/1/bNi2uIYF51cVBND --header * "Content-Type: application/octet-stream" --data-binary @local_file.txt A * successful temporary upload link consumption request returns the content hash * of the uploaded data in JSON format. Example succesful temporary upload link * consumption response: {"content-hash": * "599d71033d700ac892a0e48fa61b125d2f5994"} An unsuccessful temporary upload * link consumption request returns any of the following status codes: HTTP 400 * Bad Request: Content-Type is not one of application/octet-stream and * text/plain or request is invalid. HTTP 409 Conflict: The temporary upload * link does not exist or is currently unavailable, the upload failed, or * another error happened. HTTP 410 Gone: The temporary upload link is expired * or consumed. Example unsuccessful temporary upload link consumption * response: Temporary upload link has been recently consumed. * @function Dropbox#filesGetTemporaryUploadLink * @arg {FilesGetTemporaryUploadLinkArg} arg - The request parameters. * @returns {Promise.<FilesGetTemporaryUploadLinkResult, Error.<void>>} */ routes.filesGetTemporaryUploadLink = function (arg) { return this.request('files/get_temporary_upload_link', arg, 'user', 'api', 'rpc'); }; /** * Get a thumbnail for an image. This method currently supports files with the * following file extensions: jpg, jpeg, png, tiff, tif, gif and bmp. Photos * that are larger than 20MB in size won't be converted to a thumbnail. * @function Dropbox#filesGetThumbnail * @arg {FilesThumbnailArg} arg - The request parameters. * @returns {Promise.<FilesFileMetadata, Error.<FilesThumbnailError>>} */ routes.filesGetThumbnail = function (arg) { return this.request('files/get_thumbnail', arg, 'user', 'content', 'download'); }; /** * Get a thumbnail for a file. * @function Dropbox#filesGetThumbnailV2 * @arg {FilesThumbnailV2Arg} arg - The request parameters. * @returns {Promise.<FilesPreviewResult, Error.<FilesThumbnailV2Error>>} */ routes.filesGetThumbnailV2 = function (arg) { return this.request('files/get_thumbnail_v2', arg, 'app, user', 'content', 'download'); }; /** * Get thumbnails for a list of images. We allow up to 25 thumbnails in a single * batch. This method currently supports files with the following file * extensions: jpg, jpeg, png, tiff, tif, gif and bmp. Photos that are larger * than 20MB in size won't be converted to a thumbnail. * @function Dropbox#filesGetThumbnailBatch * @arg {FilesGetThumbnailBatchArg} arg - The request parameters. * @returns {Promise.<FilesGetThumbnailBatchResult, Error.<FilesGetThumbnailBatchError>>} */ routes.filesGetThumbnailBatch = function (arg) { return this.request('files/get_thumbnail_batch', arg, 'user', 'content', 'rpc'); }; /** * Starts returning the contents of a folder. If the result's * ListFolderResult.has_more field is true, call list_folder/continue with the * returned ListFolderResult.cursor to retrieve more entries. If you're using * ListFolderArg.recursive set to true to keep a local cache of the contents of * a Dropbox account, iterate through each entry in order and process them as * follows to keep your local state in sync: For each FileMetadata, store the * new entry at the given path in your local state. If the required parent * folders don't exist yet, create them. If there's already something else at * the given path, replace it and remove all its children. For each * FolderMetadata, store the new entry at the given path in your local state. If * the required parent folders don't exist yet, create them. If there's already * something else at the given path, replace it but leave the children as they * are. Check the new entry's FolderSharingInfo.read_only and set all its * children's read-only statuses to match. For each DeletedMetadata, if your * local state has something at the given path, remove it and all its children. * If there's nothing at the given path, ignore this entry. Note: * auth.RateLimitError may be returned if multiple list_folder or * list_folder/continue calls with same parameters are made simultaneously by * same API app for same user. If your app implements retry logic, please hold * off the retry until the previous request finishes. * @function Dropbox#filesListFolder * @arg {FilesListFolderArg} arg - The request parameters. * @returns {Promise.<FilesListFolderResult, Error.<FilesListFolderError>>} */ routes.filesListFolder = function (arg) { return this.request('files/list_folder', arg, 'user', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from list_folder, use this to paginate * through all files and retrieve updates to the folder, following the same * rules as documented for list_folder. * @function Dropbox#filesListFolderContinue * @arg {FilesListFolderContinueArg} arg - The request parameters. * @returns {Promise.<FilesListFolderResult, Error.<FilesListFolderContinueError>>} */ routes.filesListFolderContinue = function (arg) { return this.request('files/list_folder/continue', arg, 'user', 'api', 'rpc'); }; /** * A way to quickly get a cursor for the folder's state. Unlike list_folder, * list_folder/get_latest_cursor doesn't return any entries. This endpoint is * for app which only needs to know about new files and modifications and * doesn't need to know about files that already exist in Dropbox. * @function Dropbox#filesListFolderGetLatestCursor * @arg {FilesListFolderArg} arg - The request parameters. * @returns {Promise.<FilesListFolderGetLatestCursorResult, Error.<FilesListFolderError>>} */ routes.filesListFolderGetLatestCursor = function (arg) { return this.request('files/list_folder/get_latest_cursor', arg, 'user', 'api', 'rpc'); }; /** * A longpoll endpoint to wait for changes on an account. In conjunction with * list_folder/continue, this call gives you a low-latency way to monitor an * account for file changes. The connection will block until there are changes * available or a timeout occurs. This endpoint is useful mostly for client-side * apps. If you're looking for server-side notifications, check out our webhooks * documentation https://www.dropbox.com/developers/reference/webhooks. * @function Dropbox#filesListFolderLongpoll * @arg {FilesListFolderLongpollArg} arg - The request parameters. * @returns {Promise.<FilesListFolderLongpollResult, Error.<FilesListFolderLongpollError>>} */ routes.filesListFolderLongpoll = function (arg) { return this.request('files/list_folder/longpoll', arg, 'noauth', 'notify', 'rpc'); }; /** * Returns revisions for files based on a file path or a file id. The file path * or file id is identified from the latest file entry at the given file path or * id. This end point allows your app to query either by file path or file id by * setting the mode parameter appropriately. In the ListRevisionsMode.path * (default) mode, all revisions at the same file path as the latest file entry * are returned. If revisions with the same file id are desired, then mode must * be set to ListRevisionsMode.id. The ListRevisionsMode.id mode is useful to * retrieve revisions for a given file across moves or renames. * @function Dropbox#filesListRevisions * @arg {FilesListRevisionsArg} arg - The request parameters. * @returns {Promise.<FilesListRevisionsResult, Error.<FilesListRevisionsError>>} */ routes.filesListRevisions = function (arg) { return this.request('files/list_revisions', arg, 'user', 'api', 'rpc'); }; /** * Lock the files at the given paths. A locked file will be writable only by the * lock holder. A successful response indicates that the file has been locked. * Returns a list of the locked file paths and their metadata after this * operation. * @function Dropbox#filesLockFileBatch * @arg {FilesLockFileBatchArg} arg - The request parameters. * @returns {Promise.<FilesLockFileBatchResult, Error.<FilesLockFileError>>} */ routes.filesLockFileBatch = function (arg) { return this.request('files/lock_file_batch', arg, 'user', 'api', 'rpc'); }; /** * Move a file or folder to a different location in the user's Dropbox. If the * source path is a folder all its contents will be moved. Note that we do not * currently support case-only renaming. * @function Dropbox#filesMoveV2 * @arg {FilesRelocationArg} arg - The request parameters. * @returns {Promise.<FilesRelocationResult, Error.<FilesRelocationError>>} */ routes.filesMoveV2 = function (arg) { return this.request('files/move_v2', arg, 'user', 'api', 'rpc'); }; /** * Move a file or folder to a different location in the user's Dropbox. If the * source path is a folder all its contents will be moved. * @function Dropbox#filesMove * @deprecated * @arg {FilesRelocationArg} arg - The request parameters. * @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.<FilesRelocationError>>} */ routes.filesMove = function (arg) { return this.request('files/move', arg, 'user', 'api', 'rpc'); }; /** * Move multiple files or folders to different locations at once in the user's * Dropbox. Note that we do not currently support case-only renaming. This route * will replace move_batch. The main difference is this route will return status * for each entry, while move_batch raises failure if any entry fails. This * route will either finish synchronously, or return a job ID and do the async * move job in background. Please use move_batch/check_v2 to check the job * status. * @function Dropbox#filesMoveBatchV2 * @arg {FilesMoveBatchArg} arg - The request parameters. * @returns {Promise.<FilesRelocationBatchV2Launch, Error.<void>>} */ routes.filesMoveBatchV2 = function (arg) { return this.request('files/move_batch_v2', arg, 'user', 'api', 'rpc'); }; /** * Move multiple files or folders to different locations at once in the user's * Dropbox. This route will return job ID immediately and do the async moving * job in background. Please use move_batch/check to check the job status. * @function Dropbox#filesMoveBatch * @deprecated * @arg {FilesRelocationBatchArg} arg - The request parameters. * @returns {Promise.<FilesRelocationBatchLaunch, Error.<void>>} */ routes.filesMoveBatch = function (arg) { return this.request('files/move_batch', arg, 'user', 'api', 'rpc'); }; /** * Returns the status of an asynchronous job for move_batch_v2. It returns list * of results for each entry. * @function Dropbox#filesMoveBatchCheckV2 * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<FilesRelocationBatchV2JobStatus, Error.<AsyncPollError>>} */ routes.filesMoveBatchCheckV2 = function (arg) { return this.request('files/move_batch/check_v2', arg, 'user', 'api', 'rpc'); }; /** * Returns the status of an asynchronous job for move_batch. If success, it * returns list of results for each entry. * @function Dropbox#filesMoveBatchCheck * @deprecated * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<FilesRelocationBatchJobStatus, Error.<AsyncPollError>>} */ routes.filesMoveBatchCheck = function (arg) { return this.request('files/move_batch/check', arg, 'user', 'api', 'rpc'); }; /** * Permanently delete the file or folder at a given path (see * https://www.dropbox.com/en/help/40). Note: This endpoint is only available * for Dropbox Business apps. * @function Dropbox#filesPermanentlyDelete * @arg {FilesDeleteArg} arg - The request parameters. * @returns {Promise.<void, Error.<FilesDeleteError>>} */ routes.filesPermanentlyDelete = function (arg) { return this.request('files/permanently_delete', arg, 'user', 'api', 'rpc'); }; /** * @function Dropbox#filesPropertiesAdd * @deprecated * @arg {FilePropertiesAddPropertiesArg} arg - The request parameters. * @returns {Promise.<void, Error.<FilePropertiesAddPropertiesError>>} */ routes.filesPropertiesAdd = function (arg) { return this.request('files/properties/add', arg, 'user', 'api', 'rpc'); }; /** * @function Dropbox#filesPropertiesOverwrite * @deprecated * @arg {FilePropertiesOverwritePropertyGroupArg} arg - The request parameters. * @returns {Promise.<void, Error.<FilePropertiesInvalidPropertyGroupError>>} */ routes.filesPropertiesOverwrite = function (arg) { return this.request('files/properties/overwrite', arg, 'user', 'api', 'rpc'); }; /** * @function Dropbox#filesPropertiesRemove * @deprecated * @arg {FilePropertiesRemovePropertiesArg} arg - The request parameters. * @returns {Promise.<void, Error.<FilePropertiesRemovePropertiesError>>} */ routes.filesPropertiesRemove = function (arg) { return this.request('files/properties/remove', arg, 'user', 'api', 'rpc'); }; /** * @function Dropbox#filesPropertiesTemplateGet * @deprecated * @arg {FilePropertiesGetTemplateArg} arg - The request parameters. * @returns {Promise.<FilePropertiesGetTemplateResult, Error.<FilePropertiesTemplateError>>} */ routes.filesPropertiesTemplateGet = function (arg) { return this.request('files/properties/template/get', arg, 'user', 'api', 'rpc'); }; /** * @function Dropbox#filesPropertiesTemplateList * @deprecated * @arg {void} arg - The request parameters. * @returns {Promise.<FilePropertiesListTemplateResult, Error.<FilePropertiesTemplateError>>} */ routes.filesPropertiesTemplateList = function (arg) { return this.request('files/properties/template/list', arg, 'user', 'api', 'rpc'); }; /** * @function Dropbox#filesPropertiesUpdate * @deprecated * @arg {FilePropertiesUpdatePropertiesArg} arg - The request parameters. * @returns {Promise.<void, Error.<FilePropertiesUpdatePropertiesError>>} */ routes.filesPropertiesUpdate = function (arg) { return this.request('files/properties/update', arg, 'user', 'api', 'rpc'); }; /** * Restore a specific revision of a file to the given path. * @function Dropbox#filesRestore * @arg {FilesRestoreArg} arg - The request parameters. * @returns {Promise.<FilesFileMetadata, Error.<FilesRestoreError>>} */ routes.filesRestore = function (arg) { return this.request('files/restore', arg, 'user', 'api', 'rpc'); }; /** * Save the data from a specified URL into a file in user's Dropbox. Note that * the transfer from the URL must complete within 5 minutes, or the operation * will time out and the job will fail. If the given path already exists, the * file will be renamed to avoid the conflict (e.g. myfile (1).txt). * @function Dropbox#filesSaveUrl * @arg {FilesSaveUrlArg} arg - The request parameters. * @returns {Promise.<FilesSaveUrlResult, Error.<FilesSaveUrlError>>} */ routes.filesSaveUrl = function (arg) { return this.request('files/save_url', arg, 'user', 'api', 'rpc'); }; /** * Check the status of a save_url job. * @function Dropbox#filesSaveUrlCheckJobStatus * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<FilesSaveUrlJobStatus, Error.<AsyncPollError>>} */ routes.filesSaveUrlCheckJobStatus = function (arg) { return this.request('files/save_url/check_job_status', arg, 'user', 'api', 'rpc'); }; /** * Searches for files and folders. Note: Recent changes may not immediately be * reflected in search results due to a short delay in indexing. * @function Dropbox#filesSearch * @deprecated * @arg {FilesSearchArg} arg - The request parameters. * @returns {Promise.<FilesSearchResult, Error.<FilesSearchError>>} */ routes.filesSearch = function (arg) { return this.request('files/search', arg, 'user', 'api', 'rpc'); }; /** * Searches for files and folders. Note: search_v2 along with search/continue_v2 * can only be used to retrieve a maximum of 10,000 matches. Recent changes may * not immediately be reflected in search results due to a short delay in * indexing. Duplicate results may be returned across pages. Some results may * not be returned. * @function Dropbox#filesSearchV2 * @arg {FilesSearchV2Arg} arg - The request parameters. * @returns {Promise.<FilesSearchV2Result, Error.<FilesSearchError>>} */ routes.filesSearchV2 = function (arg) { return this.request('files/search_v2', arg, 'user', 'api', 'rpc'); }; /** * Fetches the next page of search results returned from search_v2. Note: * search_v2 along with search/continue_v2 can only be used to retrieve a * maximum of 10,000 matches. Recent changes may not immediately be reflected in * search results due to a short delay in indexing. Duplicate results may be * returned across pages. Some results may not be returned. * @function Dropbox#filesSearchContinueV2 * @arg {FilesSearchV2ContinueArg} arg - The request parameters. * @returns {Promise.<FilesSearchV2Result, Error.<FilesSearchError>>} */ routes.filesSearchContinueV2 = function (arg) { return this.request('files/search/continue_v2', arg, 'user', 'api', 'rpc'); }; /** * Unlock the files at the given paths. A locked file can only be unlocked by * the lock holder or, if a business account, a team admin. A successful * response indicates that the file has been unlocked. Returns a list of the * unlocked file paths and their metadata after this operation. * @function Dropbox#filesUnlockFileBatch * @arg {FilesUnlockFileBatchArg} arg - The request parameters. * @returns {Promise.<FilesLockFileBatchResult, Error.<FilesLockFileError>>} */ routes.filesUnlockFileBatch = function (arg) { return this.request('files/unlock_file_batch', arg, 'user', 'api', 'rpc'); }; /** * Create a new file with the contents provided in the request. Do not use this * to upload a file larger than 150 MB. Instead, create an upload session with * upload_session/start. Calls to this endpoint will count as data transport * calls for any Dropbox Business teams with a limit on the number of data * transport calls allowed per month. For more information, see the Data * transport limit page * https://www.dropbox.com/developers/reference/data-transport-limit. * @function Dropbox#filesUpload * @arg {FilesCommitInfo} arg - The request parameters. * @returns {Promise.<FilesFileMetadata, Error.<FilesUploadError>>} */ routes.filesUpload = function (arg) { return this.request('files/upload', arg, 'user', 'content', 'upload'); }; /** * Append more data to an upload session. When the parameter close is set, this * call will close the session. A single request should not upload more than 150 * MB. The maximum size of a file one can upload to an upload session is 350 GB. * Calls to this endpoint will count as data transport calls for any Dropbox * Business teams with a limit on the number of data transport calls allowed per * month. For more information, see the Data transport limit page * https://www.dropbox.com/developers/reference/data-transport-limit. * @function Dropbox#filesUploadSessionAppendV2 * @arg {FilesUploadSessionAppendArg} arg - The request parameters. * @returns {Promise.<void, Error.<FilesUploadSessionLookupError>>} */ routes.filesUploadSessionAppendV2 = function (arg) { return this.request('files/upload_session/append_v2', arg, 'user', 'content', 'upload'); }; /** * Append more data to an upload session. A single request should not upload * more than 150 MB. The maximum size of a file one can upload to an upload * session is 350 GB. Calls to this endpoint will count as data transport calls * for any Dropbox Business teams with a limit on the number of data transport * calls allowed per month. For more information, see the Data transport limit * page https://www.dropbox.com/developers/reference/data-transport-limit. * @function Dropbox#filesUploadSessionAppend * @deprecated * @arg {FilesUploadSessionCursor} arg - The request parameters. * @returns {Promise.<void, Error.<FilesUploadSessionLookupError>>} */ routes.filesUploadSessionAppend = function (arg) { return this.request('files/upload_session/append', arg, 'user', 'content', 'upload'); }; /** * Finish an upload session and save the uploaded data to the given file path. A * single request should not upload more than 150 MB. The maximum size of a file * one can upload to an upload session is 350 GB. Calls to this endpoint will * count as data transport calls for any Dropbox Business teams with a limit on * the number of data transport calls allowed per month. For more information, * see the Data transport limit page * https://www.dropbox.com/developers/reference/data-transport-limit. * @function Dropbox#filesUploadSessionFinish * @arg {FilesUploadSessionFinishArg} arg - The request parameters. * @returns {Promise.<FilesFileMetadata, Error.<FilesUploadSessionFinishError>>} */ routes.filesUploadSessionFinish = function (arg) { return this.request('files/upload_session/finish', arg, 'user', 'content', 'upload'); }; /** * This route helps you commit many files at once into a user's Dropbox. Use * upload_session/start and upload_session/append_v2 to upload file contents. We * recommend uploading many files in parallel to increase throughput. Once the * file contents have been uploaded, rather than calling upload_session/finish, * use this route to finish all your upload sessions in a single request. * UploadSessionStartArg.close or UploadSessionAppendArg.close needs to be true * for the last upload_session/start or upload_session/append_v2 call. The * maximum size of a file one can upload to an upload session is 350 GB. This * route will return a job_id immediately and do the async commit job in * background. Use upload_session/finish_batch/check to check the job status. * For the same account, this route should be executed serially. That means you * should not start the next job before current job finishes. We allow up to * 1000 entries in a single request. Calls to this endpoint will count as data * transport calls for any Dropbox Business teams with a limit on the number of * data transport calls allowed per month. For more information, see the Data * transport limit page * https://www.dropbox.com/developers/reference/data-transport-limit. * @function Dropbox#filesUploadSessionFinishBatch * @arg {FilesUploadSessionFinishBatchArg} arg - The request parameters. * @returns {Promise.<FilesUploadSessionFinishBatchLaunch, Error.<void>>} */ routes.filesUploadSessionFinishBatch = function (arg) { return this.request('files/upload_session/finish_batch', arg, 'user', 'api', 'rpc'); }; /** * Returns the status of an asynchronous job for upload_session/finish_batch. If * success, it returns list of result for each entry. * @function Dropbox#filesUploadSessionFinishBatchCheck * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<FilesUploadSessionFinishBatchJobStatus, Error.<AsyncPollError>>} */ routes.filesUploadSessionFinishBatchCheck = function (arg) { return this.request('files/upload_session/finish_batch/check', arg, 'user', 'api', 'rpc'); }; /** * Upload sessions allow you to upload a single file in one or more requests, * for example where the size of the file is greater than 150 MB. This call * starts a new upload session with the given data. You can then use * upload_session/append_v2 to add more data and upload_session/finish to save * all the data to a file in Dropbox. A single request should not upload more * than 150 MB. The maximum size of a file one can upload to an upload session * is 350 GB. An upload session can be used for a maximum of 48 hours. * Attempting to use an UploadSessionStartResult.session_id with * upload_session/append_v2 or upload_session/finish more than 48 hours after * its creation will return a UploadSessionLookupError.not_found. Calls to this * endpoint will count as data transport calls for any Dropbox Business teams * with a limit on the number of data transport calls allowed per month. For * more information, see the Data transport limit page * https://www.dropbox.com/developers/reference/data-transport-limit. * @function Dropbox#filesUploadSessionStart * @arg {FilesUploadSessionStartArg} arg - The request parameters. * @returns {Promise.<FilesUploadSessionStartResult, Error.<void>>} */ routes.filesUploadSessionStart = function (arg) { return this.request('files/upload_session/start', arg, 'user', 'content', 'upload'); }; /** * Marks the given Paper doc as archived. This action can be performed or undone * by anyone with edit permissions to the doc. Note that this endpoint will * continue to work for content created by users on the older version of Paper. * To check which version of Paper a user is on, use /users/features/get_values. * If the paper_as_files feature is enabled, then the user is running the new * version of Paper. This endpoint will be retired in September 2020. Refer to * the Paper Migration Guide * https://www.dropbox.com/lp/developers/reference/paper-migration-guide for * more information. * @function Dropbox#paperDocsArchive * @deprecated * @arg {PaperRefPaperDoc} arg - The request parameters. * @returns {Promise.<void, Error.<PaperDocLookupError>>} */ routes.paperDocsArchive = function (arg) { return this.request('paper/docs/archive', arg, 'user', 'api', 'rpc'); }; /** * Creates a new Paper doc with the provided content. Note that this endpoint * will continue to work for content created by users on the older version of * Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, then * the user is running the new version of Paper. This endpoint will be retired * in September 2020. Refer to the Paper Migration Guide * https://www.dropbox.com/lp/developers/reference/paper-migration-guide for * more information. * @function Dropbox#paperDocsCreate * @deprecated * @arg {PaperPaperDocCreateArgs} arg - The request parameters. * @returns {Promise.<PaperPaperDocCreateUpdateResult, Error.<PaperPaperDocCreateError>>} */ routes.paperDocsCreate = function (arg) { return this.request('paper/docs/create', arg, 'user', 'api', 'upload'); }; /** * Exports and downloads Paper doc either as HTML or markdown. Note that this * endpoint will continue to work for content created by users on the older * version of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, then * the user is running the new version of Paper. Refer to the Paper Migration * Guide https://www.dropbox.com/lp/developers/reference/paper-migration-guide * for migration information. * @function Dropbox#paperDocsDownload * @deprecated * @arg {PaperPaperDocExport} arg - The request parameters. * @returns {Promise.<PaperPaperDocExportResult, Error.<PaperDocLookupError>>} */ routes.paperDocsDownload = function (arg) { return this.request('paper/docs/download', arg, 'user', 'api', 'download'); }; /** * Lists the users who are explicitly invited to the Paper folder in which the * Paper doc is contained. For private folders all users (including owner) * shared on the folder are listed and for team folders all non-team users * shared on the folder are returned. Note that this endpoint will continue to * work for content created by users on the older version of Paper. To check * which version of Paper a user is on, use /users/features/get_values. If the * paper_as_files feature is enabled, then the user is running the new version * of Paper. Refer to the Paper Migration Guide * https://www.dropbox.com/lp/developers/reference/paper-migration-guide for * migration information. * @function Dropbox#paperDocsFolderUsersList * @deprecated * @arg {PaperListUsersOnFolderArgs} arg - The request parameters. * @returns {Promise.<PaperListUsersOnFolderResponse, Error.<PaperDocLookupError>>} */ routes.paperDocsFolderUsersList = function (arg) { return this.request('paper/docs/folder_users/list', arg, 'user', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from docs/folder_users/list, use this to * paginate through all users on the Paper folder. Note that this endpoint will * continue to work for content created by users on the older version of Paper. * To check which version of Paper a user is on, use /users/features/get_values. * If the paper_as_files feature is enabled, then the user is running the new * version of Paper. Refer to the Paper Migration Guide * https://www.dropbox.com/lp/developers/reference/paper-migration-guide for * migration information. * @function Dropbox#paperDocsFolderUsersListContinue * @deprecated * @arg {PaperListUsersOnFolderContinueArgs} arg - The request parameters. * @returns {Promise.<PaperListUsersOnFolderResponse, Error.<PaperListUsersCursorError>>} */ routes.paperDocsFolderUsersListContinue = function (arg) { return this.request('paper/docs/folder_users/list/continue', arg, 'user', 'api', 'rpc'); }; /** * Retrieves folder information for the given Paper doc. This includes: - * folder sharing policy; permissions for subfolders are set by the top-level * folder. - full 'filepath', i.e. the list of folders (both folderId and * folderName) from the root folder to the folder directly containing the * Paper doc. If the Paper doc is not in any folder (aka unfiled) the response * will be empty. Note that this endpoint will continue to work for content * created by users on the older version of Paper. To check which version of * Paper a user is on, use /users/features/get_values. If the paper_as_files * feature is enabled, then the user is running the new version of Paper. Refer * to the Paper Migration Guide * https://www.dropbox.com/lp/developers/reference/paper-migration-guide for * migration information. * @function Dropbox#paperDocsGetFolderInfo * @deprecated * @arg {PaperRefPaperDoc} arg - The request parameters. * @returns {Promise.<PaperFoldersContainingPaperDoc, Error.<PaperDocLookupError>>} */ routes.paperDocsGetFolderInfo = function (arg) { return this.request('paper/docs/get_folder_info', arg, 'user', 'api', 'rpc'); }; /** * Return the list of all Paper docs according to the argument specifications. * To iterate over through the full pagination, pass the cursor to * docs/list/continue. Note that this endpoint will continue to work for content * created by users on the older version of Paper. To check which version of * Paper a user is on, use /users/features/get_values. If the paper_as_files * feature is enabled, then the user is running the new version of Paper. Refer * to the Paper Migration Guide * https://www.dropbox.com/lp/developers/reference/paper-migration-guide for * migration information. * @function Dropbox#paperDocsList * @deprecated * @arg {PaperListPaperDocsArgs} arg - The request parameters. * @returns {Promise.<PaperListPaperDocsResponse, Error.<void>>} */ routes.paperDocsList = function (arg) { return this.request('paper/docs/list', arg, 'user', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from docs/list, use this to paginate through * all Paper doc. Note that this endpoint will continue to work for content * created by users on the older version of Paper. To check which version of * Paper a user is on, use /users/features/get_values. If the paper_as_files * feature is enabled, then the user is running the new version of Paper. Refer * to the Paper Migration Guide * https://www.dropbox.com/lp/developers/reference/paper-migration-guide for * migration information. * @function Dropbox#paperDocsListContinue * @deprecated * @arg {PaperListPaperDocsContinueArgs} arg - The request parameters. * @returns {Promise.<PaperListPaperDocsResponse, Error.<PaperListDocsCursorError>>} */ routes.paperDocsListContinue = function (arg) { return this.request('paper/docs/list/continue', arg, 'user', 'api', 'rpc'); }; /** * Permanently deletes the given Paper doc. This operation is final as the doc * cannot be recovered. This action can be performed only by the doc owner. Note * that this endpoint will continue to work for content created by users on the * older version of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, then * the user is running the new version of Paper. Refer to the Paper Migration * Guide https://www.dropbox.com/lp/developers/reference/paper-migration-guide * for migration information. * @function Dropbox#paperDocsPermanentlyDelete * @deprecated * @arg {PaperRefPaperDoc} arg - The request parameters. * @returns {Promise.<void, Error.<PaperDocLookupError>>} */ routes.paperDocsPermanentlyDelete = function (arg) { return this.request('paper/docs/permanently_delete', arg, 'user', 'api', 'rpc'); }; /** * Gets the default sharing policy for the given Paper doc. Note that this * endpoint will continue to work for content created by users on the older * version of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, then * the user is running the new version of Paper. Refer to the Paper Migration * Guide https://www.dropbox.com/lp/developers/reference/paper-migration-guide * for migration information. * @function Dropbox#paperDocsSharingPolicyGet * @deprecated * @arg {PaperRefPaperDoc} arg - The request parameters. * @returns {Promise.<PaperSharingPolicy, Error.<PaperDocLookupError>>} */ routes.paperDocsSharingPolicyGet = function (arg) { return this.request('paper/docs/sharing_policy/get', arg, 'user', 'api', 'rpc'); }; /** * Sets the default sharing policy for the given Paper doc. The default * 'team_sharing_policy' can be changed only by teams, omit this field for * personal accounts. The 'public_sharing_policy' policy can't be set to the * value 'disabled' because this setting can be changed only via the team admin * console. Note that this endpoint will continue to work for content created by * users on the older version of Paper. To check which version of Paper a user * is on, use /users/features/get_values. If the paper_as_files feature is * enabled, then the user is running the new version of Paper. Refer to the * Paper Migration Guide * https://www.dropbox.com/lp/developers/reference/paper-migration-guide for * migration information. * @function Dropbox#paperDocsSharingPolicySet * @deprecated * @arg {PaperPaperDocSharingPolicy} arg - The request parameters. * @returns {Promise.<void, Error.<PaperDocLookupError>>} */ routes.paperDocsSharingPolicySet = function (arg) { return this.request('paper/docs/sharing_policy/set', arg, 'user', 'api', 'rpc'); }; /** * Updates an existing Paper doc with the provided content. Note that this * endpoint will continue to work for content created by users on the older * version of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, then * the user is running the new version of Paper. This endpoint will be retired * in September 2020. Refer to the Paper Migration Guide * https://www.dropbox.com/lp/developers/reference/paper-migration-guide for * more information. * @function Dropbox#paperDocsUpdate * @deprecated * @arg {PaperPaperDocUpdateArgs} arg - The request parameters. * @returns {Promise.<PaperPaperDocCreateUpdateResult, Error.<PaperPaperDocUpdateError>>} */ routes.paperDocsUpdate = function (arg) { return this.request('paper/docs/update', arg, 'user', 'api', 'upload'); }; /** * Allows an owner or editor to add users to a Paper doc or change their * permissions using their email address or Dropbox account ID. The doc owner's * permissions cannot be changed. Note that this endpoint will continue to work * for content created by users on the older version of Paper. To check which * version of Paper a user is on, use /users/features/get_values. If the * paper_as_files feature is enabled, then the user is running the new version * of Paper. Refer to the Paper Migration Guide * https://www.dropbox.com/lp/developers/reference/paper-migration-guide for * migration information. * @function Dropbox#paperDocsUsersAdd * @deprecated * @arg {PaperAddPaperDocUser} arg - The request parameters. * @returns {Promise.<Array.<PaperAddPaperDocUserMemberResult>, Error.<PaperDocLookupError>>} */ routes.paperDocsUsersAdd = function (arg) { return this.request('paper/docs/users/add', arg, 'user', 'api', 'rpc'); }; /** * Lists all users who visited the Paper doc or users with explicit access. This * call excludes users who have been removed. The list is sorted by the date of * the visit or the share date. The list will include both users, the explicitly * shared ones as well as those who came in using the Paper url link. Note that * this endpoint will continue to work for content created by users on the older * version of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, then * the user is running the new version of Paper. Refer to the Paper Migration * Guide https://www.dropbox.com/lp/developers/reference/paper-migration-guide * for migration information. * @function Dropbox#paperDocsUsersList * @deprecated * @arg {PaperListUsersOnPaperDocArgs} arg - The request parameters. * @returns {Promise.<PaperListUsersOnPaperDocResponse, Error.<PaperDocLookupError>>} */ routes.paperDocsUsersList = function (arg) { return this.request('paper/docs/users/list', arg, 'user', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from docs/users/list, use this to paginate * through all users on the Paper doc. Note that this endpoint will continue to * work for content created by users on the older version of Paper. To check * which version of Paper a user is on, use /users/features/get_values. If the * paper_as_files feature is enabled, then the user is running the new version * of Paper. Refer to the Paper Migration Guide * https://www.dropbox.com/lp/developers/reference/paper-migration-guide for * migration information. * @function Dropbox#paperDocsUsersListContinue * @deprecated * @arg {PaperListUsersOnPaperDocContinueArgs} arg - The request parameters. * @returns {Promise.<PaperListUsersOnPaperDocResponse, Error.<PaperListUsersCursorError>>} */ routes.paperDocsUsersListContinue = function (arg) { return this.request('paper/docs/users/list/continue', arg, 'user', 'api', 'rpc'); }; /** * Allows an owner or editor to remove users from a Paper doc using their email * address or Dropbox account ID. The doc owner cannot be removed. Note that * this endpoint will continue to work for content created by users on the older * version of Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, then * the user is running the new version of Paper. Refer to the Paper Migration * Guide https://www.dropbox.com/lp/developers/reference/paper-migration-guide * for migration information. * @function Dropbox#paperDocsUsersRemove * @deprecated * @arg {PaperRemovePaperDocUser} arg - The request parameters. * @returns {Promise.<void, Error.<PaperDocLookupError>>} */ routes.paperDocsUsersRemove = function (arg) { return this.request('paper/docs/users/remove', arg, 'user', 'api', 'rpc'); }; /** * Create a new Paper folder with the provided info. Note that this endpoint * will continue to work for content created by users on the older version of * Paper. To check which version of Paper a user is on, use * /users/features/get_values. If the paper_as_files feature is enabled, then * the user is running the new version of Paper. Refer to the Paper Migration * Guide https://www.dropbox.com/lp/developers/reference/paper-migration-guide * for migration information. * @function Dropbox#paperFoldersCreate * @deprecated * @arg {PaperPaperFolderCreateArg} arg - The request parameters. * @returns {Promise.<PaperPaperFolderCreateResult, Error.<PaperPaperFolderCreateError>>} */ routes.paperFoldersCreate = function (arg) { return this.request('paper/folders/create', arg, 'user', 'api', 'rpc'); }; /** * Adds specified members to a file. * @function Dropbox#sharingAddFileMember * @arg {SharingAddFileMemberArgs} arg - The request parameters. * @returns {Promise.<Array.<SharingFileMemberActionResult>, Error.<SharingAddFileMemberError>>} */ routes.sharingAddFileMember = function (arg) { return this.request('sharing/add_file_member', arg, 'user', 'api', 'rpc'); }; /** * Allows an owner or editor (if the ACL update policy allows) of a shared * folder to add another member. For the new member to get access to all the * functionality for this folder, you will need to call mount_folder on their * behalf. * @function Dropbox#sharingAddFolderMember * @arg {SharingAddFolderMemberArg} arg - The request parameters. * @returns {Promise.<void, Error.<SharingAddFolderMemberError>>} */ routes.sharingAddFolderMember = function (arg) { return this.request('sharing/add_folder_member', arg, 'user', 'api', 'rpc'); }; /** * Identical to update_file_member but with less information returned. * @function Dropbox#sharingChangeFileMemberAccess * @deprecated * @arg {SharingChangeFileMemberAccessArgs} arg - The request parameters. * @returns {Promise.<SharingFileMemberActionResult, Error.<SharingFileMemberActionError>>} */ routes.sharingChangeFileMemberAccess = function (arg) { return this.request('sharing/change_file_member_access', arg, 'user', 'api', 'rpc'); }; /** * Returns the status of an asynchronous job. * @function Dropbox#sharingCheckJobStatus * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<SharingJobStatus, Error.<AsyncPollError>>} */ routes.sharingCheckJobStatus = function (arg) { return this.request('sharing/check_job_status', arg, 'user', 'api', 'rpc'); }; /** * Returns the status of an asynchronous job for sharing a folder. * @function Dropbox#sharingCheckRemoveMemberJobStatus * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<SharingRemoveMemberJobStatus, Error.<AsyncPollError>>} */ routes.sharingCheckRemoveMemberJobStatus = function (arg) { return this.request('sharing/check_remove_member_job_status', arg, 'user', 'api', 'rpc'); }; /** * Returns the status of an asynchronous job for sharing a folder. * @function Dropbox#sharingCheckShareJobStatus * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<SharingShareFolderJobStatus, Error.<AsyncPollError>>} */ routes.sharingCheckShareJobStatus = function (arg) { return this.request('sharing/check_share_job_status', arg, 'user', 'api', 'rpc'); }; /** * Create a shared link. If a shared link already exists for the given path, * that link is returned. Note that in the returned PathLinkMetadata, the * PathLinkMetadata.url field is the shortened URL if * CreateSharedLinkArg.short_url argument is set to true. Previously, it was * technically possible to break a shared link by moving or renaming the * corresponding file or folder. In the future, this will no longer be the case, * so your app shouldn't rely on this behavior. Instead, if your app needs to * revoke a shared link, use revoke_shared_link. * @function Dropbox#sharingCreateSharedLink * @deprecated * @arg {SharingCreateSharedLinkArg} arg - The request parameters. * @returns {Promise.<SharingPathLinkMetadata, Error.<SharingCreateSharedLinkError>>} */ routes.sharingCreateSharedLink = function (arg) { return this.request('sharing/create_shared_link', arg, 'user', 'api', 'rpc'); }; /** * Create a shared link with custom settings. If no settings are given then the * default visibility is RequestedVisibility.public (The resolved visibility, * though, may depend on other aspects such as team and shared folder settings). * @function Dropbox#sharingCreateSharedLinkWithSettings * @arg {SharingCreateSharedLinkWithSettingsArg} arg - The request parameters. * @returns {Promise.<(SharingFileLinkMetadata|SharingFolderLinkMetadata|SharingSharedLinkMetadata), Error.<SharingCreateSharedLinkWithSettingsError>>} */ routes.sharingCreateSharedLinkWithSettings = function (arg) { return this.request('sharing/create_shared_link_with_settings', arg, 'user', 'api', 'rpc'); }; /** * Returns shared file metadata. * @function Dropbox#sharingGetFileMetadata * @arg {SharingGetFileMetadataArg} arg - The request parameters. * @returns {Promise.<SharingSharedFileMetadata, Error.<SharingGetFileMetadataError>>} */ routes.sharingGetFileMetadata = function (arg) { return this.request('sharing/get_file_metadata', arg, 'user', 'api', 'rpc'); }; /** * Returns shared file metadata. * @function Dropbox#sharingGetFileMetadataBatch * @arg {SharingGetFileMetadataBatchArg} arg - The request parameters. * @returns {Promise.<Array.<SharingGetFileMetadataBatchResult>, Error.<SharingSharingUserError>>} */ routes.sharingGetFileMetadataBatch = function (arg) { return this.request('sharing/get_file_metadata/batch', arg, 'user', 'api', 'rpc'); }; /** * Returns shared folder metadata by its folder ID. * @function Dropbox#sharingGetFolderMetadata * @arg {SharingGetMetadataArgs} arg - The request parameters. * @returns {Promise.<SharingSharedFolderMetadata, Error.<SharingSharedFolderAccessError>>} */ routes.sharingGetFolderMetadata = function (arg) { return this.request('sharing/get_folder_metadata', arg, 'user', 'api', 'rpc'); }; /** * Download the shared link's file from a user's Dropbox. * @function Dropbox#sharingGetSharedLinkFile * @arg {Object} arg - The request parameters. * @returns {Promise.<(SharingFileLinkMetadata|SharingFolderLinkMetadata|SharingSharedLinkMetadata), Error.<SharingGetSharedLinkFileError>>} */ routes.sharingGetSharedLinkFile = function (arg) { return this.request('sharing/get_shared_link_file', arg, 'user', 'content', 'download'); }; /** * Get the shared link's metadata. * @function Dropbox#sharingGetSharedLinkMetadata * @arg {SharingGetSharedLinkMetadataArg} arg - The request parameters. * @returns {Promise.<(SharingFileLinkMetadata|SharingFolderLinkMetadata|SharingSharedLinkMetadata), Error.<SharingSharedLinkError>>} */ routes.sharingGetSharedLinkMetadata = function (arg) { return this.request('sharing/get_shared_link_metadata', arg, 'user', 'api', 'rpc'); }; /** * Returns a list of LinkMetadata objects for this user, including collection * links. If no path is given, returns a list of all shared links for the * current user, including collection links, up to a maximum of 1000 links. If a * non-empty path is given, returns a list of all shared links that allow access * to the given path. Collection links are never returned in this case. Note * that the url field in the response is never the shortened URL. * @function Dropbox#sharingGetSharedLinks * @deprecated * @arg {SharingGetSharedLinksArg} arg - The request parameters. * @returns {Promise.<SharingGetSharedLinksResult, Error.<SharingGetSharedLinksError>>} */ routes.sharingGetSharedLinks = function (arg) { return this.request('sharing/get_shared_links', arg, 'user', 'api', 'rpc'); }; /** * Use to obtain the members who have been invited to a file, both inherited and * uninherited members. * @function Dropbox#sharingListFileMembers * @arg {SharingListFileMembersArg} arg - The request parameters. * @returns {Promise.<SharingSharedFileMembers, Error.<SharingListFileMembersError>>} */ routes.sharingListFileMembers = function (arg) { return this.request('sharing/list_file_members', arg, 'user', 'api', 'rpc'); }; /** * Get members of multiple files at once. The arguments to this route are more * limited, and the limit on query result size per file is more strict. To * customize the results more, use the individual file endpoint. Inherited users * and groups are not included in the result, and permissions are not returned * for this endpoint. * @function Dropbox#sharingListFileMembersBatch * @arg {SharingListFileMembersBatchArg} arg - The request parameters. * @returns {Promise.<Array.<SharingListFileMembersBatchResult>, Error.<SharingSharingUserError>>} */ routes.sharingListFileMembersBatch = function (arg) { return this.request('sharing/list_file_members/batch', arg, 'user', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from list_file_members or * list_file_members/batch, use this to paginate through all shared file * members. * @function Dropbox#sharingListFileMembersContinue * @arg {SharingListFileMembersContinueArg} arg - The request parameters. * @returns {Promise.<SharingSharedFileMembers, Error.<SharingListFileMembersContinueError>>} */ routes.sharingListFileMembersContinue = function (arg) { return this.request('sharing/list_file_members/continue', arg, 'user', 'api', 'rpc'); }; /** * Returns shared folder membership by its folder ID. * @function Dropbox#sharingListFolderMembers * @arg {SharingListFolderMembersArgs} arg - The request parameters. * @returns {Promise.<SharingSharedFolderMembers, Error.<SharingSharedFolderAccessError>>} */ routes.sharingListFolderMembers = function (arg) { return this.request('sharing/list_folder_members', arg, 'user', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from list_folder_members, use this to * paginate through all shared folder members. * @function Dropbox#sharingListFolderMembersContinue * @arg {SharingListFolderMembersContinueArg} arg - The request parameters. * @returns {Promise.<SharingSharedFolderMembers, Error.<SharingListFolderMembersContinueError>>} */ routes.sharingListFolderMembersContinue = function (arg) { return this.request('sharing/list_folder_members/continue', arg, 'user', 'api', 'rpc'); }; /** * Return the list of all shared folders the current user has access to. * @function Dropbox#sharingListFolders * @arg {SharingListFoldersArgs} arg - The request parameters. * @returns {Promise.<SharingListFoldersResult, Error.<void>>} */ routes.sharingListFolders = function (arg) { return this.request('sharing/list_folders', arg, 'user', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from list_folders, use this to paginate * through all shared folders. The cursor must come from a previous call to * list_folders or list_folders/continue. * @function Dropbox#sharingListFoldersContinue * @arg {SharingListFoldersContinueArg} arg - The request parameters. * @returns {Promise.<SharingListFoldersResult, Error.<SharingListFoldersContinueError>>} */ routes.sharingListFoldersContinue = function (arg) { return this.request('sharing/list_folders/continue', arg, 'user', 'api', 'rpc'); }; /** * Return the list of all shared folders the current user can mount or unmount. * @function Dropbox#sharingListMountableFolders * @arg {SharingListFoldersArgs} arg - The request parameters. * @returns {Promise.<SharingListFoldersResult, Error.<void>>} */ routes.sharingListMountableFolders = function (arg) { return this.request('sharing/list_mountable_folders', arg, 'user', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from list_mountable_folders, use this to * paginate through all mountable shared folders. The cursor must come from a * previous call to list_mountable_folders or list_mountable_folders/continue. * @function Dropbox#sharingListMountableFoldersContinue * @arg {SharingListFoldersContinueArg} arg - The request parameters. * @returns {Promise.<SharingListFoldersResult, Error.<SharingListFoldersContinueError>>} */ routes.sharingListMountableFoldersContinue = function (arg) { return this.request('sharing/list_mountable_folders/continue', arg, 'user', 'api', 'rpc'); }; /** * Returns a list of all files shared with current user. Does not include files * the user has received via shared folders, and does not include unclaimed * invitations. * @function Dropbox#sharingListReceivedFiles * @arg {SharingListFilesArg} arg - The request parameters. * @returns {Promise.<SharingListFilesResult, Error.<SharingSharingUserError>>} */ routes.sharingListReceivedFiles = function (arg) { return this.request('sharing/list_received_files', arg, 'user', 'api', 'rpc'); }; /** * Get more results with a cursor from list_received_files. * @function Dropbox#sharingListReceivedFilesContinue * @arg {SharingListFilesContinueArg} arg - The request parameters. * @returns {Promise.<SharingListFilesResult, Error.<SharingListFilesContinueError>>} */ routes.sharingListReceivedFilesContinue = function (arg) { return this.request('sharing/list_received_files/continue', arg, 'user', 'api', 'rpc'); }; /** * List shared links of this user. If no path is given, returns a list of all * shared links for the current user. If a non-empty path is given, returns a * list of all shared links that allow access to the given path - direct links * to the given path and links to parent folders of the given path. Links to * parent folders can be suppressed by setting direct_only to true. * @function Dropbox#sharingListSharedLinks * @arg {SharingListSharedLinksArg} arg - The request parameters. * @returns {Promise.<SharingListSharedLinksResult, Error.<SharingListSharedLinksError>>} */ routes.sharingListSharedLinks = function (arg) { return this.request('sharing/list_shared_links', arg, 'user', 'api', 'rpc'); }; /** * Modify the shared link's settings. If the requested visibility conflict with * the shared links policy of the team or the shared folder (in case the linked * file is part of a shared folder) then the LinkPermissions.resolved_visibility * of the returned SharedLinkMetadata will reflect the actual visibility of the * shared link and the LinkPermissions.requested_visibility will reflect the * requested visibility. * @function Dropbox#sharingModifySharedLinkSettings * @arg {SharingModifySharedLinkSettingsArgs} arg - The request parameters. * @returns {Promise.<(SharingFileLinkMetadata|SharingFolderLinkMetadata|SharingSharedLinkMetadata), Error.<SharingModifySharedLinkSettingsError>>} */ routes.sharingModifySharedLinkSettings = function (arg) { return this.request('sharing/modify_shared_link_settings', arg, 'user', 'api', 'rpc'); }; /** * The current user mounts the designated folder. Mount a shared folder for a * user after they have been added as a member. Once mounted, the shared folder * will appear in their Dropbox. * @function Dropbox#sharingMountFolder * @arg {SharingMountFolderArg} arg - The request parameters. * @returns {Promise.<SharingSharedFolderMetadata, Error.<SharingMountFolderError>>} */ routes.sharingMountFolder = function (arg) { return this.request('sharing/mount_folder', arg, 'user', 'api', 'rpc'); }; /** * The current user relinquishes their membership in the designated file. Note * that the current user may still have inherited access to this file through * the parent folder. * @function Dropbox#sharingRelinquishFileMembership * @arg {SharingRelinquishFileMembershipArg} arg - The request parameters. * @returns {Promise.<void, Error.<SharingRelinquishFileMembershipError>>} */ routes.sharingRelinquishFileMembership = function (arg) { return this.request('sharing/relinquish_file_membership', arg, 'user', 'api', 'rpc'); }; /** * The current user relinquishes their membership in the designated shared * folder and will no longer have access to the folder. A folder owner cannot * relinquish membership in their own folder. This will run synchronously if * leave_a_copy is false, and asynchronously if leave_a_copy is true. * @function Dropbox#sharingRelinquishFolderMembership * @arg {SharingRelinquishFolderMembershipArg} arg - The request parameters. * @returns {Promise.<AsyncLaunchEmptyResult, Error.<SharingRelinquishFolderMembershipError>>} */ routes.sharingRelinquishFolderMembership = function (arg) { return this.request('sharing/relinquish_folder_membership', arg, 'user', 'api', 'rpc'); }; /** * Identical to remove_file_member_2 but with less information returned. * @function Dropbox#sharingRemoveFileMember * @deprecated * @arg {SharingRemoveFileMemberArg} arg - The request parameters. * @returns {Promise.<SharingFileMemberActionIndividualResult, Error.<SharingRemoveFileMemberError>>} */ routes.sharingRemoveFileMember = function (arg) { return this.request('sharing/remove_file_member', arg, 'user', 'api', 'rpc'); }; /** * Removes a specified member from the file. * @function Dropbox#sharingRemoveFileMember2 * @arg {SharingRemoveFileMemberArg} arg - The request parameters. * @returns {Promise.<SharingFileMemberRemoveActionResult, Error.<SharingRemoveFileMemberError>>} */ routes.sharingRemoveFileMember2 = function (arg) { return this.request('sharing/remove_file_member_2', arg, 'user', 'api', 'rpc'); }; /** * Allows an owner or editor (if the ACL update policy allows) of a shared * folder to remove another member. * @function Dropbox#sharingRemoveFolderMember * @arg {SharingRemoveFolderMemberArg} arg - The request parameters. * @returns {Promise.<AsyncLaunchResultBase, Error.<SharingRemoveFolderMemberError>>} */ routes.sharingRemoveFolderMember = function (arg) { return this.request('sharing/remove_folder_member', arg, 'user', 'api', 'rpc'); }; /** * Revoke a shared link. Note that even after revoking a shared link to a file, * the file may be accessible if there are shared links leading to any of the * file parent folders. To list all shared links that enable access to a * specific file, you can use the list_shared_links with the file as the * ListSharedLinksArg.path argument. * @function Dropbox#sharingRevokeSharedLink * @arg {SharingRevokeSharedLinkArg} arg - The request parameters. * @returns {Promise.<void, Error.<SharingRevokeSharedLinkError>>} */ routes.sharingRevokeSharedLink = function (arg) { return this.request('sharing/revoke_shared_link', arg, 'user', 'api', 'rpc'); }; /** * Change the inheritance policy of an existing Shared Folder. Only permitted * for shared folders in a shared team root. If a ShareFolderLaunch.async_job_id * is returned, you'll need to call check_share_job_status until the action * completes to get the metadata for the folder. * @function Dropbox#sharingSetAccessInheritance * @arg {SharingSetAccessInheritanceArg} arg - The request parameters. * @returns {Promise.<SharingShareFolderLaunch, Error.<SharingSetAccessInheritanceError>>} */ routes.sharingSetAccessInheritance = function (arg) { return this.request('sharing/set_access_inheritance', arg, 'user', 'api', 'rpc'); }; /** * Share a folder with collaborators. Most sharing will be completed * synchronously. Large folders will be completed asynchronously. To make * testing the async case repeatable, set `ShareFolderArg.force_async`. If a * ShareFolderLaunch.async_job_id is returned, you'll need to call * check_share_job_status until the action completes to get the metadata for the * folder. * @function Dropbox#sharingShareFolder * @arg {SharingShareFolderArg} arg - The request parameters. * @returns {Promise.<SharingShareFolderLaunch, Error.<SharingShareFolderError>>} */ routes.sharingShareFolder = function (arg) { return this.request('sharing/share_folder', arg, 'user', 'api', 'rpc'); }; /** * Transfer ownership of a shared folder to a member of the shared folder. User * must have AccessLevel.owner access to the shared folder to perform a * transfer. * @function Dropbox#sharingTransferFolder * @arg {SharingTransferFolderArg} arg - The request parameters. * @returns {Promise.<void, Error.<SharingTransferFolderError>>} */ routes.sharingTransferFolder = function (arg) { return this.request('sharing/transfer_folder', arg, 'user', 'api', 'rpc'); }; /** * The current user unmounts the designated folder. They can re-mount the folder * at a later time using mount_folder. * @function Dropbox#sharingUnmountFolder * @arg {SharingUnmountFolderArg} arg - The request parameters. * @returns {Promise.<void, Error.<SharingUnmountFolderError>>} */ routes.sharingUnmountFolder = function (arg) { return this.request('sharing/unmount_folder', arg, 'user', 'api', 'rpc'); }; /** * Remove all members from this file. Does not remove inherited members. * @function Dropbox#sharingUnshareFile * @arg {SharingUnshareFileArg} arg - The request parameters. * @returns {Promise.<void, Error.<SharingUnshareFileError>>} */ routes.sharingUnshareFile = function (arg) { return this.request('sharing/unshare_file', arg, 'user', 'api', 'rpc'); }; /** * Allows a shared folder owner to unshare the folder. You'll need to call * check_job_status to determine if the action has completed successfully. * @function Dropbox#sharingUnshareFolder * @arg {SharingUnshareFolderArg} arg - The request parameters. * @returns {Promise.<AsyncLaunchEmptyResult, Error.<SharingUnshareFolderError>>} */ routes.sharingUnshareFolder = function (arg) { return this.request('sharing/unshare_folder', arg, 'user', 'api', 'rpc'); }; /** * Changes a member's access on a shared file. * @function Dropbox#sharingUpdateFileMember * @arg {SharingUpdateFileMemberArgs} arg - The request parameters. * @returns {Promise.<SharingMemberAccessLevelResult, Error.<SharingFileMemberActionError>>} */ routes.sharingUpdateFileMember = function (arg) { return this.request('sharing/update_file_member', arg, 'user', 'api', 'rpc'); }; /** * Allows an owner or editor of a shared folder to update another member's * permissions. * @function Dropbox#sharingUpdateFolderMember * @arg {SharingUpdateFolderMemberArg} arg - The request parameters. * @returns {Promise.<SharingMemberAccessLevelResult, Error.<SharingUpdateFolderMemberError>>} */ routes.sharingUpdateFolderMember = function (arg) { return this.request('sharing/update_folder_member', arg, 'user', 'api', 'rpc'); }; /** * Update the sharing policies for a shared folder. User must have * AccessLevel.owner access to the shared folder to update its policies. * @function Dropbox#sharingUpdateFolderPolicy * @arg {SharingUpdateFolderPolicyArg} arg - The request parameters. * @returns {Promise.<SharingSharedFolderMetadata, Error.<SharingUpdateFolderPolicyError>>} */ routes.sharingUpdateFolderPolicy = function (arg) { return this.request('sharing/update_folder_policy', arg, 'user', 'api', 'rpc'); }; /** * Retrieves team events. If the result's GetTeamEventsResult.has_more field is * true, call get_events/continue with the returned cursor to retrieve more * entries. If end_time is not specified in your request, you may use the * returned cursor to poll get_events/continue for new events. Many attributes * note 'may be missing due to historical data gap'. Note that the * file_operations category and & analogous paper events are not available on * all Dropbox Business plans /business/plans-comparison. Use * features/get_values * /developers/documentation/http/teams#team-features-get_values to check for * this feature. Permission : Team Auditing. * @function Dropbox#teamLogGetEvents * @arg {TeamLogGetTeamEventsArg} arg - The request parameters. * @returns {Promise.<TeamLogGetTeamEventsResult, Error.<TeamLogGetTeamEventsError>>} */ routes.teamLogGetEvents = function (arg) { return this.request('team_log/get_events', arg, 'team', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from get_events, use this to paginate * through all events. Permission : Team Auditing. * @function Dropbox#teamLogGetEventsContinue * @arg {TeamLogGetTeamEventsContinueArg} arg - The request parameters. * @returns {Promise.<TeamLogGetTeamEventsResult, Error.<TeamLogGetTeamEventsContinueError>>} */ routes.teamLogGetEventsContinue = function (arg) { return this.request('team_log/get_events/continue', arg, 'team', 'api', 'rpc'); }; /** * Get a list of feature values that may be configured for the current account. * @function Dropbox#usersFeaturesGetValues * @arg {UsersUserFeaturesGetValuesBatchArg} arg - The request parameters. * @returns {Promise.<UsersUserFeaturesGetValuesBatchResult, Error.<UsersUserFeaturesGetValuesBatchError>>} */ routes.usersFeaturesGetValues = function (arg) { return this.request('users/features/get_values', arg, 'user', 'api', 'rpc'); }; /** * Get information about a user's account. * @function Dropbox#usersGetAccount * @arg {UsersGetAccountArg} arg - The request parameters. * @returns {Promise.<UsersBasicAccount, Error.<UsersGetAccountError>>} */ routes.usersGetAccount = function (arg) { return this.request('users/get_account', arg, 'user', 'api', 'rpc'); }; /** * Get information about multiple user accounts. At most 300 accounts may be * queried per request. * @function Dropbox#usersGetAccountBatch * @arg {UsersGetAccountBatchArg} arg - The request parameters. * @returns {Promise.<Object, Error.<UsersGetAccountBatchError>>} */ routes.usersGetAccountBatch = function (arg) { return this.request('users/get_account_batch', arg, 'user', 'api', 'rpc'); }; /** * Get information about the current user's account. * @function Dropbox#usersGetCurrentAccount * @arg {void} arg - The request parameters. * @returns {Promise.<UsersFullAccount, Error.<void>>} */ routes.usersGetCurrentAccount = function (arg) { return this.request('users/get_current_account', arg, 'user', 'api', 'rpc'); }; /** * Get the space usage information for the current user's account. * @function Dropbox#usersGetSpaceUsage * @arg {void} arg - The request parameters. * @returns {Promise.<UsersSpaceUsage, Error.<void>>} */ routes.usersGetSpaceUsage = function (arg) { return this.request('users/get_space_usage', arg, 'user', 'api', 'rpc'); }; var RPC = 'rpc'; var UPLOAD = 'upload'; var DOWNLOAD = 'download'; function getSafeUnicode(c) { var unicode = ('000' + c.charCodeAt(0).toString(16)).slice(-4); return '\\u' + unicode; } /* global WorkerGlobalScope */ function isWindowOrWorker() { return typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope || typeof module === 'undefined' || typeof window !== 'undefined'; } function getBaseURL(host) { return 'https://' + host + '.dropboxapi.com/2/'; } // source https://www.dropboxforum.com/t5/API-support/HTTP-header-quot-Dropbox-API-Arg-quot-could-not-decode-input-as/m-p/173823/highlight/true#M6786 function httpHeaderSafeJson(args) { return JSON.stringify(args).replace(/[\u007f-\uffff]/g, getSafeUnicode); } var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; var slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); function getDataFromConsumer(res) { if (!res.ok) { return res.text(); } return isWindowOrWorker() ? res.blob() : res.buffer(); } function responseHandler(res, data) { if (!res.ok) { // eslint-disable-next-line no-throw-literal throw { error: data, response: res, status: res.status }; } var result = JSON.parse(res.headers.get('dropbox-api-result')); if (isWindowOrWorker()) { result.fileBlob = data; } else { result.fileBinary = data; } return result; } function downloadRequest(fetch) { return function downloadRequestWithFetch(path, args, auth, host, client, options) { return client.checkAndRefreshAccessToken().then(function () { if (auth !== 'user') { throw new Error('Unexpected auth type: ' + auth); } var fetchOptions = { method: 'POST', headers: { Authorization: 'Bearer ' + client.getAccessToken(), 'Dropbox-API-Arg': httpHeaderSafeJson(args) } }; if (options) { if (options.selectUser) { fetchOptions.headers['Dropbox-API-Select-User'] = options.selectUser; } if (options.selectAdmin) { fetchOptions.headers['Dropbox-API-Select-Admin'] = options.selectAdmin; } if (options.pathRoot) { fetchOptions.headers['Dropbox-API-Path-Root'] = options.pathRoot; } } return fetchOptions; }).then(function (fetchOptions) { return fetch(getBaseURL(host) + path, fetchOptions); }).then(function (res) { return getDataFromConsumer(res).then(function (data) { return [res, data]; }); }).then(function (_ref) { var _ref2 = slicedToArray(_ref, 2), res = _ref2[0], data = _ref2[1]; return responseHandler(res, data); }); }; } function parseBodyToType(res) { var clone = res.clone(); return new Promise(function (resolve) { res.json().then(function (data) { return resolve(data); }).catch(function () { return clone.text().then(function (data) { return resolve(data); }); }); }).then(function (data) { return [res, data]; }); } function uploadRequest(fetch) { return function uploadRequestWithFetch(path, args, auth, host, client, options) { return client.checkAndRefreshAccessToken().then(function () { if (auth !== 'user') { throw new Error('Unexpected auth type: ' + auth); } var contents = args.contents; delete args.contents; var fetchOptions = { body: contents, method: 'POST', headers: { Authorization: 'Bearer ' + client.getAccessToken(), 'Content-Type': 'application/octet-stream', 'Dropbox-API-Arg': httpHeaderSafeJson(args) } }; if (options) { if (options.selectUser) { fetchOptions.headers['Dropbox-API-Select-User'] = options.selectUser; } if (options.selectAdmin) { fetchOptions.headers['Dropbox-API-Select-Admin'] = options.selectAdmin; } if (options.pathRoot) { fetchOptions.headers['Dropbox-API-Path-Root'] = options.pathRoot; } } return fetchOptions; }).then(function (fetchOptions) { return fetch(getBaseURL(host) + path, fetchOptions); }).then(function (res) { return parseBodyToType(res); }).then(function (_ref) { var _ref2 = slicedToArray(_ref, 2), res = _ref2[0], data = _ref2[1]; // maintaining existing API for error codes not equal to 200 range if (!res.ok) { // eslint-disable-next-line no-throw-literal throw { error: data, response: res, status: res.status }; } return data; }); }; } var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; var inited = false; function init () { inited = true; var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i]; revLookup[code.charCodeAt(i)] = i; } revLookup['-'.charCodeAt(0)] = 62; revLookup['_'.charCodeAt(0)] = 63; } function toByteArray (b64) { if (!inited) { init(); } var i, j, l, tmp, placeHolders, arr; var len = b64.length; if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data arr = new Arr(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len; var L = 0; for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; arr[L++] = (tmp >> 16) & 0xFF; arr[L++] = (tmp >> 8) & 0xFF; arr[L++] = tmp & 0xFF; } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); arr[L++] = tmp & 0xFF; } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); arr[L++] = (tmp >> 8) & 0xFF; arr[L++] = tmp & 0xFF; } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp; var output = []; for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); output.push(tripletToBase64(tmp)); } return output.join('') } function fromByteArray (uint8) { if (!inited) { init(); } var tmp; var len = uint8.length; var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes var output = ''; var parts = []; var maxChunkLength = 16383; // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1]; output += lookup[tmp >> 2]; output += lookup[(tmp << 4) & 0x3F]; output += '=='; } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); output += lookup[tmp >> 10]; output += lookup[(tmp >> 4) & 0x3F]; output += lookup[(tmp << 2) & 0x3F]; output += '='; } parts.push(output); return parts.join('') } function read (buffer, offset, isLE, mLen, nBytes) { var e, m; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var nBits = -7; var i = isLE ? (nBytes - 1) : 0; var d = isLE ? -1 : 1; var s = buffer[offset + i]; i += d; e = s & ((1 << (-nBits)) - 1); s >>= (-nBits); nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1); e >>= (-nBits); nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } function write (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); var i = isLE ? 0 : (nBytes - 1); var d = isLE ? 1 : -1; var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128; } var toString = {}.toString; var isArray = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; var INSPECT_MAX_BYTES = 50; /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } function createBuffer (that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); that.__proto__ = Buffer.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length); } that.length = length; } return that } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } Buffer.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype; return arr }; function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) }; if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype; Buffer.__proto__ = Uint8Array; } function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (that, size, fill, encoding) { assertSize(size); if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } } return that } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8'; } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0; that = createBuffer(that, length); var actual = that.write(string, encoding); if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual); } return that } function fromArrayLike (that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0; that = createBuffer(that, length); for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255; } return that } function fromArrayBuffer (that, array, byteOffset, length) { array.byteLength; // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array); } else if (length === undefined) { array = new Uint8Array(array, byteOffset); } else { array = new Uint8Array(array, byteOffset, length); } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; that.__proto__ = Buffer.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); } return that } function fromObject (that, obj) { if (internalIsBuffer(obj)) { var len = checked(obj.length) | 0; that = createBuffer(that, len); if (that.length === 0) { return that } obj.copy(that, 0, 0, len); return that } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } Buffer.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break } } if (x < y) return -1 if (y < x) return 1 return 0 }; Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } }; Buffer.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i; if (length === undefined) { length = 0; for (i = 0; i < list.length; ++i) { length += list[i].length; } } var buffer = Buffer.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; if (!internalIsBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos); pos += buf.length; } return buffer }; function byteLength (string, encoding) { if (internalIsBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string; } var len = string.length; if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false; for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } } Buffer.byteLength = byteLength; function slowToString (encoding, start, end) { var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0; } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length; } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0; start >>>= 0; if (end <= start) { return '' } if (!encoding) encoding = 'utf8'; while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase(); loweredCase = true; } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; b[n] = b[m]; b[m] = i; } Buffer.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1); } return this }; Buffer.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3); swap(this, i + 1, i + 2); } return this }; Buffer.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7); swap(this, i + 1, i + 6); swap(this, i + 2, i + 5); swap(this, i + 3, i + 4); } return this }; Buffer.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; Buffer.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 }; Buffer.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); if (this.length > max) str += ' ... '; } return '<Buffer ' + str + '>' }; Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0; } if (end === undefined) { end = target ? target.length : 0; } if (thisStart === undefined) { thisStart = 0; } if (thisEnd === undefined) { thisEnd = this.length; } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0; end >>>= 0; thisStart >>>= 0; thisEnd >>>= 0; if (this === target) return 0 var x = thisEnd - thisStart; var y = end - start; var len = Math.min(x, y); var thisCopy = this.slice(thisStart, thisEnd); var targetCopy = target.slice(start, end); for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i]; y = targetCopy[i]; break } } if (x < y) return -1 if (y < x) return 1 return 0 }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff; } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000; } byteOffset = +byteOffset; // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1); } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1; } else if (byteOffset < 0) { if (dir) byteOffset = 0; else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf if (internalIsBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1; var arrLength = arr.length; var valLength = val.length; if (encoding !== undefined) { encoding = String(encoding).toLowerCase(); if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2; arrLength /= 2; valLength /= 2; byteOffset /= 2; } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i; if (dir) { var foundIndex = -1; for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i; if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex; foundIndex = -1; } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; for (i = byteOffset; i >= 0; i--) { var found = true; for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false; break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0; var remaining = buf.length - offset; if (!length) { length = remaining; } else { length = Number(length); if (length > remaining) { length = remaining; } } // must be an even number of digits var strLen = string.length; if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2; } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16); if (isNaN(parsed)) return i buf[offset + i] = parsed; } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; length = this.length; offset = 0; // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset; length = this.length; offset = 0; // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0; if (isFinite(length)) { length = length | 0; if (encoding === undefined) encoding = 'utf8'; } else { encoding = length; length = undefined; } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset; if (length === undefined || length > remaining) length = remaining; if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8'; var loweredCase = false; for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } }; Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } }; function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return fromByteArray(buf) } else { return fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end); var res = []; var i = start; while (i < end) { var firstByte = buf[i]; var codePoint = null; var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1; if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint; switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte; } break case 2: secondByte = buf[i + 1]; if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); if (tempCodePoint > 0x7F) { codePoint = tempCodePoint; } } break case 3: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint; } } break case 4: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; fourthByte = buf[i + 3]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint; } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD; bytesPerSequence = 1; } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000; res.push(codePoint >>> 10 & 0x3FF | 0xD800); codePoint = 0xDC00 | codePoint & 0x3FF; } res.push(codePoint); i += bytesPerSequence; } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000; function decodeCodePointsArray (codePoints) { var len = codePoints.length; if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = ''; var i = 0; while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ); } return res } function asciiSlice (buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F); } return ret } function latin1Slice (buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]); } return ret } function hexSlice (buf, start, end) { var len = buf.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; var out = ''; for (var i = start; i < end; ++i) { out += toHex(buf[i]); } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end); var res = ''; for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; if (start < 0) { start += len; if (start < 0) start = 0; } else if (start > len) { start = len; } if (end < 0) { end += len; if (end < 0) end = 0; } else if (end > len) { end = len; } if (end < start) end = start; var newBuf; if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); newBuf.__proto__ = Buffer.prototype; } else { var sliceLen = end - start; newBuf = new Buffer(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } } return newBuf }; /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } return val }; Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { checkOffset(offset, byteLength, this.length); } var val = this[offset + --byteLength]; var mul = 1; while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul; } return val }; Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) }; Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) }; Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val }; Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var i = byteLength; var mul = 1; var val = this[offset + --i]; while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val }; Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) }; Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) }; Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; function checkInt (buf, value, offset, ext, max, min) { if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var mul = 1; var i = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF; } return offset + byteLength }; Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var i = byteLength - 1; var mul = 1; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF; } return offset + byteLength }; Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1; for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8; } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { objectWriteUInt16(this, value, offset, true); } return offset + 2 }; Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { objectWriteUInt16(this, value, offset, false); } return offset + 2 }; function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1; for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); this[offset] = (value & 0xff); } else { objectWriteUInt32(this, value, offset, true); } return offset + 4 }; Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); this[offset + 3] = (value & 0xff); } else { objectWriteUInt32(this, value, offset, false); } return offset + 4 }; Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = 0; var mul = 1; var sub = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1; } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; } return offset + byteLength }; Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = byteLength - 1; var mul = 1; var sub = 0; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1; } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; } return offset + byteLength }; Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { objectWriteUInt16(this, value, offset, true); } return offset + 2 }; Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { objectWriteUInt16(this, value, offset, false); } return offset + 2 }; Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); this[offset + 3] = (value >>> 24); } else { objectWriteUInt32(this, value, offset, true); } return offset + 4 }; Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (value < 0) value = 0xffffffff + value + 1; if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); this[offset + 3] = (value & 0xff); } else { objectWriteUInt32(this, value, offset, false); } return offset + 4 }; function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4); } write(buf, value, offset, littleEndian, 23, 4); return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8); } write(buf, value, offset, littleEndian, 52, 8); return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; if (!targetStart) targetStart = 0; if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length; if (target.length - targetStart < end - start) { end = target.length - targetStart + start; } var len = end - start; var i; if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ); } return len }; // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start; start = 0; end = this.length; } else if (typeof end === 'string') { encoding = end; end = this.length; } if (val.length === 1) { var code = val.charCodeAt(0); if (code < 256) { val = code; } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255; } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0; end = end === undefined ? this.length : end >>> 0; if (!val) val = 0; var i; if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val; } } else { var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; } } return this }; // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '='; } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity; var codePoint; var length = string.length; var leadSurrogate = null; var bytes = []; for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i); // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue } // valid lead leadSurrogate = codePoint; continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); leadSurrogate = codePoint; continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); } leadSurrogate = null; // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint); } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ); } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ); } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ); } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = []; for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF); } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo; var byteArray = []; for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i); hi = c >> 8; lo = c % 256; byteArray.push(lo); byteArray.push(hi); } return byteArray } function base64ToBytes (str) { return toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i]; } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually function isBuffer(obj) { return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) } function isFastBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) } function parseBodyToType$1(res) { if (res.headers.get('Content-Type') === 'application/json') { return res.json().then(function (data) { return [res, data]; }); } return res.text().then(function (data) { return [res, data]; }); } function rpcRequest(fetch) { return function rpcRequestWithFetch(path, body, auth, host, client, options) { return client.checkAndRefreshAccessToken().then(function () { var fetchOptions = { method: 'POST', body: body ? JSON.stringify(body) : null }; var headers = {}; if (body) { headers['Content-Type'] = 'application/json'; } var authHeader = ''; switch (auth) { case 'app': if (!options.clientId || !options.clientSecret) { throw new Error('A client id and secret is required for this function'); } authHeader = new Buffer(options.clientId + ':' + options.clientSecret).toString('base64'); headers.Authorization = 'Basic ' + authHeader; break; case 'team': case 'user': headers.Authorization = 'Bearer ' + client.getAccessToken(); break; case 'noauth': break; default: throw new Error('Unhandled auth type: ' + auth); } if (options) { if (options.selectUser) { headers['Dropbox-API-Select-User'] = options.selectUser; } if (options.selectAdmin) { headers['Dropbox-API-Select-Admin'] = options.selectAdmin; } if (options.pathRoot) { headers['Dropbox-API-Path-Root'] = options.pathRoot; } } fetchOptions.headers = headers; return fetchOptions; }).then(function (fetchOptions) { return fetch(getBaseURL(host) + path, fetchOptions); }).then(function (res) { return parseBodyToType$1(res); }).then(function (_ref) { var _ref2 = slicedToArray(_ref, 2), res = _ref2[0], data = _ref2[1]; // maintaining existing API for error codes not equal to 200 range if (!res.ok) { // eslint-disable-next-line no-throw-literal throw { error: data, response: res, status: res.status }; } return data; }); }; } var crypto = void 0; try { crypto = require('crypto'); // eslint-disable-line global-require } catch (Exception) { crypto = window.crypto; } // Expiration is 300 seconds but needs to be in milliseconds for Date object var TokenExpirationBuffer = 300 * 1000; var PKCELength = 128; var TokenAccessTypes = ['legacy', 'offline', 'online']; var GrantTypes = ['code', 'token']; var IncludeGrantedScopes = ['none', 'user', 'team']; var BaseAuthorizeUrl = 'https://www.dropbox.com/oauth2/authorize'; var BaseTokenUrl = 'https://api.dropboxapi.com/oauth2/token'; /* eslint-disable */ // Polyfill object.assign for legacy browsers // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign if (typeof Object.assign !== 'function') { (function () { Object.assign = function (target) { var output; var index; var source; var nextKey; if (target === undefined || target === null) { throw new TypeError('Cannot convert undefined or null to object'); } output = Object(target); for (index = 1; index < arguments.length; index++) { source = arguments[index]; if (source !== undefined && source !== null) { for (nextKey in source) { if (source.hasOwnProperty(nextKey)) { output[nextKey] = source[nextKey]; } } } } return output; }; })(); } // Polyfill Array.includes for legacy browsers // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes // https://tc39.github.io/ecma262/#sec-array.prototype.includes if (!Array.prototype.includes) { Object.defineProperty(Array.prototype, 'includes', { value: function value(searchElement, fromIndex) { if (this == null) { throw new TypeError('"this" is null or not defined'); } // 1. Let O be ? ToObject(this value). var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 3. If len is 0, return false. if (len === 0) { return false; } // 4. Let n be ? ToInteger(fromIndex). // (If fromIndex is undefined, this step produces the value 0.) var n = fromIndex | 0; // 5. If n ≥ 0, then // a. Let k be n. // 6. Else n < 0, // a. Let k be len + n. // b. If k < 0, let k be 0. var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); function sameValueZero(x, y) { return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y); } // 7. Repeat, while k < len while (k < len) { // a. Let elementK be the result of ? Get(O, ! ToString(k)). // b. If SameValueZero(searchElement, elementK) is true, return true. if (sameValueZero(o[k], searchElement)) { return true; } // c. Increase k by 1. k++; } // 8. Return false return false; } }); } /* eslint-enable */ /** * @private * @class DropboxBase * @classdesc The main Dropbox SDK class. This contains the methods that are * shared between Dropbox and DropboxTeam classes. It is marked as private so * that it doesn't show up in the docs because it is never used directly. * @arg {Object} options * @arg {Function} [options.fetch] - fetch library for making requests. * @arg {String} [options.accessToken] - An access token for making authenticated * requests. * @arg {String} [options.clientId] - The client id for your app. Used to create * authentication URL. * @arg {String} [options.clientSecret] - The client secret for your app. * @arg {Number} [options.selectUser] - User that the team access token would like * to act as. * @arg {String} [options.selectAdmin] - Team admin that the team access token would like * to act as. * @arg {String} [options.pathRoot] - root pass to access other namespaces * Use to access team folders for example */ function parseBodyToType$2(res) { var clone = res.clone(); return new Promise(function (resolve) { res.json().then(function (data) { return resolve(data); }).catch(function () { return clone.text().then(function (data) { return resolve(data); }); }); }).then(function (data) { return [res, data]; }); } /** * * @param expiresIn */ function getTokenExpiresAt(expiresIn) { return new Date(Date.now() + expiresIn * 1000); } var DropboxBase = function () { function DropboxBase(options) { classCallCheck(this, DropboxBase); options = options || {}; this.accessToken = options.accessToken; this.accessTokenExpiresAt = options.accessTokenExpiresAt; this.refreshToken = options.refreshToken; this.clientId = options.clientId; this.clientSecret = options.clientSecret; this.selectUser = options.selectUser; this.selectAdmin = options.selectAdmin; this.fetch = options.fetch || fetch; this.pathRoot = options.pathRoot; if (!options.fetch) { console.warn('Global fetch is deprecated and will be unsupported in a future version. Please pass fetch function as option when instantiating dropbox instance: new Dropbox({fetch})'); } // eslint-disable-line no-console } /** * Set the access token used to authenticate requests to the API. * @arg {String} accessToken - An access token * @returns {undefined} */ createClass(DropboxBase, [{ key: 'setAccessToken', value: function setAccessToken(accessToken) { this.accessToken = accessToken; } /** * Get the access token * @returns {String} Access token */ }, { key: 'getAccessToken', value: function getAccessToken() { return this.accessToken; } /** * Set the client id, which is used to help gain an access token. * @arg {String} clientId - Your apps client id * @returns {undefined} */ }, { key: 'setClientId', value: function setClientId(clientId) { this.clientId = clientId; } /** * Get the client id * @returns {String} Client id */ }, { key: 'getClientId', value: function getClientId() { return this.clientId; } /** * Set the client secret * @arg {String} clientSecret - Your app's client secret * @returns {undefined} */ }, { key: 'setClientSecret', value: function setClientSecret(clientSecret) { this.clientSecret = clientSecret; } /** * Get the client secret * @returns {String} Client secret */ }, { key: 'getClientSecret', value: function getClientSecret() { return this.clientSecret; } /** * Gets the refresh token * @returns {String} Refresh token */ }, { key: 'getRefreshToken', value: function getRefreshToken() { return this.refreshToken; } /** * Sets the refresh token * @param refreshToken - A refresh token */ }, { key: 'setRefreshToken', value: function setRefreshToken(refreshToken) { this.refreshToken = refreshToken; } /** * Gets the access token's expiration date * @returns {Date} date of token expiration */ }, { key: 'getAccessTokenExpiresAt', value: function getAccessTokenExpiresAt() { return this.accessTokenExpiresAt; } /** * Sets the access token's expiration date * @param accessTokenExpiresAt - new expiration date */ }, { key: 'setAccessTokenExpiresAt', value: function setAccessTokenExpiresAt(accessTokenExpiresAt) { this.accessTokenExpiresAt = accessTokenExpiresAt; } }, { key: 'generatePKCECodes', value: function generatePKCECodes() { var codeVerifier = crypto.randomBytes(PKCELength); codeVerifier = codeVerifier.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '').substr(0, 128); this.codeVerifier = codeVerifier; var encoder = new TextEncoder(); var codeData = encoder.encode(codeVerifier); var codeChallenge = crypto.createHash('sha256').update(codeData).digest(); codeChallenge = codeChallenge.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); this.codeChallenge = codeChallenge; } /** * Get a URL that can be used to authenticate users for the Dropbox API. * @arg {String} redirectUri - A URL to redirect the user to after * authenticating. This must be added to your app through the admin interface. * @arg {String} [state] - State that will be returned in the redirect URL to help * prevent cross site scripting attacks. * @arg {String} [authType] - auth type, defaults to 'token', other option is 'code' * @arg {String} [tokenAccessType] - type of token to request. From the following: * legacy - creates one long-lived token with no expiration * online - create one short-lived token with an expiration * offline - create one short-lived token with an expiration with a refresh token * @arg {Array<String>>} [scope] - scopes to request for the grant * @arg {String} [includeGrantedScopes] - whether or not to include previously granted scopes. * From the following: * user - include user scopes in the grant * team - include team scopes in the grant * Note: if this user has never linked the app, include_granted_scopes must be None * @arg {boolean} [usePKCE] - Whether or not to use Sha256 based PKCE. PKCE should be only use on * client apps which doesn't call your server. It is less secure than non-PKCE flow but * can be used if you are unable to safely retrieve your app secret * @returns {String} Url to send user to for Dropbox API authentication */ }, { key: 'getAuthenticationUrl', value: function getAuthenticationUrl(redirectUri, state) { var authType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'token'; var tokenAccessType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'legacy'; var scope = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; var includeGrantedScopes = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 'none'; var usePKCE = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false; var clientId = this.getClientId(); var baseUrl = BaseAuthorizeUrl; if (!clientId) { throw new Error('A client id is required. You can set the client id using .setClientId().'); } if (authType !== 'code' && !redirectUri) { throw new Error('A redirect uri is required.'); } if (!GrantTypes.includes(authType)) { throw new Error('Authorization type must be code or token'); } if (!TokenAccessTypes.includes(tokenAccessType)) { throw new Error('Token Access Type must be legacy, offline, or online'); } if (scope && !(scope instanceof Array)) { throw new Error('Scope must be an array of strings'); } if (!IncludeGrantedScopes.includes(includeGrantedScopes)) { throw new Error('includeGrantedScopes must be none, user, or team'); } var authUrl = void 0; if (authType === 'code') { authUrl = baseUrl + '?response_type=code&client_id=' + clientId; } else { authUrl = baseUrl + '?response_type=token&client_id=' + clientId; } if (redirectUri) { authUrl += '&redirect_uri=' + redirectUri; } if (state) { authUrl += '&state=' + state; } if (tokenAccessType !== 'legacy') { authUrl += '&token_access_type=' + tokenAccessType; } if (scope) { authUrl += '&scope=' + scope.join(' '); } if (includeGrantedScopes !== 'none') { authUrl += '&include_granted_scopes=' + includeGrantedScopes; } if (usePKCE) { this.generatePKCECodes(); authUrl += '&code_challenge_method=S256'; authUrl += '&code_challenge=' + this.codeChallenge; } return authUrl; } /** * Get an OAuth2 access token from an OAuth2 Code. * @arg {String} redirectUri - A URL to redirect the user to after * authenticating. This must be added to your app through the admin interface. * @arg {String} code - An OAuth2 code. */ }, { key: 'getAccessTokenFromCode', value: function getAccessTokenFromCode(redirectUri, code) { var clientId = this.getClientId(); var clientSecret = this.getClientSecret(); if (!clientId) { throw new Error('A client id is required. You can set the client id using .setClientId().'); } var path = BaseTokenUrl; path += '?grant_type=authorization_code'; path += '&code=' + code; path += '&client_id=' + clientId; if (clientSecret) { path += '&client_secret=' + clientSecret; } else { if (!this.codeChallenge) { throw new Error('You must use PKCE when generating the authorization URL to not include a client secret'); } path += '&code_verifier=' + this.codeVerifier; } if (redirectUri) { path += '&redirect_uri=' + redirectUri; } var fetchOptions = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; return this.fetch(path, fetchOptions).then(function (res) { return parseBodyToType$2(res); }).then(function (_ref) { var _ref2 = slicedToArray(_ref, 2), res = _ref2[0], data = _ref2[1]; // maintaining existing API for error codes not equal to 200 range if (!res.ok) { // eslint-disable-next-line no-throw-literal throw { error: data, response: res, status: res.status }; } if (data.refresh_token) { return { accessToken: data.access_token, refreshToken: data.refresh_token, accessTokenExpiresAt: getTokenExpiresAt(data.expires_in) }; } return data.access_token; }); } /** * Checks if a token is needed, can be refreshed and if the token is expired. * If so, attempts to refresh access token * @returns {Promise<*>} */ }, { key: 'checkAndRefreshAccessToken', value: function checkAndRefreshAccessToken() { var canRefresh = this.getRefreshToken() && this.getClientId(); var needsRefresh = this.getAccessTokenExpiresAt() && new Date(Date.now() + TokenExpirationBuffer) >= this.getAccessTokenExpiresAt(); var needsToken = !this.getAccessToken(); if ((needsRefresh || needsToken) && canRefresh) { return this.refreshAccessToken(); } return Promise.resolve(); } /** * Refreshes the access token using the refresh token, if available * @arg {List} scope - a subset of scopes from the original * refresh to acquire with an access token * @returns {Promise<*>} */ }, { key: 'refreshAccessToken', value: function refreshAccessToken() { var _this = this; var scope = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var refreshUrl = BaseTokenUrl; var clientId = this.getClientId(); var clientSecret = this.getClientSecret(); if (!clientId) { throw new Error('A client id is required. You can set the client id using .setClientId().'); } if (scope && !(scope instanceof Array)) { throw new Error('Scope must be an array of strings'); } var headers = {}; headers['Content-Type'] = 'application/json'; refreshUrl += '?grant_type=refresh_token&refresh_token=' + this.getRefreshToken(); refreshUrl += '&client_id=' + clientId; if (clientSecret) { refreshUrl += '&client_secret=' + clientSecret; } if (scope) { refreshUrl += '&scope=' + scope.join(' '); } var fetchOptions = { method: 'POST' }; fetchOptions.headers = headers; return this.fetch(refreshUrl, fetchOptions).then(function (res) { return parseBodyToType$2(res); }).then(function (_ref3) { var _ref4 = slicedToArray(_ref3, 2), res = _ref4[0], data = _ref4[1]; // maintaining existing API for error codes not equal to 200 range if (!res.ok) { // eslint-disable-next-line no-throw-literal throw { error: data, response: res, status: res.status }; } _this.setAccessToken(data.access_token); _this.setAccessTokenExpiresAt(getTokenExpiresAt(data.expires_in)); }); } /** * Called when the authentication succeed * @callback successCallback * @param {string} access_token The application's access token */ /** * Called when the authentication failed. * @callback errorCallback */ /** * An authentication process that works with cordova applications. * @param {successCallback} successCallback * @param {errorCallback} errorCallback */ }, { key: 'authenticateWithCordova', value: function authenticateWithCordova(successCallback, errorCallback) { var redirectUrl = 'https://www.dropbox.com/1/oauth2/redirect_receiver'; var url = this.getAuthenticationUrl(redirectUrl); var removed = false; var browser = window.open(url, '_blank'); function onLoadError(event) { if (event.code !== -999) { // Workaround to fix wrong behavior on cordova-plugin-inappbrowser // Try to avoid a browser crash on browser.close(). window.setTimeout(function () { browser.close(); }, 10); errorCallback(); } } function onLoadStop(event) { var errorLabel = '&error='; var errorIndex = event.url.indexOf(errorLabel); if (errorIndex > -1) { // Try to avoid a browser crash on browser.close(). window.setTimeout(function () { browser.close(); }, 10); errorCallback(); } else { var tokenLabel = '#access_token='; var tokenIndex = event.url.indexOf(tokenLabel); var tokenTypeIndex = event.url.indexOf('&token_type='); if (tokenIndex > -1) { tokenIndex += tokenLabel.length; // Try to avoid a browser crash on browser.close(). window.setTimeout(function () { browser.close(); }, 10); var accessToken = event.url.substring(tokenIndex, tokenTypeIndex); successCallback(accessToken); } } } function onExit() { if (removed) { return; } browser.removeEventListener('loaderror', onLoadError); browser.removeEventListener('loadstop', onLoadStop); browser.removeEventListener('exit', onExit); removed = true; } browser.addEventListener('loaderror', onLoadError); browser.addEventListener('loadstop', onLoadStop); browser.addEventListener('exit', onExit); } }, { key: 'request', value: function request(path, args, auth, host, style) { var request = null; switch (style) { case RPC: request = this.getRpcRequest(); break; case DOWNLOAD: request = this.getDownloadRequest(); break; case UPLOAD: request = this.getUploadRequest(); break; default: throw new Error('Invalid request style: ' + style); } var options = { selectUser: this.selectUser, selectAdmin: this.selectAdmin, clientId: this.getClientId(), clientSecret: this.getClientSecret(), pathRoot: this.pathRoot }; return request(path, args, auth, host, this, options); } }, { key: 'setRpcRequest', value: function setRpcRequest(newRpcRequest) { this.rpcRequest = newRpcRequest; } }, { key: 'getRpcRequest', value: function getRpcRequest() { if (this.rpcRequest === undefined) { this.rpcRequest = rpcRequest(this.fetch); } return this.rpcRequest; } }, { key: 'setDownloadRequest', value: function setDownloadRequest(newDownloadRequest) { this.downloadRequest = newDownloadRequest; } }, { key: 'getDownloadRequest', value: function getDownloadRequest() { if (this.downloadRequest === undefined) { this.downloadRequest = downloadRequest(this.fetch); } return this.downloadRequest; } }, { key: 'setUploadRequest', value: function setUploadRequest(newUploadRequest) { this.uploadRequest = newUploadRequest; } }, { key: 'getUploadRequest', value: function getUploadRequest() { if (this.uploadRequest === undefined) { this.uploadRequest = uploadRequest(this.fetch); } return this.uploadRequest; } }]); return DropboxBase; }(); /** * @class Dropbox * @extends DropboxBase * @classdesc The Dropbox SDK class that provides methods to read, write and * create files or folders in a user's Dropbox. * @arg {Object} options * @arg {Function} [options.fetch] - fetch library for making requests. * @arg {String} [options.accessToken] - An access token for making authenticated * requests. * @arg {String} [options.clientId] - The client id for your app. Used to create * authentication URL. * @arg {String} [options.selectUser] - Select user is only used by DropboxTeam. * It specifies which user the team access token should be acting as. * @arg {String} [options.pathRoot] - root pass to access other namespaces * Use to access team folders for example * @arg {String} [options.refreshToken] - A refresh token for retrieving access tokens * @arg {Date} [options.AccessTokenExpiresAt] - Date of the current access token's * expiration (if available) */ var Dropbox = function (_DropboxBase) { inherits(Dropbox, _DropboxBase); function Dropbox(options) { classCallCheck(this, Dropbox); var _this = possibleConstructorReturn(this, (Dropbox.__proto__ || Object.getPrototypeOf(Dropbox)).call(this, options)); Object.assign(_this, routes); return _this; } createClass(Dropbox, [{ key: 'filesGetSharedLinkFile', value: function filesGetSharedLinkFile(arg) { return this.request('sharing/get_shared_link_file', arg, 'api', 'download'); } }]); return Dropbox; }(DropboxBase); var dropbox = /*#__PURE__*/Object.freeze({ __proto__: null, Dropbox: Dropbox }); // Auto-generated by Stone, do not modify. var routes$1 = {}; /** * List all device sessions of a team's member. * @function DropboxTeam#teamDevicesListMemberDevices * @arg {TeamListMemberDevicesArg} arg - The request parameters. * @returns {Promise.<TeamListMemberDevicesResult, Error.<TeamListMemberDevicesError>>} */ routes$1.teamDevicesListMemberDevices = function (arg) { return this.request('team/devices/list_member_devices', arg, 'team', 'api', 'rpc'); }; /** * List all device sessions of a team. Permission : Team member file access. * @function DropboxTeam#teamDevicesListMembersDevices * @arg {TeamListMembersDevicesArg} arg - The request parameters. * @returns {Promise.<TeamListMembersDevicesResult, Error.<TeamListMembersDevicesError>>} */ routes$1.teamDevicesListMembersDevices = function (arg) { return this.request('team/devices/list_members_devices', arg, 'team', 'api', 'rpc'); }; /** * List all device sessions of a team. Permission : Team member file access. * @function DropboxTeam#teamDevicesListTeamDevices * @deprecated * @arg {TeamListTeamDevicesArg} arg - The request parameters. * @returns {Promise.<TeamListTeamDevicesResult, Error.<TeamListTeamDevicesError>>} */ routes$1.teamDevicesListTeamDevices = function (arg) { return this.request('team/devices/list_team_devices', arg, 'team', 'api', 'rpc'); }; /** * Revoke a device session of a team's member. * @function DropboxTeam#teamDevicesRevokeDeviceSession * @arg {TeamRevokeDeviceSessionArg} arg - The request parameters. * @returns {Promise.<void, Error.<TeamRevokeDeviceSessionError>>} */ routes$1.teamDevicesRevokeDeviceSession = function (arg) { return this.request('team/devices/revoke_device_session', arg, 'team', 'api', 'rpc'); }; /** * Revoke a list of device sessions of team members. * @function DropboxTeam#teamDevicesRevokeDeviceSessionBatch * @arg {TeamRevokeDeviceSessionBatchArg} arg - The request parameters. * @returns {Promise.<TeamRevokeDeviceSessionBatchResult, Error.<TeamRevokeDeviceSessionBatchError>>} */ routes$1.teamDevicesRevokeDeviceSessionBatch = function (arg) { return this.request('team/devices/revoke_device_session_batch', arg, 'team', 'api', 'rpc'); }; /** * Get the values for one or more featues. This route allows you to check your * account's capability for what feature you can access or what value you have * for certain features. Permission : Team information. * @function DropboxTeam#teamFeaturesGetValues * @arg {TeamFeaturesGetValuesBatchArg} arg - The request parameters. * @returns {Promise.<TeamFeaturesGetValuesBatchResult, Error.<TeamFeaturesGetValuesBatchError>>} */ routes$1.teamFeaturesGetValues = function (arg) { return this.request('team/features/get_values', arg, 'team', 'api', 'rpc'); }; /** * Retrieves information about a team. * @function DropboxTeam#teamGetInfo * @arg {void} arg - The request parameters. * @returns {Promise.<TeamTeamGetInfoResult, Error.<void>>} */ routes$1.teamGetInfo = function (arg) { return this.request('team/get_info', arg, 'team', 'api', 'rpc'); }; /** * Creates a new, empty group, with a requested name. Permission : Team member * management. * @function DropboxTeam#teamGroupsCreate * @arg {TeamGroupCreateArg} arg - The request parameters. * @returns {Promise.<TeamGroupFullInfo, Error.<TeamGroupCreateError>>} */ routes$1.teamGroupsCreate = function (arg) { return this.request('team/groups/create', arg, 'team', 'api', 'rpc'); }; /** * Deletes a group. The group is deleted immediately. However the revoking of * group-owned resources may take additional time. Use the groups/job_status/get * to determine whether this process has completed. Permission : Team member * management. * @function DropboxTeam#teamGroupsDelete * @arg {TeamGroupSelector} arg - The request parameters. * @returns {Promise.<AsyncLaunchEmptyResult, Error.<TeamGroupDeleteError>>} */ routes$1.teamGroupsDelete = function (arg) { return this.request('team/groups/delete', arg, 'team', 'api', 'rpc'); }; /** * Retrieves information about one or more groups. Note that the optional field * GroupFullInfo.members is not returned for system-managed groups. Permission : * Team Information. * @function DropboxTeam#teamGroupsGetInfo * @arg {TeamGroupsSelector} arg - The request parameters. * @returns {Promise.<Object, Error.<TeamGroupsGetInfoError>>} */ routes$1.teamGroupsGetInfo = function (arg) { return this.request('team/groups/get_info', arg, 'team', 'api', 'rpc'); }; /** * Once an async_job_id is returned from groups/delete, groups/members/add , or * groups/members/remove use this method to poll the status of granting/revoking * group members' access to group-owned resources. Permission : Team member * management. * @function DropboxTeam#teamGroupsJobStatusGet * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<AsyncPollEmptyResult, Error.<TeamGroupsPollError>>} */ routes$1.teamGroupsJobStatusGet = function (arg) { return this.request('team/groups/job_status/get', arg, 'team', 'api', 'rpc'); }; /** * Lists groups on a team. Permission : Team Information. * @function DropboxTeam#teamGroupsList * @arg {TeamGroupsListArg} arg - The request parameters. * @returns {Promise.<TeamGroupsListResult, Error.<void>>} */ routes$1.teamGroupsList = function (arg) { return this.request('team/groups/list', arg, 'team', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from groups/list, use this to paginate * through all groups. Permission : Team Information. * @function DropboxTeam#teamGroupsListContinue * @arg {TeamGroupsListContinueArg} arg - The request parameters. * @returns {Promise.<TeamGroupsListResult, Error.<TeamGroupsListContinueError>>} */ routes$1.teamGroupsListContinue = function (arg) { return this.request('team/groups/list/continue', arg, 'team', 'api', 'rpc'); }; /** * Adds members to a group. The members are added immediately. However the * granting of group-owned resources may take additional time. Use the * groups/job_status/get to determine whether this process has completed. * Permission : Team member management. * @function DropboxTeam#teamGroupsMembersAdd * @arg {TeamGroupMembersAddArg} arg - The request parameters. * @returns {Promise.<TeamGroupMembersChangeResult, Error.<TeamGroupMembersAddError>>} */ routes$1.teamGroupsMembersAdd = function (arg) { return this.request('team/groups/members/add', arg, 'team', 'api', 'rpc'); }; /** * Lists members of a group. Permission : Team Information. * @function DropboxTeam#teamGroupsMembersList * @arg {TeamGroupsMembersListArg} arg - The request parameters. * @returns {Promise.<TeamGroupsMembersListResult, Error.<TeamGroupSelectorError>>} */ routes$1.teamGroupsMembersList = function (arg) { return this.request('team/groups/members/list', arg, 'team', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from groups/members/list, use this to * paginate through all members of the group. Permission : Team information. * @function DropboxTeam#teamGroupsMembersListContinue * @arg {TeamGroupsMembersListContinueArg} arg - The request parameters. * @returns {Promise.<TeamGroupsMembersListResult, Error.<TeamGroupsMembersListContinueError>>} */ routes$1.teamGroupsMembersListContinue = function (arg) { return this.request('team/groups/members/list/continue', arg, 'team', 'api', 'rpc'); }; /** * Removes members from a group. The members are removed immediately. However * the revoking of group-owned resources may take additional time. Use the * groups/job_status/get to determine whether this process has completed. This * method permits removing the only owner of a group, even in cases where this * is not possible via the web client. Permission : Team member management. * @function DropboxTeam#teamGroupsMembersRemove * @arg {TeamGroupMembersRemoveArg} arg - The request parameters. * @returns {Promise.<TeamGroupMembersChangeResult, Error.<TeamGroupMembersRemoveError>>} */ routes$1.teamGroupsMembersRemove = function (arg) { return this.request('team/groups/members/remove', arg, 'team', 'api', 'rpc'); }; /** * Sets a member's access type in a group. Permission : Team member management. * @function DropboxTeam#teamGroupsMembersSetAccessType * @arg {TeamGroupMembersSetAccessTypeArg} arg - The request parameters. * @returns {Promise.<Object, Error.<TeamGroupMemberSetAccessTypeError>>} */ routes$1.teamGroupsMembersSetAccessType = function (arg) { return this.request('team/groups/members/set_access_type', arg, 'team', 'api', 'rpc'); }; /** * Updates a group's name and/or external ID. Permission : Team member * management. * @function DropboxTeam#teamGroupsUpdate * @arg {TeamGroupUpdateArgs} arg - The request parameters. * @returns {Promise.<TeamGroupFullInfo, Error.<TeamGroupUpdateError>>} */ routes$1.teamGroupsUpdate = function (arg) { return this.request('team/groups/update', arg, 'team', 'api', 'rpc'); }; /** * Creates new legal hold policy. Permission : Team member file access. * @function DropboxTeam#teamLegalHoldsCreatePolicy * @arg {TeamLegalHoldsPolicyCreateArg} arg - The request parameters. * @returns {Promise.<Object, Error.<TeamLegalHoldsPolicyCreateError>>} */ routes$1.teamLegalHoldsCreatePolicy = function (arg) { return this.request('team/legal_holds/create_policy', arg, 'team', 'api', 'rpc'); }; /** * Gets a legal hold by Id. Permission : Team member file access. * @function DropboxTeam#teamLegalHoldsGetPolicy * @arg {TeamLegalHoldsGetPolicyArg} arg - The request parameters. * @returns {Promise.<Object, Error.<TeamLegalHoldsGetPolicyError>>} */ routes$1.teamLegalHoldsGetPolicy = function (arg) { return this.request('team/legal_holds/get_policy', arg, 'team', 'api', 'rpc'); }; /** * @function DropboxTeam#teamLegalHoldsListHeldRevisions * @arg {TeamLegalHoldsListHeldRevisionsArg} arg - The request parameters. * @returns {Promise.<TeamLegalHoldsListHeldRevisionResult, Error.<TeamLegalHoldsListHeldRevisionsError>>} */ routes$1.teamLegalHoldsListHeldRevisions = function (arg) { return this.request('team/legal_holds/list_held_revisions', arg, 'team', 'api', 'rpc'); }; /** * @function DropboxTeam#teamLegalHoldsListHeldRevisionsContinue * @arg {TeamLegalHoldsListHeldRevisionsContinueArg} arg - The request parameters. * @returns {Promise.<TeamLegalHoldsListHeldRevisionResult, Error.<TeamLegalHoldsListHeldRevisionsError>>} */ routes$1.teamLegalHoldsListHeldRevisionsContinue = function (arg) { return this.request('team/legal_holds/list_held_revisions_continue', arg, 'team', 'api', 'rpc'); }; /** * Lists legal holds on a team. Permission : Team member file access. * @function DropboxTeam#teamLegalHoldsListPolicies * @arg {TeamLegalHoldsListPoliciesArg} arg - The request parameters. * @returns {Promise.<TeamLegalHoldsListPoliciesResult, Error.<TeamLegalHoldsListPoliciesError>>} */ routes$1.teamLegalHoldsListPolicies = function (arg) { return this.request('team/legal_holds/list_policies', arg, 'team', 'api', 'rpc'); }; /** * Releases a legal hold by Id. Permission : Team member file access. * @function DropboxTeam#teamLegalHoldsReleasePolicy * @arg {TeamLegalHoldsPolicyReleaseArg} arg - The request parameters. * @returns {Promise.<void, Error.<TeamLegalHoldsPolicyReleaseError>>} */ routes$1.teamLegalHoldsReleasePolicy = function (arg) { return this.request('team/legal_holds/release_policy', arg, 'team', 'api', 'rpc'); }; /** * Updates a legal hold. Permission : Team member file access. * @function DropboxTeam#teamLegalHoldsUpdatePolicy * @arg {TeamLegalHoldsPolicyUpdateArg} arg - The request parameters. * @returns {Promise.<Object, Error.<TeamLegalHoldsPolicyUpdateError>>} */ routes$1.teamLegalHoldsUpdatePolicy = function (arg) { return this.request('team/legal_holds/update_policy', arg, 'team', 'api', 'rpc'); }; /** * List all linked applications of the team member. Note, this endpoint does not * list any team-linked applications. * @function DropboxTeam#teamLinkedAppsListMemberLinkedApps * @arg {TeamListMemberAppsArg} arg - The request parameters. * @returns {Promise.<TeamListMemberAppsResult, Error.<TeamListMemberAppsError>>} */ routes$1.teamLinkedAppsListMemberLinkedApps = function (arg) { return this.request('team/linked_apps/list_member_linked_apps', arg, 'team', 'api', 'rpc'); }; /** * List all applications linked to the team members' accounts. Note, this * endpoint does not list any team-linked applications. * @function DropboxTeam#teamLinkedAppsListMembersLinkedApps * @arg {TeamListMembersAppsArg} arg - The request parameters. * @returns {Promise.<TeamListMembersAppsResult, Error.<TeamListMembersAppsError>>} */ routes$1.teamLinkedAppsListMembersLinkedApps = function (arg) { return this.request('team/linked_apps/list_members_linked_apps', arg, 'team', 'api', 'rpc'); }; /** * List all applications linked to the team members' accounts. Note, this * endpoint doesn't list any team-linked applications. * @function DropboxTeam#teamLinkedAppsListTeamLinkedApps * @deprecated * @arg {TeamListTeamAppsArg} arg - The request parameters. * @returns {Promise.<TeamListTeamAppsResult, Error.<TeamListTeamAppsError>>} */ routes$1.teamLinkedAppsListTeamLinkedApps = function (arg) { return this.request('team/linked_apps/list_team_linked_apps', arg, 'team', 'api', 'rpc'); }; /** * Revoke a linked application of the team member. * @function DropboxTeam#teamLinkedAppsRevokeLinkedApp * @arg {TeamRevokeLinkedApiAppArg} arg - The request parameters. * @returns {Promise.<void, Error.<TeamRevokeLinkedAppError>>} */ routes$1.teamLinkedAppsRevokeLinkedApp = function (arg) { return this.request('team/linked_apps/revoke_linked_app', arg, 'team', 'api', 'rpc'); }; /** * Revoke a list of linked applications of the team members. * @function DropboxTeam#teamLinkedAppsRevokeLinkedAppBatch * @arg {TeamRevokeLinkedApiAppBatchArg} arg - The request parameters. * @returns {Promise.<TeamRevokeLinkedAppBatchResult, Error.<TeamRevokeLinkedAppBatchError>>} */ routes$1.teamLinkedAppsRevokeLinkedAppBatch = function (arg) { return this.request('team/linked_apps/revoke_linked_app_batch', arg, 'team', 'api', 'rpc'); }; /** * Add users to member space limits excluded users list. * @function DropboxTeam#teamMemberSpaceLimitsExcludedUsersAdd * @arg {TeamExcludedUsersUpdateArg} arg - The request parameters. * @returns {Promise.<TeamExcludedUsersUpdateResult, Error.<TeamExcludedUsersUpdateError>>} */ routes$1.teamMemberSpaceLimitsExcludedUsersAdd = function (arg) { return this.request('team/member_space_limits/excluded_users/add', arg, 'team', 'api', 'rpc'); }; /** * List member space limits excluded users. * @function DropboxTeam#teamMemberSpaceLimitsExcludedUsersList * @arg {TeamExcludedUsersListArg} arg - The request parameters. * @returns {Promise.<TeamExcludedUsersListResult, Error.<TeamExcludedUsersListError>>} */ routes$1.teamMemberSpaceLimitsExcludedUsersList = function (arg) { return this.request('team/member_space_limits/excluded_users/list', arg, 'team', 'api', 'rpc'); }; /** * Continue listing member space limits excluded users. * @function DropboxTeam#teamMemberSpaceLimitsExcludedUsersListContinue * @arg {TeamExcludedUsersListContinueArg} arg - The request parameters. * @returns {Promise.<TeamExcludedUsersListResult, Error.<TeamExcludedUsersListContinueError>>} */ routes$1.teamMemberSpaceLimitsExcludedUsersListContinue = function (arg) { return this.request('team/member_space_limits/excluded_users/list/continue', arg, 'team', 'api', 'rpc'); }; /** * Remove users from member space limits excluded users list. * @function DropboxTeam#teamMemberSpaceLimitsExcludedUsersRemove * @arg {TeamExcludedUsersUpdateArg} arg - The request parameters. * @returns {Promise.<TeamExcludedUsersUpdateResult, Error.<TeamExcludedUsersUpdateError>>} */ routes$1.teamMemberSpaceLimitsExcludedUsersRemove = function (arg) { return this.request('team/member_space_limits/excluded_users/remove', arg, 'team', 'api', 'rpc'); }; /** * Get users custom quota. Returns none as the custom quota if none was set. A * maximum of 1000 members can be specified in a single call. * @function DropboxTeam#teamMemberSpaceLimitsGetCustomQuota * @arg {TeamCustomQuotaUsersArg} arg - The request parameters. * @returns {Promise.<Array.<TeamCustomQuotaResult>, Error.<TeamCustomQuotaError>>} */ routes$1.teamMemberSpaceLimitsGetCustomQuota = function (arg) { return this.request('team/member_space_limits/get_custom_quota', arg, 'team', 'api', 'rpc'); }; /** * Remove users custom quota. A maximum of 1000 members can be specified in a * single call. * @function DropboxTeam#teamMemberSpaceLimitsRemoveCustomQuota * @arg {TeamCustomQuotaUsersArg} arg - The request parameters. * @returns {Promise.<Array.<TeamRemoveCustomQuotaResult>, Error.<TeamCustomQuotaError>>} */ routes$1.teamMemberSpaceLimitsRemoveCustomQuota = function (arg) { return this.request('team/member_space_limits/remove_custom_quota', arg, 'team', 'api', 'rpc'); }; /** * Set users custom quota. Custom quota has to be at least 15GB. A maximum of * 1000 members can be specified in a single call. * @function DropboxTeam#teamMemberSpaceLimitsSetCustomQuota * @arg {TeamSetCustomQuotaArg} arg - The request parameters. * @returns {Promise.<Array.<TeamCustomQuotaResult>, Error.<TeamSetCustomQuotaError>>} */ routes$1.teamMemberSpaceLimitsSetCustomQuota = function (arg) { return this.request('team/member_space_limits/set_custom_quota', arg, 'team', 'api', 'rpc'); }; /** * Adds members to a team. Permission : Team member management A maximum of 20 * members can be specified in a single call. If no Dropbox account exists with * the email address specified, a new Dropbox account will be created with the * given email address, and that account will be invited to the team. If a * personal Dropbox account exists with the email address specified in the call, * this call will create a placeholder Dropbox account for the user on the team * and send an email inviting the user to migrate their existing personal * account onto the team. Team member management apps are required to set an * initial given_name and surname for a user to use in the team invitation and * for 'Perform as team member' actions taken on the user before they become * 'active'. * @function DropboxTeam#teamMembersAdd * @arg {TeamMembersAddArg} arg - The request parameters. * @returns {Promise.<TeamMembersAddLaunch, Error.<void>>} */ routes$1.teamMembersAdd = function (arg) { return this.request('team/members/add', arg, 'team', 'api', 'rpc'); }; /** * Once an async_job_id is returned from members/add , use this to poll the * status of the asynchronous request. Permission : Team member management. * @function DropboxTeam#teamMembersAddJobStatusGet * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<TeamMembersAddJobStatus, Error.<AsyncPollError>>} */ routes$1.teamMembersAddJobStatusGet = function (arg) { return this.request('team/members/add/job_status/get', arg, 'team', 'api', 'rpc'); }; /** * Deletes a team member's profile photo. Permission : Team member management. * @function DropboxTeam#teamMembersDeleteProfilePhoto * @arg {TeamMembersDeleteProfilePhotoArg} arg - The request parameters. * @returns {Promise.<TeamTeamMemberInfo, Error.<TeamMembersDeleteProfilePhotoError>>} */ routes$1.teamMembersDeleteProfilePhoto = function (arg) { return this.request('team/members/delete_profile_photo', arg, 'team', 'api', 'rpc'); }; /** * Returns information about multiple team members. Permission : Team * information This endpoint will return MembersGetInfoItem.id_not_found, for * IDs (or emails) that cannot be matched to a valid team member. * @function DropboxTeam#teamMembersGetInfo * @arg {TeamMembersGetInfoArgs} arg - The request parameters. * @returns {Promise.<Object, Error.<TeamMembersGetInfoError>>} */ routes$1.teamMembersGetInfo = function (arg) { return this.request('team/members/get_info', arg, 'team', 'api', 'rpc'); }; /** * Lists members of a team. Permission : Team information. * @function DropboxTeam#teamMembersList * @arg {TeamMembersListArg} arg - The request parameters. * @returns {Promise.<TeamMembersListResult, Error.<TeamMembersListError>>} */ routes$1.teamMembersList = function (arg) { return this.request('team/members/list', arg, 'team', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from members/list, use this to paginate * through all team members. Permission : Team information. * @function DropboxTeam#teamMembersListContinue * @arg {TeamMembersListContinueArg} arg - The request parameters. * @returns {Promise.<TeamMembersListResult, Error.<TeamMembersListContinueError>>} */ routes$1.teamMembersListContinue = function (arg) { return this.request('team/members/list/continue', arg, 'team', 'api', 'rpc'); }; /** * Moves removed member's files to a different member. This endpoint initiates * an asynchronous job. To obtain the final result of the job, the client should * periodically poll members/move_former_member_files/job_status/check. * Permission : Team member management. * @function DropboxTeam#teamMembersMoveFormerMemberFiles * @arg {TeamMembersDataTransferArg} arg - The request parameters. * @returns {Promise.<AsyncLaunchEmptyResult, Error.<TeamMembersTransferFormerMembersFilesError>>} */ routes$1.teamMembersMoveFormerMemberFiles = function (arg) { return this.request('team/members/move_former_member_files', arg, 'team', 'api', 'rpc'); }; /** * Once an async_job_id is returned from members/move_former_member_files , use * this to poll the status of the asynchronous request. Permission : Team member * management. * @function DropboxTeam#teamMembersMoveFormerMemberFilesJobStatusCheck * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<AsyncPollEmptyResult, Error.<AsyncPollError>>} */ routes$1.teamMembersMoveFormerMemberFilesJobStatusCheck = function (arg) { return this.request('team/members/move_former_member_files/job_status/check', arg, 'team', 'api', 'rpc'); }; /** * Recover a deleted member. Permission : Team member management Exactly one of * team_member_id, email, or external_id must be provided to identify the user * account. * @function DropboxTeam#teamMembersRecover * @arg {TeamMembersRecoverArg} arg - The request parameters. * @returns {Promise.<void, Error.<TeamMembersRecoverError>>} */ routes$1.teamMembersRecover = function (arg) { return this.request('team/members/recover', arg, 'team', 'api', 'rpc'); }; /** * Removes a member from a team. Permission : Team member management Exactly one * of team_member_id, email, or external_id must be provided to identify the * user account. Accounts can be recovered via members/recover for a 7 day * period or until the account has been permanently deleted or transferred to * another account (whichever comes first). Calling members/add while a user is * still recoverable on your team will return with * MemberAddResult.user_already_on_team. Accounts can have their files * transferred via the admin console for a limited time, based on the version * history length associated with the team (180 days for most teams). This * endpoint may initiate an asynchronous job. To obtain the final result of the * job, the client should periodically poll members/remove/job_status/get. * @function DropboxTeam#teamMembersRemove * @arg {TeamMembersRemoveArg} arg - The request parameters. * @returns {Promise.<AsyncLaunchEmptyResult, Error.<TeamMembersRemoveError>>} */ routes$1.teamMembersRemove = function (arg) { return this.request('team/members/remove', arg, 'team', 'api', 'rpc'); }; /** * Once an async_job_id is returned from members/remove , use this to poll the * status of the asynchronous request. Permission : Team member management. * @function DropboxTeam#teamMembersRemoveJobStatusGet * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<AsyncPollEmptyResult, Error.<AsyncPollError>>} */ routes$1.teamMembersRemoveJobStatusGet = function (arg) { return this.request('team/members/remove/job_status/get', arg, 'team', 'api', 'rpc'); }; /** * Add secondary emails to users. Permission : Team member management. Emails * that are on verified domains will be verified automatically. For each email * address not on a verified domain a verification email will be sent. * @function DropboxTeam#teamMembersSecondaryEmailsAdd * @arg {TeamAddSecondaryEmailsArg} arg - The request parameters. * @returns {Promise.<TeamAddSecondaryEmailsResult, Error.<TeamAddSecondaryEmailsError>>} */ routes$1.teamMembersSecondaryEmailsAdd = function (arg) { return this.request('team/members/secondary_emails/add', arg, 'team', 'api', 'rpc'); }; /** * Delete secondary emails from users Permission : Team member management. Users * will be notified of deletions of verified secondary emails at both the * secondary email and their primary email. * @function DropboxTeam#teamMembersSecondaryEmailsDelete * @arg {TeamDeleteSecondaryEmailsArg} arg - The request parameters. * @returns {Promise.<TeamDeleteSecondaryEmailsResult, Error.<void>>} */ routes$1.teamMembersSecondaryEmailsDelete = function (arg) { return this.request('team/members/secondary_emails/delete', arg, 'team', 'api', 'rpc'); }; /** * Resend secondary email verification emails. Permission : Team member * management. * @function DropboxTeam#teamMembersSecondaryEmailsResendVerificationEmails * @arg {TeamResendVerificationEmailArg} arg - The request parameters. * @returns {Promise.<TeamResendVerificationEmailResult, Error.<void>>} */ routes$1.teamMembersSecondaryEmailsResendVerificationEmails = function (arg) { return this.request('team/members/secondary_emails/resend_verification_emails', arg, 'team', 'api', 'rpc'); }; /** * Sends welcome email to pending team member. Permission : Team member * management Exactly one of team_member_id, email, or external_id must be * provided to identify the user account. No-op if team member is not pending. * @function DropboxTeam#teamMembersSendWelcomeEmail * @arg {TeamUserSelectorArg} arg - The request parameters. * @returns {Promise.<void, Error.<TeamMembersSendWelcomeError>>} */ routes$1.teamMembersSendWelcomeEmail = function (arg) { return this.request('team/members/send_welcome_email', arg, 'team', 'api', 'rpc'); }; /** * Updates a team member's permissions. Permission : Team member management. * @function DropboxTeam#teamMembersSetAdminPermissions * @arg {TeamMembersSetPermissionsArg} arg - The request parameters. * @returns {Promise.<TeamMembersSetPermissionsResult, Error.<TeamMembersSetPermissionsError>>} */ routes$1.teamMembersSetAdminPermissions = function (arg) { return this.request('team/members/set_admin_permissions', arg, 'team', 'api', 'rpc'); }; /** * Updates a team member's profile. Permission : Team member management. * @function DropboxTeam#teamMembersSetProfile * @arg {TeamMembersSetProfileArg} arg - The request parameters. * @returns {Promise.<TeamTeamMemberInfo, Error.<TeamMembersSetProfileError>>} */ routes$1.teamMembersSetProfile = function (arg) { return this.request('team/members/set_profile', arg, 'team', 'api', 'rpc'); }; /** * Updates a team member's profile photo. Permission : Team member management. * @function DropboxTeam#teamMembersSetProfilePhoto * @arg {TeamMembersSetProfilePhotoArg} arg - The request parameters. * @returns {Promise.<TeamTeamMemberInfo, Error.<TeamMembersSetProfilePhotoError>>} */ routes$1.teamMembersSetProfilePhoto = function (arg) { return this.request('team/members/set_profile_photo', arg, 'team', 'api', 'rpc'); }; /** * Suspend a member from a team. Permission : Team member management Exactly one * of team_member_id, email, or external_id must be provided to identify the * user account. * @function DropboxTeam#teamMembersSuspend * @arg {TeamMembersDeactivateArg} arg - The request parameters. * @returns {Promise.<void, Error.<TeamMembersSuspendError>>} */ routes$1.teamMembersSuspend = function (arg) { return this.request('team/members/suspend', arg, 'team', 'api', 'rpc'); }; /** * Unsuspend a member from a team. Permission : Team member management Exactly * one of team_member_id, email, or external_id must be provided to identify the * user account. * @function DropboxTeam#teamMembersUnsuspend * @arg {TeamMembersUnsuspendArg} arg - The request parameters. * @returns {Promise.<void, Error.<TeamMembersUnsuspendError>>} */ routes$1.teamMembersUnsuspend = function (arg) { return this.request('team/members/unsuspend', arg, 'team', 'api', 'rpc'); }; /** * Returns a list of all team-accessible namespaces. This list includes team * folders, shared folders containing team members, team members' home * namespaces, and team members' app folders. Home namespaces and app folders * are always owned by this team or members of the team, but shared folders may * be owned by other users or other teams. Duplicates may occur in the list. * @function DropboxTeam#teamNamespacesList * @arg {TeamTeamNamespacesListArg} arg - The request parameters. * @returns {Promise.<TeamTeamNamespacesListResult, Error.<TeamTeamNamespacesListError>>} */ routes$1.teamNamespacesList = function (arg) { return this.request('team/namespaces/list', arg, 'team', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from namespaces/list, use this to paginate * through all team-accessible namespaces. Duplicates may occur in the list. * @function DropboxTeam#teamNamespacesListContinue * @arg {TeamTeamNamespacesListContinueArg} arg - The request parameters. * @returns {Promise.<TeamTeamNamespacesListResult, Error.<TeamTeamNamespacesListContinueError>>} */ routes$1.teamNamespacesListContinue = function (arg) { return this.request('team/namespaces/list/continue', arg, 'team', 'api', 'rpc'); }; /** * Permission : Team member file access. * @function DropboxTeam#teamPropertiesTemplateAdd * @deprecated * @arg {FilePropertiesAddTemplateArg} arg - The request parameters. * @returns {Promise.<FilePropertiesAddTemplateResult, Error.<FilePropertiesModifyTemplateError>>} */ routes$1.teamPropertiesTemplateAdd = function (arg) { return this.request('team/properties/template/add', arg, 'team', 'api', 'rpc'); }; /** * Permission : Team member file access. * @function DropboxTeam#teamPropertiesTemplateGet * @deprecated * @arg {FilePropertiesGetTemplateArg} arg - The request parameters. * @returns {Promise.<FilePropertiesGetTemplateResult, Error.<FilePropertiesTemplateError>>} */ routes$1.teamPropertiesTemplateGet = function (arg) { return this.request('team/properties/template/get', arg, 'team', 'api', 'rpc'); }; /** * Permission : Team member file access. * @function DropboxTeam#teamPropertiesTemplateList * @deprecated * @arg {void} arg - The request parameters. * @returns {Promise.<FilePropertiesListTemplateResult, Error.<FilePropertiesTemplateError>>} */ routes$1.teamPropertiesTemplateList = function (arg) { return this.request('team/properties/template/list', arg, 'team', 'api', 'rpc'); }; /** * Permission : Team member file access. * @function DropboxTeam#teamPropertiesTemplateUpdate * @deprecated * @arg {FilePropertiesUpdateTemplateArg} arg - The request parameters. * @returns {Promise.<FilePropertiesUpdateTemplateResult, Error.<FilePropertiesModifyTemplateError>>} */ routes$1.teamPropertiesTemplateUpdate = function (arg) { return this.request('team/properties/template/update', arg, 'team', 'api', 'rpc'); }; /** * Retrieves reporting data about a team's user activity. * @function DropboxTeam#teamReportsGetActivity * @arg {TeamDateRange} arg - The request parameters. * @returns {Promise.<TeamGetActivityReport, Error.<TeamDateRangeError>>} */ routes$1.teamReportsGetActivity = function (arg) { return this.request('team/reports/get_activity', arg, 'team', 'api', 'rpc'); }; /** * Retrieves reporting data about a team's linked devices. * @function DropboxTeam#teamReportsGetDevices * @arg {TeamDateRange} arg - The request parameters. * @returns {Promise.<TeamGetDevicesReport, Error.<TeamDateRangeError>>} */ routes$1.teamReportsGetDevices = function (arg) { return this.request('team/reports/get_devices', arg, 'team', 'api', 'rpc'); }; /** * Retrieves reporting data about a team's membership. * @function DropboxTeam#teamReportsGetMembership * @arg {TeamDateRange} arg - The request parameters. * @returns {Promise.<TeamGetMembershipReport, Error.<TeamDateRangeError>>} */ routes$1.teamReportsGetMembership = function (arg) { return this.request('team/reports/get_membership', arg, 'team', 'api', 'rpc'); }; /** * Retrieves reporting data about a team's storage usage. * @function DropboxTeam#teamReportsGetStorage * @arg {TeamDateRange} arg - The request parameters. * @returns {Promise.<TeamGetStorageReport, Error.<TeamDateRangeError>>} */ routes$1.teamReportsGetStorage = function (arg) { return this.request('team/reports/get_storage', arg, 'team', 'api', 'rpc'); }; /** * Sets an archived team folder's status to active. Permission : Team member * file access. * @function DropboxTeam#teamTeamFolderActivate * @arg {TeamTeamFolderIdArg} arg - The request parameters. * @returns {Promise.<TeamTeamFolderMetadata, Error.<TeamTeamFolderActivateError>>} */ routes$1.teamTeamFolderActivate = function (arg) { return this.request('team/team_folder/activate', arg, 'team', 'api', 'rpc'); }; /** * Sets an active team folder's status to archived and removes all folder and * file members. Permission : Team member file access. * @function DropboxTeam#teamTeamFolderArchive * @arg {TeamTeamFolderArchiveArg} arg - The request parameters. * @returns {Promise.<TeamTeamFolderArchiveLaunch, Error.<TeamTeamFolderArchiveError>>} */ routes$1.teamTeamFolderArchive = function (arg) { return this.request('team/team_folder/archive', arg, 'team', 'api', 'rpc'); }; /** * Returns the status of an asynchronous job for archiving a team folder. * Permission : Team member file access. * @function DropboxTeam#teamTeamFolderArchiveCheck * @arg {AsyncPollArg} arg - The request parameters. * @returns {Promise.<TeamTeamFolderArchiveJobStatus, Error.<AsyncPollError>>} */ routes$1.teamTeamFolderArchiveCheck = function (arg) { return this.request('team/team_folder/archive/check', arg, 'team', 'api', 'rpc'); }; /** * Creates a new, active, team folder with no members. Permission : Team member * file access. * @function DropboxTeam#teamTeamFolderCreate * @arg {TeamTeamFolderCreateArg} arg - The request parameters. * @returns {Promise.<TeamTeamFolderMetadata, Error.<TeamTeamFolderCreateError>>} */ routes$1.teamTeamFolderCreate = function (arg) { return this.request('team/team_folder/create', arg, 'team', 'api', 'rpc'); }; /** * Retrieves metadata for team folders. Permission : Team member file access. * @function DropboxTeam#teamTeamFolderGetInfo * @arg {TeamTeamFolderIdListArg} arg - The request parameters. * @returns {Promise.<Array.<TeamTeamFolderGetInfoItem>, Error.<void>>} */ routes$1.teamTeamFolderGetInfo = function (arg) { return this.request('team/team_folder/get_info', arg, 'team', 'api', 'rpc'); }; /** * Lists all team folders. Permission : Team member file access. * @function DropboxTeam#teamTeamFolderList * @arg {TeamTeamFolderListArg} arg - The request parameters. * @returns {Promise.<TeamTeamFolderListResult, Error.<TeamTeamFolderListError>>} */ routes$1.teamTeamFolderList = function (arg) { return this.request('team/team_folder/list', arg, 'team', 'api', 'rpc'); }; /** * Once a cursor has been retrieved from team_folder/list, use this to paginate * through all team folders. Permission : Team member file access. * @function DropboxTeam#teamTeamFolderListContinue * @arg {TeamTeamFolderListContinueArg} arg - The request parameters. * @returns {Promise.<TeamTeamFolderListResult, Error.<TeamTeamFolderListContinueError>>} */ routes$1.teamTeamFolderListContinue = function (arg) { return this.request('team/team_folder/list/continue', arg, 'team', 'api', 'rpc'); }; /** * Permanently deletes an archived team folder. Permission : Team member file * access. * @function DropboxTeam#teamTeamFolderPermanentlyDelete * @arg {TeamTeamFolderIdArg} arg - The request parameters. * @returns {Promise.<void, Error.<TeamTeamFolderPermanentlyDeleteError>>} */ routes$1.teamTeamFolderPermanentlyDelete = function (arg) { return this.request('team/team_folder/permanently_delete', arg, 'team', 'api', 'rpc'); }; /** * Changes an active team folder's name. Permission : Team member file access. * @function DropboxTeam#teamTeamFolderRename * @arg {TeamTeamFolderRenameArg} arg - The request parameters. * @returns {Promise.<TeamTeamFolderMetadata, Error.<TeamTeamFolderRenameError>>} */ routes$1.teamTeamFolderRename = function (arg) { return this.request('team/team_folder/rename', arg, 'team', 'api', 'rpc'); }; /** * Updates the sync settings on a team folder or its contents. Use of this * endpoint requires that the team has team selective sync enabled. * @function DropboxTeam#teamTeamFolderUpdateSyncSettings * @arg {TeamTeamFolderUpdateSyncSettingsArg} arg - The request parameters. * @returns {Promise.<TeamTeamFolderMetadata, Error.<TeamTeamFolderUpdateSyncSettingsError>>} */ routes$1.teamTeamFolderUpdateSyncSettings = function (arg) { return this.request('team/team_folder/update_sync_settings', arg, 'team', 'api', 'rpc'); }; /** * Returns the member profile of the admin who generated the team access token * used to make the call. * @function DropboxTeam#teamTokenGetAuthenticatedAdmin * @arg {void} arg - The request parameters. * @returns {Promise.<TeamTokenGetAuthenticatedAdminResult, Error.<TeamTokenGetAuthenticatedAdminError>>} */ routes$1.teamTokenGetAuthenticatedAdmin = function (arg) { return this.request('team/token/get_authenticated_admin', arg, 'team', 'api', 'rpc'); }; /** * @class DropboxTeam * @extends DropboxBase * @classdesc The Dropbox SDK class that provides access to team endpoints. * @arg {Object} options * @arg {String} [options.accessToken] - An access token for making authenticated * requests. * @arg {String} [options.clientId] - The client id for your app. Used to create * authentication URL. */ var DropboxTeam = function (_DropboxBase) { inherits(DropboxTeam, _DropboxBase); function DropboxTeam(options) { classCallCheck(this, DropboxTeam); var _this = possibleConstructorReturn(this, (DropboxTeam.__proto__ || Object.getPrototypeOf(DropboxTeam)).call(this, options)); Object.assign(_this, routes$1); return _this; } /** * Returns an instance of Dropbox that can make calls to user api endpoints on * behalf of the passed user id, using the team access token. * @arg {String} userId - The user id to use the Dropbox class as * @returns {Dropbox} An instance of Dropbox used to make calls to user api * endpoints */ createClass(DropboxTeam, [{ key: 'actAsUser', value: function actAsUser(userId) { return new Dropbox({ accessToken: this.accessToken, clientId: this.clientId, selectUser: userId }); } }]); return DropboxTeam; }(DropboxBase); var dropboxTeam = /*#__PURE__*/Object.freeze({ __proto__: null, DropboxTeam: DropboxTeam }); var dropbox$1 = ( dropbox && undefined ) || dropbox; var dropboxTeam$1 = ( dropboxTeam && undefined ) || dropboxTeam; var src = { Dropbox: dropbox$1.Dropbox, DropboxTeam: dropboxTeam$1.DropboxTeam }; var src_1 = src.Dropbox; var src_2 = src.DropboxTeam; exports.Dropbox = src_1; exports.DropboxTeam = src_2; exports.default = src; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=Dropbox-sdk.js.map
cdnjs/cdnjs
ajax/libs/dropbox.js/5.1.0/Dropbox-sdk.js
JavaScript
mit
236,211
/*jshint eqeqeq:false, eqnull:true, devel:true */ /*global jQuery, define */ (function( factory ) { "use strict"; if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./grid.base", "./grid.common" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { "use strict"; //module begin var rp_ge = {}; $.jgrid.extend({ editGridRow : function(rowid, p){ var regional = $.jgrid.getRegional(this[0], 'edit'), currstyle = this[0].p.styleUI, styles = $.jgrid.styleUI[currstyle].formedit, commonstyle = $.jgrid.styleUI[currstyle].common; p = $.extend(true, { top : 0, left: 0, width: '500', datawidth: 'auto', height: 'auto', dataheight: 'auto', modal: false, overlay : 30, drag: true, resize: true, url: null, mtype : "POST", clearAfterAdd :true, closeAfterEdit : false, reloadAfterSubmit : true, onInitializeForm: null, beforeInitData: null, beforeShowForm: null, afterShowForm: null, beforeSubmit: null, afterSubmit: null, onclickSubmit: null, afterComplete: null, onclickPgButtons : null, afterclickPgButtons: null, editData : {}, recreateForm : false, jqModal : true, closeOnEscape : false, addedrow : "first", topinfo : '', bottominfo: '', saveicon : [], closeicon : [], savekey: [false,13], navkeys: [false,38,40], checkOnSubmit : false, checkOnUpdate : false, processing : false, onClose : null, ajaxEditOptions : {}, serializeEditData : null, viewPagerButtons : true, overlayClass : commonstyle.overlay, removemodal : true, form: 'edit', template : null, focusField : true, editselected : false, html5Check : false, buttons : [] }, regional, p || {}); rp_ge[$(this)[0].p.id] = p; return this.each(function(){ var $t = this; if (!$t.grid || !rowid) {return;} $t.p.savedData = {}; var gID = $t.p.id, frmgr = "FrmGrid_"+gID, frmtborg = "TblGrid_"+gID, frmtb = "#"+$.jgrid.jqID(frmtborg), frmtb2, IDs = {themodal:'editmod'+gID,modalhead:'edithd'+gID,modalcontent:'editcnt'+gID, scrollelm : frmgr}, showFrm = true, maxCols = 1, maxRows=0, postdata, diff, frmoper, templ = typeof rp_ge[$t.p.id].template === "string" && rp_ge[$t.p.id].template.length > 0, errors =$.jgrid.getRegional(this, 'errors'); rp_ge[$t.p.id].styleUI = $t.p.styleUI || 'jQueryUI'; if($.jgrid.isMobile()) { rp_ge[$t.p.id].resize = false; } if (rowid === "new") { rowid = "_empty"; frmoper = "add"; p.caption=rp_ge[$t.p.id].addCaption; } else { p.caption=rp_ge[$t.p.id].editCaption; frmoper = "edit"; } if(!p.recreateForm) { if( $($t).data("formProp") ) { $.extend(rp_ge[$(this)[0].p.id], $($t).data("formProp")); } } var closeovrl = true; if(p.checkOnUpdate && p.jqModal && !p.modal) { closeovrl = false; } function getFormData(){ var a2 ={}, i; $(frmtb).find(".FormElement").each(function() { var celm = $(".customelement", this); if (celm.length) { var elem = celm[0], nm = $(elem).attr('name'); $.each($t.p.colModel, function(){ if(this.name === nm && this.editoptions && $.jgrid.isFunction(this.editoptions.custom_value)) { try { postdata[nm] = this.editoptions.custom_value.call($t, $("#"+$.jgrid.jqID(nm),frmtb),'get'); if (postdata[nm] === undefined) {throw "e1";} } catch (e) { if (e==="e1") {$.jgrid.info_dialog(errors.errcap,"function 'custom_value' "+rp_ge[$(this)[0]].p.msg.novalue,rp_ge[$(this)[0]].p.bClose, {styleUI : rp_ge[$(this)[0]].p.styleUI });} else {$.jgrid.info_dialog(errors.errcap,e.message,rp_ge[$(this)[0]].p.bClose, {styleUI : rp_ge[$(this)[0]].p.styleUI });} } return true; } }); } else { switch ($(this).get(0).type) { case "checkbox": if($(this).is(":checked")) { postdata[this.name]= $(this).val(); } else { var ofv = $(this).attr("offval"); postdata[this.name]= ofv; } break; case "select-one": postdata[this.name]= $(this).val(); break; case "select-multiple": postdata[this.name]= $(this).val(); postdata[this.name] = postdata[this.name] ? postdata[this.name].join(",") : ""; break; case "radio" : if(a2.hasOwnProperty(this.name)) { return true; } else { a2[this.name] = ($(this).attr("offval") === undefined) ? "off" : $(this).attr("offval"); } break; default: postdata[this.name] = $(this).val(); } if($t.p.autoencode) { postdata[this.name] = $.jgrid.htmlEncode(postdata[this.name]); } } }); for(i in a2 ) { if( a2.hasOwnProperty(i)) { var val = $('input[name="'+i+'"]:checked',frmtb).val(); postdata[i] = (val !== undefined) ? val : a2[i]; if($t.p.autoencode) { postdata[i] = $.jgrid.htmlEncode(postdata[i]); } } } return true; } function createData(rowid,obj,tb,maxcols){ var nm, hc,trdata, cnt=0,tmp, dc,elc, retpos=[], ind=false, tdtmpl = "<td class='CaptionTD'></td><td class='DataTD'></td>", tmpl="", i, ffld; //*2 for (i =1; i<=maxcols;i++) { tmpl += tdtmpl; } if(rowid !== '_empty') { ind = $(obj).jqGrid("getInd",rowid); } $(obj.p.colModel).each( function(i) { nm = this.name; // hidden fields are included in the form if(this.editrules && this.editrules.edithidden === true) { hc = false; } else { hc = this.hidden === true ? true : false; } dc = hc ? "style='display:none'" : ""; if ( nm !== 'cb' && nm !== 'subgrid' && this.editable===true && nm !== 'rn') { if(ind === false) { tmp = ""; } else { if(nm === obj.p.ExpandColumn && obj.p.treeGrid === true) { tmp = $("td[role='gridcell']",obj.rows[ind]).eq( i ).text(); } else { try { tmp = $.unformat.call(obj, $("td[role='gridcell']",obj.rows[ind]).eq( i ),{rowId:rowid, colModel:this},i); } catch (_) { tmp = (this.edittype && this.edittype === "textarea") ? $("td[role='gridcell']",obj.rows[ind]).eq( i ).text() : $("td[role='gridcell']",obj.rows[ind]).eq( i ).html(); } if(!tmp || tmp === "&nbsp;" || tmp === "&#160;" || (tmp.length===1 && tmp.charCodeAt(0)===160) ) {tmp='';} } } var opt = $.extend({}, this.editoptions || {} ,{id:nm,name:nm, rowId: rowid, oper:'edit', module : 'form', checkUpdate : rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate}), frmopt = $.extend({}, {elmprefix:'',elmsuffix:'',rowabove:false,rowcontent:''}, this.formoptions || {}), rp = parseInt(frmopt.rowpos,10) || cnt+1, cp = parseInt((parseInt(frmopt.colpos,10) || 1)*2,10); if(rowid === "_empty" && opt.defaultValue ) { tmp = $.jgrid.isFunction(opt.defaultValue) ? opt.defaultValue.call($t) : opt.defaultValue; } if(!this.edittype) { this.edittype = "text"; } if($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); } elc = $.jgrid.createEl.call($t,this.edittype,opt,tmp,false,$.extend({},$.jgrid.ajaxOptions,obj.p.ajaxSelectOptions || {})); //if(tmp === "" && this.edittype == "checkbox") {tmp = $(elc).attr("offval");} //if(tmp === "" && this.edittype == "select") {tmp = $("option:eq(0)",elc).text();} if(this.edittype === "select") { tmp = $(elc).val(); if($(elc).get(0).type === 'select-multiple' && tmp) { tmp = tmp.join(","); } } if(this.edittype === 'checkbox') { if($(elc).is(":checked")) { tmp= $(elc).val(); } else { tmp = $(elc).attr("offval"); } } $(elc).addClass("FormElement"); if( $.inArray(this.edittype, ['text','textarea','password','select', 'color', 'date', 'datetime', 'datetime-local','email','month', 'number','range', 'search', 'tel', 'time', 'url','week'] ) > -1) { $(elc).addClass( styles.inputClass ); } ffld = true; if(templ) { var ftmplfld = $(frm).find("#"+nm); if(ftmplfld.length){ ftmplfld.replaceWith( elc ); } else { ffld = false; } } else { //-------------------- trdata = $(tb).find("tr[rowpos="+rp+"]"); if(frmopt.rowabove) { var newdata = $("<tr><td class='contentinfo' colspan='"+(maxcols*2)+"'>"+frmopt.rowcontent+"</td></tr>"); $(tb).append(newdata); newdata[0].rp = rp; } if ( trdata.length===0 ) { if(maxcols > 1) { trdata = $("<tr rowpos='"+rp+"'></tr>").addClass("FormData").attr("id","tr_"+nm); } else { trdata = $("<tr "+dc+" rowpos='"+rp+"'></tr>").addClass("FormData").attr("id","tr_"+nm); } $(trdata).append(tmpl); $(tb).append(trdata); trdata[0].rp = rp; } $("td",trdata[0]).eq( cp-2 ).html("<label for='"+nm+"'>"+ (frmopt.label === undefined ? obj.p.colNames[i]: frmopt.label) + "</label>"); $("td",trdata[0]).eq( cp-1 ).append(frmopt.elmprefix).append(elc).append(frmopt.elmsuffix); if( maxcols > 1 && hc) { $("td",trdata[0]).eq( cp-2 ).hide(); $("td",trdata[0]).eq( cp-1 ).hide(); } //------------------------- } if( (rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) && ffld) { $t.p.savedData[nm] = tmp; } if(this.edittype==='custom' && $.jgrid.isFunction(opt.custom_value) ) { opt.custom_value.call($t, $("#"+nm, frmgr),'set',tmp); } $.jgrid.bindEv.call($t, elc, opt); retpos[cnt] = i; cnt++; } }); if( cnt > 0) { var idrow; if(templ) { idrow = "<div class='FormData' style='display:none'><input class='FormElement' id='id_g' type='text' name='"+obj.p.id+"_id' value='"+rowid+"'/>"; $(frm).append(idrow); } else { idrow = $("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+ (maxcols*2-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='"+obj.p.id+"_id' value='"+rowid+"'/></td></tr>"); idrow[0].rp = cnt+999; $(tb).append(idrow); } //$(tb).append(idrow); if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) { $t.p.savedData[obj.p.id+"_id"] = rowid; } } return retpos; } function fillData(rowid,obj,fmid){ var nm,cnt=0,tmp, fld,opt,vl,vlc; if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) { $t.p.savedData = {}; $t.p.savedData[obj.p.id+"_id"]=rowid; } var cm = obj.p.colModel; if(rowid === '_empty') { $(cm).each(function(){ nm = this.name; opt = $.extend({}, this.editoptions || {} ); fld = $("#"+$.jgrid.jqID(nm),fmid); if(fld && fld.length && fld[0] !== null) { vl = ""; if(this.edittype === 'custom' && $.jgrid.isFunction(opt.custom_value)) { opt.custom_value.call($t, $("#"+nm,fmid),'set',vl); } else if(opt.defaultValue ) { vl = $.jgrid.isFunction(opt.defaultValue) ? opt.defaultValue.call($t) : opt.defaultValue; if(fld[0].type==='checkbox') { vlc = vl.toLowerCase(); if(vlc.search(/(false|f|0|no|n|off|undefined)/i)<0 && vlc!=="") { fld[0].checked = true; fld[0].defaultChecked = true; fld[0].value = vl; } else { fld[0].checked = false; fld[0].defaultChecked = false; } } else {fld.val(vl);} } else { if( fld[0].type==='checkbox' ) { fld[0].checked = false; fld[0].defaultChecked = false; vl = $(fld).attr("offval"); } else if (fld[0].type && fld[0].type.substr(0,6)==='select') { fld[0].selectedIndex = 0; } else { fld.val(vl); } } if(rp_ge[$t.p.id].checkOnSubmit===true || rp_ge[$t.p.id].checkOnUpdate) { $t.p.savedData[nm] = vl; } } }); $("#id_g",fmid).val(rowid); return; } var tre = $(obj).jqGrid("getInd",rowid,true); if(!tre) {return;} $('td[role="gridcell"]',tre).each( function(i) { nm = cm[i].name; // hidden fields are included in the form if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn' && cm[i].editable===true) { if(nm === obj.p.ExpandColumn && obj.p.treeGrid === true) { tmp = $(this).text(); } else { try { tmp = $.unformat.call(obj, $(this),{rowId:rowid, colModel:cm[i]},i); } catch (_) { tmp = cm[i].edittype==="textarea" ? $(this).text() : $(this).html(); } } if($t.p.autoencode) {tmp = $.jgrid.htmlDecode(tmp);} if(rp_ge[$t.p.id].checkOnSubmit===true || rp_ge[$t.p.id].checkOnUpdate) { $t.p.savedData[nm] = tmp; } nm = $.jgrid.jqID(nm); switch (cm[i].edittype) { case "select": var opv = tmp.split(","); opv = $.map(opv,function(n){return $.jgrid.trim(n);}); $("#"+nm+" option",fmid).each(function(){ if (!cm[i].editoptions.multiple && ($.jgrid.trim(tmp) === $.jgrid.trim($(this).text()) || opv[0] === $.jgrid.trim($(this).text()) || opv[0] === $.jgrid.trim($(this).val())) ){ this.selected= true; } else if (cm[i].editoptions.multiple){ if( $.inArray($.jgrid.trim($(this).text()), opv ) > -1 || $.inArray($.jgrid.trim($(this).val()), opv ) > -1 ){ this.selected = true; }else{ this.selected = false; } } else { this.selected = false; } }); if(rp_ge[$t.p.id].checkOnSubmit===true || rp_ge[$t.p.id].checkOnUpdate) { tmp = $("#"+nm,fmid).val(); if(cm[i].editoptions.multiple) { tmp = tmp.join(","); } $t.p.savedData[nm] = tmp; } break; case "checkbox": tmp = String(tmp); if(cm[i].editoptions && cm[i].editoptions.value) { var cb = cm[i].editoptions.value.split(":"); if(cb[0] === tmp) { $("#"+nm, fmid)[$t.p.useProp ? 'prop': 'attr']({"checked":true, "defaultChecked" : true}); } else { $("#"+nm, fmid)[$t.p.useProp ? 'prop': 'attr']({"checked":false, "defaultChecked" : false}); } } else { tmp = tmp.toLowerCase(); if(tmp.search(/(false|f|0|no|n|off|undefined)/i)<0 && tmp!=="") { $("#"+nm, fmid)[$t.p.useProp ? 'prop': 'attr']("checked",true); $("#"+nm, fmid)[$t.p.useProp ? 'prop': 'attr']("defaultChecked",true); //ie } else { $("#"+nm, fmid)[$t.p.useProp ? 'prop': 'attr']("checked", false); $("#"+nm, fmid)[$t.p.useProp ? 'prop': 'attr']("defaultChecked", false); //ie } } if(rp_ge[$t.p.id].checkOnSubmit===true || rp_ge[$t.p.id].checkOnUpdate) { if($("#"+nm, fmid).is(":checked")) { tmp = $("#"+nm, fmid).val(); } else { tmp = $("#"+nm, fmid).attr("offval"); } $t.p.savedData[nm] = tmp; } break; case 'custom' : try { if(cm[i].editoptions && $.jgrid.isFunction(cm[i].editoptions.custom_value)) { cm[i].editoptions.custom_value.call($t, $("#"+nm, fmid),'set',tmp); } else {throw "e1";} } catch (e) { if (e==="e1") {$.jgrid.info_dialog(errors.errcap,"function 'custom_value' "+rp_ge[$(this)[0]].p.msg.nodefined,$.rp_ge[$(this)[0]].p.bClose, {styleUI : rp_ge[$(this)[0]].p.styleUI });} else {$.jgrid.info_dialog(errors.errcap,e.message,$.rp_ge[$(this)[0]].p.bClose, {styleUI : rp_ge[$(this)[0]].p.styleUI });} } break; default : if(tmp === "&nbsp;" || tmp === "&#160;" || (tmp.length===1 && tmp.charCodeAt(0)===160) ) {tmp='';} $("#"+nm,fmid).val(tmp); } cnt++; } }); if(cnt>0) { $("#id_g",frmtb).val(rowid); if( rp_ge[$t.p.id].checkOnSubmit===true || rp_ge[$t.p.id].checkOnUpdate ) { $t.p.savedData[obj.p.id+"_id"] = rowid; } } } function setNulls() { $.each($t.p.colModel, function(i,n){ if(n.editoptions && n.editoptions.NullIfEmpty === true) { if(postdata.hasOwnProperty(n.name) && postdata[n.name] === "") { postdata[n.name] = 'null'; } } }); } function postIt() { var copydata, ret=[true,"",""], onCS = {}, opers = $t.p.prmNames, idname, oper, key, selr, i, url; var retvals = $($t).triggerHandler("jqGridAddEditBeforeCheckValues", [postdata, $(frmgr), frmoper]); if(retvals && typeof retvals === 'object') {postdata = retvals;} if($.jgrid.isFunction(rp_ge[$t.p.id].beforeCheckValues)) { retvals = rp_ge[$t.p.id].beforeCheckValues.call($t, postdata, $(frmgr),frmoper); if(retvals && typeof retvals === 'object') {postdata = retvals;} } if(rp_ge[$t.p.id].html5Check) { if( !$.jgrid.validateForm(frm[0]) ) { return false; } } for( key in postdata ){ if(postdata.hasOwnProperty(key)) { ret = $.jgrid.checkValues.call($t,postdata[key],key); if(ret[0] === false) {break;} } } setNulls(); if(ret[0]) { onCS = $($t).triggerHandler("jqGridAddEditClickSubmit", [rp_ge[$t.p.id], postdata, frmoper]); if( onCS === undefined && $.jgrid.isFunction( rp_ge[$t.p.id].onclickSubmit)) { onCS = rp_ge[$t.p.id].onclickSubmit.call($t, rp_ge[$t.p.id], postdata, frmoper) || {}; } ret = $($t).triggerHandler("jqGridAddEditBeforeSubmit", [postdata, $(frmgr), frmoper]); if(ret === undefined) { ret = [true,"",""]; } if( ret[0] && $.jgrid.isFunction(rp_ge[$t.p.id].beforeSubmit)) { ret = rp_ge[$t.p.id].beforeSubmit.call($t,postdata,$(frmgr), frmoper); } } if(ret[0] && !rp_ge[$t.p.id].processing) { rp_ge[$t.p.id].processing = true; $("#sData", frmtb+"_2").addClass( commonstyle.active ); url = rp_ge[$t.p.id].url || $($t).jqGrid('getGridParam','editurl'); oper = opers.oper; idname = url === 'clientArray' ? $t.p.keyName : opers.id; // we add to pos data array the action - the name is oper postdata[oper] = ($.jgrid.trim(postdata[$t.p.id+"_id"]) === "_empty") ? opers.addoper : opers.editoper; if(postdata[oper] !== opers.addoper) { postdata[idname] = postdata[$t.p.id+"_id"]; } else { // check to see if we have allredy this field in the form and if yes lieve it if( postdata[idname] === undefined ) {postdata[idname] = postdata[$t.p.id+"_id"];} } delete postdata[$t.p.id+"_id"]; postdata = $.extend(postdata,rp_ge[$t.p.id].editData,onCS); if($t.p.treeGrid === true) { if(postdata[oper] === opers.addoper) { selr = $($t).jqGrid("getGridParam", 'selrow'); var tr_par_id = $t.p.treeGridModel === 'adjacency' ? $t.p.treeReader.parent_id_field : 'parent_id'; postdata[tr_par_id] = selr; } for(i in $t.p.treeReader){ if($t.p.treeReader.hasOwnProperty(i)) { var itm = $t.p.treeReader[i]; if(postdata.hasOwnProperty(itm)) { if(postdata[oper] === opers.addoper && i === 'parent_id_field') {continue;} delete postdata[itm]; } } } } postdata[idname] = $.jgrid.stripPref($t.p.idPrefix, postdata[idname]); var ajaxOptions = $.extend({ url: url, type: rp_ge[$t.p.id].mtype, data: $.jgrid.isFunction(rp_ge[$t.p.id].serializeEditData) ? rp_ge[$t.p.id].serializeEditData.call($t,postdata) : postdata, complete:function(data,status){ var key; $("#sData", frmtb+"_2").removeClass( commonstyle.active ); postdata[idname] = $t.p.idPrefix + postdata[idname]; if(data.status >= 300 && data.status !== 304) { ret[0] = false; ret[1] = $($t).triggerHandler("jqGridAddEditErrorTextFormat", [data, frmoper]); if ($.jgrid.isFunction(rp_ge[$t.p.id].errorTextFormat)) { ret[1] = rp_ge[$t.p.id].errorTextFormat.call($t, data, frmoper); } else { ret[1] = status + " Status: '" + data.statusText + "'. Error code: " + data.status; } } else { // data is posted successful // execute aftersubmit with the returned data from server ret = $($t).triggerHandler("jqGridAddEditAfterSubmit", [data, postdata, frmoper]); if(ret === undefined) { ret = [true,"",""]; } if( ret[0] && $.jgrid.isFunction(rp_ge[$t.p.id].afterSubmit) ) { ret = rp_ge[$t.p.id].afterSubmit.call($t, data,postdata, frmoper); } } if(ret[0] === false) { $(".FormError",frmgr).html(ret[1]); $(".FormError",frmgr).show(); } else { if($t.p.autoencode) { $.each(postdata,function(n,v){ postdata[n] = $.jgrid.htmlDecode(v); }); } //rp_ge[$t.p.id].reloadAfterSubmit = rp_ge[$t.p.id].reloadAfterSubmit && $t.p.datatype != "local"; // the action is add if(postdata[oper] === opers.addoper ) { //id processing // user not set the id ret[2] if(!ret[2]) {ret[2] = $.jgrid.randId();} if(postdata[idname] == null || postdata[idname] === ($t.p.idPrefix + "_empty") || postdata[idname] === ""){ postdata[idname] = ret[2]; } else { ret[2] = postdata[idname]; } if(rp_ge[$t.p.id].reloadAfterSubmit) { $($t).trigger("reloadGrid"); } else { if($t.p.treeGrid === true){ $($t).jqGrid("addChildNode",ret[2],selr,postdata ); } else { $($t).jqGrid("addRowData",ret[2],postdata,p.addedrow); } } if(rp_ge[$t.p.id].closeAfterAdd) { if($t.p.treeGrid !== true){ $($t).jqGrid("setSelection",ret[2]); } $.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form}); } else if (rp_ge[$t.p.id].clearAfterAdd) { fillData("_empty", $t, frmgr); } } else { // the action is update if(rp_ge[$t.p.id].reloadAfterSubmit) { $($t).trigger("reloadGrid"); if( !rp_ge[$t.p.id].closeAfterEdit ) {setTimeout(function(){$($t).jqGrid("setSelection",postdata[idname]);},1000);} } else { if($t.p.treeGrid === true) { $($t).jqGrid("setTreeRow", postdata[idname],postdata); } else { $($t).jqGrid("setRowData", postdata[idname],postdata); } } if(rp_ge[$t.p.id].closeAfterEdit) {$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});} } if( $.jgrid.isFunction(rp_ge[$t.p.id].afterComplete) || Object.prototype.hasOwnProperty.call($._data( $($t)[0], 'events' ), 'jqGridAddEditAfterComplete') ) { copydata = data; setTimeout(function(){ $($t).triggerHandler("jqGridAddEditAfterComplete", [copydata, postdata, $(frmgr), frmoper]); try { rp_ge[$t.p.id].afterComplete.call($t, copydata, postdata, $(frmgr), frmoper); } catch(excacmp) { //do nothing } copydata=null; },500); } if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) { $(frmgr).data("disabled",false); if($t.p.savedData[$t.p.id+"_id"] !== "_empty"){ for(key in $t.p.savedData) { if($t.p.savedData.hasOwnProperty(key) && postdata[key]) { $t.p.savedData[key] = postdata[key]; } } } } } rp_ge[$t.p.id].processing=false; try{$(':input:visible',frmgr)[0].focus();} catch (e){} } }, $.jgrid.ajaxOptions, rp_ge[$t.p.id].ajaxEditOptions ); if (!ajaxOptions.url && !rp_ge[$t.p.id].useDataProxy) { if ($.jgrid.isFunction($t.p.dataProxy)) { rp_ge[$t.p.id].useDataProxy = true; } else { ret[0]=false;ret[1] += " "+errors.nourl; } } if (ret[0]) { if (rp_ge[$t.p.id].useDataProxy) { var dpret = $t.p.dataProxy.call($t, ajaxOptions, "set_"+$t.p.id); if(dpret === undefined) { dpret = [true, ""]; } if(dpret[0] === false ) { ret[0] = false; ret[1] = dpret[1] || "Error deleting the selected row!" ; } else { if(ajaxOptions.data.oper === opers.addoper && rp_ge[$t.p.id].closeAfterAdd ) { $.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form}); } if(ajaxOptions.data.oper === opers.editoper && rp_ge[$t.p.id].closeAfterEdit ) { $.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form}); } } } else { if(ajaxOptions.url === "clientArray") { rp_ge[$t.p.id].reloadAfterSubmit = false; postdata = ajaxOptions.data; ajaxOptions.complete({status:200, statusText:''},''); } else { $.ajax(ajaxOptions); } } } } if(ret[0] === false) { $(".FormError",frmgr).html(ret[1]); $(".FormError",frmgr).show(); // return; } } function compareData(nObj, oObj ) { var ret = false,key; ret = !( $.isPlainObject(nObj) && $.isPlainObject(oObj) && Object.getOwnPropertyNames(nObj).length === Object.getOwnPropertyNames(oObj).length); if(!ret) { for (key in oObj) { if(oObj.hasOwnProperty(key) ) { if(nObj.hasOwnProperty(key) ) { if( nObj[key] !== oObj[key] ) { ret = true; break; } } else { ret = true; break; } } } } return ret; } function checkUpdates () { var stat = true; $(".FormError",frmgr).hide(); if(rp_ge[$t.p.id].checkOnUpdate) { postdata = {}; getFormData(); diff = compareData(postdata, $t.p.savedData); if(diff) { $(frmgr).data("disabled",true); $(".confirm","#"+IDs.themodal).show(); stat = false; } } return stat; } function restoreInline() { var i; if (rowid !== "_empty" && $t.p.savedRow !== undefined && $t.p.savedRow.length > 0 && $.jgrid.isFunction($.fn.jqGrid.restoreRow)) { for (i=0;i<$t.p.savedRow.length;i++) { if ($t.p.savedRow[i].id === rowid) { $($t).jqGrid('restoreRow',rowid); break; } } } } function updateNav(cr, posarr){ var totr = posarr[1].length-1; if (cr===0) { $("#pData",frmtb2).addClass( commonstyle.disabled ); } else if( posarr[1][cr-1] !== undefined && $("#"+$.jgrid.jqID(posarr[1][cr-1])).hasClass( commonstyle.disabled )) { $("#pData",frmtb2).addClass( commonstyle.disabled ); } else { $("#pData",frmtb2).removeClass( commonstyle.disabled ); } if (cr===totr) { $("#nData",frmtb2).addClass( commonstyle.disabled ); } else if( posarr[1][cr+1] !== undefined && $("#"+$.jgrid.jqID(posarr[1][cr+1])).hasClass( commonstyle.disabled )) { $("#nData",frmtb2).addClass( commonstyle.disabled ); } else { $("#nData",frmtb2).removeClass( commonstyle.disabled ); } } function getCurrPos() { var rowsInGrid = $($t).jqGrid("getDataIDs"), selrow = $("#id_g",frmtb).val(), pos; if($t.p.multiselect && rp_ge[$t.p.id].editselected) { var arr = []; for(var i=0, len = rowsInGrid.length;i<len;i++) { if($.inArray(rowsInGrid[i],$t.p.selarrrow) !== -1) { arr.push(rowsInGrid[i]); } } pos = $.inArray(selrow,arr); return [pos, arr]; } else { pos = $.inArray(selrow,rowsInGrid); } return [pos,rowsInGrid]; } function parseTemplate ( template ){ var tmpl =""; if(typeof template === "string") { tmpl = template.replace(/\{([\w\-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, function(m,i){ return '<span id="'+ i+ '" ></span>'; }); } return tmpl; } function syncSavedData () { if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) { var a1=[], a2={}; a1 = $.map($t.p.savedData, function(v, i){ return i; }); $(".FormElement", frm ).each(function(){ if( $.jgrid.trim(this.name) !== "" && a1.indexOf(this.name) === -1 ) { var tv = $(this).val(), tt = $(this).get(0).type; if( tt === 'checkbox') { if(!$(this).is(":checked")) { tv = $(this).attr("offval"); } } else if(tt === 'select-multiple') { tv = tv.join(","); } else if(tt === 'radio') { if(a2.hasOwnProperty(this.name)) { return true; } else { a2[this.name] = ($(this).attr("offval") === undefined) ? "off" : $(this).attr("offval"); } } $t.p.savedData[this.name] = tv; } }); for(var i in a2 ) { if( a2.hasOwnProperty(i)) { var val = $('input[name="'+i+'"]:checked',frm).val(); $t.p.savedData[i] = (val !== undefined) ? val : a2[i]; } } } } var dh = isNaN(rp_ge[$(this)[0].p.id].dataheight) ? rp_ge[$(this)[0].p.id].dataheight : rp_ge[$(this)[0].p.id].dataheight+"px", dw = isNaN(rp_ge[$(this)[0].p.id].datawidth) ? rp_ge[$(this)[0].p.id].datawidth : rp_ge[$(this)[0].p.id].datawidth+"px", frm = $("<form name='FormPost' id='"+frmgr+"' class='FormGrid' onSubmit='return false;' style='width:"+dw+";height:"+dh+";'></form>").data("disabled",false), tbl; if(templ) { tbl = parseTemplate( rp_ge[$(this)[0].p.id].template ); frmtb2 = frmtb; } else { tbl = $("<table id='"+frmtborg+"' class='EditTable ui-common-table'><tbody></tbody></table>"); frmtb2 = frmtb+"_2"; } frmgr = "#"+ $.jgrid.jqID(frmgr); // errors $(frm).append("<div class='FormError " + commonstyle.error + "' style='display:none;'></div>" ); // topinfo $(frm).append("<div class='tinfo topinfo'>"+rp_ge[$t.p.id].topinfo+"</div>"); $($t.p.colModel).each( function() { var fmto = this.formoptions; maxCols = Math.max(maxCols, fmto ? fmto.colpos || 0 : 0 ); maxRows = Math.max(maxRows, fmto ? fmto.rowpos || 0 : 0 ); }); $(frm).append(tbl); showFrm = $($t).triggerHandler("jqGridAddEditBeforeInitData", [frm, frmoper]); if(showFrm === undefined) { showFrm = true; } if(showFrm && $.jgrid.isFunction(rp_ge[$t.p.id].beforeInitData)) { showFrm = rp_ge[$t.p.id].beforeInitData.call($t,frm, frmoper); } if(showFrm === false) {return;} restoreInline(); // set the id. // use carefull only to change here colproperties. // create data createData(rowid,$t,tbl,maxCols); // buttons at footer var rtlb = $t.p.direction === "rtl" ? true :false, bp = rtlb ? "nData" : "pData", bn = rtlb ? "pData" : "nData"; var bP = "<a id='"+bp+"' class='fm-button " + commonstyle.button + "'><span class='" + commonstyle.icon_base + " " + styles.icon_prev+ "'></span></a>", bN = "<a id='"+bn+"' class='fm-button " + commonstyle.button + "'><span class='" + commonstyle.icon_base + " " + styles.icon_next+ "'></span></a>", bS ="<a id='sData' class='fm-button " + commonstyle.button + "'>"+p.bSubmit+"</a>", bC ="<a id='cData' class='fm-button " + commonstyle.button + "'>"+p.bCancel+"</a>", user_buttons = ( Array.isArray( rp_ge[$t.p.id].buttons ) ? $.jgrid.buildButtons( rp_ge[$t.p.id].buttons, bS + bC, commonstyle ) : bS + bC ); var bt = "<table style='height:auto' class='EditTable ui-common-table' id='"+frmtborg+"_2'><tbody><tr><td colspan='2'><hr class='"+commonstyle.content+"' style='margin:1px'/></td></tr><tr id='Act_Buttons'><td class='navButton'>"+(rtlb ? bN+bP : bP+bN)+"</td><td class='EditButton'>"+ user_buttons +"</td></tr>"; //bt += "<tr style='display:none' class='binfo'><td class='bottominfo' colspan='2'>"+rp_ge[$t.p.id].bottominfo+"</td></tr>"; bt += "</tbody></table>"; if(maxRows > 0) { var sd=[]; $.each($(tbl)[0].rows,function(i,r){ sd[i] = r; }); sd.sort(function(a,b){ if(a.rp > b.rp) {return 1;} if(a.rp < b.rp) {return -1;} return 0; }); $.each(sd, function(index, row) { $('tbody',tbl).append(row); }); } p.gbox = "#gbox_"+$.jgrid.jqID(gID); var cle = false; if(p.closeOnEscape===true){ p.closeOnEscape = false; cle = true; } var tms; if(templ) { $(frm).find("#pData").replaceWith( bP ); $(frm).find("#nData").replaceWith( bN ); $(frm).find("#sData").replaceWith( bS ); $(frm).find("#cData").replaceWith( bC ); tms = $("<div id="+frmtborg+"></div>").append(frm); } else { tms = $("<div></div>").append(frm).append(bt); } $(frm).append("<div class='binfo topinfo bottominfo'>"+rp_ge[$t.p.id].bottominfo+"</div>"); var fs = $('.ui-jqgrid').css('font-size') || '11px'; $.jgrid.createModal(IDs, tms, rp_ge[$(this)[0].p.id], "#gview_"+$.jgrid.jqID($t.p.id), $("#gbox_"+$.jgrid.jqID($t.p.id))[0], null, {"font-size": fs}); if(rtlb) { $("#pData, #nData",frmtb+"_2").css("float","right"); $(".EditButton",frmtb+"_2").css("text-align","left"); } if(rp_ge[$t.p.id].topinfo) {$(".tinfo", frmgr).show();} if(rp_ge[$t.p.id].bottominfo) {$(".binfo",frmgr).show();} tms = null;bt=null; $("#"+$.jgrid.jqID(IDs.themodal)).keydown( function( e ) { var wkey = e.target; if ($(frmgr).data("disabled")===true ) {return false;}//?? if(rp_ge[$t.p.id].savekey[0] === true && e.which === rp_ge[$t.p.id].savekey[1]) { // save if(wkey.tagName !== "TEXTAREA") { $("#sData", frmtb+"_2").trigger("click"); return false; } } if(e.which === 27) { if(!checkUpdates()) {return false;} if(cle) {$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:p.gbox,jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});} return false; } if(rp_ge[$t.p.id].navkeys[0]===true) { if($("#id_g",frmtb).val() === "_empty") {return true;} if(e.which === rp_ge[$t.p.id].navkeys[1]){ //up $("#pData", frmtb2).trigger("click"); return false; } if(e.which === rp_ge[$t.p.id].navkeys[2]){ //down $("#nData", frmtb2).trigger("click"); return false; } } }); if(p.checkOnUpdate) { $("a.ui-jqdialog-titlebar-close span","#"+$.jgrid.jqID(IDs.themodal)).removeClass("jqmClose"); $("a.ui-jqdialog-titlebar-close","#"+$.jgrid.jqID(IDs.themodal)).off("click") .click(function(){ if(!checkUpdates()) {return false;} $.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form}); return false; }); } p.saveicon = $.extend([true,"left", styles.icon_save ],p.saveicon); p.closeicon = $.extend([true,"left", styles.icon_close ],p.closeicon); // beforeinitdata after creation of the form if(p.saveicon[0]===true) { $("#sData",frmtb2).addClass(p.saveicon[1] === "right" ? 'fm-button-icon-right' : 'fm-button-icon-left') .append("<span class='"+commonstyle.icon_base + " " +p.saveicon[2]+"'></span>"); } if(p.closeicon[0]===true) { $("#cData",frmtb2).addClass(p.closeicon[1] === "right" ? 'fm-button-icon-right' : 'fm-button-icon-left') .append("<span class='" + commonstyle.icon_base +" "+p.closeicon[2]+"'></span>"); } if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) { bS ="<a id='sNew' class='fm-button "+commonstyle.button + "' style='z-index:1002'>"+p.bYes+"</a>"; bN ="<a id='nNew' class='fm-button "+commonstyle.button + "' style='z-index:1002;margin-left:5px'>"+p.bNo+"</a>"; bC ="<a id='cNew' class='fm-button "+commonstyle.button + "' style='z-index:1002;margin-left:5px;'>"+p.bExit+"</a>"; var zI = p.zIndex || 999;zI ++; $("#"+IDs.themodal).append("<div class='"+ p.overlayClass+" jqgrid-overlay confirm' style='z-index:"+zI+";display:none;position:absolute;'>&#160;"+"</div><div class='confirm ui-jqconfirm "+commonstyle.content+"' style='z-index:"+(zI+1)+"'>"+p.saveData+"<br/><br/>"+bS+bN+bC+"</div>"); $("#sNew","#"+$.jgrid.jqID(IDs.themodal)).click(function(){ postIt(); $(frmgr).data("disabled",false); $(".confirm","#"+$.jgrid.jqID(IDs.themodal)).hide(); return false; }); $("#nNew","#"+$.jgrid.jqID(IDs.themodal)).click(function(){ $(".confirm","#"+$.jgrid.jqID(IDs.themodal)).hide(); $(frmgr).data("disabled",false); setTimeout(function(){$(":input:visible",frmgr)[0].focus();},0); return false; }); $("#cNew","#"+$.jgrid.jqID(IDs.themodal)).click(function(){ $(".confirm","#"+$.jgrid.jqID(IDs.themodal)).hide(); $(frmgr).data("disabled",false); $.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form}); return false; }); } // here initform $($t).triggerHandler("jqGridAddEditInitializeForm", [$(frmgr), frmoper]); if($.jgrid.isFunction(rp_ge[$t.p.id].onInitializeForm)) { rp_ge[$t.p.id].onInitializeForm.call($t,$(frmgr), frmoper);} if(rowid==="_empty" || !rp_ge[$t.p.id].viewPagerButtons) {$("#pData,#nData",frmtb2).hide();} else {$("#pData,#nData",frmtb2).show();} $($t).triggerHandler("jqGridAddEditBeforeShowForm", [$(frmgr), frmoper]); if($.jgrid.isFunction(rp_ge[$t.p.id].beforeShowForm)) { rp_ge[$t.p.id].beforeShowForm.call($t, $(frmgr), frmoper);} syncSavedData(); $("#"+$.jgrid.jqID(IDs.themodal)).data("onClose",rp_ge[$t.p.id].onClose); $.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{ gbox:"#gbox_"+$.jgrid.jqID(gID), jqm:p.jqModal, overlay: p.overlay, modal:p.modal, overlayClass: p.overlayClass, focusField : p.focusField, onHide : function(h) { var fh = $('#editmod'+gID)[0].style.height, fw = $('#editmod'+gID)[0].style.width, rtlsup = $("#gbox_"+$.jgrid.jqID(gID)).attr("dir") === "rtl" ? true : false; if(fh.indexOf("px") > -1 ) { fh = parseFloat(fh); } if(fw.indexOf("px") > -1 ) { fw = parseFloat(fw); } $($t).data("formProp", { top:parseFloat($(h.w).css("top")), left : rtlsup ? ( $("#gbox_"+$.jgrid.jqID(gID)).outerWidth() - fw - parseFloat($(h.w).css("left")) + 12 ) : parseFloat($(h.w).css("left")), width : fw, height : fh, dataheight : $(frmgr).height(), datawidth: $(frmgr).width() }); h.w.remove(); if(h.o) {h.o.remove();} } }); if(!closeovrl) { $("." + $.jgrid.jqID(p.overlayClass)).click(function(){ if(!checkUpdates()) {return false;} $.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form}); return false; }); } $(".fm-button","#"+$.jgrid.jqID(IDs.themodal)).hover( function(){$(this).addClass( commonstyle.hover );}, function(){$(this).removeClass( commonstyle.hover );} ); $("#sData", frmtb2).click(function(){ postdata = {}; $(".FormError",frmgr).hide(); // all depend on ret array //ret[0] - succes //ret[1] - msg if not succes //ret[2] - the id that will be set if reload after submit false getFormData(); if(postdata[$t.p.id+"_id"] === "_empty") { postIt(); } else if(p.checkOnSubmit===true ) { diff = compareData(postdata, $t.p.savedData); if(diff) { $(frmgr).data("disabled",true); $(".confirm","#"+$.jgrid.jqID(IDs.themodal)).show(); } else { postIt(); } } else { postIt(); } return false; }); $("#cData", frmtb2).click(function(){ if(!checkUpdates()) {return false;} $.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form}); return false; }); // user buttons bind $(frmtb2).find("[data-index]").each(function(){ var index = parseInt($(this).attr('data-index'),10); if(index >=0 ) { if( p.buttons[index].hasOwnProperty('click')) { $(this).on('click', function(e) { p.buttons[index].click.call($t, $(frmgr)[0], rp_ge[$t.p.id], e); }); } } }); $("#nData", frmtb2).click(function(){ if(!checkUpdates()) {return false;} $(".FormError",frmgr).hide(); var npos = getCurrPos(); npos[0] = parseInt(npos[0],10); if(npos[0] !== -1 && npos[1][npos[0]+1]) { $($t).triggerHandler("jqGridAddEditClickPgButtons", ['next',$(frmgr),npos[1][npos[0]]]); var nposret; if($.jgrid.isFunction(p.onclickPgButtons)) { nposret = p.onclickPgButtons.call($t, 'next',$(frmgr),npos[1][npos[0]]); if( nposret !== undefined && nposret === false ) {return false;} } if( $("#"+$.jgrid.jqID(npos[1][npos[0]+1])).hasClass( commonstyle.disabled )) {return false;} fillData(npos[1][npos[0]+1],$t,frmgr); if(!($t.p.multiselect && rp_ge[$t.p.id].editselected)) { $($t).jqGrid("setSelection",npos[1][npos[0]+1]); } $($t).triggerHandler("jqGridAddEditAfterClickPgButtons", ['next',$(frmgr),npos[1][npos[0]]]); if($.jgrid.isFunction(p.afterclickPgButtons)) { p.afterclickPgButtons.call($t, 'next',$(frmgr),npos[1][npos[0]+1]); } syncSavedData(); updateNav(npos[0]+1,npos); } return false; }); $("#pData", frmtb2).click(function(){ if(!checkUpdates()) {return false;} $(".FormError",frmgr).hide(); var ppos = getCurrPos(); if(ppos[0] !== -1 && ppos[1][ppos[0]-1]) { $($t).triggerHandler("jqGridAddEditClickPgButtons", ['prev',$(frmgr),ppos[1][ppos[0]]]); var pposret; if($.jgrid.isFunction(p.onclickPgButtons)) { pposret = p.onclickPgButtons.call($t, 'prev',$(frmgr),ppos[1][ppos[0]]); if( pposret !== undefined && pposret === false ) {return false;} } if( $("#"+$.jgrid.jqID(ppos[1][ppos[0]-1])).hasClass( commonstyle.disabled )) {return false;} fillData(ppos[1][ppos[0]-1],$t,frmgr); if(!($t.p.multiselect && rp_ge[$t.p.id].editselected)) { $($t).jqGrid("setSelection",ppos[1][ppos[0]-1]); } $($t).triggerHandler("jqGridAddEditAfterClickPgButtons", ['prev',$(frmgr),ppos[1][ppos[0]]]); if($.jgrid.isFunction(p.afterclickPgButtons)) { p.afterclickPgButtons.call($t, 'prev',$(frmgr),ppos[1][ppos[0]-1]); } syncSavedData(); updateNav(ppos[0]-1,ppos); } return false; }); $($t).triggerHandler("jqGridAddEditAfterShowForm", [$(frmgr), frmoper]); if($.jgrid.isFunction(rp_ge[$t.p.id].afterShowForm)) { rp_ge[$t.p.id].afterShowForm.call($t, $(frmgr), frmoper); } var posInit =getCurrPos(); updateNav(posInit[0],posInit); }); }, viewGridRow : function(rowid, p){ var regional = $.jgrid.getRegional(this[0], 'view'), currstyle = this[0].p.styleUI, styles = $.jgrid.styleUI[currstyle].formedit, commonstyle = $.jgrid.styleUI[currstyle].common; p = $.extend(true, { top : 0, left: 0, width: 500, datawidth: 'auto', height: 'auto', dataheight: 'auto', modal: false, overlay: 30, drag: true, resize: true, jqModal: true, closeOnEscape : false, labelswidth: 'auto', closeicon: [], navkeys: [false,38,40], onClose: null, beforeShowForm : null, beforeInitData : null, viewPagerButtons : true, recreateForm : false, removemodal: true, form: 'view', buttons : [] }, regional, p || {}); rp_ge[$(this)[0].p.id] = p; return this.each(function(){ var $t = this; if (!$t.grid || !rowid) {return;} var gID = $t.p.id, frmgr = "ViewGrid_"+$.jgrid.jqID( gID ), frmtb = "ViewTbl_" + $.jgrid.jqID( gID ), frmgr_id = "ViewGrid_"+gID, frmtb_id = "ViewTbl_"+gID, IDs = {themodal:'viewmod'+gID,modalhead:'viewhd'+gID,modalcontent:'viewcnt'+gID, scrollelm : frmgr}, showFrm = true, maxCols = 1, maxRows=0; rp_ge[$t.p.id].styleUI = $t.p.styleUI || 'jQueryUI'; if(!p.recreateForm) { if( $($t).data("viewProp") ) { $.extend(rp_ge[$(this)[0].p.id], $($t).data("viewProp")); } } function focusaref(){ //Sfari 3 issues if(rp_ge[$t.p.id].closeOnEscape===true || rp_ge[$t.p.id].navkeys[0]===true) { setTimeout(function(){$(".ui-jqdialog-titlebar-close","#"+$.jgrid.jqID(IDs.modalhead)).attr("tabindex", "-1").focus();},0); } } function createData(rowid,obj,tb,maxcols){ var nm, hc,trdata, cnt=0,tmp, dc, retpos=[], ind=false, i, tdtmpl = "<td class='CaptionTD form-view-label " + commonstyle.content + "' width='"+p.labelswidth+"'></td><td class='DataTD form-view-data ui-helper-reset " + commonstyle.content +"'></td>", tmpl="", tdtmpl2 = "<td class='CaptionTD form-view-label " + commonstyle.content +"'></td><td class='DataTD form-view-data " + commonstyle.content +"'></td>", fmtnum = ['integer','number','currency'],max1 =0, max2=0 ,maxw,setme, viewfld; for (i=1;i<=maxcols;i++) { tmpl += i === 1 ? tdtmpl : tdtmpl2; } // find max number align rigth with property formatter $(obj.p.colModel).each( function() { if(this.editrules && this.editrules.edithidden === true) { hc = false; } else { hc = this.hidden === true ? true : false; } if(!hc && this.align==='right') { if(this.formatter && $.inArray(this.formatter,fmtnum) !== -1 ) { max1 = Math.max(max1,parseInt(this.width,10)); } else { max2 = Math.max(max2,parseInt(this.width,10)); } } }); maxw = max1 !==0 ? max1 : max2 !==0 ? max2 : 0; ind = $(obj).jqGrid("getInd",rowid); $(obj.p.colModel).each( function(i) { nm = this.name; setme = false; // hidden fields are included in the form if(this.editrules && this.editrules.edithidden === true) { hc = false; } else { hc = this.hidden === true ? true : false; } dc = hc ? "style='display:none'" : ""; viewfld = (typeof this.viewable !== 'boolean') ? true : this.viewable; if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn' && viewfld) { if(ind === false) { tmp = ""; } else { if(nm === obj.p.ExpandColumn && obj.p.treeGrid === true) { tmp = $("td",obj.rows[ind]).eq( i ).text(); } else { tmp = $("td",obj.rows[ind]).eq( i ).html(); } } setme = this.align === 'right' && maxw !==0 ? true : false; var frmopt = $.extend({},{rowabove:false,rowcontent:''}, this.formoptions || {}), rp = parseInt(frmopt.rowpos,10) || cnt+1, cp = parseInt((parseInt(frmopt.colpos,10) || 1)*2,10); if(frmopt.rowabove) { var newdata = $("<tr><td class='contentinfo' colspan='"+(maxcols*2)+"'>"+frmopt.rowcontent+"</td></tr>"); $(tb).append(newdata); newdata[0].rp = rp; } trdata = $(tb).find("tr[rowpos="+rp+"]"); if ( trdata.length===0 ) { trdata = $("<tr "+dc+" rowpos='"+rp+"'></tr>").addClass("FormData").attr("id","trv_"+nm); $(trdata).append(tmpl); $(tb).append(trdata); trdata[0].rp = rp; } $("td",trdata[0]).eq( cp-2 ).html('<b>'+ (frmopt.label === undefined ? obj.p.colNames[i]: frmopt.label)+'</b>'); $("td",trdata[0]).eq( cp-1 ).append("<span>"+tmp+"</span>").attr("id","v_"+nm); if(setme){ $("td",trdata[0]).eq( cp-1 ).find('span').css({ 'text-align':'right',width:maxw+"px" }); } retpos[cnt] = i; cnt++; } }); if( cnt > 0) { var idrow = $("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+ (maxcols*2-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='"+rowid+"'/></td></tr>"); idrow[0].rp = cnt+99; $(tb).append(idrow); } return retpos; } function fillData(rowid,obj){ var nm, hc,cnt=0,tmp,trv; trv = $(obj).jqGrid("getInd",rowid,true); if(!trv) {return;} $('td',trv).each( function(i) { nm = obj.p.colModel[i].name; // hidden fields are included in the form if(obj.p.colModel[i].editrules && obj.p.colModel[i].editrules.edithidden === true) { hc = false; } else { hc = obj.p.colModel[i].hidden === true ? true : false; } if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn') { if(nm === obj.p.ExpandColumn && obj.p.treeGrid === true) { tmp = $(this).text(); } else { tmp = $(this).html(); } nm = $.jgrid.jqID("v_"+nm); $("#"+nm+" span","#"+frmtb).html(tmp); if (hc) {$("#"+nm,"#"+frmtb).parents("tr").first().hide();} cnt++; } }); if(cnt>0) {$("#id_g","#"+frmtb).val(rowid);} } function updateNav(cr,posarr){ var totr = posarr[1].length-1; if (cr===0) { $("#pData","#"+frmtb+"_2").addClass( commonstyle.disabled ); } else if( posarr[1][cr-1] !== undefined && $("#"+$.jgrid.jqID(posarr[1][cr-1])).hasClass(commonstyle.disabled)) { $("#pData",frmtb+"_2").addClass( commonstyle.disabled ); } else { $("#pData","#"+frmtb+"_2").removeClass( commonstyle.disabled ); } if (cr===totr) { $("#nData","#"+frmtb+"_2").addClass( commonstyle.disabled ); } else if( posarr[1][cr+1] !== undefined && $("#"+$.jgrid.jqID(posarr[1][cr+1])).hasClass( commonstyle.disabled )) { $("#nData",frmtb+"_2").addClass( commonstyle.disabled ); } else { $("#nData","#"+frmtb+"_2").removeClass( commonstyle.disabled ); } } function getCurrPos() { var rowsInGrid = $($t).jqGrid("getDataIDs"), selrow = $("#id_g","#"+frmtb).val(), pos; if($t.p.multiselect && rp_ge[$t.p.id].viewselected) { var arr = []; for(var i=0, len = rowsInGrid.length;i<len;i++) { if($.inArray(rowsInGrid[i],$t.p.selarrrow) !== -1) { arr.push(rowsInGrid[i]); } } pos = $.inArray(selrow,arr); return [pos, arr]; } else { pos = $.inArray(selrow,rowsInGrid); } return [pos,rowsInGrid]; } var dh = isNaN(rp_ge[$(this)[0].p.id].dataheight) ? rp_ge[$(this)[0].p.id].dataheight : rp_ge[$(this)[0].p.id].dataheight+"px", dw = isNaN(rp_ge[$(this)[0].p.id].datawidth) ? rp_ge[$(this)[0].p.id].datawidth : rp_ge[$(this)[0].p.id].datawidth+"px", frm = $("<form name='FormPost' id='"+frmgr_id+"' class='FormGrid' style='width:"+dw+";height:"+dh+";'></form>"), tbl =$("<table id='"+frmtb_id+"' class='EditTable ViewTable'><tbody></tbody></table>"); $($t.p.colModel).each( function() { var fmto = this.formoptions; maxCols = Math.max(maxCols, fmto ? fmto.colpos || 0 : 0 ); maxRows = Math.max(maxRows, fmto ? fmto.rowpos || 0 : 0 ); }); // set the id. $(frm).append(tbl); showFrm = $($t).triggerHandler("jqGridViewRowBeforeInitData", [frm]); if(showFrm === undefined) { showFrm = true; } if(showFrm && $.jgrid.isFunction(rp_ge[$t.p.id].beforeInitData)) { showFrm = rp_ge[$t.p.id].beforeInitData.call($t, frm); } if(showFrm === false) {return;} createData(rowid, $t, tbl, maxCols); var rtlb = $t.p.direction === "rtl" ? true :false, bp = rtlb ? "nData" : "pData", bn = rtlb ? "pData" : "nData", // buttons at footer bP = "<a id='"+bp+"' class='fm-button " + commonstyle.button + "'><span class='" + commonstyle.icon_base + " " + styles.icon_prev+ "'></span></a>", bN = "<a id='"+bn+"' class='fm-button " + commonstyle.button + "'><span class='" + commonstyle.icon_base + " " + styles.icon_next+ "'></span></a>", bC ="<a id='cData' class='fm-button " + commonstyle.button + "'>"+p.bClose+"</a>", user_buttons = ( Array.isArray( rp_ge[$t.p.id].buttons ) ? $.jgrid.buildButtons( rp_ge[$t.p.id].buttons, bC, commonstyle ) : bC ); if(maxRows > 0) { var sd=[]; $.each($(tbl)[0].rows,function(i,r){ sd[i] = r; }); sd.sort(function(a,b){ if(a.rp > b.rp) {return 1;} if(a.rp < b.rp) {return -1;} return 0; }); $.each(sd, function(index, row) { $('tbody',tbl).append(row); }); } p.gbox = "#gbox_"+$.jgrid.jqID(gID); var bt = $("<div></div>").append(frm).append("<table border='0' class='EditTable' id='"+frmtb+"_2'><tbody><tr id='Act_Buttons'><td class='navButton' width='"+p.labelswidth+"'>"+(rtlb ? bN+bP : bP+bN)+"</td><td class='EditButton'>"+ user_buttons+"</td></tr></tbody></table>"), fs = $('.ui-jqgrid').css('font-size') || '11px'; $.jgrid.createModal(IDs,bt, rp_ge[$(this)[0].p.id],"#gview_"+$.jgrid.jqID($t.p.id),$("#gview_"+$.jgrid.jqID($t.p.id))[0], null, {"font-size":fs}); if(rtlb) { $("#pData, #nData","#"+frmtb+"_2").css("float","right"); $(".EditButton","#"+frmtb+"_2").css("text-align","left"); } if(!p.viewPagerButtons) {$("#pData, #nData","#"+frmtb+"_2").hide();} bt = null; $("#"+IDs.themodal).keydown( function( e ) { if(e.which === 27) { if(rp_ge[$t.p.id].closeOnEscape) {$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:p.gbox,jqm:p.jqModal, onClose: p.onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});} return false; } if(p.navkeys[0]===true) { if(e.which === p.navkeys[1]){ //up $("#pData", "#"+frmtb+"_2").trigger("click"); return false; } if(e.which === p.navkeys[2]){ //down $("#nData", "#"+frmtb+"_2").trigger("click"); return false; } } }); p.closeicon = $.extend([true,"left", styles.icon_close ],p.closeicon); if(p.closeicon[0]===true) { $("#cData","#"+frmtb+"_2").addClass(p.closeicon[1] === "right" ? 'fm-button-icon-right' : 'fm-button-icon-left') .append("<span class='" + commonstyle.icon_base+ " " +p.closeicon[2]+"'></span>"); } $($t).triggerHandler("jqGridViewRowBeforeShowForm", [$("#"+frmgr)]); if($.jgrid.isFunction(p.beforeShowForm)) {p.beforeShowForm.call($t,$("#"+frmgr));} $.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{ gbox:"#gbox_"+$.jgrid.jqID(gID), jqm:p.jqModal, overlay: p.overlay, modal:p.modal, onHide : function(h) { var rtlsup = $("#gbox_"+$.jgrid.jqID(gID)).attr("dir") === "rtl" ? true : false, fw = parseFloat($('#viewmod'+gID)[0].style.width); $($t).data("viewProp", { top:parseFloat($(h.w).css("top")), left : rtlsup ? ( $("#gbox_"+$.jgrid.jqID(gID)).outerWidth() - fw - parseFloat($(h.w).css("left")) + 12 ) : parseFloat($(h.w).css("left")), width : $(h.w).width(), height : $(h.w).height(), dataheight : $("#"+frmgr).height(), datawidth: $("#"+frmgr).width() }); h.w.remove(); if(h.o) {h.o.remove();} } }); $(".fm-button:not(." + commonstyle.disabled + ")","#"+frmtb+"_2").hover( function(){$(this).addClass( commonstyle.hover );}, function(){$(this).removeClass( commonstyle.hover );} ); focusaref(); $("#cData", "#"+frmtb+"_2").click(function(){ $.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: p.onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form}); return false; }); $("#"+frmtb+"_2").find("[data-index]").each(function(){ var index = parseInt($(this).attr('data-index'),10); if(index >=0 ) { if( p.buttons[index].hasOwnProperty('click')) { $(this).on('click', function(e) { p.buttons[index].click.call($t, $("#"+frmgr_id)[0], rp_ge[$t.p.id], e); }); } } }); $("#nData", "#"+frmtb+"_2").click(function(){ $("#FormError","#"+frmtb).hide(); var npos = getCurrPos(); npos[0] = parseInt(npos[0],10); if(npos[0] !== -1 && npos[1][npos[0]+1]) { $($t).triggerHandler("jqGridViewRowClickPgButtons", ['next',$("#"+frmgr),npos[1][npos[0]]]); if($.jgrid.isFunction(p.onclickPgButtons)) { p.onclickPgButtons.call($t,'next',$("#"+frmgr),npos[1][npos[0]]); } fillData(npos[1][npos[0]+1],$t); if(!($t.p.multiselect && rp_ge[$t.p.id].viewselected)) { $($t).jqGrid("setSelection",npos[1][npos[0]+1]); } $($t).triggerHandler("jqGridViewRowAfterClickPgButtons", ['next',$("#"+frmgr),npos[1][npos[0]+1]]); if($.jgrid.isFunction(p.afterclickPgButtons)) { p.afterclickPgButtons.call($t,'next',$("#"+frmgr),npos[1][npos[0]+1]); } updateNav(npos[0]+1,npos); } focusaref(); return false; }); $("#pData", "#"+frmtb+"_2").click(function(){ $("#FormError","#"+frmtb).hide(); var ppos = getCurrPos(); if(ppos[0] !== -1 && ppos[1][ppos[0]-1]) { $($t).triggerHandler("jqGridViewRowClickPgButtons", ['prev',$("#"+frmgr),ppos[1][ppos[0]]]); if($.jgrid.isFunction(p.onclickPgButtons)) { p.onclickPgButtons.call($t,'prev',$("#"+frmgr),ppos[1][ppos[0]]); } fillData(ppos[1][ppos[0]-1],$t); if(!($t.p.multiselect && rp_ge[$t.p.id].viewselected)) { $($t).jqGrid("setSelection",ppos[1][ppos[0]-1]); } $($t).triggerHandler("jqGridViewRowAfterClickPgButtons", ['prev',$("#"+frmgr),ppos[1][ppos[0]-1]]); if($.jgrid.isFunction(p.afterclickPgButtons)) { p.afterclickPgButtons.call($t,'prev',$("#"+frmgr),ppos[1][ppos[0]-1]); } updateNav(ppos[0]-1,ppos); } focusaref(); return false; }); var posInit =getCurrPos(); updateNav(posInit[0],posInit); }); }, delGridRow : function(rowids,p) { var regional = $.jgrid.getRegional(this[0], 'del'), currstyle = this[0].p.styleUI, styles = $.jgrid.styleUI[currstyle].formedit, commonstyle = $.jgrid.styleUI[currstyle].common; p = $.extend(true, { top : 0, left: 0, width: 240, height: 'auto', dataheight : 'auto', modal: false, overlay: 30, drag: true, resize: true, url : '', mtype : "POST", reloadAfterSubmit: true, beforeShowForm: null, beforeInitData : null, afterShowForm: null, beforeSubmit: null, onclickSubmit: null, afterSubmit: null, jqModal : true, closeOnEscape : false, delData: {}, delicon : [], cancelicon : [], onClose : null, ajaxDelOptions : {}, processing : false, serializeDelData : null, useDataProxy : false }, regional, p ||{}); rp_ge[$(this)[0].p.id] = p; return this.each(function(){ var $t = this; if (!$t.grid ) {return;} if(!rowids) {return;} var gID = $t.p.id, onCS = {}, showFrm = true, dtbl = "DelTbl_"+$.jgrid.jqID(gID),postd, idname, opers, oper, dtbl_id = "DelTbl_" + gID, IDs = {themodal:'delmod'+gID,modalhead:'delhd'+gID,modalcontent:'delcnt'+gID, scrollelm: dtbl}; rp_ge[$t.p.id].styleUI = $t.p.styleUI || 'jQueryUI'; if (Array.isArray(rowids)) {rowids = rowids.join();} if ( $("#"+$.jgrid.jqID(IDs.themodal))[0] !== undefined ) { showFrm = $($t).triggerHandler("jqGridDelRowBeforeInitData", [$("#"+dtbl)]); if(showFrm === undefined) { showFrm = true; } if(showFrm && $.jgrid.isFunction(rp_ge[$t.p.id].beforeInitData)) { showFrm = rp_ge[$t.p.id].beforeInitData.call($t, $("#"+dtbl)); } if(showFrm === false) {return;} $("#DelData>td","#"+dtbl).text(rowids); $("#DelError","#"+dtbl).hide(); if( rp_ge[$t.p.id].processing === true) { rp_ge[$t.p.id].processing=false; $("#dData", "#"+dtbl).removeClass( commonstyle.active ); } $($t).triggerHandler("jqGridDelRowBeforeShowForm", [$("#"+dtbl)]); if($.jgrid.isFunction( rp_ge[$t.p.id].beforeShowForm )) { rp_ge[$t.p.id].beforeShowForm.call($t,$("#"+dtbl)); } $.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{gbox:"#gbox_"+$.jgrid.jqID(gID),jqm:rp_ge[$t.p.id].jqModal, overlay: rp_ge[$t.p.id].overlay, modal:rp_ge[$t.p.id].modal}); $($t).triggerHandler("jqGridDelRowAfterShowForm", [$("#"+dtbl)]); if($.jgrid.isFunction( rp_ge[$t.p.id].afterShowForm )) { rp_ge[$t.p.id].afterShowForm.call($t, $("#"+dtbl)); } } else { var dh = isNaN(rp_ge[$t.p.id].dataheight) ? rp_ge[$t.p.id].dataheight : rp_ge[$t.p.id].dataheight+"px", dw = isNaN(p.datawidth) ? p.datawidth : p.datawidth+"px", tbl = "<div id='"+dtbl_id+"' class='formdata' style='width:"+dw+";overflow:auto;position:relative;height:"+dh+";'>"; tbl += "<table class='DelTable'><tbody>"; // error data tbl += "<tr id='DelError' style='display:none'><td class='" + commonstyle.error +"'></td></tr>"; tbl += "<tr id='DelData' style='display:none'><td >"+rowids+"</td></tr>"; tbl += "<tr><td class=\"delmsg\" style=\"white-space:pre;\">"+rp_ge[$t.p.id].msg+"</td></tr><tr><td >&#160;</td></tr>"; // buttons at footer tbl += "</tbody></table></div>"; var bS = "<a id='dData' class='fm-button " + commonstyle.button + "'>"+p.bSubmit+"</a>", bC = "<a id='eData' class='fm-button " + commonstyle.button + "'>"+p.bCancel+"</a>", user_buttons = ( Array.isArray( rp_ge[$t.p.id].buttons ) ? $.jgrid.buildButtons( rp_ge[$t.p.id].buttons, bS + bC, commonstyle ) : bS + bC ), fs = $('.ui-jqgrid').css('font-size') || '11px'; tbl += "<table class='EditTable ui-common-table' id='"+dtbl+"_2'><tbody><tr><td><hr class='" + commonstyle.content + "' style='margin:1px'/></td></tr><tr><td class='DelButton EditButton'>"+ user_buttons +"</td></tr></tbody></table>"; p.gbox = "#gbox_"+$.jgrid.jqID(gID); $.jgrid.createModal(IDs,tbl, rp_ge[$t.p.id] ,"#gview_"+$.jgrid.jqID($t.p.id),$("#gview_"+$.jgrid.jqID($t.p.id))[0], null, {"font-size": fs}); $(".fm-button","#"+dtbl+"_2").hover( function(){$(this).addClass( commonstyle.hover );}, function(){$(this).removeClass( commonstyle.hover );} ); p.delicon = $.extend([true,"left", styles.icon_del ],rp_ge[$t.p.id].delicon); p.cancelicon = $.extend([true,"left", styles.icon_cancel ],rp_ge[$t.p.id].cancelicon); if(p.delicon[0]===true) { $("#dData","#"+dtbl+"_2").addClass(p.delicon[1] === "right" ? 'fm-button-icon-right' : 'fm-button-icon-left') .append("<span class='" + commonstyle.icon_base + " " + p.delicon[2]+"'></span>"); } if(p.cancelicon[0]===true) { $("#eData","#"+dtbl+"_2").addClass(p.cancelicon[1] === "right" ? 'fm-button-icon-right' : 'fm-button-icon-left') .append("<span class='" + commonstyle.icon_base + " " + p.cancelicon[2]+"'></span>"); } $("#dData","#"+dtbl+"_2").click(function(){ var ret=[true,""], pk, postdata = $("#DelData>td","#"+dtbl).text(); //the pair is name=val1,val2,... onCS = {}; onCS = $($t).triggerHandler("jqGridDelRowClickSubmit", [rp_ge[$t.p.id], postdata]); if(onCS === undefined && $.jgrid.isFunction( rp_ge[$t.p.id].onclickSubmit ) ) { onCS = rp_ge[$t.p.id].onclickSubmit.call($t, rp_ge[$t.p.id], postdata) || {}; } ret = $($t).triggerHandler("jqGridDelRowBeforeSubmit", [postdata]); if(ret === undefined) { ret = [true,"",""]; } if( ret[0] && $.jgrid.isFunction(rp_ge[$t.p.id].beforeSubmit)) { ret = rp_ge[$t.p.id].beforeSubmit.call($t, postdata); } if(ret[0] && !rp_ge[$t.p.id].processing) { rp_ge[$t.p.id].processing = true; opers = $t.p.prmNames; postd = $.extend({},rp_ge[$t.p.id].delData, onCS); oper = opers.oper; postd[oper] = opers.deloper; idname = opers.id; postdata = String(postdata).split(","); if(!postdata.length) { return false; } for(pk in postdata) { if(postdata.hasOwnProperty(pk)) { postdata[pk] = $.jgrid.stripPref($t.p.idPrefix, postdata[pk]); } } postd[idname] = postdata.join(); $(this).addClass( commonstyle.active ); var ajaxOptions = $.extend({ url: rp_ge[$t.p.id].url || $($t).jqGrid('getGridParam','editurl'), type: rp_ge[$t.p.id].mtype, data: $.jgrid.isFunction(rp_ge[$t.p.id].serializeDelData) ? rp_ge[$t.p.id].serializeDelData.call($t,postd) : postd, complete:function(data,status){ var i; $("#dData", "#"+dtbl+"_2").removeClass( commonstyle.active ); if(data.status >= 300 && data.status !== 304) { ret[0] = false; ret[1] = $($t).triggerHandler("jqGridDelRowErrorTextFormat", [data]); if ($.jgrid.isFunction(rp_ge[$t.p.id].errorTextFormat)) { ret[1] = rp_ge[$t.p.id].errorTextFormat.call($t, data); } if(ret[1] === undefined) { ret[1] = status + " Status: '" + data.statusText + "'. Error code: " + data.status; } } else { // data is posted successful // execute aftersubmit with the returned data from server ret = $($t).triggerHandler("jqGridDelRowAfterSubmit", [data, postd]); if(ret === undefined) { ret = [true,"",""]; } if( ret[0] && $.jgrid.isFunction(rp_ge[$t.p.id].afterSubmit) ) { ret = rp_ge[$t.p.id].afterSubmit.call($t, data, postd); } } if(ret[0] === false) { $("#DelError>td","#"+dtbl).html(ret[1]); $("#DelError","#"+dtbl).show(); } else { if(rp_ge[$t.p.id].reloadAfterSubmit && $t.p.datatype !== "local") { $($t).trigger("reloadGrid"); } else { if($t.p.treeGrid===true){ try {$($t).jqGrid("delTreeNode",$t.p.idPrefix+postdata[0]);} catch(e){} } else { for(i=0;i<postdata.length;i++) { $($t).jqGrid("delRowData",$t.p.idPrefix+ postdata[i]); } } $t.p.selrow = null; $t.p.selarrrow = []; } if($.jgrid.isFunction(rp_ge[$t.p.id].afterComplete) || Object.prototype.hasOwnProperty.call($._data( $($t)[0], 'events' ), 'jqGridDelRowAfterComplete')) { var copydata = data; setTimeout(function(){ $($t).triggerHandler("jqGridDelRowAfterComplete", [copydata, postd]); try { rp_ge[$t.p.id].afterComplete.call($t, copydata, postd); } catch(eacg) { // do nothing } },500); } } rp_ge[$t.p.id].processing=false; if(ret[0]) {$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose});} } }, $.jgrid.ajaxOptions, rp_ge[$t.p.id].ajaxDelOptions); if (!ajaxOptions.url && !rp_ge[$t.p.id].useDataProxy) { if ($.jgrid.isFunction($t.p.dataProxy)) { rp_ge[$t.p.id].useDataProxy = true; } else { ret[0]=false;ret[1] += " "+$.jgrid.getRegional($t, 'errors.nourl'); } } if (ret[0]) { if (rp_ge[$t.p.id].useDataProxy) { var dpret = $t.p.dataProxy.call($t, ajaxOptions, "del_"+$t.p.id); if(dpret === undefined) { dpret = [true, ""]; } if(dpret[0] === false ) { ret[0] = false; ret[1] = dpret[1] || "Error deleting the selected row!" ; } else { $.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose}); } } else { if(ajaxOptions.url === "clientArray") { postd = ajaxOptions.data; ajaxOptions.complete({status:200, statusText:''},''); } else { $.ajax(ajaxOptions); } } } } if(ret[0] === false) { $("#DelError>td","#"+dtbl).html(ret[1]); $("#DelError","#"+dtbl).show(); } return false; }); $("#eData", "#"+dtbl+"_2").click(function(){ $.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:rp_ge[$t.p.id].jqModal, onClose: rp_ge[$t.p.id].onClose}); return false; }); $("#"+dtbl+"_2").find("[data-index]").each(function(){ var index = parseInt($(this).attr('data-index'),10); if(index >=0 ) { if( p.buttons[index].hasOwnProperty('click')) { $(this).on('click', function(e) { p.buttons[index].click.call($t, $("#"+dtbl_id)[0], rp_ge[$t.p.id], e); }); } } }); showFrm = $($t).triggerHandler("jqGridDelRowBeforeInitData", [$("#"+dtbl)]); if(showFrm === undefined) { showFrm = true; } if(showFrm && $.jgrid.isFunction(rp_ge[$t.p.id].beforeInitData)) { showFrm = rp_ge[$t.p.id].beforeInitData.call($t, $("#"+dtbl)); } if(showFrm === false) {return;} $($t).triggerHandler("jqGridDelRowBeforeShowForm", [$("#"+dtbl)]); if($.jgrid.isFunction( rp_ge[$t.p.id].beforeShowForm )) { rp_ge[$t.p.id].beforeShowForm.call($t,$("#"+dtbl)); } $.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{gbox:"#gbox_"+$.jgrid.jqID(gID),jqm:rp_ge[$t.p.id].jqModal, overlay: rp_ge[$t.p.id].overlay, modal:rp_ge[$t.p.id].modal}); $($t).triggerHandler("jqGridDelRowAfterShowForm", [$("#"+dtbl)]); if($.jgrid.isFunction( rp_ge[$t.p.id].afterShowForm )) { rp_ge[$t.p.id].afterShowForm.call($t,$("#"+dtbl)); } } if(rp_ge[$t.p.id].closeOnEscape===true) { setTimeout(function(){$(".ui-jqdialog-titlebar-close","#"+$.jgrid.jqID(IDs.modalhead)).attr("tabindex","-1").focus();},0); } }); }, navGrid : function (elem, p, pEdit, pAdd, pDel, pSearch, pView) { var regional = $.jgrid.getRegional(this[0], 'nav'), currstyle = this[0].p.styleUI, styles = $.jgrid.styleUI[currstyle].navigator, commonstyle = $.jgrid.styleUI[currstyle].common; p = $.extend({ edit: true, editicon: styles.icon_edit_nav, add: true, addicon: styles.icon_add_nav, del: true, delicon: styles.icon_del_nav, search: true, searchicon: styles.icon_search_nav, refresh: true, refreshicon: styles.icon_refresh_nav, refreshstate: 'firstpage', view: false, viewicon : styles.icon_view_nav, position : "left", closeOnEscape : true, beforeRefresh : null, afterRefresh : null, cloneToTop : false, alertwidth : 200, alertheight : 'auto', alerttop: null, alertleft: null, alertzIndex : null, dropmenu : false, navButtonText : '' }, regional, p ||{}); return this.each(function() { if(this.p.navGrid) {return;} var alertIDs = {themodal: 'alertmod_' + this.p.id, modalhead: 'alerthd_' + this.p.id,modalcontent: 'alertcnt_' + this.p.id}, $t = this, twd, tdw, o; if(!$t.grid || typeof elem !== 'string') {return;} if(!$($t).data('navGrid')) { $($t).data('navGrid',p); } // speedoverhead, but usefull for future o = $($t).data('navGrid'); if($t.p.force_regional) { o = $.extend(o, regional); } if ($("#"+alertIDs.themodal)[0] === undefined) { if(!o.alerttop && !o.alertleft) { var pos=$.jgrid.findPos(this); pos[0]=Math.round(pos[0]); pos[1]=Math.round(pos[1]); o.alertleft = pos[0] + (this.p.width/2)-parseInt(o.alertwidth,10)/2; o.alerttop = pos[1] + (this.p.height/2)-25; } var fs = $('.ui-jqgrid').css('font-size') || '11px'; $.jgrid.createModal(alertIDs, "<div>"+o.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>", { gbox:"#gbox_"+$.jgrid.jqID($t.p.id), jqModal:true, drag:true, resize:true, caption:o.alertcap, top:o.alerttop, left:o.alertleft, width:o.alertwidth, height: o.alertheight, closeOnEscape:o.closeOnEscape, zIndex: o.alertzIndex, styleUI: $t.p.styleUI }, "#gview_"+$.jgrid.jqID($t.p.id), $("#gbox_"+$.jgrid.jqID($t.p.id))[0], true, {"font-size": fs} ); } var clone = 1, i, onHoverIn = function () { if (!$(this).hasClass(commonstyle.disabled)) { $(this).addClass(commonstyle.hover); } }, onHoverOut = function () { $(this).removeClass(commonstyle.hover); }; if(o.cloneToTop && $t.p.toppager) {clone = 2;} for(i = 0; i<clone; i++) { var tbd, navtbl = $("<table class='ui-pg-table navtable ui-common-table'><tbody><tr></tr></tbody></table>"), sep = "<td class='ui-pg-button " +commonstyle.disabled + "' style='width:4px;'><span class='ui-separator'></span></td>", pgid, elemids; if(i===0) { pgid = elem; if(pgid.indexOf("#") === 0 ) { pgid = pgid.substring(1); pgid = "#"+ $.jgrid.jqID( pgid ); } elemids = $t.p.id; if(pgid === $t.p.toppager) { elemids += "_top"; clone = 1; } } else { pgid = $t.p.toppager; elemids = $t.p.id+"_top"; } if($t.p.direction === "rtl") { $(navtbl).attr("dir","rtl").css("float","right"); } pAdd = pAdd || {}; if (o.add) { tbd = $("<td class='ui-pg-button "+commonstyle.cornerall+"'></td>"); $(tbd).append("<div class='ui-pg-div'><span class='"+commonstyle.icon_base +" " +o.addicon+"'></span>"+o.addtext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.addtitle || "",id : pAdd.id || "add_"+elemids}) .click(function(){ if (!$(this).hasClass( commonstyle.disabled )) { $.jgrid.setSelNavIndex( $t, this); if ($.jgrid.isFunction( o.addfunc )) { o.addfunc.call($t); } else { $($t).jqGrid("editGridRow","new",pAdd); } } return false; }).hover(onHoverIn, onHoverOut); tbd = null; } pEdit = pEdit || {}; if (o.edit) { tbd = $("<td class='ui-pg-button "+commonstyle.cornerall+"'></td>"); $(tbd).append("<div class='ui-pg-div'><span class='"+commonstyle.icon_base+" "+o.editicon+"'></span>"+o.edittext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.edittitle || "",id: pEdit.id || "edit_"+elemids}) .click(function(){ if (!$(this).hasClass( commonstyle.disabled )) { var sr = $t.p.selrow; if (sr) { $.jgrid.setSelNavIndex( $t, this); if($.jgrid.isFunction( o.editfunc ) ) { o.editfunc.call($t, sr); } else { $($t).jqGrid("editGridRow",sr,pEdit); } } else { $.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true}); $("#jqg_alrt").focus(); } } return false; }).hover(onHoverIn, onHoverOut); tbd = null; } pView = pView || {}; if (o.view) { tbd = $("<td class='ui-pg-button "+commonstyle.cornerall+"'></td>"); $(tbd).append("<div class='ui-pg-div'><span class='"+commonstyle.icon_base+" "+o.viewicon+"'></span>"+o.viewtext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.viewtitle || "",id: pView.id || "view_"+elemids}) .click(function(){ if (!$(this).hasClass( commonstyle.disabled )) { var sr = $t.p.selrow; if (sr) { $.jgrid.setSelNavIndex( $t, this); if($.jgrid.isFunction( o.viewfunc ) ) { o.viewfunc.call($t, sr); } else { $($t).jqGrid("viewGridRow",sr,pView); } } else { $.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true}); $("#jqg_alrt").focus(); } } return false; }).hover(onHoverIn, onHoverOut); tbd = null; } pDel = pDel || {}; if (o.del) { tbd = $("<td class='ui-pg-button "+commonstyle.cornerall+"'></td>"); $(tbd).append("<div class='ui-pg-div'><span class='"+commonstyle.icon_base+" "+o.delicon+"'></span>"+o.deltext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.deltitle || "",id: pDel.id || "del_"+elemids}) .click(function(){ if (!$(this).hasClass( commonstyle.disabled )) { var dr; if($t.p.multiselect) { dr = $t.p.selarrrow; if(dr.length===0) {dr = null;} } else { dr = $t.p.selrow; } if(dr){ $.jgrid.setSelNavIndex( $t, this); if($.jgrid.isFunction( o.delfunc )){ o.delfunc.call($t, dr); }else{ $($t).jqGrid("delGridRow",dr,pDel); } } else { $.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true});$("#jqg_alrt").focus(); } } return false; }).hover(onHoverIn, onHoverOut); tbd = null; } if(o.add || o.edit || o.del || o.view) {$("tr",navtbl).append(sep);} pSearch = pSearch || {}; if (o.search) { tbd = $("<td class='ui-pg-button "+commonstyle.cornerall+"'></td>"); $(tbd).append("<div class='ui-pg-div'><span class='"+commonstyle.icon_base+" "+o.searchicon+"'></span>"+o.searchtext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.searchtitle || "",id:pSearch.id || "search_"+elemids}) .click(function(){ if (!$(this).hasClass( commonstyle.disabled )) { $.jgrid.setSelNavIndex( $t, this); if($.jgrid.isFunction( o.searchfunc )) { o.searchfunc.call($t, pSearch); } else { $($t).jqGrid("searchGrid",pSearch); } } return false; }).hover(onHoverIn, onHoverOut); if (pSearch.showOnLoad && pSearch.showOnLoad === true) { $(tbd,navtbl).click(); } tbd = null; } if (o.refresh) { tbd = $("<td class='ui-pg-button "+commonstyle.cornerall+"'></td>"); $(tbd).append("<div class='ui-pg-div'><span class='"+commonstyle.icon_base+" "+o.refreshicon+"'></span>"+o.refreshtext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.refreshtitle || "",id: "refresh_"+elemids}) .click(function(){ if (!$(this).hasClass( commonstyle.disabled )) { if($.jgrid.isFunction(o.beforeRefresh)) {o.beforeRefresh.call($t);} $t.p.search = false; $t.p.resetsearch = true; try { if( o.refreshstate !== 'currentfilter') { var gID = $t.p.id; $t.p.postData.filters =""; try { $("#fbox_"+$.jgrid.jqID(gID)).jqFilter('resetFilter'); } catch(ef) {} if($.jgrid.isFunction($t.clearToolbar)) {$t.clearToolbar.call($t,false);} } } catch (e) {} switch (o.refreshstate) { case 'firstpage': $($t).trigger("reloadGrid", [{page:1}]); break; case 'current': case 'currentfilter': $($t).trigger("reloadGrid", [{current:true}]); break; } if($.jgrid.isFunction(o.afterRefresh)) {o.afterRefresh.call($t);} $.jgrid.setSelNavIndex( $t, this); } return false; }).hover(onHoverIn, onHoverOut); tbd = null; } tdw = $(".ui-jqgrid").css("font-size") || "11px"; $('body').append("<div id='testpg2' class='ui-jqgrid "+$.jgrid.styleUI[currstyle].base.entrieBox+"' style='font-size:"+tdw+";visibility:hidden;' ></div>"); twd = $(navtbl).clone().appendTo("#testpg2").width(); $("#testpg2").remove(); if($t.p._nvtd) { if(o.dropmenu) { navtbl = null; $($t).jqGrid('_buildNavMenu', pgid, elemids, p, pEdit, pAdd, pDel, pSearch, pView ); } else if(twd > $t.p._nvtd[0] ) { if($t.p.responsive) { navtbl = null; $($t).jqGrid('_buildNavMenu', pgid, elemids, p, pEdit, pAdd, pDel, pSearch, pView ); } else { $(pgid+"_"+o.position,pgid).append(navtbl).width(twd); } $t.p._nvtd[0] = twd; } else { $(pgid+"_"+o.position,pgid).append(navtbl); } $t.p._nvtd[1] = twd; } $t.p.navGrid = true; } if($t.p.storeNavOptions) { $t.p.navOptions = o; $t.p.editOptions = pEdit; $t.p.addOptions = pAdd; $t.p.delOptions = pDel; $t.p.searchOptions = pSearch; $t.p.viewOptions = pView; $t.p.navButtons =[]; } }); }, navButtonAdd : function (elem, p) { var currstyle = this[0].p.styleUI, styles = $.jgrid.styleUI[currstyle].navigator; p = $.extend({ caption : "newButton", title: '', buttonicon : styles.icon_newbutton_nav, onClickButton: null, position : "last", cursor : 'pointer', internal : false }, p ||{}); return this.each(function() { if(!this.grid || typeof elem !== 'string') {return;} if( elem.indexOf("#") === 0 ) { elem = elem.substring(1); } elem = "#" + $.jgrid.jqID(elem); var findnav = $(".navtable",elem)[0], $t = this, //getstyle = $.jgrid.getMethod("getStyleUI"), disabled = $.jgrid.styleUI[currstyle].common.disabled, hover = $.jgrid.styleUI[currstyle].common.hover, cornerall = $.jgrid.styleUI[currstyle].common.cornerall, iconbase = $.jgrid.styleUI[currstyle].common.icon_base; if ($t.p.storeNavOptions && !p.internal) { $t.p.navButtons.push([elem,p]); } if (findnav) { if( p.id && $("#"+$.jgrid.jqID(p.id), findnav)[0] !== undefined ) {return;} var tbd = $("<td></td>"); if(p.buttonicon.toString().toUpperCase() === "NONE") { $(tbd).addClass('ui-pg-button '+cornerall).append("<div class='ui-pg-div'>"+p.caption+"</div>"); } else { $(tbd).addClass('ui-pg-button '+cornerall).append("<div class='ui-pg-div'><span class='"+iconbase+" "+p.buttonicon+"'></span>"+p.caption+"</div>"); } if(p.id) {$(tbd).attr("id",p.id);} if(p.position==='first'){ if(findnav.rows[0].cells.length ===0 ) { $("tr",findnav).append(tbd); } else { $("tr td",findnav).eq( 0 ).before(tbd); } } else { $("tr",findnav).append(tbd); } $(tbd,findnav) .attr("title",p.title || "") .click(function(e){ if (!$(this).hasClass(disabled)) { $.jgrid.setSelNavIndex( $t, this); if ($.jgrid.isFunction(p.onClickButton) ) {p.onClickButton.call($t,e);} } return false; }) .hover( function () { if (!$(this).hasClass(disabled)) { $(this).addClass(hover); } }, function () {$(this).removeClass(hover);} ); } else { findnav = $(".dropdownmenu",elem)[0]; if (findnav) { var id = $(findnav).val(), eid = p.id || $.jgrid.randId(), item = $('<li class="ui-menu-item" role="presentation"><a class="'+ cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.caption || p.title)+'</a></li>'); if(id) { if(p.position === 'first') { $("#"+id).prepend( item ); } else { $("#"+id).append( item ); } $(item).on("click", function(e){ if (!$(this).hasClass(disabled)) { $("#"+id).hide(); if ($.jgrid.isFunction(p.onClickButton) ) { p.onClickButton.call($t,e); } } return false; }).find("a") .hover( function () { if (!$(this).hasClass(disabled)) { $(this).addClass(hover); } }, function () {$(this).removeClass(hover);} ); } } } }); }, navSeparatorAdd:function (elem,p) { var currstyle = this[0].p.styleUI, commonstyle = $.jgrid.styleUI[currstyle].common; p = $.extend({ sepclass : "ui-separator", sepcontent: '', position : "last" }, p ||{}); return this.each(function() { if( !this.grid) {return;} if( typeof elem === "string" && elem.indexOf("#") !== 0) {elem = "#"+$.jgrid.jqID(elem);} var findnav = $(".navtable",elem)[0], sep, id; if ( this.p.storeNavOptions ) { this.p.navButtons.push([elem,p]); } if(findnav) { sep = "<td class='ui-pg-button "+ commonstyle.disabled +"' style='width:4px;'><span class='"+p.sepclass+"'></span>"+p.sepcontent+"</td>"; if (p.position === 'first') { if (findnav.rows[0].cells.length === 0) { $("tr", findnav).append(sep); } else { $("tr td", findnav).eq( 0 ).before(sep); } } else { $("tr", findnav).append(sep); } } else { findnav = $(".dropdownmenu",elem)[0]; sep = "<li class='ui-menu-item " +commonstyle.disabled + "' style='width:100%' role='presentation'><hr class='ui-separator-li'></li>"; if(findnav) { id = $(findnav).val(); if(id) { if(p.position === "first") { $("#"+id).prepend( sep ); } else { $("#"+id).append( sep ); } } } } }); }, _buildNavMenu : function ( elem, elemids, p, pEdit, pAdd, pDel, pSearch, pView ) { return this.each(function() { var $t = this, //actions = ['add','edit', 'del', 'view', 'search','refresh'], regional = $.jgrid.getRegional($t, 'nav'), currstyle = $t.p.styleUI, styles = $.jgrid.styleUI[currstyle].navigator, classes = $.jgrid.styleUI[currstyle].filter, commonstyle = $.jgrid.styleUI[currstyle].common, mid = "form_menu_"+$.jgrid.randId(), bt = p.navButtonText ? p.navButtonText : regional.selectcaption || 'Actions', act = "<button class='dropdownmenu "+commonstyle.button+"' value='"+mid+"'>" + bt +"</button>"; $(elem+"_"+p.position, elem).append( act ); var alertIDs = {themodal: 'alertmod_' + this.p.id, modalhead: 'alerthd_' + this.p.id,modalcontent: 'alertcnt_' + this.p.id}, _buildMenu = function() { var fs = $('.ui-jqgrid').css('font-size') || '11px', eid, itm, str = $('<ul id="'+mid+'" class="ui-nav-menu modal-content" role="menu" tabindex="0" style="display:none;font-size:'+fs+'"></ul>'); if( p.add ) { pAdd = pAdd || {}; eid = pAdd.id || "add_"+elemids; itm = $('<li class="ui-menu-item" role="presentation"><a class="'+ commonstyle.cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.addtext || p.addtitle)+'</a></li>').click(function(){ if (!$(this).hasClass( commonstyle.disabled )) { if ($.jgrid.isFunction( p.addfunc )) { p.addfunc.call($t); } else { $($t).jqGrid("editGridRow","new",pAdd); } $(str).hide(); } return false; }); $(str).append(itm); } if( p.edit ) { pEdit = pEdit || {}; eid = pEdit.id || "edit_"+elemids; itm = $('<li class="ui-menu-item" role="presentation"><a class="'+ commonstyle.cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.edittext || p.edittitle)+'</a></li>').click(function(){ if (!$(this).hasClass( commonstyle.disabled )) { var sr = $t.p.selrow; if (sr) { if($.jgrid.isFunction( p.editfunc ) ) { p.editfunc.call($t, sr); } else { $($t).jqGrid("editGridRow",sr,pEdit); } } else { $.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true}); $("#jqg_alrt").focus(); } $(str).hide(); } return false; }); $(str).append(itm); } if( p.view ) { pView = pView || {}; eid = pView.id || "view_"+elemids; itm = $('<li class="ui-menu-item" role="presentation"><a class="'+ commonstyle.cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.viewtext || p.viewtitle)+'</a></li>').click(function(){ if (!$(this).hasClass( commonstyle.disabled )) { var sr = $t.p.selrow; if (sr) { if($.jgrid.isFunction( p.editfunc ) ) { p.viewfunc.call($t, sr); } else { $($t).jqGrid("viewGridRow",sr,pView); } } else { $.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true}); $("#jqg_alrt").focus(); } $(str).hide(); } return false; }); $(str).append(itm); } if( p.del ) { pDel = pDel || {}; eid = pDel.id || "del_"+elemids; itm = $('<li class="ui-menu-item" role="presentation"><a class="'+ commonstyle.cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.deltext || p.deltitle)+'</a></li>').click(function(){ if (!$(this).hasClass( commonstyle.disabled )) { var dr; if($t.p.multiselect) { dr = $t.p.selarrrow; if(dr.length===0) {dr = null;} } else { dr = $t.p.selrow; } if(dr){ if($.jgrid.isFunction( p.delfunc )){ p.delfunc.call($t, dr); }else{ $($t).jqGrid("delGridRow",dr,pDel); } } else { $.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true});$("#jqg_alrt").focus(); } $(str).hide(); } return false; }); $(str).append(itm); } if(p.add || p.edit || p.del || p.view) { $(str).append("<li class='ui-menu-item " +commonstyle.disabled + "' style='width:100%' role='presentation'><hr class='ui-separator-li'></li>"); } if( p.search ) { pSearch = pSearch || {}; eid = pSearch.id || "search_"+elemids; itm = $('<li class="ui-menu-item" role="presentation"><a class="'+ commonstyle.cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.searchtext || p.searchtitle)+'</a></li>').click(function(){ if (!$(this).hasClass( commonstyle.disabled )) { if($.jgrid.isFunction( p.searchfunc )) { p.searchfunc.call($t, pSearch); } else { $($t).jqGrid("searchGrid",pSearch); } $(str).hide(); } return false; }); $(str).append(itm); if (pSearch.showOnLoad && pSearch.showOnLoad === true) { $( itm ).click(); } } if( p.refresh ) { eid = pSearch.id || "search_"+elemids; itm = $('<li class="ui-menu-item" role="presentation"><a class="'+ commonstyle.cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.refreshtext || p.refreshtitle)+'</a></li>').click(function(){ if (!$(this).hasClass( commonstyle.disabled )) { if($.jgrid.isFunction(p.beforeRefresh)) {p.beforeRefresh.call($t);} $t.p.search = false; $t.p.resetsearch = true; try { if( p.refreshstate !== 'currentfilter') { var gID = $t.p.id; $t.p.postData.filters =""; try { $("#fbox_"+$.jgrid.jqID(gID)).jqFilter('resetFilter'); } catch(ef) {} if($.jgrid.isFunction($t.clearToolbar)) {$t.clearToolbar.call($t,false);} } } catch (e) {} switch (p.refreshstate) { case 'firstpage': $($t).trigger("reloadGrid", [{page:1}]); break; case 'current': case 'currentfilter': $($t).trigger("reloadGrid", [{current:true}]); break; } if($.jgrid.isFunction(p.afterRefresh)) {p.afterRefresh.call($t);} $(str).hide(); } return false; }); $(str).append(itm); } $(str).hide(); $('body').append(str); $("#"+mid).addClass("ui-menu " + classes.menu_widget); $("#"+mid+" > li > a").hover( function(){ $(this).addClass(commonstyle.hover); }, function(){ $(this).removeClass(commonstyle.hover); } ); }; _buildMenu(); $(".dropdownmenu", elem+"_"+p.position).on("click", function( e ){ var offset = $(this).offset(), left = ( offset.left ), top = parseInt( offset.top), bid =$(this).val(); //if( $("#"+mid)[0] === undefined) { //_buildMenu(); //} $("#"+bid).show().css({"top":top - ($("#"+bid).height() +10)+"px", "left":left+"px"}); e.stopPropagation(); }); $("body").on('click', function(e){ if(!$(e.target).hasClass("dropdownmenu")) { $("#"+mid).hide(); } }); }); }, GridToForm : function( rowid, formid ) { return this.each(function(){ var $t = this, i; if (!$t.grid) {return;} var rowdata = $($t).jqGrid("getRowData",rowid); if (rowdata) { for(i in rowdata) { if(rowdata.hasOwnProperty(i)) { if ( $("[name="+$.jgrid.jqID(i)+"]",formid).is("input:radio") || $("[name="+$.jgrid.jqID(i)+"]",formid).is("input:checkbox")) { $("[name="+$.jgrid.jqID(i)+"]",formid).each( function() { if( $(this).val() == rowdata[i] ) { $(this)[$t.p.useProp ? 'prop': 'attr']("checked",true); } else { $(this)[$t.p.useProp ? 'prop': 'attr']("checked", false); } }); } else { // this is very slow on big table and form. $("[name="+$.jgrid.jqID(i)+"]",formid).val(rowdata[i]); } } } } }); }, FormToGrid : function(rowid, formid, mode, position){ return this.each(function() { var $t = this; if(!$t.grid) {return;} if(!mode) {mode = 'set';} if(!position) {position = 'first';} var fields = $(formid).serializeArray(); var griddata = {}; $.each(fields, function(i, field){ griddata[field.name] = field.value; }); if(mode==='add') {$($t).jqGrid("addRowData",rowid,griddata, position);} else if(mode==='set') {$($t).jqGrid("setRowData",rowid,griddata);} }); } }); //module end }));
cdnjs/cdnjs
ajax/libs/jqgrid/5.5.4/js/grid.formedit.js
JavaScript
mit
93,444
function createBrowserLocalStorageCache(options) { const namespaceKey = `algoliasearch-client-js-${options.key}`; // eslint-disable-next-line functional/no-let let storage; const getStorage = () => { if (storage === undefined) { storage = options.localStorage || window.localStorage; } return storage; }; const getNamespace = () => { return JSON.parse(getStorage().getItem(namespaceKey) || '{}'); }; return { get(key, defaultValue, events = { miss: () => Promise.resolve(), }) { return Promise.resolve() .then(() => { const keyAsString = JSON.stringify(key); const value = getNamespace()[keyAsString]; return Promise.all([value || defaultValue(), value !== undefined]); }) .then(([value, exists]) => { return Promise.all([value, exists || events.miss(value)]); }) .then(([value]) => value); }, set(key, value) { return Promise.resolve().then(() => { const namespace = getNamespace(); // eslint-disable-next-line functional/immutable-data namespace[JSON.stringify(key)] = value; getStorage().setItem(namespaceKey, JSON.stringify(namespace)); return value; }); }, delete(key) { return Promise.resolve().then(() => { const namespace = getNamespace(); // eslint-disable-next-line functional/immutable-data delete namespace[JSON.stringify(key)]; getStorage().setItem(namespaceKey, JSON.stringify(namespace)); }); }, clear() { return Promise.resolve().then(() => { getStorage().removeItem(namespaceKey); }); }, }; } // @todo Add logger on options to debug when caches go wrong. function createFallbackableCache(options) { const caches = [...options.caches]; const current = caches.shift(); // eslint-disable-line functional/immutable-data if (current === undefined) { return createNullCache(); } return { get(key, defaultValue, events = { miss: () => Promise.resolve(), }) { return current.get(key, defaultValue, events).catch(() => { return createFallbackableCache({ caches }).get(key, defaultValue, events); }); }, set(key, value) { return current.set(key, value).catch(() => { return createFallbackableCache({ caches }).set(key, value); }); }, delete(key) { return current.delete(key).catch(() => { return createFallbackableCache({ caches }).delete(key); }); }, clear() { return current.clear().catch(() => { return createFallbackableCache({ caches }).clear(); }); }, }; } function createNullCache() { return { get(_key, defaultValue, events = { miss: () => Promise.resolve(), }) { const value = defaultValue(); return value .then(result => Promise.all([result, events.miss(result)])) .then(([result]) => result); }, set(_key, value) { return Promise.resolve(value); }, delete(_key) { return Promise.resolve(); }, clear() { return Promise.resolve(); }, }; } function createInMemoryCache(options = { serializable: true }) { // eslint-disable-next-line functional/no-let let cache = {}; return { get(key, defaultValue, events = { miss: () => Promise.resolve(), }) { const keyAsString = JSON.stringify(key); if (keyAsString in cache) { return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]); } const promise = defaultValue(); const miss = (events && events.miss) || (() => Promise.resolve()); return promise.then((value) => miss(value)).then(() => promise); }, set(key, value) { // eslint-disable-next-line functional/immutable-data cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value; return Promise.resolve(value); }, delete(key) { // eslint-disable-next-line functional/immutable-data delete cache[JSON.stringify(key)]; return Promise.resolve(); }, clear() { cache = {}; return Promise.resolve(); }, }; } function createAuth(authMode, appId, apiKey) { const credentials = { 'x-algolia-api-key': apiKey, 'x-algolia-application-id': appId, }; return { headers() { return authMode === AuthMode.WithinHeaders ? credentials : {}; }, queryParameters() { return authMode === AuthMode.WithinQueryParameters ? credentials : {}; }, }; } // eslint-disable-next-line functional/prefer-readonly-type function shuffle(array) { let c = array.length - 1; // eslint-disable-line functional/no-let // eslint-disable-next-line functional/no-loop-statement for (c; c > 0; c--) { const b = Math.floor(Math.random() * (c + 1)); const a = array[c]; array[c] = array[b]; // eslint-disable-line functional/immutable-data, no-param-reassign array[b] = a; // eslint-disable-line functional/immutable-data, no-param-reassign } return array; } function addMethods(base, methods) { if (!methods) { return base; } Object.keys(methods).forEach(key => { // eslint-disable-next-line functional/immutable-data, no-param-reassign base[key] = methods[key](base); }); return base; } function encode(format, ...args) { // eslint-disable-next-line functional/no-let let i = 0; return format.replace(/%s/g, () => encodeURIComponent(args[i++])); } const version = '4.12.1'; const AuthMode = { /** * If auth credentials should be in query parameters. */ WithinQueryParameters: 0, /** * If auth credentials should be in headers. */ WithinHeaders: 1, }; function createMappedRequestOptions(requestOptions, timeout) { const options = requestOptions || {}; const data = options.data || {}; Object.keys(options).forEach(key => { if (['timeout', 'headers', 'queryParameters', 'data', 'cacheable'].indexOf(key) === -1) { data[key] = options[key]; // eslint-disable-line functional/immutable-data } }); return { data: Object.entries(data).length > 0 ? data : undefined, timeout: options.timeout || timeout, headers: options.headers || {}, queryParameters: options.queryParameters || {}, cacheable: options.cacheable, }; } const CallEnum = { /** * If the host is read only. */ Read: 1, /** * If the host is write only. */ Write: 2, /** * If the host is both read and write. */ Any: 3, }; const HostStatusEnum = { Up: 1, Down: 2, Timeouted: 3, }; // By default, API Clients at Algolia have expiration delay // of 5 mins. In the JavaScript client, we have 2 mins. const EXPIRATION_DELAY = 2 * 60 * 1000; function createStatefulHost(host, status = HostStatusEnum.Up) { return { ...host, status, lastUpdate: Date.now(), }; } function isStatefulHostUp(host) { return host.status === HostStatusEnum.Up || Date.now() - host.lastUpdate > EXPIRATION_DELAY; } function isStatefulHostTimeouted(host) { return (host.status === HostStatusEnum.Timeouted && Date.now() - host.lastUpdate <= EXPIRATION_DELAY); } function createStatelessHost(options) { if (typeof options === 'string') { return { protocol: 'https', url: options, accept: CallEnum.Any, }; } return { protocol: options.protocol || 'https', url: options.url, accept: options.accept || CallEnum.Any, }; } const MethodEnum = { Delete: 'DELETE', Get: 'GET', Post: 'POST', Put: 'PUT', }; function createRetryableOptions(hostsCache, statelessHosts) { return Promise.all(statelessHosts.map(statelessHost => { return hostsCache.get(statelessHost, () => { return Promise.resolve(createStatefulHost(statelessHost)); }); })).then(statefulHosts => { const hostsUp = statefulHosts.filter(host => isStatefulHostUp(host)); const hostsTimeouted = statefulHosts.filter(host => isStatefulHostTimeouted(host)); /** * Note, we put the hosts that previously timeouted on the end of the list. */ const hostsAvailable = [...hostsUp, ...hostsTimeouted]; const statelessHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable.map(host => createStatelessHost(host)) : statelessHosts; return { getTimeout(timeoutsCount, baseTimeout) { /** * Imagine that you have 4 hosts, if timeouts will increase * on the following way: 1 (timeouted) > 4 (timeouted) > 5 (200) * * Note that, the very next request, we start from the previous timeout * * 5 (timeouted) > 6 (timeouted) > 7 ... * * This strategy may need to be reviewed, but is the strategy on the our * current v3 version. */ const timeoutMultiplier = hostsTimeouted.length === 0 && timeoutsCount === 0 ? 1 : hostsTimeouted.length + 3 + timeoutsCount; return timeoutMultiplier * baseTimeout; }, statelessHosts: statelessHostsAvailable, }; }); } const isNetworkError = ({ isTimedOut, status }) => { return !isTimedOut && ~~status === 0; }; const isRetryable = (response) => { const status = response.status; const isTimedOut = response.isTimedOut; return (isTimedOut || isNetworkError(response) || (~~(status / 100) !== 2 && ~~(status / 100) !== 4)); }; const isSuccess = ({ status }) => { return ~~(status / 100) === 2; }; const retryDecision = (response, outcomes) => { if (isRetryable(response)) { return outcomes.onRetry(response); } if (isSuccess(response)) { return outcomes.onSuccess(response); } return outcomes.onFail(response); }; function retryableRequest(transporter, statelessHosts, request, requestOptions) { const stackTrace = []; // eslint-disable-line functional/prefer-readonly-type /** * First we prepare the payload that do not depend from hosts. */ const data = serializeData(request, requestOptions); const headers = serializeHeaders(transporter, requestOptions); const method = request.method; // On `GET`, the data is proxied to query parameters. const dataQueryParameters = request.method !== MethodEnum.Get ? {} : { ...request.data, ...requestOptions.data, }; const queryParameters = { 'x-algolia-agent': transporter.userAgent.value, ...transporter.queryParameters, ...dataQueryParameters, ...requestOptions.queryParameters, }; let timeoutsCount = 0; // eslint-disable-line functional/no-let const retry = (hosts, // eslint-disable-line functional/prefer-readonly-type getTimeout) => { /** * We iterate on each host, until there is no host left. */ const host = hosts.pop(); // eslint-disable-line functional/immutable-data if (host === undefined) { throw createRetryError(stackTraceWithoutCredentials(stackTrace)); } const payload = { data, headers, method, url: serializeUrl(host, request.path, queryParameters), connectTimeout: getTimeout(timeoutsCount, transporter.timeouts.connect), responseTimeout: getTimeout(timeoutsCount, requestOptions.timeout), }; /** * The stackFrame is pushed to the stackTrace so we * can have information about onRetry and onFailure * decisions. */ const pushToStackTrace = (response) => { const stackFrame = { request: payload, response, host, triesLeft: hosts.length, }; // eslint-disable-next-line functional/immutable-data stackTrace.push(stackFrame); return stackFrame; }; const decisions = { onSuccess: response => deserializeSuccess(response), onRetry(response) { const stackFrame = pushToStackTrace(response); /** * If response is a timeout, we increaset the number of * timeouts so we can increase the timeout later. */ if (response.isTimedOut) { timeoutsCount++; } return Promise.all([ /** * Failures are individually send the logger, allowing * the end user to debug / store stack frames even * when a retry error does not happen. */ transporter.logger.info('Retryable failure', stackFrameWithoutCredentials(stackFrame)), /** * We also store the state of the host in failure cases. If the host, is * down it will remain down for the next 2 minutes. In a timeout situation, * this host will be added end of the list of hosts on the next request. */ transporter.hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? HostStatusEnum.Timeouted : HostStatusEnum.Down)), ]).then(() => retry(hosts, getTimeout)); }, onFail(response) { pushToStackTrace(response); throw deserializeFailure(response, stackTraceWithoutCredentials(stackTrace)); }, }; return transporter.requester.send(payload).then(response => { return retryDecision(response, decisions); }); }; /** * Finally, for each retryable host perform request until we got a non * retryable response. Some notes here: * * 1. The reverse here is applied so we can apply a `pop` later on => more performant. * 2. We also get from the retryable options a timeout multiplier that is tailored * for the current context. */ return createRetryableOptions(transporter.hostsCache, statelessHosts).then(options => { return retry([...options.statelessHosts].reverse(), options.getTimeout); }); } function createTransporter(options) { const { hostsCache, logger, requester, requestsCache, responsesCache, timeouts, userAgent, hosts, queryParameters, headers, } = options; const transporter = { hostsCache, logger, requester, requestsCache, responsesCache, timeouts, userAgent, headers, queryParameters, hosts: hosts.map(host => createStatelessHost(host)), read(request, requestOptions) { /** * First, we compute the user request options. Now, keep in mind, * that using request options the user is able to modified the intire * payload of the request. Such as headers, query parameters, and others. */ const mappedRequestOptions = createMappedRequestOptions(requestOptions, transporter.timeouts.read); const createRetryableRequest = () => { /** * Then, we prepare a function factory that contains the construction of * the retryable request. At this point, we may *not* perform the actual * request. But we want to have the function factory ready. */ return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Read) !== 0), request, mappedRequestOptions); }; /** * Once we have the function factory ready, we need to determine of the * request is "cacheable" - should be cached. Note that, once again, * the user can force this option. */ const cacheable = mappedRequestOptions.cacheable !== undefined ? mappedRequestOptions.cacheable : request.cacheable; /** * If is not "cacheable", we immediatly trigger the retryable request, no * need to check cache implementations. */ if (cacheable !== true) { return createRetryableRequest(); } /** * If the request is "cacheable", we need to first compute the key to ask * the cache implementations if this request is on progress or if the * response already exists on the cache. */ const key = { request, mappedRequestOptions, transporter: { queryParameters: transporter.queryParameters, headers: transporter.headers, }, }; /** * With the computed key, we first ask the responses cache * implemention if this request was been resolved before. */ return transporter.responsesCache.get(key, () => { /** * If the request has never resolved before, we actually ask if there * is a current request with the same key on progress. */ return transporter.requestsCache.get(key, () => { return (transporter.requestsCache /** * Finally, if there is no request in progress with the same key, * this `createRetryableRequest()` will actually trigger the * retryable request. */ .set(key, createRetryableRequest()) .then(response => Promise.all([transporter.requestsCache.delete(key), response]), err => Promise.all([transporter.requestsCache.delete(key), Promise.reject(err)])) .then(([_, response]) => response)); }); }, { /** * Of course, once we get this response back from the server, we * tell response cache to actually store the received response * to be used later. */ miss: response => transporter.responsesCache.set(key, response), }); }, write(request, requestOptions) { /** * On write requests, no cache mechanisms are applied, and we * proxy the request immediately to the requester. */ return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Write) !== 0), request, createMappedRequestOptions(requestOptions, transporter.timeouts.write)); }, }; return transporter; } function createUserAgent(version) { const userAgent = { value: `Algolia for JavaScript (${version})`, add(options) { const addedUserAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`; if (userAgent.value.indexOf(addedUserAgent) === -1) { // eslint-disable-next-line functional/immutable-data userAgent.value = `${userAgent.value}${addedUserAgent}`; } return userAgent; }, }; return userAgent; } function deserializeSuccess(response) { // eslint-disable-next-line functional/no-try-statement try { return JSON.parse(response.content); } catch (e) { throw createDeserializationError(e.message, response); } } function deserializeFailure({ content, status }, stackFrame) { // eslint-disable-next-line functional/no-let let message = content; // eslint-disable-next-line functional/no-try-statement try { message = JSON.parse(content).message; } catch (e) { // .. } return createApiError(message, status, stackFrame); } function serializeUrl(host, path, queryParameters) { const queryParametersAsString = serializeQueryParameters(queryParameters); // eslint-disable-next-line functional/no-let let url = `${host.protocol}://${host.url}/${path.charAt(0) === '/' ? path.substr(1) : path}`; if (queryParametersAsString.length) { url += `?${queryParametersAsString}`; } return url; } function serializeQueryParameters(parameters) { const isObjectOrArray = (value) => Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object Array]'; return Object.keys(parameters) .map(key => encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key])) .join('&'); } function serializeData(request, requestOptions) { if (request.method === MethodEnum.Get || (request.data === undefined && requestOptions.data === undefined)) { return undefined; } const data = Array.isArray(request.data) ? request.data : { ...request.data, ...requestOptions.data }; return JSON.stringify(data); } function serializeHeaders(transporter, requestOptions) { const headers = { ...transporter.headers, ...requestOptions.headers, }; const serializedHeaders = {}; Object.keys(headers).forEach(header => { const value = headers[header]; // @ts-ignore // eslint-disable-next-line functional/immutable-data serializedHeaders[header.toLowerCase()] = value; }); return serializedHeaders; } function stackTraceWithoutCredentials(stackTrace) { return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame)); } function stackFrameWithoutCredentials(stackFrame) { const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key'] ? { 'x-algolia-api-key': '*****' } : {}; return { ...stackFrame, request: { ...stackFrame.request, headers: { ...stackFrame.request.headers, ...modifiedHeaders, }, }, }; } function createApiError(message, status, transporterStackTrace) { return { name: 'ApiError', message, status, transporterStackTrace, }; } function createDeserializationError(message, response) { return { name: 'DeserializationError', message, response, }; } function createRetryError(transporterStackTrace) { return { name: 'RetryError', message: 'Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.', transporterStackTrace, }; } const createSearchClient = options => { const appId = options.appId; const auth = createAuth(options.authMode !== undefined ? options.authMode : AuthMode.WithinHeaders, appId, options.apiKey); const transporter = createTransporter({ hosts: [ { url: `${appId}-dsn.algolia.net`, accept: CallEnum.Read }, { url: `${appId}.algolia.net`, accept: CallEnum.Write }, ].concat(shuffle([ { url: `${appId}-1.algolianet.com` }, { url: `${appId}-2.algolianet.com` }, { url: `${appId}-3.algolianet.com` }, ])), ...options, headers: { ...auth.headers(), ...{ 'content-type': 'application/x-www-form-urlencoded' }, ...options.headers, }, queryParameters: { ...auth.queryParameters(), ...options.queryParameters, }, }); const base = { transporter, appId, addAlgoliaAgent(segment, version) { transporter.userAgent.add({ segment, version }); }, clearCache() { return Promise.all([ transporter.requestsCache.clear(), transporter.responsesCache.clear(), ]).then(() => undefined); }, }; return addMethods(base, options.methods); }; const customRequest = (base) => { return (request, requestOptions) => { if (request.method === MethodEnum.Get) { return base.transporter.read(request, requestOptions); } return base.transporter.write(request, requestOptions); }; }; const initIndex = (base) => { return (indexName, options = {}) => { const searchIndex = { transporter: base.transporter, appId: base.appId, indexName, }; return addMethods(searchIndex, options.methods); }; }; const multipleQueries = (base) => { return (queries, requestOptions) => { const requests = queries.map(query => { return { ...query, params: serializeQueryParameters(query.params || {}), }; }); return base.transporter.read({ method: MethodEnum.Post, path: '1/indexes/*/queries', data: { requests, }, cacheable: true, }, requestOptions); }; }; const multipleSearchForFacetValues = (base) => { return (queries, requestOptions) => { return Promise.all(queries.map(query => { const { facetName, facetQuery, ...params } = query.params; return initIndex(base)(query.indexName, { methods: { searchForFacetValues }, }).searchForFacetValues(facetName, facetQuery, { ...requestOptions, ...params, }); })); }; }; const findAnswers = (base) => { return (query, queryLanguages, requestOptions) => { return base.transporter.read({ method: MethodEnum.Post, path: encode('1/answers/%s/prediction', base.indexName), data: { query, queryLanguages, }, cacheable: true, }, requestOptions); }; }; const search = (base) => { return (query, requestOptions) => { return base.transporter.read({ method: MethodEnum.Post, path: encode('1/indexes/%s/query', base.indexName), data: { query, }, cacheable: true, }, requestOptions); }; }; const searchForFacetValues = (base) => { return (facetName, facetQuery, requestOptions) => { return base.transporter.read({ method: MethodEnum.Post, path: encode('1/indexes/%s/facets/%s/query', base.indexName, facetName), data: { facetQuery, }, cacheable: true, }, requestOptions); }; }; const LogLevelEnum = { Debug: 1, Info: 2, Error: 3, }; /* eslint no-console: 0 */ function createConsoleLogger(logLevel) { return { debug(message, args) { if (LogLevelEnum.Debug >= logLevel) { console.debug(message, args); } return Promise.resolve(); }, info(message, args) { if (LogLevelEnum.Info >= logLevel) { console.info(message, args); } return Promise.resolve(); }, error(message, args) { console.error(message, args); return Promise.resolve(); }, }; } function createBrowserXhrRequester() { return { send(request) { return new Promise((resolve) => { const baseRequester = new XMLHttpRequest(); baseRequester.open(request.method, request.url, true); Object.keys(request.headers).forEach(key => baseRequester.setRequestHeader(key, request.headers[key])); const createTimeout = (timeout, content) => { return setTimeout(() => { baseRequester.abort(); resolve({ status: 0, content, isTimedOut: true, }); }, timeout * 1000); }; const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout'); // eslint-disable-next-line functional/no-let let responseTimeout; // eslint-disable-next-line functional/immutable-data baseRequester.onreadystatechange = () => { if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) { clearTimeout(connectTimeout); responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout'); } }; // eslint-disable-next-line functional/immutable-data baseRequester.onerror = () => { // istanbul ignore next if (baseRequester.status === 0) { clearTimeout(connectTimeout); clearTimeout(responseTimeout); resolve({ content: baseRequester.responseText || 'Network request failed', status: baseRequester.status, isTimedOut: false, }); } }; // eslint-disable-next-line functional/immutable-data baseRequester.onload = () => { clearTimeout(connectTimeout); clearTimeout(responseTimeout); resolve({ content: baseRequester.responseText, status: baseRequester.status, isTimedOut: false, }); }; baseRequester.send(request.data); }); }, }; } function algoliasearch(appId, apiKey, options) { const commonOptions = { appId, apiKey, timeouts: { connect: 1, read: 2, write: 30, }, requester: createBrowserXhrRequester(), logger: createConsoleLogger(LogLevelEnum.Error), responsesCache: createInMemoryCache(), requestsCache: createInMemoryCache({ serializable: false }), hostsCache: createFallbackableCache({ caches: [ createBrowserLocalStorageCache({ key: `${version}-${appId}` }), createInMemoryCache(), ], }), userAgent: createUserAgent(version).add({ segment: 'Browser', version: 'lite', }), authMode: AuthMode.WithinQueryParameters, }; return createSearchClient({ ...commonOptions, ...options, methods: { search: multipleQueries, searchForFacetValues: multipleSearchForFacetValues, multipleQueries, multipleSearchForFacetValues, customRequest, initIndex: base => (indexName) => { return initIndex(base)(indexName, { methods: { search, searchForFacetValues, findAnswers }, }); }, }, }); } // eslint-disable-next-line functional/immutable-data algoliasearch.version = version; export default algoliasearch;
cdnjs/cdnjs
ajax/libs/algoliasearch/4.12.1/algoliasearch-lite.esm.browser.js
JavaScript
mit
33,346
/*! * chartjs-plugin-annotation v1.3.1 * https://www.chartjs.org/chartjs-plugin-annotation/index * (c) 2022 chartjs-plugin-annotation Contributors * Released under the MIT License */ import { Element, defaults, Chart, Animations } from 'chart.js'; import { defined, distanceBetweenPoints, callback, isFinite, valueOrDefault, isObject, toRadians, toFont, isArray, addRoundedRectPath, toTRBLCorners, toPadding, PI, drawPoint, RAD_PER_DEG, clipArea, unclipArea } from 'chart.js/helpers'; const clickHooks = ['click', 'dblclick']; const moveHooks = ['enter', 'leave']; const hooks = clickHooks.concat(moveHooks); function updateListeners(chart, state, options) { state.listened = false; state.moveListened = false; hooks.forEach(hook => { if (typeof options[hook] === 'function') { state.listened = true; state.listeners[hook] = options[hook]; } else if (defined(state.listeners[hook])) { delete state.listeners[hook]; } }); moveHooks.forEach(hook => { if (typeof options[hook] === 'function') { state.moveListened = true; } }); if (!state.listened || !state.moveListened) { state.annotations.forEach(scope => { if (!state.listened) { clickHooks.forEach(hook => { if (typeof scope[hook] === 'function') { state.listened = true; } }); } if (!state.moveListened) { moveHooks.forEach(hook => { if (typeof scope[hook] === 'function') { state.listened = true; state.moveListened = true; } }); } }); } } function handleEvent(state, event, options) { if (state.listened) { switch (event.type) { case 'mousemove': case 'mouseout': handleMoveEvents(state, event); break; case 'click': handleClickEvents(state, event, options); break; } } } function handleMoveEvents(state, event) { if (!state.moveListened) { return; } let element; if (event.type === 'mousemove') { element = getNearestItem(state.elements, event); } const previous = state.hovered; state.hovered = element; dispatchMoveEvents(state, {previous, element}, event); } function dispatchMoveEvents(state, elements, event) { const {previous, element} = elements; if (previous && previous !== element) { dispatchEvent(previous.options.leave || state.listeners.leave, previous, event); } if (element && element !== previous) { dispatchEvent(element.options.enter || state.listeners.enter, element, event); } } function handleClickEvents(state, event, options) { const listeners = state.listeners; const element = getNearestItem(state.elements, event); if (element) { const elOpts = element.options; const dblclick = elOpts.dblclick || listeners.dblclick; const click = elOpts.click || listeners.click; if (element.clickTimeout) { // 2nd click before timeout, so its a double click clearTimeout(element.clickTimeout); delete element.clickTimeout; dispatchEvent(dblclick, element, event); } else if (dblclick) { // if there is a dblclick handler, wait for dblClickSpeed ms before deciding its a click element.clickTimeout = setTimeout(() => { delete element.clickTimeout; dispatchEvent(click, element, event); }, options.dblClickSpeed); } else { // no double click handler, just call the click handler directly dispatchEvent(click, element, event); } } } function dispatchEvent(handler, element, event) { callback(handler, [element.$context, event]); } function getNearestItem(elements, position) { let minDistance = Number.POSITIVE_INFINITY; return elements .filter((element) => element.options.display && element.inRange(position.x, position.y)) .reduce((nearestItems, element) => { const center = element.getCenterPoint(); const distance = distanceBetweenPoints(position, center); if (distance < minDistance) { nearestItems = [element]; minDistance = distance; } else if (distance === minDistance) { // Can have multiple items at the same distance in which case we sort by size nearestItems.push(element); } return nearestItems; }, []) .sort((a, b) => a._index - b._index) .slice(0, 1)[0]; // return only the top item } function adjustScaleRange(chart, scale, annotations) { const range = getScaleLimits(scale, annotations); let changed = changeScaleLimit(scale, range, 'min', 'suggestedMin'); changed = changeScaleLimit(scale, range, 'max', 'suggestedMax') || changed; if (changed && typeof scale.handleTickRangeOptions === 'function') { scale.handleTickRangeOptions(); } } function verifyScaleOptions(annotations, scales) { for (const annotation of annotations) { verifyScaleIDs(annotation, scales); } } function changeScaleLimit(scale, range, limit, suggestedLimit) { if (isFinite(range[limit]) && !scaleLimitDefined(scale.options, limit, suggestedLimit)) { const changed = scale[limit] !== range[limit]; scale[limit] = range[limit]; return changed; } } function scaleLimitDefined(scaleOptions, limit, suggestedLimit) { return defined(scaleOptions[limit]) || defined(scaleOptions[suggestedLimit]); } function verifyScaleIDs(annotation, scales) { for (const key of ['scaleID', 'xScaleID', 'yScaleID']) { if (annotation[key] && !scales[annotation[key]] && verifyProperties(annotation, key)) { console.warn(`No scale found with id '${annotation[key]}' for annotation '${annotation.id}'`); } } } function verifyProperties(annotation, key) { if (key === 'scaleID') { return true; } const axis = key.charAt(0); for (const prop of ['Min', 'Max', 'Value']) { if (defined(annotation[axis + prop])) { return true; } } return false; } function getScaleLimits(scale, annotations) { const axis = scale.axis; const scaleID = scale.id; const scaleIDOption = axis + 'ScaleID'; const limits = { min: valueOrDefault(scale.min, Number.NEGATIVE_INFINITY), max: valueOrDefault(scale.max, Number.POSITIVE_INFINITY) }; for (const annotation of annotations) { if (annotation.scaleID === scaleID) { updateLimits(annotation, scale, ['value', 'endValue'], limits); } else if (annotation[scaleIDOption] === scaleID) { updateLimits(annotation, scale, [axis + 'Min', axis + 'Max', axis + 'Value'], limits); } } return limits; } function updateLimits(annotation, scale, props, limits) { for (const prop of props) { const raw = annotation[prop]; if (defined(raw)) { const value = scale.parse(raw); limits.min = Math.min(limits.min, value); limits.max = Math.max(limits.max, value); } } } const clamp = (x, from, to) => Math.min(to, Math.max(from, x)); function clampAll(obj, from, to) { for (const key of Object.keys(obj)) { obj[key] = clamp(obj[key], from, to); } return obj; } function inPointRange(point, center, radius, borderWidth) { if (!point || !center || radius <= 0) { return false; } const hBorderWidth = borderWidth / 2 || 0; return (Math.pow(point.x - center.x, 2) + Math.pow(point.y - center.y, 2)) <= Math.pow(radius + hBorderWidth, 2); } function inBoxRange(mouseX, mouseY, {x, y, width, height}, borderWidth) { const hBorderWidth = borderWidth / 2 || 0; return mouseX >= x - hBorderWidth && mouseX <= x + width + hBorderWidth && mouseY >= y - hBorderWidth && mouseY <= y + height + hBorderWidth; } function getElementCenterPoint(element, useFinalPosition) { const {x, y} = element.getProps(['x', 'y'], useFinalPosition); return {x, y}; } const isOlderPart = (act, req) => req > act || (act.length > req.length && act.substr(0, req.length) === req); function requireVersion(pkg, min, ver, strict = true) { const parts = ver.split('.'); let i = 0; for (const req of min.split('.')) { const act = parts[i++]; if (parseInt(req, 10) < parseInt(act, 10)) { break; } if (isOlderPart(act, req)) { if (strict) { throw new Error(`${pkg} v${ver} is not supported. v${min} or newer is required.`); } else { return false; } } } return true; } const isPercentString = (s) => typeof s === 'string' && s.endsWith('%'); const toPercent = (s) => clamp(parseFloat(s) / 100, 0, 1); function getRelativePosition(size, positionOption) { if (positionOption === 'start') { return 0; } if (positionOption === 'end') { return size; } if (isPercentString(positionOption)) { return toPercent(positionOption) * size; } return size / 2; } function getSize(size, value) { if (typeof value === 'number') { return value; } else if (isPercentString(value)) { return toPercent(value) * size; } return size; } function calculateTextAlignment(size, options) { const {x, width} = size; const textAlign = options.textAlign; if (textAlign === 'center') { return x + width / 2; } else if (textAlign === 'end' || textAlign === 'right') { return x + width; } return x; } function toPosition(value) { if (isObject(value)) { return { x: valueOrDefault(value.x, 'center'), y: valueOrDefault(value.y, 'center'), }; } value = valueOrDefault(value, 'center'); return { x: value, y: value }; } function isBoundToPoint(options) { return options && (defined(options.xValue) || defined(options.yValue)); } const widthCache = new Map(); function isImageOrCanvas(content) { return content instanceof Image || content instanceof HTMLCanvasElement; } /** * Set the translation on the canvas if the rotation must be applied. * @param {CanvasRenderingContext2D} ctx - chart canvas context * @param {Element} element - annotation element to use for applying the translation * @param {number} rotation - rotation (in degrees) to apply */ function translate(ctx, element, rotation) { if (rotation) { const center = element.getCenterPoint(); ctx.translate(center.x, center.y); ctx.rotate(toRadians(rotation)); ctx.translate(-center.x, -center.y); } } /** * Apply border options to the canvas context before drawing a shape * @param {CanvasRenderingContext2D} ctx - chart canvas context * @param {Object} options - options with border configuration * @returns {boolean} true is the border options have been applied */ function setBorderStyle(ctx, options) { if (options && options.borderWidth) { ctx.lineCap = options.borderCapStyle; ctx.setLineDash(options.borderDash); ctx.lineDashOffset = options.borderDashOffset; ctx.lineJoin = options.borderJoinStyle; ctx.lineWidth = options.borderWidth; ctx.strokeStyle = options.borderColor; return true; } } /** * Apply shadow options to the canvas context before drawing a shape * @param {CanvasRenderingContext2D} ctx - chart canvas context * @param {Object} options - options with shadow configuration */ function setShadowStyle(ctx, options) { ctx.shadowColor = options.backgroundShadowColor; ctx.shadowBlur = options.shadowBlur; ctx.shadowOffsetX = options.shadowOffsetX; ctx.shadowOffsetY = options.shadowOffsetY; } /** * Measure the label size using the label options. * @param {CanvasRenderingContext2D} ctx - chart canvas context * @param {Object} options - options to configure the label * @returns {{width: number, height: number}} the measured size of the label */ function measureLabelSize(ctx, options) { const content = options.content; if (isImageOrCanvas(content)) { return { width: getSize(content.width, options.width), height: getSize(content.height, options.height) }; } const font = toFont(options.font); const lines = isArray(content) ? content : [content]; const mapKey = lines.join() + font.string + (ctx._measureText ? '-spriting' : ''); if (!widthCache.has(mapKey)) { ctx.save(); ctx.font = font.string; const count = lines.length; let width = 0; for (let i = 0; i < count; i++) { const text = lines[i]; width = Math.max(width, ctx.measureText(text).width); } ctx.restore(); const height = count * font.lineHeight; widthCache.set(mapKey, {width, height}); } return widthCache.get(mapKey); } /** * Draw a box with the size and the styling options. * @param {CanvasRenderingContext2D} ctx - chart canvas context * @param {{x: number, y: number, width: number, height: number}} rect - rect to draw * @param {Object} options - options to style the box * @returns {undefined} */ function drawBox(ctx, rect, options) { const {x, y, width, height} = rect; ctx.save(); setShadowStyle(ctx, options); const stroke = setBorderStyle(ctx, options); ctx.fillStyle = options.backgroundColor; ctx.beginPath(); addRoundedRectPath(ctx, { x, y, w: width, h: height, // TODO: v2 remove support for cornerRadius radius: clampAll(toTRBLCorners(valueOrDefault(options.cornerRadius, options.borderRadius)), 0, Math.min(width, height) / 2) }); ctx.closePath(); ctx.fill(); if (stroke) { ctx.shadowColor = options.borderShadowColor; ctx.stroke(); } ctx.restore(); } function drawLabel(ctx, rect, options) { const content = options.content; if (isImageOrCanvas(content)) { ctx.drawImage(content, rect.x, rect.y, rect.width, rect.height); return; } const labels = isArray(content) ? content : [content]; const font = toFont(options.font); const lh = font.lineHeight; const x = calculateTextAlignment(rect, options); const y = rect.y + (lh / 2); ctx.font = font.string; ctx.textBaseline = 'middle'; ctx.textAlign = options.textAlign; ctx.fillStyle = options.color; labels.forEach((l, i) => ctx.fillText(l, x, y + (i * lh))); } /** * @typedef {import('chart.js').Point} Point */ /** * @param {{x: number, y: number, width: number, height: number}} rect * @returns {Point} */ function getRectCenterPoint(rect) { const {x, y, width, height} = rect; return { x: x + width / 2, y: y + height / 2 }; } /** * Rotate a `point` relative to `center` point by `angle` * @param {Point} point - the point to rotate * @param {Point} center - center point for rotation * @param {number} angle - angle for rotation, in radians * @returns {Point} rotated point */ function rotated(point, center, angle) { const cos = Math.cos(angle); const sin = Math.sin(angle); const cx = center.x; const cy = center.y; return { x: cx + cos * (point.x - cx) - sin * (point.y - cy), y: cy + sin * (point.x - cx) + cos * (point.y - cy) }; } /** * @typedef { import("chart.js").Chart } Chart * @typedef { import("chart.js").Scale } Scale * @typedef { import("chart.js").Point } Point * @typedef { import('../../types/options').CoreAnnotationOptions } CoreAnnotationOptions * @typedef { import('../../types/options').PointAnnotationOptions } PointAnnotationOptions */ /** * @param {Scale} scale * @param {number|string} value * @param {number} fallback * @returns {number} */ function scaleValue(scale, value, fallback) { value = typeof value === 'number' ? value : scale.parse(value); return isFinite(value) ? scale.getPixelForValue(value) : fallback; } /** * @param {Scale} scale * @param {{start: number, end: number}} options * @returns {{start: number, end: number}} */ function getChartDimensionByScale(scale, options) { if (scale) { const min = scaleValue(scale, options.min, options.start); const max = scaleValue(scale, options.max, options.end); return { start: Math.min(min, max), end: Math.max(min, max) }; } return { start: options.start, end: options.end }; } /** * @param {Chart} chart * @param {CoreAnnotationOptions} options * @returns {Point} */ function getChartPoint(chart, options) { const {chartArea, scales} = chart; const xScale = scales[options.xScaleID]; const yScale = scales[options.yScaleID]; let x = chartArea.width / 2; let y = chartArea.height / 2; if (xScale) { x = scaleValue(xScale, options.xValue, x); } if (yScale) { y = scaleValue(yScale, options.yValue, y); } return {x, y}; } /** * @param {Chart} chart * @param {CoreAnnotationOptions} options * @returns {{x?:number, y?: number, x2?: number, y2?: number, width?: number, height?: number}} */ function getChartRect(chart, options) { const xScale = chart.scales[options.xScaleID]; const yScale = chart.scales[options.yScaleID]; let {top: y, left: x, bottom: y2, right: x2} = chart.chartArea; if (!xScale && !yScale) { return {}; } const xDim = getChartDimensionByScale(xScale, {min: options.xMin, max: options.xMax, start: x, end: x2}); x = xDim.start; x2 = xDim.end; const yDim = getChartDimensionByScale(yScale, {min: options.yMin, max: options.yMax, start: y, end: y2}); y = yDim.start; y2 = yDim.end; return { x, y, x2, y2, width: x2 - x, height: y2 - y }; } /** * @param {Chart} chart * @param {PointAnnotationOptions} options */ function getChartCircle(chart, options) { const point = getChartPoint(chart, options); return { x: point.x + options.xAdjust, y: point.y + options.yAdjust, width: options.radius * 2, height: options.radius * 2 }; } /** * @param {Chart} chart * @param {PointAnnotationOptions} options * @returns */ function resolvePointPosition(chart, options) { if (!isBoundToPoint(options)) { const box = getChartRect(chart, options); const point = getRectCenterPoint(box); let radius = options.radius; if (!radius || isNaN(radius)) { radius = Math.min(box.width, box.height) / 2; options.radius = radius; } return { x: point.x + options.xAdjust, y: point.y + options.yAdjust, width: radius * 2, height: radius * 2 }; } return getChartCircle(chart, options); } class BoxAnnotation extends Element { inRange(mouseX, mouseY, useFinalPosition) { return inBoxRange(mouseX, mouseY, this.getProps(['x', 'y', 'width', 'height'], useFinalPosition), this.options.borderWidth); } getCenterPoint(useFinalPosition) { return getRectCenterPoint(this.getProps(['x', 'y', 'width', 'height'], useFinalPosition)); } draw(ctx) { ctx.save(); drawBox(ctx, this, this.options); ctx.restore(); } drawLabel(ctx) { const {x, y, width, height, options} = this; const {label, borderWidth} = options; const halfBorder = borderWidth / 2; const position = toPosition(label.position); const padding = toPadding(label.padding); const labelSize = measureLabelSize(ctx, label); const labelRect = { x: calculateX(this, labelSize, position, padding), y: calculateY(this, labelSize, position, padding), width: labelSize.width, height: labelSize.height }; ctx.save(); ctx.beginPath(); ctx.rect(x + halfBorder + padding.left, y + halfBorder + padding.top, width - borderWidth - padding.width, height - borderWidth - padding.height); ctx.clip(); drawLabel(ctx, labelRect, label); ctx.restore(); } resolveElementProperties(chart, options) { return getChartRect(chart, options); } } BoxAnnotation.id = 'boxAnnotation'; BoxAnnotation.defaults = { adjustScaleRange: true, backgroundShadowColor: 'transparent', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0, borderJoinStyle: 'miter', borderRadius: 0, borderShadowColor: 'transparent', borderWidth: 1, cornerRadius: undefined, // TODO: v2 remove support for cornerRadius display: true, label: { borderWidth: undefined, color: 'black', content: null, drawTime: undefined, enabled: false, font: { family: undefined, lineHeight: undefined, size: undefined, style: undefined, weight: 'bold' }, height: undefined, padding: 6, position: 'center', textAlign: 'start', xAdjust: 0, yAdjust: 0, width: undefined }, shadowBlur: 0, shadowOffsetX: 0, shadowOffsetY: 0, xMax: undefined, xMin: undefined, xScaleID: 'x', yMax: undefined, yMin: undefined, yScaleID: 'y' }; BoxAnnotation.defaultRoutes = { borderColor: 'color', backgroundColor: 'color' }; BoxAnnotation.descriptors = { label: { _fallback: true } }; function calculateX(box, labelSize, position, padding) { const {x: start, x2: end, width: size, options} = box; const {xAdjust: adjust, borderWidth} = options.label; return calculatePosition$1({start, end, size}, { position: position.x, padding: {start: padding.left, end: padding.right}, adjust, borderWidth, size: labelSize.width }); } function calculateY(box, labelSize, position, padding) { const {y: start, y2: end, height: size, options} = box; const {yAdjust: adjust, borderWidth} = options.label; return calculatePosition$1({start, end, size}, { position: position.y, padding: {start: padding.top, end: padding.bottom}, adjust, borderWidth, size: labelSize.height }); } function calculatePosition$1(boxOpts, labelOpts) { const {start, end} = boxOpts; const {position, padding: {start: padStart, end: padEnd}, adjust, borderWidth} = labelOpts; const availableSize = end - borderWidth - start - padStart - padEnd - labelOpts.size; return start + borderWidth / 2 + adjust + padStart + getRelativePosition(availableSize, position); } const pointInLine = (p1, p2, t) => ({x: p1.x + t * (p2.x - p1.x), y: p1.y + t * (p2.y - p1.y)}); const interpolateX = (y, p1, p2) => pointInLine(p1, p2, Math.abs((y - p1.y) / (p2.y - p1.y))).x; const interpolateY = (x, p1, p2) => pointInLine(p1, p2, Math.abs((x - p1.x) / (p2.x - p1.x))).y; const sqr = v => v * v; const defaultEpsilon = 0.001; function isLineInArea({x, y, x2, y2}, {top, right, bottom, left}) { return !( (x < left && x2 < left) || (x > right && x2 > right) || (y < top && y2 < top) || (y > bottom && y2 > bottom) ); } function limitPointToArea({x, y}, p2, {top, right, bottom, left}) { if (x < left) { y = interpolateY(left, {x, y}, p2); x = left; } if (x > right) { y = interpolateY(right, {x, y}, p2); x = right; } if (y < top) { x = interpolateX(top, {x, y}, p2); y = top; } if (y > bottom) { x = interpolateX(bottom, {x, y}, p2); y = bottom; } return {x, y}; } function limitLineToArea(p1, p2, area) { const {x, y} = limitPointToArea(p1, p2, area); const {x: x2, y: y2} = limitPointToArea(p2, p1, area); return {x, y, x2, y2, width: Math.abs(x2 - x), height: Math.abs(y2 - y)}; } class LineAnnotation extends Element { // TODO: make private in v2 intersects(x, y, epsilon = defaultEpsilon, useFinalPosition) { // Adapted from https://stackoverflow.com/a/6853926/25507 const {x: x1, y: y1, x2, y2} = this.getProps(['x', 'y', 'x2', 'y2'], useFinalPosition); const dx = x2 - x1; const dy = y2 - y1; const lenSq = sqr(dx) + sqr(dy); const t = lenSq === 0 ? -1 : ((x - x1) * dx + (y - y1) * dy) / lenSq; let xx, yy; if (t < 0) { xx = x1; yy = y1; } else if (t > 1) { xx = x2; yy = y2; } else { xx = x1 + t * dx; yy = y1 + t * dy; } return (sqr(x - xx) + sqr(y - yy)) <= epsilon; } /** * @todo make private in v2 * @param {boolean} useFinalPosition - use the element's animation target instead of current position * @param {top, right, bottom, left} [chartArea] - optional, area of the chart * @returns {boolean} true if the label is visible */ labelIsVisible(useFinalPosition, chartArea) { const labelOpts = this.options.label; if (!labelOpts || !labelOpts.enabled) { return false; } return !chartArea || isLineInArea(this.getProps(['x', 'y', 'x2', 'y2'], useFinalPosition), chartArea); } // TODO: make private in v2 isOnLabel(mouseX, mouseY, useFinalPosition) { if (!this.labelIsVisible(useFinalPosition)) { return false; } const {labelX, labelY, labelWidth, labelHeight, labelRotation} = this.getProps(['labelX', 'labelY', 'labelWidth', 'labelHeight', 'labelRotation'], useFinalPosition); const {x, y} = rotated({x: mouseX, y: mouseY}, {x: labelX, y: labelY}, -labelRotation); const hBorderWidth = this.options.label.borderWidth / 2 || 0; const w2 = labelWidth / 2 + hBorderWidth; const h2 = labelHeight / 2 + hBorderWidth; return x >= labelX - w2 - defaultEpsilon && x <= labelX + w2 + defaultEpsilon && y >= labelY - h2 - defaultEpsilon && y <= labelY + h2 + defaultEpsilon; } inRange(mouseX, mouseY, useFinalPosition) { const epsilon = sqr(this.options.borderWidth / 2); return this.intersects(mouseX, mouseY, epsilon, useFinalPosition) || this.isOnLabel(mouseX, mouseY, useFinalPosition); } getCenterPoint() { return { x: (this.x2 + this.x) / 2, y: (this.y2 + this.y) / 2 }; } draw(ctx) { const {x, y, x2, y2, options} = this; ctx.save(); if (!setBorderStyle(ctx, options)) { // no border width, then line is not drawn return ctx.restore(); } setShadowStyle(ctx, options); const angle = Math.atan2(y2 - y, x2 - x); const length = Math.sqrt(Math.pow(x2 - x, 2) + Math.pow(y2 - y, 2)); const {startOpts, endOpts, startAdjust, endAdjust} = getArrowHeads(this); ctx.translate(x, y); ctx.rotate(angle); ctx.beginPath(); ctx.moveTo(0 + startAdjust, 0); ctx.lineTo(length - endAdjust, 0); ctx.shadowColor = options.borderShadowColor; ctx.stroke(); drawArrowHead(ctx, 0, startAdjust, startOpts); drawArrowHead(ctx, length, -endAdjust, endOpts); ctx.restore(); } drawLabel(ctx, chartArea) { if (!this.labelIsVisible(false, chartArea)) { return; } const {labelX, labelY, labelWidth, labelHeight, labelRotation, labelPadding, labelTextSize, options: {label}} = this; ctx.save(); ctx.translate(labelX, labelY); ctx.rotate(labelRotation); const boxRect = { x: -(labelWidth / 2), y: -(labelHeight / 2), width: labelWidth, height: labelHeight }; drawBox(ctx, boxRect, label); const labelTextRect = { x: -(labelWidth / 2) + labelPadding.left + label.borderWidth / 2, y: -(labelHeight / 2) + labelPadding.top + label.borderWidth / 2, width: labelTextSize.width, height: labelTextSize.height }; drawLabel(ctx, labelTextRect, label); ctx.restore(); } resolveElementProperties(chart, options) { const scale = chart.scales[options.scaleID]; let {top: y, left: x, bottom: y2, right: x2} = chart.chartArea; let min, max; if (scale) { min = scaleValue(scale, options.value, NaN); max = scaleValue(scale, options.endValue, min); if (scale.isHorizontal()) { x = min; x2 = max; } else { y = min; y2 = max; } } else { const xScale = chart.scales[options.xScaleID]; const yScale = chart.scales[options.yScaleID]; if (xScale) { x = scaleValue(xScale, options.xMin, x); x2 = scaleValue(xScale, options.xMax, x2); } if (yScale) { y = scaleValue(yScale, options.yMin, y); y2 = scaleValue(yScale, options.yMax, y2); } } const inside = isLineInArea({x, y, x2, y2}, chart.chartArea); const properties = inside ? limitLineToArea({x, y}, {x: x2, y: y2}, chart.chartArea) : {x, y, x2, y2, width: Math.abs(x2 - x), height: Math.abs(y2 - y)}; const label = options.label; if (label && label.content) { return loadLabelRect(properties, chart, label); } return properties; } } LineAnnotation.id = 'lineAnnotation'; const arrowHeadsDefaults = { backgroundColor: undefined, backgroundShadowColor: undefined, borderColor: undefined, borderDash: undefined, borderDashOffset: undefined, borderShadowColor: undefined, borderWidth: undefined, enabled: undefined, fill: undefined, length: undefined, shadowBlur: undefined, shadowOffsetX: undefined, shadowOffsetY: undefined, width: undefined }; LineAnnotation.defaults = { adjustScaleRange: true, arrowHeads: { enabled: false, end: Object.assign({}, arrowHeadsDefaults), fill: false, length: 12, start: Object.assign({}, arrowHeadsDefaults), width: 6 }, borderDash: [], borderDashOffset: 0, borderShadowColor: 'transparent', borderWidth: 2, display: true, endValue: undefined, label: { backgroundColor: 'rgba(0,0,0,0.8)', backgroundShadowColor: 'transparent', borderCapStyle: 'butt', borderColor: 'black', borderDash: [], borderDashOffset: 0, borderJoinStyle: 'miter', borderRadius: 6, borderShadowColor: 'transparent', borderWidth: 0, color: '#fff', content: null, cornerRadius: undefined, // TODO: v2 remove support for cornerRadius drawTime: undefined, enabled: false, font: { family: undefined, lineHeight: undefined, size: undefined, style: undefined, weight: 'bold' }, height: undefined, padding: 6, position: 'center', rotation: 0, shadowBlur: 0, shadowOffsetX: 0, shadowOffsetY: 0, textAlign: 'center', width: undefined, xAdjust: 0, xPadding: undefined, // TODO: v2 remove support for xPadding yAdjust: 0, yPadding: undefined, // TODO: v2 remove support for yPadding }, scaleID: undefined, shadowBlur: 0, shadowOffsetX: 0, shadowOffsetY: 0, value: undefined, xMax: undefined, xMin: undefined, xScaleID: 'x', yMax: undefined, yMin: undefined, yScaleID: 'y' }; LineAnnotation.descriptors = { arrowHeads: { start: { _fallback: true }, end: { _fallback: true }, _fallback: true } }; LineAnnotation.defaultRoutes = { borderColor: 'color' }; function loadLabelRect(line, chart, options) { // TODO: v2 remove support for xPadding and yPadding const {padding: lblPadding, xPadding, yPadding, borderWidth} = options; const padding = getPadding(lblPadding, xPadding, yPadding); const textSize = measureLabelSize(chart.ctx, options); const width = textSize.width + padding.width + borderWidth; const height = textSize.height + padding.height + borderWidth; const labelRect = calculateLabelPosition(line, options, {width, height, padding}, chart.chartArea); line.labelX = labelRect.x; line.labelY = labelRect.y; line.labelWidth = labelRect.width; line.labelHeight = labelRect.height; line.labelRotation = labelRect.rotation; line.labelPadding = padding; line.labelTextSize = textSize; return line; } function calculateAutoRotation(line) { const {x, y, x2, y2} = line; const rotation = Math.atan2(y2 - y, x2 - x); // Flip the rotation if it goes > PI/2 or < -PI/2, so label stays upright return rotation > PI / 2 ? rotation - PI : rotation < PI / -2 ? rotation + PI : rotation; } // TODO: v2 remove support for xPadding and yPadding function getPadding(padding, xPadding, yPadding) { let tempPadding = padding; if (xPadding || yPadding) { tempPadding = {x: xPadding || 6, y: yPadding || 6}; } return toPadding(tempPadding); } function calculateLabelPosition(line, label, sizes, chartArea) { const {width, height, padding} = sizes; const {xAdjust, yAdjust} = label; const p1 = {x: line.x, y: line.y}; const p2 = {x: line.x2, y: line.y2}; const rotation = label.rotation === 'auto' ? calculateAutoRotation(line) : toRadians(label.rotation); const size = rotatedSize(width, height, rotation); const t = calculateT(line, label, {labelSize: size, padding}, chartArea); const pt = pointInLine(p1, p2, t); const xCoordinateSizes = {size: size.w, min: chartArea.left, max: chartArea.right, padding: padding.left}; const yCoordinateSizes = {size: size.h, min: chartArea.top, max: chartArea.bottom, padding: padding.top}; return { x: adjustLabelCoordinate(pt.x, xCoordinateSizes) + xAdjust, y: adjustLabelCoordinate(pt.y, yCoordinateSizes) + yAdjust, width, height, rotation }; } function rotatedSize(width, height, rotation) { const cos = Math.cos(rotation); const sin = Math.sin(rotation); return { w: Math.abs(width * cos) + Math.abs(height * sin), h: Math.abs(width * sin) + Math.abs(height * cos) }; } function calculateT(line, label, sizes, chartArea) { let t; const space = spaceAround(line, chartArea); if (label.position === 'start') { t = calculateTAdjust({w: line.x2 - line.x, h: line.y2 - line.y}, sizes, label, space); } else if (label.position === 'end') { t = 1 - calculateTAdjust({w: line.x - line.x2, h: line.y - line.y2}, sizes, label, space); } else { t = getRelativePosition(1, label.position); } return t; } function calculateTAdjust(lineSize, sizes, label, space) { const {labelSize, padding} = sizes; const lineW = lineSize.w * space.dx; const lineH = lineSize.h * space.dy; const x = (lineW > 0) && ((labelSize.w / 2 + padding.left - space.x) / lineW); const y = (lineH > 0) && ((labelSize.h / 2 + padding.top - space.y) / lineH); return clamp(Math.max(x, y), 0, 0.25); } function spaceAround(line, chartArea) { const {x, x2, y, y2} = line; const t = Math.min(y, y2) - chartArea.top; const l = Math.min(x, x2) - chartArea.left; const b = chartArea.bottom - Math.max(y, y2); const r = chartArea.right - Math.max(x, x2); return { x: Math.min(l, r), y: Math.min(t, b), dx: l <= r ? 1 : -1, dy: t <= b ? 1 : -1 }; } function adjustLabelCoordinate(coordinate, labelSizes) { const {size, min, max, padding} = labelSizes; const halfSize = size / 2; if (size > max - min) { // if it does not fit, display as much as possible return (max + min) / 2; } if (min >= (coordinate - padding - halfSize)) { coordinate = min + padding + halfSize; } if (max <= (coordinate + padding + halfSize)) { coordinate = max - padding - halfSize; } return coordinate; } function getArrowHeads(line) { const options = line.options; const arrowStartOpts = options.arrowHeads && options.arrowHeads.start; const arrowEndOpts = options.arrowHeads && options.arrowHeads.end; return { startOpts: arrowStartOpts, endOpts: arrowEndOpts, startAdjust: getLineAdjust(line, arrowStartOpts), endAdjust: getLineAdjust(line, arrowEndOpts) }; } function getLineAdjust(line, arrowOpts) { if (!arrowOpts || !arrowOpts.enabled) { return 0; } const {length, width} = arrowOpts; const adjust = line.options.borderWidth / 2; const p1 = {x: length, y: width + adjust}; const p2 = {x: 0, y: adjust}; return Math.abs(interpolateX(0, p1, p2)); } function drawArrowHead(ctx, offset, adjust, arrowOpts) { if (!arrowOpts || !arrowOpts.enabled) { return; } const {length, width, fill, backgroundColor, borderColor} = arrowOpts; const arrowOffsetX = Math.abs(offset - length) + adjust; ctx.beginPath(); setShadowStyle(ctx, arrowOpts); setBorderStyle(ctx, arrowOpts); ctx.moveTo(arrowOffsetX, -width); ctx.lineTo(offset + adjust, 0); ctx.lineTo(arrowOffsetX, width); if (fill === true) { ctx.fillStyle = backgroundColor || borderColor; ctx.closePath(); ctx.fill(); ctx.shadowColor = 'transparent'; } else { ctx.shadowColor = arrowOpts.borderShadowColor; } ctx.stroke(); } class EllipseAnnotation extends Element { inRange(mouseX, mouseY, useFinalPosition) { return pointInEllipse({x: mouseX, y: mouseY}, this.getProps(['width', 'height'], useFinalPosition), this.options.rotation, this.options.borderWidth); } getCenterPoint(useFinalPosition) { return getRectCenterPoint(this.getProps(['x', 'y', 'width', 'height'], useFinalPosition)); } draw(ctx) { const {width, height, options} = this; const center = this.getCenterPoint(); ctx.save(); translate(ctx, this, options.rotation); setShadowStyle(ctx, this.options); ctx.beginPath(); ctx.fillStyle = options.backgroundColor; const stroke = setBorderStyle(ctx, options); ctx.ellipse(center.x, center.y, height / 2, width / 2, PI / 2, 0, 2 * PI); ctx.fill(); if (stroke) { ctx.shadowColor = options.borderShadowColor; ctx.stroke(); } ctx.restore(); } resolveElementProperties(chart, options) { return getChartRect(chart, options); } } EllipseAnnotation.id = 'ellipseAnnotation'; EllipseAnnotation.defaults = { adjustScaleRange: true, backgroundShadowColor: 'transparent', borderDash: [], borderDashOffset: 0, borderShadowColor: 'transparent', borderWidth: 1, display: true, rotation: 0, shadowBlur: 0, shadowOffsetX: 0, shadowOffsetY: 0, xMax: undefined, xMin: undefined, xScaleID: 'x', yMax: undefined, yMin: undefined, yScaleID: 'y' }; EllipseAnnotation.defaultRoutes = { borderColor: 'color', backgroundColor: 'color' }; function pointInEllipse(p, ellipse, rotation, borderWidth) { const {width, height} = ellipse; const center = ellipse.getCenterPoint(true); const xRadius = width / 2; const yRadius = height / 2; if (xRadius <= 0 || yRadius <= 0) { return false; } // https://stackoverflow.com/questions/7946187/point-and-ellipse-rotated-position-test-algorithm const angle = toRadians(rotation || 0); const hBorderWidth = borderWidth / 2 || 0; const cosAngle = Math.cos(angle); const sinAngle = Math.sin(angle); const a = Math.pow(cosAngle * (p.x - center.x) + sinAngle * (p.y - center.y), 2); const b = Math.pow(sinAngle * (p.x - center.x) - cosAngle * (p.y - center.y), 2); return (a / Math.pow(xRadius + hBorderWidth, 2)) + (b / Math.pow(yRadius + hBorderWidth, 2)) <= 1.0001; } class LabelAnnotation extends Element { inRange(mouseX, mouseY, useFinalPosition) { return inBoxRange(mouseX, mouseY, this.getProps(['x', 'y', 'width', 'height'], useFinalPosition), this.options.borderWidth); } getCenterPoint(useFinalPosition) { return getRectCenterPoint(this.getProps(['x', 'y', 'width', 'height'], useFinalPosition)); } draw(ctx) { if (!this.options.content) { return; } const {labelX, labelY, labelWidth, labelHeight, options} = this; drawCallout(ctx, this); drawBox(ctx, this, options); drawLabel(ctx, {x: labelX, y: labelY, width: labelWidth, height: labelHeight}, options); } // TODO: make private in v2 resolveElementProperties(chart, options) { const point = !isBoundToPoint(options) ? getRectCenterPoint(getChartRect(chart, options)) : getChartPoint(chart, options); const padding = toPadding(options.padding); const labelSize = measureLabelSize(chart.ctx, options); const boxSize = measureRect(point, labelSize, options, padding); const hBorderWidth = options.borderWidth / 2; const properties = { pointX: point.x, pointY: point.y, ...boxSize, labelX: boxSize.x + padding.left + hBorderWidth, labelY: boxSize.y + padding.top + hBorderWidth, labelWidth: labelSize.width, labelHeight: labelSize.height }; properties.calloutPosition = options.callout.enabled && resolveCalloutPosition(properties, options.callout); return properties; } } LabelAnnotation.id = 'labelAnnotation'; LabelAnnotation.defaults = { adjustScaleRange: true, backgroundColor: 'transparent', backgroundShadowColor: 'transparent', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0, borderJoinStyle: 'miter', borderRadius: 0, borderShadowColor: 'transparent', borderWidth: 0, callout: { borderCapStyle: 'butt', borderColor: undefined, borderDash: [], borderDashOffset: 0, borderJoinStyle: 'miter', borderWidth: 1, enabled: false, margin: 5, position: 'auto', side: 5, start: '50%', }, color: 'black', content: null, display: true, font: { family: undefined, lineHeight: undefined, size: undefined, style: undefined, weight: undefined }, height: undefined, padding: 6, position: 'center', shadowBlur: 0, shadowOffsetX: 0, shadowOffsetY: 0, textAlign: 'center', width: undefined, xAdjust: 0, xMax: undefined, xMin: undefined, xScaleID: 'x', xValue: undefined, yAdjust: 0, yMax: undefined, yMin: undefined, yScaleID: 'y', yValue: undefined }; LabelAnnotation.defaultRoutes = { borderColor: 'color' }; function measureRect(point, size, options, padding) { const width = size.width + padding.width + options.borderWidth; const height = size.height + padding.height + options.borderWidth; const position = toPosition(options.position); return { x: calculatePosition(point.x, width, options.xAdjust, position.x), y: calculatePosition(point.y, height, options.yAdjust, position.y), width, height }; } function calculatePosition(start, size, adjust = 0, position) { return start - getRelativePosition(size, position) + adjust; } function drawCallout(ctx, element) { const {pointX, pointY, calloutPosition, options} = element; if (!calloutPosition) { return; } const callout = options.callout; ctx.save(); ctx.beginPath(); const stroke = setBorderStyle(ctx, callout); if (!stroke) { return ctx.restore(); } const {separatorStart, separatorEnd} = getCalloutSeparatorCoord(element, calloutPosition); const {sideStart, sideEnd} = getCalloutSideCoord(element, calloutPosition, separatorStart); if (callout.margin > 0 || options.borderWidth === 0) { ctx.moveTo(separatorStart.x, separatorStart.y); ctx.lineTo(separatorEnd.x, separatorEnd.y); } ctx.moveTo(sideStart.x, sideStart.y); ctx.lineTo(sideEnd.x, sideEnd.y); ctx.lineTo(pointX, pointY); ctx.stroke(); ctx.restore(); } function getCalloutSeparatorCoord(element, position) { const {x, y, width, height} = element; const adjust = getCalloutSeparatorAdjust(element, position); let separatorStart, separatorEnd; if (position === 'left' || position === 'right') { separatorStart = {x: x + adjust, y}; separatorEnd = {x: separatorStart.x, y: separatorStart.y + height}; } else { // position 'top' or 'bottom' separatorStart = {x, y: y + adjust}; separatorEnd = {x: separatorStart.x + width, y: separatorStart.y}; } return {separatorStart, separatorEnd}; } function getCalloutSeparatorAdjust(element, position) { const {width, height, options} = element; const adjust = options.callout.margin + options.borderWidth / 2; if (position === 'right') { return width + adjust; } else if (position === 'bottom') { return height + adjust; } return -adjust; } function getCalloutSideCoord(element, position, separatorStart) { const {y, width, height, options} = element; const start = options.callout.start; const side = getCalloutSideAdjust(position, options.callout); let sideStart, sideEnd; if (position === 'left' || position === 'right') { sideStart = {x: separatorStart.x, y: y + getSize(height, start)}; sideEnd = {x: sideStart.x + side, y: sideStart.y}; } else { // position 'top' or 'bottom' sideStart = {x: separatorStart.x + getSize(width, start), y: separatorStart.y}; sideEnd = {x: sideStart.x, y: sideStart.y + side}; } return {sideStart, sideEnd}; } function getCalloutSideAdjust(position, options) { const side = options.side; if (position === 'left' || position === 'top') { return -side; } return side; } function resolveCalloutPosition(element, options) { const position = options.position; if (position === 'left' || position === 'right' || position === 'top' || position === 'bottom') { return position; } return resolveCalloutAutoPosition(element, options); } function resolveCalloutAutoPosition(element, options) { const {x, y, width, height, pointX, pointY} = element; const {margin, side} = options; const adjust = margin + side; if (pointX < (x - adjust)) { return 'left'; } else if (pointX > (x + width + adjust)) { return 'right'; } else if (pointY < (y - adjust)) { return 'top'; } else if (pointY > (y + height + adjust)) { return 'bottom'; } } class PointAnnotation extends Element { inRange(mouseX, mouseY, useFinalPosition) { const {width} = this.getProps(['width'], useFinalPosition); return inPointRange({x: mouseX, y: mouseY}, this.getCenterPoint(useFinalPosition), width / 2, this.options.borderWidth); } getCenterPoint(useFinalPosition) { return getElementCenterPoint(this, useFinalPosition); } draw(ctx) { const options = this.options; const borderWidth = options.borderWidth; if (options.radius < 0.1) { return; } ctx.save(); ctx.fillStyle = options.backgroundColor; setShadowStyle(ctx, options); const stroke = setBorderStyle(ctx, options); options.borderWidth = 0; drawPoint(ctx, options, this.x, this.y); if (stroke && !isImageOrCanvas(options.pointStyle)) { ctx.shadowColor = options.borderShadowColor; ctx.stroke(); } ctx.restore(); options.borderWidth = borderWidth; } resolveElementProperties(chart, options) { return resolvePointPosition(chart, options); } } PointAnnotation.id = 'pointAnnotation'; PointAnnotation.defaults = { adjustScaleRange: true, backgroundShadowColor: 'transparent', borderDash: [], borderDashOffset: 0, borderShadowColor: 'transparent', borderWidth: 1, display: true, pointStyle: 'circle', radius: 10, rotation: 0, shadowBlur: 0, shadowOffsetX: 0, shadowOffsetY: 0, xAdjust: 0, xMax: undefined, xMin: undefined, xScaleID: 'x', xValue: undefined, yAdjust: 0, yMax: undefined, yMin: undefined, yScaleID: 'y', yValue: undefined }; PointAnnotation.defaultRoutes = { borderColor: 'color', backgroundColor: 'color' }; class PolygonAnnotation extends Element { inRange(mouseX, mouseY, useFinalPosition) { return this.options.radius >= 0.1 && this.elements.length > 1 && pointIsInPolygon(this.elements, mouseX, mouseY, useFinalPosition); } getCenterPoint(useFinalPosition) { return getElementCenterPoint(this, useFinalPosition); } draw(ctx) { const {elements, options} = this; ctx.save(); ctx.beginPath(); ctx.fillStyle = options.backgroundColor; setShadowStyle(ctx, options); const stroke = setBorderStyle(ctx, options); let first = true; for (const el of elements) { if (first) { ctx.moveTo(el.x, el.y); first = false; } else { ctx.lineTo(el.x, el.y); } } ctx.closePath(); ctx.fill(); // If no border, don't draw it if (stroke) { ctx.shadowColor = options.borderShadowColor; ctx.stroke(); } ctx.restore(); } resolveElementProperties(chart, options) { const {x, y, width, height} = resolvePointPosition(chart, options); const {sides, radius, rotation, borderWidth} = options; const halfBorder = borderWidth / 2; const elements = []; const angle = (2 * PI) / sides; let rad = rotation * RAD_PER_DEG; for (let i = 0; i < sides; i++, rad += angle) { const sin = Math.sin(rad); const cos = Math.cos(rad); elements.push({ type: 'point', optionScope: 'point', properties: { x: x + sin * radius, y: y - cos * radius, bX: x + sin * (radius + halfBorder), bY: y - cos * (radius + halfBorder) } }); } return {x, y, width, height, elements, initProperties: {x, y}}; } } PolygonAnnotation.id = 'polygonAnnotation'; PolygonAnnotation.defaults = { adjustScaleRange: true, backgroundShadowColor: 'transparent', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0, borderJoinStyle: 'miter', borderShadowColor: 'transparent', borderWidth: 1, display: true, point: { radius: 0 }, radius: 10, rotation: 0, shadowBlur: 0, shadowOffsetX: 0, shadowOffsetY: 0, sides: 3, xAdjust: 0, xMax: undefined, xMin: undefined, xScaleID: 'x', xValue: undefined, yAdjust: 0, yMax: undefined, yMin: undefined, yScaleID: 'y', yValue: undefined }; PolygonAnnotation.defaultRoutes = { borderColor: 'color', backgroundColor: 'color' }; function pointIsInPolygon(points, x, y, useFinalPosition) { let isInside = false; let A = points[points.length - 1].getProps(['bX', 'bY'], useFinalPosition); for (const point of points) { const B = point.getProps(['bX', 'bY'], useFinalPosition); if ((B.bY > y) !== (A.bY > y) && x < (A.bX - B.bX) * (y - B.bY) / (A.bY - B.bY) + B.bX) { isInside = !isInside; } A = B; } return isInside; } const annotationTypes = { box: BoxAnnotation, ellipse: EllipseAnnotation, label: LabelAnnotation, line: LineAnnotation, point: PointAnnotation, polygon: PolygonAnnotation }; /** * Register fallback for annotation elements * For example lineAnnotation options would be looked through: * - the annotation object (options.plugins.annotation.annotations[id]) * - element options (options.elements.lineAnnotation) * - element defaults (defaults.elements.lineAnnotation) * - annotation plugin defaults (defaults.plugins.annotation, this is what we are registering here) */ Object.keys(annotationTypes).forEach(key => { defaults.describe(`elements.${annotationTypes[key].id}`, { _fallback: 'plugins.annotation' }); }); var name = "chartjs-plugin-annotation"; var version = "1.3.1"; const chartStates = new Map(); var annotation = { id: 'annotation', version, /* TODO: enable in v2 beforeRegister() { requireVersion('chart.js', '3.7', Chart.version); }, */ afterRegister() { Chart.register(annotationTypes); // TODO: Remove this check, warning and workaround in v2 if (!requireVersion('chart.js', '3.7', Chart.version, false)) { console.warn(`${name} has known issues with chart.js versions prior to 3.7, please consider upgrading.`); // Workaround for https://github.com/chartjs/chartjs-plugin-annotation/issues/572 Chart.defaults.set('elements.lineAnnotation', { callout: {}, font: {}, padding: 6 }); } }, afterUnregister() { Chart.unregister(annotationTypes); }, beforeInit(chart) { chartStates.set(chart, { annotations: [], elements: [], visibleElements: [], listeners: {}, listened: false, moveListened: false }); }, beforeUpdate(chart, args, options) { const state = chartStates.get(chart); const annotations = state.annotations = []; let annotationOptions = options.annotations; if (isObject(annotationOptions)) { Object.keys(annotationOptions).forEach(key => { const value = annotationOptions[key]; if (isObject(value)) { value.id = key; annotations.push(value); } }); } else if (isArray(annotationOptions)) { annotations.push(...annotationOptions); } verifyScaleOptions(annotations, chart.scales); }, afterDataLimits(chart, args) { const state = chartStates.get(chart); adjustScaleRange(chart, args.scale, state.annotations.filter(a => a.display && a.adjustScaleRange)); }, afterUpdate(chart, args, options) { const state = chartStates.get(chart); updateListeners(chart, state, options); updateElements(chart, state, options, args.mode); state.visibleElements = state.elements.filter(el => !el.skip && el.options.display); }, beforeDatasetsDraw(chart, _args, options) { draw(chart, 'beforeDatasetsDraw', options.clip); }, afterDatasetsDraw(chart, _args, options) { draw(chart, 'afterDatasetsDraw', options.clip); }, beforeDraw(chart, _args, options) { draw(chart, 'beforeDraw', options.clip); }, afterDraw(chart, _args, options) { draw(chart, 'afterDraw', options.clip); }, beforeEvent(chart, args, options) { const state = chartStates.get(chart); handleEvent(state, args.event, options); }, destroy(chart) { chartStates.delete(chart); }, _getState(chart) { return chartStates.get(chart); }, defaults: { animations: { numbers: { properties: ['x', 'y', 'x2', 'y2', 'width', 'height', 'pointX', 'pointY', 'labelX', 'labelY', 'labelWidth', 'labelHeight', 'radius'], type: 'number' }, }, clip: true, dblClickSpeed: 350, // ms drawTime: 'afterDatasetsDraw', label: { drawTime: null } }, descriptors: { _indexable: false, _scriptable: (prop) => !hooks.includes(prop), annotations: { _allKeys: false, _fallback: (prop, opts) => `elements.${annotationTypes[resolveType(opts.type)].id}`, }, }, additionalOptionScopes: [''] }; const directUpdater = { update: Object.assign }; function resolveAnimations(chart, animOpts, mode) { if (mode === 'reset' || mode === 'none' || mode === 'resize') { return directUpdater; } return new Animations(chart, animOpts); } function resolveType(type = 'line') { if (annotationTypes[type]) { return type; } console.warn(`Unknown annotation type: '${type}', defaulting to 'line'`); return 'line'; } function updateElements(chart, state, options, mode) { const animations = resolveAnimations(chart, options.animations, mode); const annotations = state.annotations; const elements = resyncElements(state.elements, annotations); for (let i = 0; i < annotations.length; i++) { const annotationOptions = annotations[i]; const element = getOrCreateElement(elements, i, annotationOptions.type); const resolver = annotationOptions.setContext(getContext(chart, element, annotationOptions)); const properties = element.resolveElementProperties(chart, resolver); properties.skip = isNaN(properties.x) || isNaN(properties.y); if ('elements' in properties) { updateSubElements(element, properties, resolver, animations); // Remove the sub-element definitions from properties, so the actual elements // are not overwritten by their definitions delete properties.elements; } if (!defined(element.x)) { // If the element is newly created, assing the properties directly - to // make them readily awailable to any scriptable options. If we do not do this, // the properties retruned by `resolveElementProperties` are available only // after options resolution. Object.assign(element, properties); } properties.options = resolveAnnotationOptions(resolver); animations.update(element, properties); } } function updateSubElements(mainElement, {elements, initProperties}, resolver, animations) { const subElements = mainElement.elements || (mainElement.elements = []); subElements.length = elements.length; for (let i = 0; i < elements.length; i++) { const definition = elements[i]; const properties = definition.properties; const subElement = getOrCreateElement(subElements, i, definition.type, initProperties); const subResolver = resolver[definition.optionScope].override(definition); properties.options = resolveAnnotationOptions(subResolver); animations.update(subElement, properties); } } function getOrCreateElement(elements, index, type, initProperties) { const elementClass = annotationTypes[resolveType(type)]; let element = elements[index]; if (!element || !(element instanceof elementClass)) { element = elements[index] = new elementClass(); if (isObject(initProperties)) { Object.assign(element, initProperties); } } return element; } function resolveAnnotationOptions(resolver) { const elementClass = annotationTypes[resolveType(resolver.type)]; const result = {}; result.id = resolver.id; result.type = resolver.type; result.drawTime = resolver.drawTime; Object.assign(result, resolveObj(resolver, elementClass.defaults), resolveObj(resolver, elementClass.defaultRoutes)); for (const hook of hooks) { result[hook] = resolver[hook]; } return result; } function resolveObj(resolver, defs) { const result = {}; for (const prop of Object.keys(defs)) { const optDefs = defs[prop]; const value = resolver[prop]; result[prop] = isObject(optDefs) ? resolveObj(value, optDefs) : value; } return result; } function getContext(chart, element, annotation) { return element.$context || (element.$context = Object.assign(Object.create(chart.getContext()), { element, id: annotation.id, type: 'annotation' })); } function resyncElements(elements, annotations) { const count = annotations.length; const start = elements.length; if (start < count) { const add = count - start; elements.splice(start, 0, ...new Array(add)); } else if (start > count) { elements.splice(count, start - count); } return elements; } function draw(chart, caller, clip) { const {ctx, chartArea} = chart; const {visibleElements} = chartStates.get(chart); if (clip) { clipArea(ctx, chartArea); } drawElements(ctx, visibleElements, caller); drawSubElements(ctx, visibleElements, caller); if (clip) { unclipArea(ctx); } visibleElements.forEach(el => { if (!('drawLabel' in el)) { return; } const label = el.options.label; if (label && label.enabled && label.content && (label.drawTime || el.options.drawTime) === caller) { el.drawLabel(ctx, chartArea); } }); } function drawElements(ctx, elements, caller) { for (const el of elements) { if (el.options.drawTime === caller) { el.draw(ctx); } } } function drawSubElements(ctx, elements, caller) { for (const el of elements) { if (isArray(el.elements)) { drawElements(ctx, el.elements, caller); } } } export { annotation as default };
cdnjs/cdnjs
ajax/libs/chartjs-plugin-annotation/1.3.1/chartjs-plugin-annotation.esm.js
JavaScript
mit
57,862
/** * @license Highstock JS v8.0.2 (2020-03-03) * * Indicator series type for Highstock * * (c) 2010-2019 Paweł Fus * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/indicators/bollinger-bands', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'mixins/multipe-lines.js', [_modules['parts/Globals.js'], _modules['parts/Utilities.js']], function (H, U) { /** * * (c) 2010-2020 Wojciech Chmiel * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var defined = U.defined, error = U.error, merge = U.merge; var each = H.each, SMA = H.seriesTypes.sma; /** * Mixin useful for all indicators that have more than one line. * Merge it with your implementation where you will provide * getValues method appropriate to your indicator and pointArrayMap, * pointValKey, linesApiNames properites. Notice that pointArrayMap * should be consistent with amount of lines calculated in getValues method. * * @private * @mixin multipleLinesMixin */ var multipleLinesMixin = { /* eslint-disable valid-jsdoc */ /** * Lines ids. Required to plot appropriate amount of lines. * Notice that pointArrayMap should have more elements than * linesApiNames, because it contains main line and additional lines ids. * Also it should be consistent with amount of lines calculated in * getValues method from your implementation. * * @private * @name multipleLinesMixin.pointArrayMap * @type {Array<string>} */ pointArrayMap: ['top', 'bottom'], /** * Main line id. * * @private * @name multipleLinesMixin.pointValKey * @type {string} */ pointValKey: 'top', /** * Additional lines DOCS names. Elements of linesApiNames array should * be consistent with DOCS line names defined in your implementation. * Notice that linesApiNames should have decreased amount of elements * relative to pointArrayMap (without pointValKey). * * @private * @name multipleLinesMixin.linesApiNames * @type {Array<string>} */ linesApiNames: ['bottomLine'], /** * Create translatedLines Collection based on pointArrayMap. * * @private * @function multipleLinesMixin.getTranslatedLinesNames * @param {string} [excludedValue] * Main line id * @return {Array<string>} * Returns translated lines names without excluded value. */ getTranslatedLinesNames: function (excludedValue) { var translatedLines = []; each(this.pointArrayMap, function (propertyName) { if (propertyName !== excludedValue) { translatedLines.push('plot' + propertyName.charAt(0).toUpperCase() + propertyName.slice(1)); } }); return translatedLines; }, /** * @private * @function multipleLinesMixin.toYData * @param {Highcharts.Point} point * Indicator point * @return {Array<number>} * Returns point Y value for all lines */ toYData: function (point) { var pointColl = []; each(this.pointArrayMap, function (propertyName) { pointColl.push(point[propertyName]); }); return pointColl; }, /** * Add lines plot pixel values. * * @private * @function multipleLinesMixin.translate * @return {void} */ translate: function () { var indicator = this, pointArrayMap = indicator.pointArrayMap, LinesNames = [], value; LinesNames = indicator.getTranslatedLinesNames(); SMA.prototype.translate.apply(indicator, arguments); each(indicator.points, function (point) { each(pointArrayMap, function (propertyName, i) { value = point[propertyName]; if (value !== null) { point[LinesNames[i]] = indicator.yAxis.toPixels(value, true); } }); }); }, /** * Draw main and additional lines. * * @private * @function multipleLinesMixin.drawGraph * @return {void} */ drawGraph: function () { var indicator = this, pointValKey = indicator.pointValKey, linesApiNames = indicator.linesApiNames, mainLinePoints = indicator.points, pointsLength = mainLinePoints.length, mainLineOptions = indicator.options, mainLinePath = indicator.graph, gappedExtend = { options: { gapSize: mainLineOptions.gapSize } }, // additional lines point place holders: secondaryLines = [], secondaryLinesNames = indicator.getTranslatedLinesNames(pointValKey), point; // Generate points for additional lines: each(secondaryLinesNames, function (plotLine, index) { // create additional lines point place holders secondaryLines[index] = []; while (pointsLength--) { point = mainLinePoints[pointsLength]; secondaryLines[index].push({ x: point.x, plotX: point.plotX, plotY: point[plotLine], isNull: !defined(point[plotLine]) }); } pointsLength = mainLinePoints.length; }); // Modify options and generate additional lines: each(linesApiNames, function (lineName, i) { if (secondaryLines[i]) { indicator.points = secondaryLines[i]; if (mainLineOptions[lineName]) { indicator.options = merge(mainLineOptions[lineName].styles, gappedExtend); } else { error('Error: "There is no ' + lineName + ' in DOCS options declared. Check if linesApiNames' + ' are consistent with your DOCS line names."' + ' at mixin/multiple-line.js:34'); } indicator.graph = indicator['graph' + lineName]; SMA.prototype.drawGraph.call(indicator); // Now save lines: indicator['graph' + lineName] = indicator.graph; } else { error('Error: "' + lineName + ' doesn\'t have equivalent ' + 'in pointArrayMap. To many elements in linesApiNames ' + 'relative to pointArrayMap."'); } }); // Restore options and draw a main line: indicator.points = mainLinePoints; indicator.options = mainLineOptions; indicator.graph = mainLinePath; SMA.prototype.drawGraph.call(indicator); } }; return multipleLinesMixin; }); _registerModule(_modules, 'indicators/bollinger-bands.src.js', [_modules['parts/Globals.js'], _modules['parts/Utilities.js'], _modules['mixins/multipe-lines.js']], function (H, U, multipleLinesMixin) { /** * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var isArray = U.isArray, merge = U.merge, seriesType = U.seriesType; var SMA = H.seriesTypes.sma; /* eslint-disable valid-jsdoc */ // Utils: /** * @private */ function getStandardDeviation(arr, index, isOHLC, mean) { var variance = 0, arrLen = arr.length, std = 0, i = 0, value; for (; i < arrLen; i++) { value = (isOHLC ? arr[i][index] : arr[i]) - mean; variance += value * value; } variance = variance / (arrLen - 1); std = Math.sqrt(variance); return std; } /* eslint-enable valid-jsdoc */ /** * Bollinger Bands series type. * * @private * @class * @name Highcharts.seriesTypes.bb * * @augments Highcharts.Series */ seriesType('bb', 'sma', /** * Bollinger bands (BB). This series requires the `linkedTo` option to be * set and should be loaded after the `stock/indicators/indicators.js` file. * * @sample stock/indicators/bollinger-bands * Bollinger bands * * @extends plotOptions.sma * @since 6.0.0 * @product highstock * @requires stock/indicators/indicators * @requires stock/indicators/bollinger-bands * @optionparent plotOptions.bb */ { params: { period: 20, /** * Standard deviation for top and bottom bands. */ standardDeviation: 2, index: 3 }, /** * Bottom line options. */ bottomLine: { /** * Styles for a bottom line. */ styles: { /** * Pixel width of the line. */ lineWidth: 1, /** * Color of the line. If not set, it's inherited from * [plotOptions.bb.color](#plotOptions.bb.color). * * @type {Highcharts.ColorString} */ lineColor: void 0 } }, /** * Top line options. * * @extends plotOptions.bb.bottomLine */ topLine: { styles: { lineWidth: 1, /** * @type {Highcharts.ColorString} */ lineColor: void 0 } }, tooltip: { pointFormat: '<span style="color:{point.color}">\u25CF</span><b> {series.name}</b><br/>Top: {point.top}<br/>Middle: {point.middle}<br/>Bottom: {point.bottom}<br/>' }, marker: { enabled: false }, dataGrouping: { approximation: 'averages' } }, /** * @lends Highcharts.Series# */ merge(multipleLinesMixin, { pointArrayMap: ['top', 'middle', 'bottom'], pointValKey: 'middle', nameComponents: ['period', 'standardDeviation'], linesApiNames: ['topLine', 'bottomLine'], init: function () { SMA.prototype.init.apply(this, arguments); // Set default color for lines: this.options = merge({ topLine: { styles: { lineColor: this.color } }, bottomLine: { styles: { lineColor: this.color } } }, this.options); }, getValues: function (series, params) { var period = params.period, standardDeviation = params.standardDeviation, xVal = series.xData, yVal = series.yData, yValLen = yVal ? yVal.length : 0, // 0- date, 1-middle line, 2-top line, 3-bottom line BB = [], // middle line, top line and bottom line ML, TL, BL, date, xData = [], yData = [], slicedX, slicedY, stdDev, isOHLC, point, i; if (xVal.length < period) { return; } isOHLC = isArray(yVal[0]); for (i = period; i <= yValLen; i++) { slicedX = xVal.slice(i - period, i); slicedY = yVal.slice(i - period, i); point = SMA.prototype.getValues.call(this, { xData: slicedX, yData: slicedY }, params); date = point.xData[0]; ML = point.yData[0]; stdDev = getStandardDeviation(slicedY, params.index, isOHLC, ML); TL = ML + standardDeviation * stdDev; BL = ML - standardDeviation * stdDev; BB.push([date, TL, ML, BL]); xData.push(date); yData.push([TL, ML, BL]); } return { values: BB, xData: xData, yData: yData }; } })); /** * A bollinger bands indicator. If the [type](#series.bb.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.bb * @since 6.0.0 * @excluding dataParser, dataURL * @product highstock * @requires stock/indicators/indicators * @requires stock/indicators/bollinger-bands * @apioption series.bb */ ''; // to include the above in the js output }); _registerModule(_modules, 'masters/indicators/bollinger-bands.src.js', [], function () { }); }));
cdnjs/cdnjs
ajax/libs/highcharts/8.0.2/indicators/bollinger-bands.src.js
JavaScript
mit
16,410
/*! @license * Shaka Player * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ declare class GlobalError extends Error {} //!! generated by clutz. // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka { class Player extends shaka.util.FakeEventTarget implements shaka.util.IDestroyable { private noStructuralTyping_shaka_Player : any; constructor (mediaElement ? : HTMLMediaElement | null , dependencyInjector ? : (a : shaka.Player | null ) => any ) ; /** * Adds the given text track to the loaded manifest. <code>load()</code> must * resolve before calling. The presentation must have a duration. * This returns the created track, which can immediately be selected by the * application. The track will not be automatically selected. */ addTextTrack (uri : string , language : string , kind : string , mimeType ? : string , codec ? : string , label ? : string , forced ? : boolean ) : shaka.extern.Track ; /** * Adds the given text track to the loaded manifest. <code>load()</code> must * resolve before calling. The presentation must have a duration. * This returns the created track, which can immediately be selected by the * application. The track will not be automatically selected. */ addTextTrackAsync (uri : string , language : string , kind : string , mimeType ? : string , codec ? : string , label ? : string , forced ? : boolean ) : Promise < shaka.extern.Track > ; /** * Tell the player to use <code>mediaElement</code> for all <code>load</code> * requests until <code>detach</code> or <code>destroy</code> are called. * <p> * Calling <code>attach</code> with <code>initializedMediaSource=true</code> * will tell the player to take the initial load step and initialize media * source. * <p> * Calls to <code>attach</code> will interrupt any in-progress calls to * <code>load</code> but cannot interrupt calls to <code>attach</code>, * <code>detach</code>, or <code>unload</code>. */ attach (mediaElement : HTMLMediaElement , initializeMediaSource ? : boolean ) : Promise < any > ; /** * Cancel trick-play. If the player has not loaded content or is still loading * content this will be a no-op. */ cancelTrickPlay ( ) : any ; /** * Changes configuration settings on the Player. This checks the names of * keys and the types of values to avoid coding errors. If there are errors, * this logs them to the console and returns false. Correct fields are still * applied even if there are other errors. You can pass an explicit * <code>undefined</code> value to restore the default value. This has two * modes of operation: * <p> * First, this can be passed a single "plain" object. This object should * follow the {@link shaka.extern.PlayerConfiguration} object. Not all fields * need to be set; unset fields retain their old values. * <p> * Second, this can be passed two arguments. The first is the name of the key * to set. This should be a '.' separated path to the key. For example, * <code>'streaming.alwaysStreamText'</code>. The second argument is the * value to set. * @param config This should either be a field name or an object. * @param value In the second mode, this is the value to set. */ configure (config : string | object , value ? : any ) : boolean ; /** * After destruction, a Player object cannot be used again. */ destroy ( ) : Promise < any > ; /** * Tell the player to stop using its current media element. If the player is: * <ul> * <li>detached, this will do nothing, * <li>attached, this will release the media element, * <li>loading, this will abort loading, unload, and release the media * element, * <li>playing content, this will stop playback, unload, and release the * media element. * </ul> * <p> * Calls to <code>detach</code> will interrupt any in-progress calls to * <code>load</code> but cannot interrupt calls to <code>attach</code>, * <code>detach</code>, or <code>unload</code>. */ detach ( ) : Promise < any > ; /** * Get the drm info used to initialize EME. If EME is not being used, this * will return <code>null</code>. If the player is idle or has not initialized * EME yet, this will return <code>null</code>. */ drmInfo ( ) : shaka.extern.DrmInfo | null ; /** * Returns a shaka.ads.AdManager instance, responsible for Dynamic * Ad Insertion functionality. */ getAdManager ( ) : shaka.extern.IAdManager | null ; /** * Get the uri to the asset that the player has loaded. If the player has not * loaded content, this will return <code>null</code>. */ getAssetUri ( ) : string | null ; /** * Return a list of audio languages available. If the player has not loaded * any content, this will return an empty list. */ getAudioLanguages ( ) : string [] ; /** * Return a list of audio language-role combinations available. If the * player has not loaded any content, this will return an empty list. */ getAudioLanguagesAndRoles ( ) : shaka.extern.LanguageRole [] ; /** * Get information about what the player has buffered. If the player has not * loaded content or is currently loading content, the buffered content will * be empty. */ getBufferedInfo ( ) : shaka.extern.BufferedInfo ; /** * Return a copy of the current configuration. Modifications of the returned * value will not affect the Player's active configuration. You must call * <code>player.configure()</code> to make changes. */ getConfiguration ( ) : shaka.extern.PlayerConfiguration ; /** * Get the next known expiration time for any EME session. If the session * never expires, this will return <code>Infinity</code>. If there are no EME * sessions, this will return <code>Infinity</code>. If the player has not * loaded content, this will return <code>Infinity</code>. */ getExpiration ( ) : number ; /** * Return a list of image tracks that can be switched to. * If the player has not loaded content, this will return an empty list. */ getImageTracks ( ) : shaka.extern.TrackList ; /** * Gets a map of EME key ID to the current key status. */ getKeyStatuses ( ) : { [ key: string ]: string } ; /** * Get the current load mode. */ getLoadMode ( ) : shaka.Player.LoadMode ; /** * Get the manifest that the player has loaded. If the player has not loaded * any content, this will return <code>null</code>. * NOTE: This structure is NOT covered by semantic versioning compatibility * guarantees. It may change at any time! * This is marked as deprecated to warn Closure Compiler users at compile-time * to avoid using this method. */ getManifest ( ) : shaka.extern.Manifest | null ; /** * Get the type of manifest parser that the player is using. If the player has * not loaded any content, this will return <code>null</code>. */ getManifestParserFactory ( ) : ( shaka.extern.ManifestParser.Factory ) | null ; /** * Get the media element that the player is currently using to play loaded * content. If the player has not loaded content, this will return * <code>null</code>. */ getMediaElement ( ) : HTMLMediaElement | null ; getNetworkingEngine ( ) : shaka.net.NetworkingEngine | null ; /** * Get the playback rate of what is playing right now. If we are using trick * play, this will return the trick play rate. * If no content is playing, this will return 0. * If content is buffering, this will return the expected playback rate once * the video starts playing. * <p> * If the player has not loaded content, this will return a playback rate of * 0. */ getPlaybackRate ( ) : number ; /** * Get the current playhead position as a date. This should only be called * when the player has loaded a live stream. If the player has not loaded a * live stream, this will return <code>null</code>. */ getPlayheadTimeAsDate ( ) : Date | null ; /** * Get the presentation start time as a date. This should only be called when * the player has loaded a live stream. If the player has not loaded a live * stream, this will return <code>null</code>. */ getPresentationStartTimeAsDate ( ) : Date | null ; /** * Get statistics for the current playback session. If the player is not * playing content, this will return an empty stats object. */ getStats ( ) : shaka.extern.Stats ; /** * Return a list of text languages available. If the player has not loaded * any content, this will return an empty list. */ getTextLanguages ( ) : string [] ; /** * Return a list of text language-role combinations available. If the player * has not loaded any content, this will be return an empty list. */ getTextLanguagesAndRoles ( ) : shaka.extern.LanguageRole [] ; /** * Return a list of text tracks that can be switched to. * <p> * If the player has not loaded content, this will return an empty list. */ getTextTracks ( ) : shaka.extern.TrackList ; /** * Return a Thumbnail object from a image track Id and time. * If the player has not loaded content, this will return a null. */ getThumbnails (trackId : number , time : number ) : Promise < shaka.extern.Thumbnail | null > ; /** * Return a list of variant tracks that can be switched to. * <p> * If the player has not loaded content, this will return an empty list. */ getVariantTracks ( ) : shaka.extern.TrackList ; /** * Check if the manifest contains only audio-only content. If the player has * not loaded content, this will return <code>false</code>. * <p> * The player does not support content that contain more than one type of * variants (i.e. mixing audio-only, video-only, audio-video). Content will be * filtered to only contain one type of variant. */ isAudioOnly ( ) : boolean ; /** * Check if the player is currently in a buffering state (has too little * content to play smoothly). If the player has not loaded content, this will * return <code>false</code>. */ isBuffering ( ) : boolean ; /** * Get if the player is playing in-progress content. If the player has not * loaded content, this will return <code>false</code>. */ isInProgress ( ) : boolean ; /** * Get if the player is playing live content. If the player has not loaded * content, this will return <code>false</code>. */ isLive ( ) : boolean ; /** * Check if the text displayer is enabled. */ isTextTrackVisible ( ) : boolean ; /** * Get the key system currently used by EME. If EME is not being used, this * will return an empty string. If the player has not loaded content, this * will return an empty string. */ keySystem ( ) : string ; /** * Tell the player to load the content at <code>assetUri</code> and start * playback at <code>startTime</code>. Before calling <code>load</code>, * a call to <code>attach</code> must have succeeded. * <p> * Calls to <code>load</code> will interrupt any in-progress calls to * <code>load</code> but cannot interrupt calls to <code>attach</code>, * <code>detach</code>, or <code>unload</code>. * @param startTime When <code>startTime</code> is <code>null</code> or <code>undefined</code>, playback will start at the default start time (0 for VOD and liveEdge for LIVE). */ load (assetUri : string , startTime ? : number | null , mimeType ? : string ) : Promise < any > ; /** * Reset configuration to default. */ resetConfiguration ( ) : any ; /** * Retry streaming after a streaming failure has occurred. When the player has * not loaded content or is loading content, this will be a no-op and will * return <code>false</code>. * <p> * If the player has loaded content, and streaming has not seen an error, this * will return <code>false</code>. * <p> * If the player has loaded content, and streaming seen an error, but the * could not resume streaming, this will return <code>false</code>. */ retryStreaming ( ) : boolean ; /** * Get the range of time (in seconds) that seeking is allowed. If the player * has not loaded content, this will return a range from 0 to 0. */ seekRange ( ) : shaka.extern.BufferedRange ; /** * Sets the current audio language and current variant role to the selected * language and role, and chooses a new variant if need be. If the player has * not loaded any content, this will be a no-op. */ selectAudioLanguage (language : string , role ? : string ) : any ; /** * Sets the current text language and current text role to the selected * language and role, and chooses a new variant if need be. If the player has * not loaded any content, this will be a no-op. */ selectTextLanguage (language : string , role ? : string , forced ? : boolean ) : any ; /** * Select a specific text track. <code>track</code> should come from a call to * <code>getTextTracks</code>. If the track is not found, this will be a * no-op. If the player has not loaded content, this will be a no-op. * <p> * Note that <code>AdaptationEvents</code> are not fired for manual track * selections. */ selectTextTrack (track : shaka.extern.Track ) : any ; /** * Select a specific variant track to play. <code>track</code> should come * from a call to <code>getVariantTracks</code>. If <code>track</code> cannot * be found, this will be a no-op. If the player has not loaded content, this * will be a no-op. * <p> * Changing variants will take effect once the currently buffered content has * been played. To force the change to happen sooner, use * <code>clearBuffer</code> with <code>safeMargin</code>. Setting * <code>clearBuffer</code> to <code>true</code> will clear all buffered * content after <code>safeMargin</code>, allowing the new variant to start * playing sooner. * <p> * Note that <code>AdaptationEvents</code> are not fired for manual track * selections. * @param safeMargin Optional amount of buffer (in seconds) to retain when clearing the buffer. Useful for switching variant quickly without causing a buffering event. Defaults to 0 if not provided. Ignored if clearBuffer is false. Can cause hiccups on some browsers if chosen too small, e.g. The amount of two segments is a fair minimum to consider as safeMargin value. */ selectVariantTrack (track : shaka.extern.Track , clearBuffer ? : boolean , safeMargin ? : number ) : any ; /** * Select variant tracks that have a given label. This assumes the * label uniquely identifies an audio stream, so all the variants * are expected to have the same variant.audio. */ selectVariantsByLabel (label : string ) : any ; /** * Set the maximum resolution that the platform's hardware can handle. * This will be called automatically by <code>shaka.cast.CastReceiver</code> * to enforce limitations of the Chromecast hardware. */ setMaxHardwareResolution (width : number , height : number ) : any ; /** * Enable or disable the text displayer. If the player is in an unloaded * state, the request will be applied next time content is loaded. */ setTextTrackVisibility (isVisible : boolean ) : any ; /** * Set the videoContainer to construct UITextDisplayer. */ setVideoContainer (videoContainer : HTMLElement | null ) : any ; /** * Enable trick play to skip through content without playing by repeatedly * seeking. For example, a rate of 2.5 would result in 2.5 seconds of content * being skipped every second. A negative rate will result in moving * backwards. * <p> * If the player has not loaded content or is still loading content this will * be a no-op. Wait until <code>load</code> has completed before calling. * <p> * Trick play will be canceled automatically if the playhead hits the * beginning or end of the seekable range for the content. */ trickPlay (rate : number ) : any ; /** * Tell the player to either return to: * <ul> * <li>detached (when it does not have a media element), * <li>attached (when it has a media element and * <code>initializedMediaSource=false</code>) * <li>media source initialized (when it has a media element and * <code>initializedMediaSource=true</code>) * </ul> * <p> * Calls to <code>unload</code> will interrupt any in-progress calls to * <code>load</code> but cannot interrupt calls to <code>attach</code>, * <code>detach</code>, or <code>unload</code>. */ unload (initializeMediaSource ? : boolean ) : Promise < any > ; /** * Return whether the browser provides basic support. If this returns false, * Shaka Player cannot be used at all. In this case, do not construct a * Player instance and do not use the library. */ static isBrowserSupported ( ) : boolean ; /** * Probes the browser to determine what features are supported. This makes a * number of requests to EME/MSE/etc which may result in user prompts. This * should only be used for diagnostics. * <p> * NOTE: This may show a request to the user for permission. */ static probeSupport (promptsOkay ? : boolean ) : Promise < shaka.extern.SupportType > ; /** * Registers a plugin callback that will be called with * <code>support()</code>. The callback will return the value that will be * stored in the return value from <code>support()</code>. */ static registerSupportPlugin (name : string , callback : ( ) => any ) : any ; /** * Set a factory to create an ad manager during player construction time. * This method needs to be called bafore instantiating the Player class. */ static setAdManagerFactory (factory : shaka.extern.IAdManager.Factory ) : any ; static version : string ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.Player { /** * In order to know what method of loading the player used for some content, we * have this enum. It lets us know if content has not been loaded, loaded with * media source, or loaded with src equals. * This enum has a low resolution, because it is only meant to express the * outer limits of the various states that the player is in. For example, when * someone calls a public method on player, it should not matter if they have * initialized drm engine, it should only matter if they finished loading * content. */ /** * In order to know what method of loading the player used for some content, we * have this enum. It lets us know if content has not been loaded, loaded with * media source, or loaded with src equals. * This enum has a low resolution, because it is only meant to express the * outer limits of the various states that the player is in. For example, when * someone calls a public method on player, it should not matter if they have * initialized drm engine, it should only matter if they finished loading * content. */ enum LoadMode { DESTROYED = 0.0 , MEDIA_SOURCE = 2.0 , NOT_LOADED = 1.0 , SRC_EQUALS = 3.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.abr { class SimpleAbrManager implements shaka.extern.AbrManager { private noStructuralTyping_shaka_abr_SimpleAbrManager : any; chooseVariant ( ) : any ; configure (config : any ) : any ; disable ( ) : any ; enable ( ) : any ; getBandwidthEstimate ( ) : any ; init (switchCallback : any ) : any ; playbackRateChanged (rate : any ) : any ; segmentDownloaded (deltaTimeMs : any , numBytes : any ) : any ; setVariants (variants : any ) : any ; stop ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ads { /** * A class responsible for ad-related interactions. */ class AdManager extends shaka.util.FakeEventTarget implements shaka.extern.IAdManager , shaka.util.IReleasable { private noStructuralTyping_shaka_ads_AdManager : any; getStats ( ) : shaka.extern.AdsStats ; initClientSide (adContainer : any , video : any ) : any ; initServerSide (adContainer : any , video : any ) : any ; onAssetUnload ( ) : any ; onCueMetadataChange (value : any ) : any ; onDashTimedMetadata (region : any ) : any ; onHlsTimedMetadata (metadata : any , timestamp : any ) : any ; release ( ) : any ; replaceServerSideAdTagParameters (adTagParameters : any ) : any ; requestClientSideAds (imaRequest : any ) : any ; requestServerSideStream (imaRequest : google.ima.dai.api.StreamRequest , backupUrl ? : string ) : Promise < string > ; setLocale (locale : any ) : any ; /** * The event name for when a sequence of ads has been loaded. */ static ADS_LOADED : string ; /** * The event name for when the client side SDK signalled its readiness * to play a VPAID ad or an ad rule. */ static AD_BREAK_READY : string ; /** * The event name for when the ad is buffering. */ static AD_BUFFERING : string ; /** * The event name for when the ad was clicked. */ static AD_CLICKED : string ; /** * The event name for when the ad was closed by the user. */ static AD_CLOSED : string ; /** * The event name for when an ad has completed playing. */ static AD_COMPLETE : string ; /** * The event name for when the ad's duration changed. */ static AD_DURATION_CHANGED : string ; /** * The event name for when an ad playhead crosses first quartile. */ static AD_FIRST_QUARTILE : string ; /** * The event name for when the ad's URL was hit. */ static AD_IMPRESSION : string ; /** * The event name for when the interaction callback for the ad was * triggered. */ static AD_INTERACTION : string ; /** * The event name for when the ad changes from or to linear. */ static AD_LINEAR_CHANGED : string ; /** * The event name for when the ad data becomes available. */ static AD_LOADED : string ; /** * The event name for when the ad's metadata becomes available. */ static AD_METADATA : string ; /** * The event name for when an ad playhead crosses midpoint. */ static AD_MIDPOINT : string ; /** * The event name for when the ad was muted. */ static AD_MUTED : string ; /** * The event name for when the ad was paused. */ static AD_PAUSED : string ; /** * The event name for when there is an update to the current ad's progress. */ static AD_PROGRESS : string ; /** * The event name for when the ad display encountered a recoverable * error. */ static AD_RECOVERABLE_ERROR : string ; /** * The event name for when the ad was resumed after a pause. */ static AD_RESUMED : string ; /** * The event name for when an ad is skipped by the user.. */ static AD_SKIPPED : string ; /** * The event name for when the ad's skip status changes * (usually it becomes skippable when it wasn't before). */ static AD_SKIP_STATE_CHANGED : string ; /** * The event name for when an ad has started playing. */ static AD_STARTED : string ; /** * The event name for when an ad has finished playing * (played all the way through, was skipped, or was unable to proceed * due to an error). */ static AD_STOPPED : string ; /** * The event name for when an ad playhead crosses third quartile. */ static AD_THIRD_QUARTILE : string ; /** * The event name for when the ad volume has changed. */ static AD_VOLUME_CHANGED : string ; /** * The event name for when all the ads were completed. */ static ALL_ADS_COMPLETED : string ; /** * The event name for when the ad's cue points (start/end markers) * have changed. */ static CUEPOINTS_CHANGED : string ; /** * The event name for when the native IMA ad manager object has * loaded and become available. */ static IMA_AD_MANAGER_LOADED : string ; /** * The event name for when the native IMA stream manager object has * loaded and become available. */ static IMA_STREAM_MANAGER_LOADED : string ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ads { class ClientSideAd implements shaka.extern.IAd { private noStructuralTyping_shaka_ads_ClientSideAd : any; constructor (imaAd : google.ima.Ad , imaAdManager : google.ima.AdsManager ) ; canSkipNow ( ) : any ; getDuration ( ) : any ; getMinSuggestedDuration ( ) : any ; getPositionInSequence ( ) : any ; getRemainingTime ( ) : any ; getSequenceLength ( ) : any ; getTimeUntilSkippable ( ) : any ; getVolume ( ) : any ; isMuted ( ) : any ; isPaused ( ) : any ; isSkippable ( ) : any ; pause ( ) : any ; play ( ) : any ; release ( ) : any ; resize (width : any , height : any ) : any ; setMuted (muted : any ) : any ; setVolume (volume : any ) : any ; skip ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ads { class ServerSideAd implements shaka.extern.IAd { private noStructuralTyping_shaka_ads_ServerSideAd : any; constructor (imaAd : google.ima.dai.api.Ad | null , video : HTMLMediaElement | null ) ; canSkipNow ( ) : any ; getDuration ( ) : any ; getMinSuggestedDuration ( ) : any ; getPositionInSequence ( ) : any ; getRemainingTime ( ) : any ; getSequenceLength ( ) : any ; getTimeUntilSkippable ( ) : any ; getVolume ( ) : any ; isMuted ( ) : any ; isPaused ( ) : any ; isSkippable ( ) : any ; pause ( ) : any ; play ( ) : any ; release ( ) : any ; resize (width : any , height : any ) : any ; setMuted (muted : any ) : any ; setVolume (volume : any ) : any ; skip ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.cast { class CastProxy extends shaka.util.FakeEventTarget implements shaka.util.IDestroyable { private noStructuralTyping_shaka_cast_CastProxy : any; constructor (video : HTMLMediaElement , player : shaka.Player , receiverAppId : string ) ; canCast ( ) : boolean ; cast ( ) : Promise < any > ; changeReceiverId (newAppId : string ) : any ; /** * Destroys the proxy and the underlying local Player. * @param forceDisconnect If true, force the receiver app to shut down by disconnecting. Does nothing if not connected. */ destroy (forceDisconnect ? : boolean ) : Promise < any > ; /** * Force the receiver app to shut down by disconnecting. */ forceDisconnect ( ) : any ; /** * Get a proxy for the Player that delegates to local and remote Player * objects as appropriate. */ getPlayer ( ) : shaka.Player ; /** * Get a proxy for the video element that delegates to local and remote video * elements as appropriate. */ getVideo ( ) : HTMLMediaElement ; isCasting ( ) : boolean ; receiverName ( ) : string ; /** * Set application-specific data. * @param appData Application-specific data to relay to the receiver. */ setAppData (appData : object | null ) : any ; /** * Show a dialog where user can choose to disconnect from the cast connection. */ suggestDisconnect ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.cast { /** * A receiver to communicate between the Chromecast-hosted player and the * sender application. */ class CastReceiver extends shaka.util.FakeEventTarget implements shaka.util.IDestroyable { private noStructuralTyping_shaka_cast_CastReceiver : any; /** * A receiver to communicate between the Chromecast-hosted player and the * sender application. */ constructor (video : HTMLMediaElement , player : shaka.Player , appDataCallback ? : (a : object | null ) => any , contentIdCallback ? : (a : string ) => string ) ; /** * Clear all Cast content metadata. * Should be called from an appDataCallback. */ clearContentMetadata ( ) : any ; /** * Destroys the underlying Player, then terminates the cast receiver app. */ destroy ( ) : Promise < any > ; isConnected ( ) : boolean ; isIdle ( ) : boolean ; /** * Set the Cast content's artist. * Also sets the metadata type to music. * Should be called from an appDataCallback. */ setContentArtist (artist : string ) : any ; /** * Set the Cast content's thumbnail image. * Should be called from an appDataCallback. */ setContentImage (imageUrl : string ) : any ; /** * Set all Cast content metadata, as defined by the Cast SDK. * Should be called from an appDataCallback. * For a simpler way to set basic metadata, see: * - setContentTitle() * - setContentImage() * - setContentArtist() * @param metadata A Cast metadata object, one of: - https://developers.google.com/cast/docs/reference/messages#GenericMediaMetadata - https://developers.google.com/cast/docs/reference/messages#MovieMediaMetadata - https://developers.google.com/cast/docs/reference/messages#TvShowMediaMetadata - https://developers.google.com/cast/docs/reference/messages#MusicTrackMediaMetadata */ setContentMetadata (metadata : object | null ) : any ; /** * Set the Cast content's title. * Should be called from an appDataCallback. */ setContentTitle (title : string ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.dash { /** * Creates a new DASH parser. */ class DashParser implements shaka.extern.ManifestParser { private noStructuralTyping_shaka_dash_DashParser : any; configure (config : any ) : any ; onExpirationUpdated (sessionId : any , expiration : any ) : any ; start (uri : any , playerInterface : any ) : any ; stop ( ) : any ; update ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka { class dependencies { private noStructuralTyping_shaka_dependencies : any; /** * Registers a new dependency. * @param key which is used for retrieving a dependency * @param dep a dependency */ static add (key : shaka.dependencies.Allowed , dep : any ) : any ; /** * Check if we have a dependency for the key. * @param key key */ static has (key : shaka.dependencies.Allowed ) : boolean ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.dependencies { enum Allowed { muxjs = 'muxjs' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.hls { /** * HLS parser. */ class HlsParser implements shaka.extern.ManifestParser { private noStructuralTyping_shaka_hls_HlsParser : any; configure (config : any ) : any ; onExpirationUpdated (sessionId : any , expiration : any ) : any ; start (uri : any , playerInterface : any ) : any ; stop ( ) : any ; update ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.media { /** * Creates an InitSegmentReference, which provides the location to an * initialization segment. */ class InitSegmentReference { private noStructuralTyping_shaka_media_InitSegmentReference : any; constructor (uris : ( ) => string [] , startByte : number , endByte : number | null ) ; /** * Returns the offset from the start of the resource to the end of the * segment, inclusive. A value of null indicates that the segment extends * to the end of the resource. */ getEndByte ( ) : number | null ; /** * Returns the offset from the start of the resource to the * start of the segment. */ getStartByte ( ) : number ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.media { class ManifestParser { private noStructuralTyping_shaka_media_ManifestParser : any; /** * Registers a manifest parser by file extension. * @param extension The file extension of the manifest. * @param parserFactory The factory used to create parser instances. */ static registerParserByExtension (extension : string , parserFactory : shaka.extern.ManifestParser.Factory ) : any ; /** * Registers a manifest parser by MIME type. * @param mimeType The MIME type of the manifest. * @param parserFactory The factory used to create parser instances. */ static registerParserByMime (mimeType : string , parserFactory : shaka.extern.ManifestParser.Factory ) : any ; /** * Unregisters a manifest parser by MIME type. * @param mimeType The MIME type of the manifest. */ static unregisterParserByMime (mimeType : string ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.media { /** * A meta-SegmentIndex composed of multiple other SegmentIndexes. * Used in constructing multi-Period Streams for DASH. */ class MetaSegmentIndex extends shaka.media.SegmentIndex implements Iterable < shaka.media.SegmentReference > { private noStructuralTyping_shaka_media_MetaSegmentIndex : any; /** * A meta-SegmentIndex composed of multiple other SegmentIndexes. * Used in constructing multi-Period Streams for DASH. */ constructor ( ) ; //!! Symbol.iterator inserted by Clutz for Iterable subtype [Symbol.iterator](): Iterator < shaka.media.SegmentReference > ; evict (time : number ) : any ; find (time : number ) : number | null ; fit (windowStart : number , windowEnd : number | null , c ? : boolean ) : any ; get (position : number ) : shaka.media.SegmentReference | null ; merge (references : shaka.media.SegmentReference [] ) : any ; mergeAndEvict (references : shaka.media.SegmentReference [] , windowStart : number ) : any ; offset (offset : number ) : any ; release ( ) : any ; updateEvery (interval : number , updateCallback : ( ) => ( shaka.media.SegmentReference | null ) [] | null ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.media { /** * PresentationTimeline. */ class PresentationTimeline { private noStructuralTyping_shaka_media_PresentationTimeline : any; constructor (presentationStartTime : number | null , presentationDelay : number , autoCorrectDrift ? : boolean ) ; /** * Gets the presentation delay in seconds. */ getDelay ( ) : number ; getDuration ( ) : number ; getMaxSegmentDuration ( ) : number ; getPresentationStartTime ( ) : number | null ; /** * Gets the seek range start time, offset by the given amount. This is used * to ensure that we don't "fall" back out of the seek window while we are * buffering. * @param offset The offset to add to the start time for live streams. */ getSafeSeekRangeStart (offset : number ) : number ; /** * Gets the seek range end. */ getSeekRangeEnd ( ) : number ; /** * Gets the seek range start time. */ getSeekRangeStart ( ) : number ; /** * Gets the presentation's current segment availability end time. Segments * starting after this time should be assumed to be unavailable. */ getSegmentAvailabilityEnd ( ) : number ; /** * Gets the presentation's current segment availability start time. Segments * ending at or before this time should be assumed to be unavailable. */ getSegmentAvailabilityStart ( ) : number ; isInProgress ( ) : boolean ; isLive ( ) : boolean ; /** * Gives PresentationTimeline a Stream's maximum segment duration so it can * size and position the segment availability window. This function should be * called once for each Stream (no more, no less), but does not have to be * called if notifySegments() is called instead for a particular stream. * @param maxSegmentDuration The maximum segment duration for a particular stream. */ notifyMaxSegmentDuration (maxSegmentDuration : number ) : any ; /** * Gives PresentationTimeline a Stream's minimum segment start time. */ notifyMinSegmentStartTime (startTime : number ) : any ; /** * Gives PresentationTimeline a Stream's segments so it can size and position * the segment availability window, and account for missing segment * information. This function should be called once for each Stream (no more, * no less). */ notifySegments (references : shaka.media.SegmentReference [] ) : any ; /** * Offsets the segment times by the given amount. * @param offset The number of seconds to offset by. A positive number adjusts the segment times forward. */ offset (offset : number ) : any ; /** * Sets the presentation's segment availability time offset. This should be * only set for Low Latency Dash. * The segments are available earlier for download than the availability start * time, so we can move closer to the live edge. */ setAvailabilityTimeOffset (offset : number ) : any ; /** * Sets the clock offset, which is the difference between the client's clock * and the server's clock, in milliseconds (i.e., serverTime = Date.now() + * clockOffset). * @param offset The clock offset, in ms. */ setClockOffset (offset : number ) : any ; /** * Sets the presentation delay in seconds. */ setDelay (delay : number ) : any ; /** * Sets the presentation's duration. * @param duration The presentation's duration in seconds. Infinity indicates that the presentation continues indefinitely. */ setDuration (duration : number ) : any ; /** * Sets the presentation's segment availability duration. The segment * availability duration should only be set for live. * @param segmentAvailabilityDuration The presentation's new segment availability duration in seconds. */ setSegmentAvailabilityDuration (segmentAvailabilityDuration : number ) : any ; /** * Sets the presentation's static flag. * @param isStatic If true, the presentation is static, meaning all segments are available at once. */ setStatic (isStatic : boolean ) : any ; /** * Sets the start time of the user-defined seek range. This is only used for * VOD content. */ setUserSeekStart (time : number ) : any ; /** * True if the presentation start time is being used to calculate the live * edge. * Using the presentation start time means that the stream may be subject to * encoder drift. At runtime, we will avoid using the presentation start time * whenever possible. */ usingPresentationStartTime ( ) : boolean ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.media { /** * SegmentIndex. */ class SegmentIndex implements Iterable < shaka.media.SegmentReference > { private noStructuralTyping_shaka_media_SegmentIndex : any; /** * SegmentIndex. */ constructor (references : shaka.media.SegmentReference [] ) ; //!! Symbol.iterator inserted by Clutz for Iterable subtype [Symbol.iterator](): Iterator < shaka.media.SegmentReference > ; /** * SegmentIndex used to be an IDestroyable. Now it is an IReleasable. * This method is provided for backward compatibility. */ destroy ( ) : Promise < any > ; /** * Removes all SegmentReferences that end before the given time. * @param time The time in seconds. */ evict (time : number ) : any ; /** * Finds the position of the segment for the given time, in seconds, relative * to the start of the presentation. Returns the position of the segment * with the largest end time if more than one segment is known for the given * time. */ find (time : number ) : number | null ; /** * Drops references that start after windowEnd, or end before windowStart, * and contracts the last reference so that it ends at windowEnd. * Do not call on the last period of a live presentation (unknown duration). * It is okay to call on the other periods of a live presentation, where the * duration is known and another period has been added. * @param isNew Whether this is a new SegmentIndex and we shouldn't update the number of evicted elements. */ fit (windowStart : number , windowEnd : number | null , isNew ? : boolean ) : any ; /** * Gets the SegmentReference for the segment at the given position. * @param position The position of the segment as returned by find(). */ get (position : number ) : shaka.media.SegmentReference | null ; /** * Returns a new iterator that initially points to the segment that contains * the given time. Like the normal iterator, next() must be called first to * get to the first element. Returns null if we do not find a segment at the * requested time. */ getIteratorForTime (time : number ) : shaka.media.SegmentIterator | null ; /** * Marks the index as immutable. Segments cannot be added or removed after * this point. This doesn't affect the references themselves. This also * makes the destroy/release methods do nothing. * This is mainly for testing. */ markImmutable ( ) : any ; /** * Merges the given SegmentReferences. Supports extending the original * references only. Will replace old references with equivalent new ones, and * keep any unique old ones. * Used, for example, by the DASH and HLS parser, where manifests may not list * all available references, so we must keep available references in memory to * fill the availability window. * @param references The list of SegmentReferences, which must be sorted first by their start times (ascending) and second by their end times (ascending). */ merge (references : shaka.media.SegmentReference [] ) : any ; /** * Merges the given SegmentReferences and evicts the ones that end before the * given time. Supports extending the original references only. * Will not replace old references or interleave new ones. * Used, for example, by the DASH and HLS parser, where manifests may not list * all available references, so we must keep available references in memory to * fill the availability window. * @param references The list of SegmentReferences, which must be sorted first by their start times (ascending) and second by their end times (ascending). * @param windowStart The start of the availability window to filter out the references that are no longer available. */ mergeAndEvict (references : shaka.media.SegmentReference [] , windowStart : number ) : any ; /** * Offset all segment references by a fixed amount. * @param offset The amount to add to each segment's start and end times. */ offset (offset : number ) : any ; release ( ) : any ; /** * Updates the references every so often. Stops when the references list * returned by the callback is null. * @param interval The interval in seconds. */ updateEvery (interval : number , updateCallback : ( ) => ( shaka.media.SegmentReference | null ) [] | null ) : any ; /** * Create a SegmentIndex for a single segment of the given start time and * duration at the given URIs. */ static forSingleSegment (startTime : number , duration : number , uris : string [] ) : shaka.media.SegmentIndex ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.media { /** * An iterator over a SegmentIndex's references. */ class SegmentIterator implements Iterator < shaka.media.SegmentReference | null > { private noStructuralTyping_shaka_media_SegmentIterator : any; /** * An iterator over a SegmentIndex's references. */ constructor (segmentIndex : shaka.media.SegmentIndex | null , index : number , partialSegmentIndex : number ) ; current ( ) : shaka.media.SegmentReference | null ; next ( ) : any ; /** * Move the iterator to a given timestamp in the underlying SegmentIndex. */ seek (time : number ) : shaka.media.SegmentReference | null ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.media { /** * SegmentReference provides the start time, end time, and location to a media * segment. */ class SegmentReference { private noStructuralTyping_shaka_media_SegmentReference : any; constructor (startTime : number , endTime : number , uris : ( ) => string [] , startByte : number , endByte : number | null , initSegmentReference : shaka.media.InitSegmentReference | null , timestampOffset : number , appendWindowStart : number , appendWindowEnd : number , partialReferences ? : shaka.media.SegmentReference [] ) ; /** * Returns the offset from the start of the resource to the end of the * segment, inclusive. A value of null indicates that the segment extends to * the end of the resource. */ getEndByte ( ) : number | null ; /** * Returns the segment's end time in seconds. */ getEndTime ( ) : number ; /** * Returns the offset from the start of the resource to the * start of the segment. */ getStartByte ( ) : number ; /** * Returns the segment's start time in seconds. */ getStartTime ( ) : number ; /** * Creates and returns the URIs of the resource containing the segment. */ getUris ( ) : string [] ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.net { class DataUriPlugin { private noStructuralTyping_shaka_net_DataUriPlugin : any; static parse (uri : string , request : shaka.extern.Request , requestType : shaka.net.NetworkingEngine.RequestType , progressUpdated : shaka.extern.ProgressUpdated ) : shaka.extern.IAbortableOperation < any > ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.net { class HttpFetchPlugin { private noStructuralTyping_shaka_net_HttpFetchPlugin : any; /** * Determine if the Fetch API is supported in the browser. Note: this is * deliberately exposed as a method to allow the client app to use the same * logic as Shaka when determining support. */ static isSupported ( ) : boolean ; static parse (uri : string , request : shaka.extern.Request , requestType : shaka.net.NetworkingEngine.RequestType , progressUpdated : shaka.extern.ProgressUpdated ) : shaka.extern.IAbortableOperation < any > ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.net { class HttpXHRPlugin { private noStructuralTyping_shaka_net_HttpXHRPlugin : any; static parse (uri : string , request : shaka.extern.Request , requestType : shaka.net.NetworkingEngine.RequestType , progressUpdated : shaka.extern.ProgressUpdated ) : shaka.extern.IAbortableOperation < any > ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.net { /** * NetworkingEngine wraps all networking operations. This accepts plugins that * handle the actual request. A plugin is registered using registerScheme. * Each scheme has at most one plugin to handle the request. */ class NetworkingEngine extends shaka.util.FakeEventTarget implements shaka.util.IDestroyable { private noStructuralTyping_shaka_net_NetworkingEngine : any; /** * NetworkingEngine wraps all networking operations. This accepts plugins that * handle the actual request. A plugin is registered using registerScheme. * Each scheme has at most one plugin to handle the request. */ constructor (onProgressUpdated ? : (a : number , b : number ) => any ) ; /** * Clears all request filters. */ clearAllRequestFilters ( ) : any ; /** * Clears all response filters. */ clearAllResponseFilters ( ) : any ; destroy ( ) : Promise < any > ; /** * Registers a new request filter. All filters are applied in the order they * are registered. */ registerRequestFilter (filter : shaka.extern.RequestFilter ) : any ; /** * Registers a new response filter. All filters are applied in the order they * are registered. */ registerResponseFilter (filter : shaka.extern.ResponseFilter ) : any ; /** * Makes a network request and returns the resulting data. */ request (type : shaka.net.NetworkingEngine.RequestType , request : shaka.extern.Request ) : shaka.net.NetworkingEngine.PendingRequest ; setForceHTTPS (forceHTTPS : boolean ) : any ; /** * Removes a request filter. */ unregisterRequestFilter (filter : shaka.extern.RequestFilter ) : any ; /** * Removes a response filter. */ unregisterResponseFilter (filter : shaka.extern.ResponseFilter ) : any ; /** * Gets a copy of the default retry parameters. */ static defaultRetryParameters ( ) : shaka.extern.RetryParameters ; /** * Makes a simple network request for the given URIs. */ static makeRequest (uris : string [] , retryParams : shaka.extern.RetryParameters , streamDataCallback ? : ( (a : ArrayBuffer | ArrayBufferView ) => Promise < any > ) | null ) : shaka.extern.Request ; /** * Registers a scheme plugin. This plugin will handle all requests with the * given scheme. If a plugin with the same scheme already exists, it is * replaced, unless the existing plugin is of higher priority. * If no priority is provided, this defaults to the highest priority of * APPLICATION. */ static registerScheme (scheme : string , plugin : shaka.extern.SchemePlugin , priority ? : number , progressSupport ? : boolean ) : any ; /** * Removes a scheme plugin. */ static unregisterScheme (scheme : string ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.net.NetworkingEngine { /** * A wrapper class for the number of bytes remaining to be downloaded for the * request. * Instead of using PendingRequest directly, this class is needed to be sent to * plugin as a parameter, and a Promise is returned, before PendingRequest is * created. */ class NumBytesRemainingClass { private noStructuralTyping_shaka_net_NetworkingEngine_NumBytesRemainingClass : any; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.net.NetworkingEngine { /** * A pending network request. This can track the current progress of the * download, and allows the request to be aborted if the network is slow. */ class PendingRequest extends shaka.util.AbortableOperation < any > implements shaka.extern.IAbortableOperation < any > { private noStructuralTyping_shaka_net_NetworkingEngine_PendingRequest : any; /** * A pending network request. This can track the current progress of the * download, and allows the request to be aborted if the network is slow. */ constructor (promise : Promise < any > , onAbort : shaka.extern.CreateSegmentIndexFunction , numBytesRemainingObj : shaka.net.NetworkingEngine.NumBytesRemainingClass | null ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.net.NetworkingEngine { /** * Priority level for network scheme plugins. * If multiple plugins are provided for the same scheme, only the * highest-priority one is used. */ /** * Priority level for network scheme plugins. * If multiple plugins are provided for the same scheme, only the * highest-priority one is used. */ enum PluginPriority { APPLICATION = 3.0 , FALLBACK = 1.0 , PREFERRED = 2.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.net.NetworkingEngine { /** * Request types. Allows a filter to decide which requests to read/alter. */ /** * Request types. Allows a filter to decide which requests to read/alter. */ enum RequestType { APP = 3.0 , LICENSE = 2.0 , MANIFEST = 0.0 , SEGMENT = 1.0 , TIMING = 4.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.offline { class OfflineScheme { private noStructuralTyping_shaka_offline_OfflineScheme : any; static plugin (uri : string , request : shaka.extern.Request , requestType : shaka.net.NetworkingEngine.RequestType , progressUpdated : shaka.extern.ProgressUpdated ) : shaka.extern.IAbortableOperation < any > ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.offline { class Storage implements shaka.util.IDestroyable { private noStructuralTyping_shaka_offline_Storage : any; constructor (player ? : shaka.Player ) ; /** * Sets configuration values for Storage. This is associated with * Player.configure and will change the player instance given at * initialization. * @param config This should either be a field name or an object following the form of {@link shaka.extern.PlayerConfiguration}, where you may omit any field you do not wish to change. * @param value This should be provided if the previous parameter was a string field name. */ configure (config : string | object , value ? : any ) : boolean ; destroy ( ) : Promise < any > ; /** * Return a copy of the current configuration. Modifications of the returned * value will not affect the Storage instance's active configuration. You * must call storage.configure() to make changes. */ getConfiguration ( ) : shaka.extern.PlayerConfiguration ; /** * Return the networking engine that storage is using. If storage was * initialized with a player instance, then the networking engine returned * will be the same as |player.getNetworkingEngine()|. * The returned value will only be null if |destroy| was called before * |getNetworkingEngine|. */ getNetworkingEngine ( ) : shaka.net.NetworkingEngine | null ; /** * Returns true if an asset is currently downloading. */ getStoreInProgress ( ) : boolean ; /** * Lists all the stored content available. */ list ( ) : Promise < shaka.extern.StoredContent [] > ; /** * Removes the given stored content. This will also attempt to release the * licenses, if any. */ remove (contentUri : string ) : Promise < any > ; /** * Removes any EME sessions that were not successfully removed before. This * returns whether all the sessions were successfully removed. */ removeEmeSessions ( ) : Promise < boolean > ; /** * Stores the given manifest. If the content is encrypted, and encrypted * content cannot be stored on this platform, the Promise will be rejected * with error code 6001, REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE. * Multiple assets can be downloaded at the same time, but note that since * the storage instance has a single networking engine, multiple storage * objects will be necessary if some assets require unique network filters. * This snapshots the storage config at the time of the call, so it will not * honor any changes to config mid-store operation. * @param uri The URI of the manifest to store. * @param appMetadata An arbitrary object from the application that will be stored along-side the offline content. Use this for any application-specific metadata you need associated with the stored content. For details on the data types that can be stored here, please refer to {@link https://bit.ly/StructClone} * @param mimeType The mime type for the content |manifestUri| points to. */ store (uri : string , appMetadata ? : object , mimeType ? : string ) : shaka.extern.IAbortableOperation < any > ; /** * Delete the on-disk storage and all the content it contains. This should not * be done in normal circumstances. Only do it when storage is rendered * unusable, such as by a version mismatch. No business logic will be run, and * licenses will not be released. */ static deleteAll ( ) : Promise < any > ; /** * Gets whether offline storage is supported. Returns true if offline storage * is supported for clear content. Support for offline storage of encrypted * content will not be determined until storage is attempted. */ static support ( ) : boolean ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.offline { /** * StorageMuxer is responsible for managing StorageMechanisms and addressing * cells. The primary purpose of the muxer is to give the caller the correct * cell for the operations they want to perform. * |findActive| will be used when the caller wants a cell that supports * add-operations. This will be used when saving new content to storage. * |findAll| will be used when the caller want to look at all the content * in storage. * |resolvePath| will be used to convert a path (from |findActive| and * |findAll|) into a cell, which it then returns. */ class StorageMuxer implements shaka.util.IDestroyable { private noStructuralTyping_shaka_offline_StorageMuxer : any; /** * Free all resources used by the muxer, mechanisms, and cells. This should * not affect the stored content. */ destroy ( ) : Promise < any > ; /** * Register a storage mechanism for use with the default storage muxer. This * will have no effect on any storage muxer already in main memory. */ static register (name : string , factory : ( ) => shaka.extern.StorageMechanism | null ) : any ; /** * Unregister a storage mechanism for use with the default storage muxer. This * will have no effect on any storage muxer already in main memory. * @param name The name that the storage mechanism was registered under. */ static unregister (name : string ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka { class polyfill { private noStructuralTyping_shaka_polyfill : any; /** * Install all polyfills. */ static installAll ( ) : any ; /** * Registers a new polyfill to be installed. * @param priority An optional number priority. Higher priorities will be executed before lower priority ones. Default is 0. */ static register (polyfill : ( ) => any , priority ? : number ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class EncryptionScheme { private noStructuralTyping_shaka_polyfill_EncryptionScheme : any; /** * Install the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class Fullscreen { private noStructuralTyping_shaka_polyfill_Fullscreen : any; /** * Install the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class MathRound { private noStructuralTyping_shaka_polyfill_MathRound : any; /** * Install the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class MediaCapabilities { private noStructuralTyping_shaka_polyfill_MediaCapabilities : any; /** * Install the polyfill if needed. */ static install ( ) : any ; /** * A copy of the MediaCapabilities instance, to prevent Safari from * garbage-collecting the polyfilled method on it. We make it public and export * it to ensure that it is not stripped out by the compiler. */ static originalMcap : any | null ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class MediaSource { private noStructuralTyping_shaka_polyfill_MediaSource : any; /** * Install the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class Orientation { private noStructuralTyping_shaka_polyfill_Orientation : any; /** * Install the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class PatchedMediaKeysApple { private noStructuralTyping_shaka_polyfill_PatchedMediaKeysApple : any; /** * Installs the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class PatchedMediaKeysMs { private noStructuralTyping_shaka_polyfill_PatchedMediaKeysMs : any; /** * Installs the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class PatchedMediaKeysNop { private noStructuralTyping_shaka_polyfill_PatchedMediaKeysNop : any; /** * Installs the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class PatchedMediaKeysWebkit { private noStructuralTyping_shaka_polyfill_PatchedMediaKeysWebkit : any; /** * Installs the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class PiPWebkit { private noStructuralTyping_shaka_polyfill_PiPWebkit : any; /** * Install the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class StorageEstimate { private noStructuralTyping_shaka_polyfill_StorageEstimate : any; /** * Install the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class VTTCue { private noStructuralTyping_shaka_polyfill_VTTCue : any; /** * Install the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class VideoPlayPromise { private noStructuralTyping_shaka_polyfill_VideoPlayPromise : any; /** * Install the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.polyfill { class VideoPlaybackQuality { private noStructuralTyping_shaka_polyfill_VideoPlaybackQuality : any; /** * Install the polyfill if needed. */ static install ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { class Cue implements shaka.extern.Cue { private noStructuralTyping_shaka_text_Cue : any; constructor (startTime : number , endTime : number , payload : string ) ; backgroundColor : any ; backgroundImage : any ; border : any ; cellResolution : any ; color : any ; direction : any ; /** * Set the captions at the bottom of the text container by default. */ displayAlign : any ; endTime : any ; fontFamily : any ; fontSize : any ; fontStyle : any ; fontWeight : any ; id : any ; isContainer : any ; letterSpacing : any ; line : any ; /** * Line Alignment is set to start by default. */ lineAlign : any ; lineBreak : any ; lineHeight : any ; lineInterpretation : any ; linePadding : any ; nestedCues : any ; opacity : any ; payload : string ; position : any ; positionAlign : any ; region : any ; size : any ; spacer : any ; startTime : any ; textAlign : any ; textDecoration : any ; wrapLine : any ; writingMode : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.Cue { /** * Default text background color according to * https://w3c.github.io/webvtt/#default-text-background */ /** * Default text background color according to * https://w3c.github.io/webvtt/#default-text-background */ enum defaultTextBackgroundColor { bg_black = '#000' , bg_blue = '#00F' , bg_cyan = '#0FF' , bg_lime = '#0F0' , bg_magenta = '#F0F' , bg_red = '#F00' , bg_white = '#FFF' , bg_yellow = '#FF0' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.Cue { /** * Default text color according to * https://w3c.github.io/webvtt/#default-text-color */ /** * Default text color according to * https://w3c.github.io/webvtt/#default-text-color */ enum defaultTextColor { black = '#000' , blue = '#00F' , cyan = '#0FF' , lime = '#0F0' , magenta = '#F0F' , red = '#F00' , white = '#FFF' , yellow = '#FF0' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.Cue { enum direction { HORIZONTAL_LEFT_TO_RIGHT = 'ltr' , HORIZONTAL_RIGHT_TO_LEFT = 'rtl' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.Cue { /** * Vertical alignments of the cues within their extents. * 'BEFORE' means displaying at the top of the captions container box, 'CENTER' * means in the middle, 'AFTER' means at the bottom. */ /** * Vertical alignments of the cues within their extents. * 'BEFORE' means displaying at the top of the captions container box, 'CENTER' * means in the middle, 'AFTER' means at the bottom. */ enum displayAlign { AFTER = 'after' , BEFORE = 'before' , CENTER = 'center' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.Cue { enum fontStyle { ITALIC = 'italic' , NORMAL = 'normal' , OBLIQUE = 'oblique' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.Cue { /** * In CSS font weight can be a number, where 400 is normal and 700 is bold. * Use these values for the enum for consistency. */ /** * In CSS font weight can be a number, where 400 is normal and 700 is bold. * Use these values for the enum for consistency. */ enum fontWeight { BOLD = 700.0 , NORMAL = 400.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.Cue { enum lineAlign { CENTER = 'center' , END = 'end' , START = 'start' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.Cue { enum lineInterpretation { LINE_NUMBER = 0.0 , PERCENTAGE = 1.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.Cue { enum positionAlign { AUTO = 'auto' , CENTER = 'center' , LEFT = 'line-left' , RIGHT = 'line-right' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.Cue { enum textAlign { CENTER = 'center' , END = 'end' , LEFT = 'left' , RIGHT = 'right' , START = 'start' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.Cue { enum textDecoration { LINE_THROUGH = 'lineThrough' , OVERLINE = 'overline' , UNDERLINE = 'underline' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.Cue { enum writingMode { HORIZONTAL_TOP_TO_BOTTOM = 'horizontal-tb' , VERTICAL_LEFT_TO_RIGHT = 'vertical-lr' , VERTICAL_RIGHT_TO_LEFT = 'vertical-rl' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { class CueRegion implements shaka.extern.CueRegion { private noStructuralTyping_shaka_text_CueRegion : any; height : any ; heightUnits : any ; id : any ; regionAnchorX : any ; regionAnchorY : any ; scroll : any ; viewportAnchorUnits : any ; viewportAnchorX : any ; viewportAnchorY : any ; width : any ; widthUnits : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.CueRegion { enum scrollMode { NONE = '' , UP = 'up' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text.CueRegion { enum units { LINES = 2.0 , PERCENTAGE = 1.0 , PX = 0.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { /** * LRC file format: https://en.wikipedia.org/wiki/LRC_(file_format) */ class LrcTextParser implements shaka.extern.TextParser { private noStructuralTyping_shaka_text_LrcTextParser : any; parseInit (data : any ) : any ; parseMedia (data : any , time : any ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { class Mp4TtmlParser implements shaka.extern.TextParser { private noStructuralTyping_shaka_text_Mp4TtmlParser : any; parseInit (data : any ) : any ; parseMedia (data : any , time : any ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { class Mp4VttParser implements shaka.extern.TextParser { private noStructuralTyping_shaka_text_Mp4VttParser : any; parseInit (data : any ) : any ; parseMedia (data : any , time : any ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { class SbvTextParser implements shaka.extern.TextParser { private noStructuralTyping_shaka_text_SbvTextParser : any; parseInit (data : any ) : any ; parseMedia (data : any , time : any ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { /** * A text displayer plugin using the browser's native VTTCue interface. */ class SimpleTextDisplayer implements shaka.extern.TextDisplayer { private noStructuralTyping_shaka_text_SimpleTextDisplayer : any; /** * A text displayer plugin using the browser's native VTTCue interface. */ constructor (video : HTMLMediaElement | null ) ; append (cues : any ) : any ; destroy ( ) : any ; isTextVisible ( ) : any ; remove (start : any , end : any ) : any ; setTextVisibility (on : any ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { class SrtTextParser implements shaka.extern.TextParser { private noStructuralTyping_shaka_text_SrtTextParser : any; parseInit (data : any ) : any ; parseMedia (data : any , time : any ) : any ; /** * Convert a SRT format to WebVTT */ static srt2webvtt (data : string ) : string ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { /** * Documentation: http://moodub.free.fr/video/ass-specs.doc * https://en.wikipedia.org/wiki/SubStation_Alpha */ class SsaTextParser implements shaka.extern.TextParser { private noStructuralTyping_shaka_text_SsaTextParser : any; parseInit (data : any ) : any ; parseMedia (data : any , time : any ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { class TextEngine implements shaka.util.IDestroyable { private noStructuralTyping_shaka_text_TextEngine : any; constructor (displayer : shaka.extern.TextDisplayer | null ) ; destroy ( ) : Promise < any > ; static findParser (mimeType : any ) : ( shaka.extern.TextParserPlugin ) | null ; static registerParser (mimeType : string , plugin : shaka.extern.TextParserPlugin ) : any ; static unregisterParser (mimeType : string ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { class TtmlTextParser implements shaka.extern.TextParser { private noStructuralTyping_shaka_text_TtmlTextParser : any; parseInit (data : any ) : any ; parseMedia (data : any , time : any ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { /** * The text displayer plugin for the Shaka Player UI. Can also be used directly * by providing an appropriate container element. */ class UITextDisplayer implements shaka.extern.TextDisplayer { private noStructuralTyping_shaka_text_UITextDisplayer : any; /** * The text displayer plugin for the Shaka Player UI. Can also be used directly * by providing an appropriate container element. */ constructor (video : HTMLMediaElement | null , videoContainer : HTMLElement | null ) ; append (cues : any ) : any ; destroy ( ) : any ; isTextVisible ( ) : any ; remove (start : any , end : any ) : any ; setTextVisibility (on : any ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { class VttTextParser implements shaka.extern.TextParser { private noStructuralTyping_shaka_text_VttTextParser : any; parseInit (data : any ) : any ; parseMedia (data : any , time : any ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.text { class WebVttGenerator { private noStructuralTyping_shaka_text_WebVttGenerator : any; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class AdCounter extends shaka.ui.Element { private noStructuralTyping_shaka_ui_AdCounter : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class AdPosition extends shaka.ui.Element { private noStructuralTyping_shaka_ui_AdPosition : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class AirPlayButton extends shaka.ui.Element { private noStructuralTyping_shaka_ui_AirPlayButton : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class AudioLanguageSelection extends shaka.ui.SettingsMenu { private noStructuralTyping_shaka_ui_AudioLanguageSelection : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class BigPlayButton extends shaka.ui.PlayButton { private noStructuralTyping_shaka_ui_BigPlayButton : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class CastButton extends shaka.ui.Element { private noStructuralTyping_shaka_ui_CastButton : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { /** * A container for custom video controls. */ class Controls extends shaka.util.FakeEventTarget implements shaka.util.IDestroyable { private noStructuralTyping_shaka_ui_Controls : any; /** * A container for custom video controls. */ constructor (player : shaka.Player , videoContainer : HTMLElement , video : HTMLMediaElement , config : shaka.extern.UIConfiguration ) ; /** * This allows the application to inhibit casting. */ allowCast (allow : boolean ) : any ; anySettingsMenusAreOpen ( ) : boolean ; configure (config : shaka.extern.UIConfiguration ) : any ; destroy ( ) : Promise < any > ; getAd ( ) : shaka.extern.IAd | null ; getCastProxy ( ) : shaka.cast.CastProxy | null ; getClientSideAdContainer ( ) : HTMLElement ; getConfig ( ) : shaka.extern.UIConfiguration ; getControlsContainer ( ) : HTMLElement ; getDisplayTime ( ) : number ; getLocalPlayer ( ) : shaka.Player | null ; getLocalVideo ( ) : HTMLMediaElement | null ; getLocalization ( ) : shaka.ui.Localization | null ; getPlayer ( ) : shaka.Player | null ; getServerSideAdContainer ( ) : HTMLElement ; getVideo ( ) : HTMLMediaElement | null ; getVideoContainer ( ) : HTMLElement ; hideAdUI ( ) : any ; hideSettingsMenus ( ) : any ; isCastAllowed ( ) : boolean ; isOpaque ( ) : boolean ; isSeeking ( ) : boolean ; /** * Used by the application to notify the controls that a load operation is * complete. This allows the controls to recalculate play/paused state, which * is important for platforms like Android where autoplay is disabled. */ loadComplete ( ) : any ; /** * Enable or disable native browser controls. Enabling disables shaka * controls. */ setEnabledNativeControls (enabled : boolean ) : any ; /** * Enable or disable the custom controls. Enabling disables native * browser controls. */ setEnabledShakaControls (enabled : boolean ) : any ; setLastTouchEventTime (time : number | null ) : any ; setSeeking (seeking : boolean ) : any ; showAdUI ( ) : any ; toggleFullScreen ( ) : any ; static registerElement (name : string , factory : shaka.extern.IUIElement.Factory ) : any ; static registerSeekBar (factory : shaka.extern.IUISeekBar.Factory ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { abstract class Element implements shaka.extern.IUIElement { private noStructuralTyping_shaka_ui_Element : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; ad : shaka.extern.IAd | null ; adManager : shaka.extern.IAdManager | null ; controls : shaka.ui.Controls | null ; eventManager : shaka.util.EventManager | null ; localization : shaka.ui.Localization | null ; parent : HTMLElement | null ; player : shaka.Player | null ; release ( ) : any ; video : HTMLMediaElement | null ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class FastForwardButton extends shaka.ui.Element { private noStructuralTyping_shaka_ui_FastForwardButton : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class FullscreenButton extends shaka.ui.Element { private noStructuralTyping_shaka_ui_FullscreenButton : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { /** * Localization system provided by the shaka ui library. * It can be used to store the various localized forms of * strings that are expected to be displayed to the user. * If a string is not available, it will return the localized * form in the closest related locale. */ class Localization extends shaka.util.FakeEventTarget { private noStructuralTyping_shaka_ui_Localization : any; constructor (fallbackLocale : string ) ; /** * Request the localization system to change which locale it serves. If any of * of the preferred locales cannot be found, the localization system will fire * an event identifying which locales it does not know. The localization * system will then continue to operate using the closest matches it has. * @param locales The locale codes for the requested locales in order of preference. */ changeLocale (locales : Iterable < string > ) : any ; /** * Insert a set of localizations for a single locale. This will amend the * existing localizations for the given locale. * @param locale The locale that the localizations should be added to. * @param localizations A mapping of id to localized text that should used to modify the internal collection of localizations. * @param conflictResolution The strategy used to resolve conflicts when the id of an existing entry matches the id of a new entry. Default to |USE_NEW|, where the new entry will replace the old entry. */ insert (locale : string , localizations : Map < string , string > , conflictResolution ? : shaka.ui.Localization.ConflictResolution ) : shaka.ui.Localization ; release ( ) : any ; /** * Request the localized string under the given id. If there is no localized * version of the string, then the fallback localization will be given * ("en" version). If there is no fallback localization, a non-null empty * string will be returned. * @param id The id for the localization entry. */ resolve (id : string ) : string ; /** * Set the value under each key in |dictionary| to the resolved value. * Convenient for apps with some kind of data binding system. * Equivalent to: * for (const key of dictionary.keys()) { * dictionary.set(key, localization.resolve(key)); * } */ resolveDictionary (dictionary : Map < string , string > ) : any ; /** * The event name for when a new locale has been requested and any previously * resolved values should be updated. */ static LOCALE_CHANGED : string ; /** * The event name for when |insert| was called and it changed entries that could * affect previously resolved values. */ static LOCALE_UPDATED : string ; /** * The event name for when entries are missing from the user's preferred * locale, but we were able to find an entry in a related locale or the fallback * locale. */ static MISSING_LOCALIZATIONS : string ; /** * The event name for when locales were requested, but we could not find any * entries for them. The localization system will continue to use the closest * matches it has. */ static UNKNOWN_LOCALES : string ; /** * The event name for when an entry could not be found in the preferred locale, * related locales, or the fallback locale. */ static UNKNOWN_LOCALIZATION : string ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui.Localization { /** * An enum for how the localization system should resolve conflicts between old * translations and new translations. */ /** * An enum for how the localization system should resolve conflicts between old * translations and new translations. */ enum ConflictResolution { USE_NEW = 1.0 , USE_OLD = 0.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class LoopButton extends shaka.ui.Element { private noStructuralTyping_shaka_ui_LoopButton : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class MuteButton extends shaka.ui.Element { private noStructuralTyping_shaka_ui_MuteButton : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class OverflowMenu extends shaka.ui.Element { private noStructuralTyping_shaka_ui_OverflowMenu : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; static registerElement (name : string , factory : shaka.extern.IUIElement.Factory ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class Overlay implements shaka.util.IDestroyable { private noStructuralTyping_shaka_ui_Overlay : any; constructor (player : shaka.Player , videoContainer : HTMLElement , video : HTMLMediaElement ) ; configure (config : string | object , value ? : any ) : any ; destroy ( ) : Promise < any > ; getConfiguration ( ) : shaka.extern.UIConfiguration ; getControls ( ) : shaka.ui.Controls | null ; /** * Detects if this is a mobile platform, in case you want to choose a * different UI configuration on mobile devices. */ isMobile ( ) : boolean ; /** * Enable or disable the custom controls. */ setEnabled (enabled : boolean ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui.Overlay { /** * Describes the possible reasons that the UI might fail to load. */ /** * Describes the possible reasons that the UI might fail to load. */ enum FailReasonCode { NO_BROWSER_SUPPORT = 0.0 , PLAYER_FAILED_TO_LOAD = 1.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui.Overlay { /** * Describes what information should show up in labels for selecting audio * variants and text tracks. */ /** * Describes what information should show up in labels for selecting audio * variants and text tracks. */ enum TrackLabelFormat { LABEL = 3.0 , LANGUAGE = 0.0 , LANGUAGE_ROLE = 2.0 , ROLE = 1.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class PipButton extends shaka.ui.Element { private noStructuralTyping_shaka_ui_PipButton : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class PlayButton extends shaka.ui.Element { private noStructuralTyping_shaka_ui_PlayButton : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class PlaybackRateSelection extends shaka.ui.SettingsMenu { private noStructuralTyping_shaka_ui_PlaybackRateSelection : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class PresentationTimeTracker extends shaka.ui.Element { private noStructuralTyping_shaka_ui_PresentationTimeTracker : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { /** * A range element, built to work across browsers. * In particular, getting styles to work right on IE requires a specific * structure. * This also handles the case where the range element is being manipulated and * updated at the same time. This can happen when seeking during playback or * when casting. */ class RangeElement extends shaka.ui.Element implements shaka.extern.IUIRangeElement { private noStructuralTyping_shaka_ui_RangeElement : any; /** * A range element, built to work across browsers. * In particular, getting styles to work right on IE requires a specific * structure. * This also handles the case where the range element is being manipulated and * updated at the same time. This can happen when seeking during playback or * when casting. */ constructor (parent : HTMLElement , controls : shaka.ui.Controls , containerClassNames : string [] , barClassNames : string [] ) ; bar : HTMLInputElement ; /** * Called to implement keyboard-based changes, where this is no clear "end". * This will simulate events like onChangeStart(), onChange(), and * onChangeEnd() as appropriate. */ changeTo (value : any ) : any ; container : HTMLElement ; getValue ( ) : any ; /** * Called when a new value is set by user interaction. * To be overridden by subclasses. */ onChange ( ) : any ; /** * Called when user interaction ends. * To be overridden by subclasses. */ onChangeEnd ( ) : any ; /** * Called when user interaction begins. * To be overridden by subclasses. */ onChangeStart ( ) : any ; setRange (min : any , max : any ) : any ; setValue (value : any ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class ResolutionSelection extends shaka.ui.SettingsMenu { private noStructuralTyping_shaka_ui_ResolutionSelection : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class RewindButton extends shaka.ui.Element { private noStructuralTyping_shaka_ui_RewindButton : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class SeekBar extends shaka.ui.RangeElement implements shaka.extern.IUISeekBar { private noStructuralTyping_shaka_ui_SeekBar : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; isShowing ( ) : boolean ; update ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui.SeekBar { class Factory implements shaka.extern.IUISeekBar.Factory { private noStructuralTyping_shaka_ui_SeekBar_Factory : any; create (rootElement : HTMLElement , controls : shaka.ui.Controls ) : shaka.extern.IUISeekBar ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class SettingsMenu extends shaka.ui.Element implements shaka.extern.IUISettingsMenu { private noStructuralTyping_shaka_ui_SettingsMenu : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls , iconText : string ) ; backButton : HTMLButtonElement ; backSpan : HTMLElement ; button : HTMLButtonElement ; currentSelection : HTMLElement ; icon : HTMLElement ; menu : HTMLElement ; nameSpan : HTMLElement ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class SkipAdButton extends shaka.ui.Element { private noStructuralTyping_shaka_ui_SkipAdButton : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class SmallPlayButton extends shaka.ui.PlayButton { private noStructuralTyping_shaka_ui_SmallPlayButton : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class Spacer extends shaka.ui.Element { private noStructuralTyping_shaka_ui_Spacer : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class TextSelection extends shaka.ui.SettingsMenu { private noStructuralTyping_shaka_ui_TextSelection : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.ui { class VolumeBar extends shaka.ui.RangeElement { private noStructuralTyping_shaka_ui_VolumeBar : any; constructor (parent : HTMLElement , controls : shaka.ui.Controls ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { /** * A utility to wrap abortable operations. Note that these are not cancelable. * Cancelation implies undoing what has been done so far, whereas aborting only * means that further work is stopped. */ class AbortableOperation < T > implements shaka.extern.IAbortableOperation < T > { private noStructuralTyping_shaka_util_AbortableOperation : any; /** * A utility to wrap abortable operations. Note that these are not cancelable. * Cancelation implies undoing what has been done so far, whereas aborting only * means that further work is stopped. */ constructor (promise : Promise < T > , onAbort : shaka.extern.CreateSegmentIndexFunction ) ; abort ( ) : any ; chain < U > (onSuccess : undefined | Function , onError ? : (a : any ) => any ) : shaka.util.AbortableOperation < U > ; finally (onFinal : any ) : any ; promise : Promise < T > ; static aborted ( ) : shaka.util.AbortableOperation < any > ; static all (operations : shaka.util.AbortableOperation < any > [] ) : shaka.util.AbortableOperation < any > ; static completed < U > (value : U ) : shaka.util.AbortableOperation < U > ; static failed (error : shaka.util.Error ) : shaka.util.AbortableOperation < any > ; static notAbortable < U > (promise : Promise < U > ) : shaka.util.AbortableOperation < U > ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class BufferUtils { private noStructuralTyping_shaka_util_BufferUtils : any; /** * Compare two buffers for equality. For buffers of different types, this * compares the underlying buffers as binary data. */ static equal (arr1 : ArrayBuffer | ArrayBufferView | null , arr2 : ArrayBuffer | ArrayBufferView | null ) : boolean ; /** * Gets an ArrayBuffer that contains the data from the given TypedArray. Note * this will allocate a new ArrayBuffer if the object is a partial view of * the data. */ static toArrayBuffer (view : ArrayBuffer | ArrayBufferView ) : ArrayBuffer ; /** * Creates a DataView over the given buffer. */ static toDataView (buffer : ArrayBuffer | ArrayBufferView , offset ? : number , length ? : number ) : DataView ; /** * Creates a new Uint8Array view on the same buffer. This clamps the values * to be within the same view (i.e. you can't use this to move past the end * of the view, even if the underlying buffer is larger). However, you can * pass a negative offset to access the data before the view. * @param offset The offset from the beginning of this data's view to start the new view at. * @param length The byte length of the new view. */ static toUint8 (data : ArrayBuffer | ArrayBufferView , offset ? : number , length ? : number ) : Uint8Array ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class ConfigUtils { private noStructuralTyping_shaka_util_ConfigUtils : any; /** * Convert config from ('fieldName', value) format to a partial config object. * E. g. from ('manifest.retryParameters.maxAttempts', 1) to * { manifest: { retryParameters: { maxAttempts: 1 }}}. */ static convertToConfigObject (fieldName : string , value : any ) : object ; static mergeConfigObjects (destination : object , source : object , template : object , overrides : object , path : string ) : boolean ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class DataViewReader { private noStructuralTyping_shaka_util_DataViewReader : any; constructor (data : ArrayBuffer | ArrayBufferView , endianness : shaka.util.DataViewReader.Endianness ) ; /** * Gets the byte length of the DataView. */ getLength ( ) : number ; /** * Gets the current byte position. */ getPosition ( ) : number ; hasMoreData ( ) : boolean ; /** * Reads the specified number of raw bytes. * @param bytes The number of bytes to read. */ readBytes (bytes : number ) : Uint8Array ; /** * Reads a signed 32 bit integer, and advances the reader. */ readInt32 ( ) : number ; /** * Keeps reading until it reaches a byte that equals to zero. The text is * assumed to be UTF-8. */ readTerminatedString ( ) : string ; /** * Reads an unsigned 16 bit integer, and advances the reader. */ readUint16 ( ) : number ; /** * Reads an unsigned 32 bit integer, and advances the reader. */ readUint32 ( ) : number ; /** * Reads an unsigned 64 bit integer, and advances the reader. */ readUint64 ( ) : number ; /** * Reads an unsigned 8 bit integer, and advances the reader. */ readUint8 ( ) : number ; /** * Rewinds the specified number of bytes. * @param bytes The number of bytes to rewind. */ rewind (bytes : number ) : any ; /** * Seeks to a specified position. * @param position The desired byte position within the DataView. */ seek (position : number ) : any ; /** * Skips the specified number of bytes. * @param bytes The number of bytes to skip. */ skip (bytes : number ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util.DataViewReader { /** * Endianness. */ /** * Endianness. */ enum Endianness { BIG_ENDIAN = 0.0 , LITTLE_ENDIAN = 1.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class Dom { private noStructuralTyping_shaka_util_Dom : any; /** * Remove all of the child nodes of an element. */ static removeAllChildren (element : Element ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class Error extends GlobalError implements shaka.extern.Error { private noStructuralTyping_shaka_util_Error : any; constructor (severity : shaka.util.Error.Severity , category : shaka.util.Error.Category , code : shaka.util.Error.Code , ...varArgs : any [] ) ; category : any ; code : any ; data : any ; handled : any ; severity : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util.Error { enum Category { ADS = 10.0 , CAST = 8.0 , DRM = 6.0 , MANIFEST = 4.0 , MEDIA = 3.0 , NETWORK = 1.0 , PLAYER = 7.0 , STORAGE = 9.0 , STREAMING = 5.0 , TEXT = 2.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util.Error { enum Code { ALREADY_CASTING = 8002.0 , ATTEMPTS_EXHAUSTED = 1010.0 , BAD_ENCODING = 2004.0 , BAD_HTTP_STATUS = 1001.0 , BUFFER_READ_OUT_OF_BOUNDS = 3000.0 , CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM = 4033.0 , CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS = 2012.0 , CANNOT_STORE_LIVE_OFFLINE = 9005.0 , CAST_API_UNAVAILABLE = 8000.0 , CAST_CANCELED_BY_USER = 8004.0 , CAST_CONNECTION_TIMED_OUT = 8005.0 , CAST_RECEIVER_APP_UNAVAILABLE = 8006.0 , CONTENT_NOT_LOADED = 7004.0 , CONTENT_TRANSFORMATION_FAILED = 3019.0 , CONTENT_UNSUPPORTED_BY_BROWSER = 4032.0 , CS_AD_MANAGER_NOT_INITIALIZED = 10001.0 , CS_IMA_SDK_MISSING = 10000.0 , CURRENT_DAI_REQUEST_NOT_FINISHED = 10004.0 , DASH_CONFLICTING_KEY_IDS = 4010.0 , DASH_DUPLICATE_REPRESENTATION_ID = 4018.0 , DASH_EMPTY_ADAPTATION_SET = 4003.0 , DASH_EMPTY_PERIOD = 4004.0 , DASH_INVALID_XML = 4001.0 , DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED = 4009.0 , DASH_NO_COMMON_KEY_SYSTEM = 4008.0 , DASH_NO_SEGMENT_INFO = 4002.0 , DASH_PSSH_BAD_ENCODING = 4007.0 , DASH_UNSUPPORTED_CONTAINER = 4006.0 , DASH_UNSUPPORTED_XLINK_ACTUATE = 4027.0 , DASH_WEBM_MISSING_INIT = 4005.0 , DASH_XLINK_DEPTH_LIMIT = 4028.0 , DEPRECATED_OPERATION_ABORTED = 9002.0 , DOWNLOAD_SIZE_CALLBACK_ERROR = 9015.0 , EBML_BAD_FLOATING_POINT_SIZE = 3003.0 , EBML_OVERFLOW = 3002.0 , ENCRYPTED_CONTENT_WITHOUT_DRM_INFO = 6010.0 , EXPIRED = 6014.0 , FAILED_TO_ATTACH_TO_VIDEO = 6003.0 , FAILED_TO_CREATE_CDM = 6002.0 , FAILED_TO_CREATE_SESSION = 6005.0 , FAILED_TO_GENERATE_LICENSE_REQUEST = 6006.0 , HLS_AES_128_ENCRYPTION_NOT_SUPPORTED = 4034.0 , HLS_COULD_NOT_GUESS_CODECS = 4025.0 , HLS_COULD_NOT_PARSE_SEGMENT_START_TIME = 4030.0 , HLS_INTERNAL_SKIP_STREAM = 4035.0 , HLS_INVALID_PLAYLIST_HIERARCHY = 4017.0 , HLS_KEYFORMATS_NOT_SUPPORTED = 4026.0 , HLS_MASTER_PLAYLIST_NOT_PROVIDED = 4022.0 , HLS_MULTIPLE_MEDIA_INIT_SECTIONS_FOUND = 4020.0 , HLS_PLAYLIST_HEADER_MISSING = 4015.0 , HLS_REQUIRED_ATTRIBUTE_MISSING = 4023.0 , HLS_REQUIRED_TAG_MISSING = 4024.0 , HLS_VARIABLE_NOT_FOUND = 4039.0 , HTTP_ERROR = 1002.0 , INCONSISTENT_DRM_ACROSS_PERIODS = 4038.0 , INDEXED_DB_ERROR = 9001.0 , INIT_DATA_TRANSFORM_ERROR = 6016.0 , INVALID_HLS_TAG = 4016.0 , INVALID_MP4_CEA = 2010.0 , INVALID_MP4_TTML = 2007.0 , INVALID_MP4_VTT = 2008.0 , INVALID_SERVER_CERTIFICATE = 6004.0 , INVALID_TEXT_CUE = 2001.0 , INVALID_TEXT_HEADER = 2000.0 , INVALID_XML = 2005.0 , JS_INTEGER_OVERFLOW = 3001.0 , KEY_NOT_FOUND = 9012.0 , LICENSE_REQUEST_FAILED = 6007.0 , LICENSE_RESPONSE_REJECTED = 6008.0 , LOAD_INTERRUPTED = 7000.0 , LOCAL_PLAYER_INSTANCE_REQUIRED = 9008.0 , MALFORMED_DATA_URI = 1004.0 , MALFORMED_OFFLINE_URI = 9004.0 , MALFORMED_TEST_URI = 1008.0 , MEDIA_SOURCE_OPERATION_FAILED = 3014.0 , MEDIA_SOURCE_OPERATION_THREW = 3015.0 , MISSING_STORAGE_CELL = 9013.0 , MISSING_TEXT_PLUGIN = 2014.0 , MP4_SIDX_INVALID_TIMESCALE = 3005.0 , MP4_SIDX_TYPE_NOT_SUPPORTED = 3006.0 , MP4_SIDX_WRONG_BOX_TYPE = 3004.0 , NEW_KEY_OPERATION_NOT_SUPPORTED = 9011.0 , NO_CAST_RECEIVERS = 8001.0 , NO_INIT_DATA_FOR_OFFLINE = 9007.0 , NO_LICENSE_SERVER_GIVEN = 6012.0 , NO_RECOGNIZED_KEY_SYSTEMS = 6000.0 , NO_VARIANTS = 4036.0 , NO_VIDEO_ELEMENT = 7002.0 , OBJECT_DESTROYED = 7003.0 , OFFLINE_SESSION_REMOVED = 6013.0 , OPERATION_ABORTED = 7001.0 , PERIOD_FLATTENING_FAILED = 4037.0 , QUOTA_EXCEEDED_ERROR = 3017.0 , REQUESTED_ITEM_NOT_FOUND = 9003.0 , REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE = 6001.0 , REQUEST_FILTER_ERROR = 1006.0 , RESPONSE_FILTER_ERROR = 1007.0 , RESTRICTIONS_CANNOT_BE_MET = 4012.0 , SERVER_CERTIFICATE_REQUIRED = 6015.0 , SS_AD_MANAGER_NOT_INITIALIZED = 10003.0 , SS_IMA_SDK_MISSING = 10002.0 , STORAGE_LIMIT_REACHED = 9014.0 , STORAGE_NOT_SUPPORTED = 9000.0 , STREAMING_ENGINE_STARTUP_INVALID_STATE = 5006.0 , TEXT_COULD_NOT_GUESS_MIME_TYPE = 2011.0 , TEXT_ONLY_WEBVTT_SRC_EQUALS = 2013.0 , TIMEOUT = 1003.0 , TRANSMUXING_FAILED = 3018.0 , UNABLE_TO_DETECT_ENCODING = 2003.0 , UNABLE_TO_EXTRACT_CUE_START_TIME = 2009.0 , UNABLE_TO_GUESS_MANIFEST_TYPE = 4000.0 , UNEXPECTED_CAST_ERROR = 8003.0 , UNEXPECTED_TEST_REQUEST = 1009.0 , UNSUPPORTED_SCHEME = 1000.0 , VIDEO_ERROR = 3016.0 , WEBM_CUES_ELEMENT_MISSING = 3007.0 , WEBM_CUE_TIME_ELEMENT_MISSING = 3013.0 , WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING = 3012.0 , WEBM_DURATION_ELEMENT_MISSING = 3011.0 , WEBM_EBML_HEADER_ELEMENT_MISSING = 3008.0 , WEBM_INFO_ELEMENT_MISSING = 3010.0 , WEBM_SEGMENT_ELEMENT_MISSING = 3009.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util.Error { enum Severity { CRITICAL = 2.0 , RECOVERABLE = 1.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class EventManager implements shaka.util.IReleasable { private noStructuralTyping_shaka_util_EventManager : any; /** * Attaches an event listener to an event target. * @param target The event target. * @param type The event type. * @param listener The event listener. * @param options An object that specifies characteristics about the event listener. The passive option, if true, indicates that this function will never call preventDefault(), which improves scrolling performance. */ listen (target : EventTarget | null , type : string , listener : shaka.util.EventManager.ListenerType , options ? : boolean | AddEventListenerOptions ) : any ; /** * Attaches an event listener to an event target. The listener will be * removed when the first instance of the event is fired. * @param target The event target. * @param type The event type. * @param listener The event listener. * @param options An object that specifies characteristics about the event listener. The passive option, if true, indicates that this function will never call preventDefault(), which improves scrolling performance. */ listenOnce (target : EventTarget | null , type : string , listener : shaka.util.EventManager.ListenerType , options ? : boolean | AddEventListenerOptions ) : any ; /** * Detaches all event listeners. */ release ( ) : any ; /** * Detaches all event listeners from all targets. */ removeAll ( ) : any ; /** * Detaches an event listener from an event target. * @param target The event target. * @param type The event type. * @param listener The event listener. */ unlisten (target : EventTarget | null , type : string , listener ? : shaka.util.EventManager.ListenerType ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util.EventManager { type ListenerType = (a : Event ) => any ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class FairPlayUtils { private noStructuralTyping_shaka_util_FairPlayUtils : any; /** * Using the default method, extract a content ID from the init data. This is * based on the FairPlay example documentation. */ static defaultGetContentId (initData : ArrayBuffer | ArrayBufferView ) : string ; /** * Transforms the init data buffer using the given data. The format is: * <pre> * [4 bytes] initDataSize * [initDataSize bytes] initData * [4 bytes] contentIdSize * [contentIdSize bytes] contentId * [4 bytes] certSize * [certSize bytes] cert * </pre> * @param cert The server certificate; this will throw if not provided. */ static initDataTransform (initData : ArrayBuffer | ArrayBufferView , contentId : ArrayBuffer | ArrayBufferView | string , cert : ArrayBuffer | ArrayBufferView | null ) : Uint8Array ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class FakeEvent extends Event { private noStructuralTyping_shaka_util_FakeEvent : any; constructor (type : string , dict ? : Map < string , object | null > | null ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class FakeEventTarget implements EventTarget , shaka.util.IReleasable { private noStructuralTyping_shaka_util_FakeEventTarget : any; /** * Add an event listener to this object. * @param type The event type to listen for. * @param listener The callback or listener object to invoke. * @param options Ignored. */ addEventListener (type : string , listener : EventListener | null | ( (a : Event ) => any ) , options ? : AddEventListenerOptions | boolean ) : any ; /** * Dispatch an event from this object. * @param event The event to be dispatched from this object. */ dispatchEvent (event : Event ) : boolean ; /** * Add an event listener to this object that is invoked for all events types * the object fires. * @param listener The callback or listener object to invoke. */ listenToAllEvents (listener : EventListener | null | ( (a : Event ) => any ) ) : any ; release ( ) : any ; /** * Remove an event listener from this object. * @param type The event type for which you wish to remove a listener. * @param listener The callback or listener object to remove. * @param options Ignored. */ removeEventListener (type : string , listener : EventListener | null | ( (a : Event ) => any ) , options ? : EventListenerOptions | null | boolean ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util.FakeEventTarget { /** * These are the listener types defined in the closure extern for EventTarget. */ type ListenerType = EventListener | null | ( (a : Event ) => any ) ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { /** * An interface to standardize how objects are destroyed. */ interface IDestroyable { /** * Request that this object be destroyed, releasing all resources and shutting * down all operations. Returns a Promise which is resolved when destruction * is complete. This Promise should never be rejected. */ destroy ( ) : Promise < any > ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { /** * An interface to standardize how objects release internal references * synchronously. If an object needs to asynchronously release references, then * it should use 'shaka.util.IDestroyable'. */ interface IReleasable { /** * Request that this object release all internal references. */ release ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class Mp4Parser { private noStructuralTyping_shaka_util_Mp4Parser : any; /** * Declare a box type as a Box. */ box (type : string , definition : shaka.util.Mp4Parser.CallbackType ) : shaka.util.Mp4Parser ; /** * Declare a box type as a Full Box. */ fullBox (type : string , definition : shaka.util.Mp4Parser.CallbackType ) : shaka.util.Mp4Parser ; /** * Parse the given data using the added callbacks. * @param partialOkay If true, allow reading partial payloads from some boxes. If the goal is a child box, we can sometimes find it without enough data to find all child boxes. * @param stopOnPartial If true, stop reading if an incomplete box is detected. */ parse (data : ArrayBuffer | ArrayBufferView , partialOkay ? : boolean , stopOnPartial ? : boolean ) : any ; /** * Parse the next box on the current level. * @param absStart The absolute start position in the original byte array. * @param partialOkay If true, allow reading partial payloads from some boxes. If the goal is a child box, we can sometimes find it without enough data to find all child boxes. * @param stopOnPartial If true, stop reading if an incomplete box is detected. */ parseNext (absStart : number , reader : shaka.util.DataViewReader , partialOkay ? : boolean , stopOnPartial ? : boolean ) : any ; /** * Stop parsing. Useful for extracting information from partial segments and * avoiding an out-of-bounds error once you find what you are looking for. */ stop ( ) : any ; /** * Create a callback that tells the Mp4 parser to treat the body of a box as a * binary blob and to parse the body's contents using the provided callback. */ static allData (callback : (a : Uint8Array ) => any ) : shaka.util.Mp4Parser.CallbackType ; /** * A callback that tells the Mp4 parser to treat the body of a box as a series * of boxes. The number of boxes is limited by the size of the parent box. */ static children (box : shaka.extern.ParsedBox ) : any ; /** * Find the header size of the box. * Useful for modifying boxes in place or finding the exact offset of a field. */ static headerSize (box : shaka.extern.ParsedBox ) : number ; /** * A callback that tells the Mp4 parser to treat the body of a box as a sample * description. A sample description box has a fixed number of children. The * number of children is represented by a 4 byte unsigned integer. Each child * is a box. */ static sampleDescription (box : shaka.extern.ParsedBox ) : any ; /** * Convert an integer type from a box into an ascii string name. * Useful for debugging. * @param type The type of the box, a uint32. */ static typeToString (type : number ) : string ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util.Mp4Parser { type CallbackType = (a : shaka.extern.ParsedBox ) => any ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class PlayerConfiguration { private noStructuralTyping_shaka_util_PlayerConfiguration : any; /** * Merges the given configuration changes into the given destination. This * uses the default Player configurations as the template. */ static mergeConfigObjects (destination : shaka.extern.PlayerConfiguration , updates : object , template ? : shaka.extern.PlayerConfiguration ) : boolean ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class StringUtils { private noStructuralTyping_shaka_util_StringUtils : any; /** * Creates a string from the given buffer, auto-detecting the encoding that is * being used. If it cannot detect the encoding, it will throw an exception. */ static fromBytesAutoDetect (data : ArrayBuffer | ArrayBufferView | null ) : string ; /** * Creates a string from the given buffer as UTF-16 encoding. * @param littleEndian true to read little endian, false to read big. * @param noThrow true to avoid throwing in cases where we may expect invalid input. If noThrow is true and the data has an odd length,it will be truncated. */ static fromUTF16 (data : ArrayBuffer | ArrayBufferView | null , littleEndian : boolean , noThrow ? : boolean ) : string ; /** * Creates a string from the given buffer as UTF-8 encoding. */ static fromUTF8 (data : ArrayBuffer | ArrayBufferView | null ) : string ; /** * Resets the fromCharCode method's implementation. * For debug use. */ static resetFromCharCode ( ) : any ; /** * Creates a ArrayBuffer from the given string, converting to UTF-16 encoding. */ static toUTF16 (str : string , littleEndian : boolean ) : ArrayBuffer ; /** * Creates a ArrayBuffer from the given string, converting to UTF-8 encoding. */ static toUTF8 (str : string ) : ArrayBuffer ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { /** * A timer allows a single function to be executed at a later time or at * regular intervals. */ class Timer { private noStructuralTyping_shaka_util_Timer : any; constructor (onTick : ( ) => any ) ; /** * Stop the timer and clear the previous behaviour. The timer is still usable * after calling |stop|. */ stop ( ) : any ; /** * Have the timer call |onTick| after |seconds| has elapsed unless |stop| is * called first. */ tickAfter (seconds : number ) : shaka.util.Timer ; /** * Have the timer call |onTick| every |seconds| until |stop| is called. */ tickEvery (seconds : number ) : shaka.util.Timer ; /** * Have the timer call |onTick| now. */ tickNow ( ) : shaka.util.Timer ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/dist/shaka-player.ui.externs.js declare namespace shaka.util { class Uint8ArrayUtils { private noStructuralTyping_shaka_util_Uint8ArrayUtils : any; /** * Concatenate buffers. */ static concat ( ...varArgs : ( ArrayBuffer | ArrayBufferView ) [] ) : Uint8Array ; /** * Compare two Uint8Arrays for equality. */ static equal (arr1 : Uint8Array | null , arr2 : Uint8Array | null ) : boolean ; /** * Convert a base64 string to a Uint8Array. Accepts either the standard * alphabet or the alternate "base64url" alphabet. */ static fromBase64 (str : string ) : Uint8Array ; /** * Convert a hex string to a Uint8Array. */ static fromHex (str : string ) : Uint8Array ; /** * Convert a buffer to a base64 string. The output will always use the * alternate encoding/alphabet also known as "base64url". * @param padding If true, pad the output with equals signs. Defaults to true. */ static toBase64 (data : ArrayBuffer | ArrayBufferView , padding ? : boolean ) : string ; /** * Convert a buffer to a hex string. */ static toHex (data : ArrayBuffer | ArrayBufferView ) : string ; /** * Convert a buffer to a base64 string. The output will be standard * alphabet as opposed to base64url safe alphabet. */ static toStandardBase64 (data : ArrayBuffer | ArrayBufferView ) : string ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/airplay.js declare namespace ಠ_ಠ.clutz { class AirPlayEvent extends Event { private noStructuralTyping_AirPlayEvent : any; constructor ( ...a : any [] ) ; availability : String | null ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/awesomplete.js declare namespace ಠ_ಠ.clutz { class Awesomplete { private noStructuralTyping_Awesomplete : any; constructor (input : Element ) ; list : string [] ; minChars : number ; evaluate ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace ಠ_ಠ.clutz { function __onGCastApiAvailable (a : boolean ) : any ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace cast.receiver { class CastChannel { private noStructuralTyping_cast_receiver_CastChannel : any; send (message : any ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace cast.receiver { class CastMessageBus { private noStructuralTyping_cast_receiver_CastMessageBus : any; broadcast (message : any ) : any ; getCastChannel (senderId : string ) : cast.receiver.CastChannel ; onMessage : Function | null ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace cast.receiver.CastMessageBus { class Event { private noStructuralTyping_cast_receiver_CastMessageBus_Event : any; data : any ; senderId : string ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace cast.receiver { class CastReceiverManager { private noStructuralTyping_cast_receiver_CastReceiverManager : any; onSenderConnected : Function | null ; onSenderDisconnected : Function | null ; onSystemVolumeChanged : Function | null ; getCastMessageBus (namespace : string , messageType ? : string ) : cast.receiver.CastMessageBus | null ; getSenders ( ) : string [] | null ; getSystemVolume ( ) : cast.receiver.system.SystemVolumeData | null ; isSystemReady ( ) : boolean ; setSystemVolumeLevel (level : number ) : any ; setSystemVolumeMuted (muted : number ) : any ; start ( ) : any ; stop ( ) : any ; static getInstance ( ) : cast.receiver.CastReceiverManager | null ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace cast.receiver.media { enum MetadataType { GENERIC = 0.0 , MOVIE = 1.0 , MUSIC_TRACK = 3.0 , PHOTO = 4.0 , TV_SHOW = 2.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace cast.receiver.system { class SystemVolumeData { private noStructuralTyping_cast_receiver_system_SystemVolumeData : any; level : number ; muted : boolean ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace chrome.cast { class ApiConfig { private noStructuralTyping_chrome_cast_ApiConfig : any; constructor (sessionRequest : chrome.cast.SessionRequest | null , sessionListener : Function | null , receiverListener : Function | null , autoJoinPolicy ? : string , defaultActionPolicy ? : string ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace chrome.cast { class Error { private noStructuralTyping_chrome_cast_Error : any; constructor (code : string , description ? : string , details ? : object | null ) ; code : string ; description : string | null ; details : object | null ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace chrome.cast { class Receiver { private noStructuralTyping_chrome_cast_Receiver : any; friendlyName : string ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace chrome.cast { class Session { private noStructuralTyping_chrome_cast_Session : any; receiver : chrome.cast.Receiver | null ; sessionId : string ; status : string ; addMessageListener (namespace : string , listener : Function | null ) : any ; addUpdateListener (listener : Function | null ) : any ; leave (successCallback : Function | null , errorCallback : Function | null ) : any ; removeMessageListener (namespace : string , listener : Function | null ) : any ; removeUpdateListener (listener : Function | null ) : any ; sendMessage (namespace : string , message : object | string , successCallback : Function | null , errorCallback : Function | null ) : any ; stop (successCallback : Function | null , errorCallback : Function | null ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace chrome.cast { class SessionRequest { private noStructuralTyping_chrome_cast_SessionRequest : any; constructor (appId : string ) ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace chrome.cast.SessionStatus { let STOPPED : string ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/chromecast.js declare namespace chrome.cast { let isAvailable : boolean ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/ima.js declare namespace google.ima.AdErrorEvent { enum Type { AD_ERROR = 'AD_ERROR' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/ima.js declare namespace google.ima.AdEvent { enum Type { AD_BREAK_READY = 'AD_BREAK_READY' , AD_BUFFERING = 'AD_BUFFERING' , AD_ERROR = 'AD_ERROR' , AD_METADATA = 'AD_METADATA' , AD_PROGRESS = 'AD_PROGRESS' , ALL_ADS_COMPLETED = 'ALL_ADS_COMPLETED' , CLICK = 'CLICK' , COMPLETE = 'COMPLETE' , CONTENT_PAUSE_REQUESTED = 'CONTENT_PAUSE_REQUESTED' , CONTENT_RESUME_REQUESTED = 'CONTENT_RESUME_REQUESTED' , DURATION_CHANGE = 'DURATION_CHANGE' , FIRST_QUARTILE = 'FIRST_QUARTILE' , IMPRESSION = 'IMPRESSION' , INTERACTION = 'INTERACTION' , LINEAR_CHANGED = 'LINEAR_CHANGED' , LOADED = 'LOADED' , LOG = 'LOG' , MIDPOINT = 'MIDPOINT' , PAUSED = 'PAUSED' , RESUMED = 'RESUMED' , SKIPPABLE_STATE_CHANGED = 'SKIPPABLE_STATE_CHANGED' , SKIPPED = 'SKIPPED' , STARTED = 'STARTED' , THIRD_QUARTILE = 'THIRD_QUARTILE' , USER_CLOSE = 'USER_CLOSE' , VOLUME_CHANGED = 'VOLUME_CHANGED' , VOLUME_MUTED = 'VOLUME_MUTED' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/ima.js declare namespace google.ima { class AdsLoader implements EventTarget { private noStructuralTyping_google_ima_AdsLoader : any; constructor (container : google.ima.AdDisplayContainer ) ; addEventListener ( ) : any ; contentComplete ( ) : any ; destroy ( ) : any ; dispatchEvent ( ) : any ; getSettings ( ) : google.ima.ImaSdkSettings | null ; removeEventListener ( ) : any ; requestAds (request : google.ima.AdsRequest ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/ima.js declare namespace google.ima { class AdsManager implements EventTarget { private noStructuralTyping_google_ima_AdsManager : any; addEventListener ( ) : any ; destroy ( ) : any ; dispatchEvent ( ) : any ; getAdSkippableState ( ) : boolean ; getCuePoints ( ) : number [] ; getRemainingTime ( ) : number ; getVolume ( ) : any ; init (width : number , height : number , viewMode : google.ima.ViewMode ) : any ; pause ( ) : any ; removeEventListener ( ) : any ; resize (width : number , height : number , viewMode : google.ima.ViewMode ) : any ; resume ( ) : any ; setVolume (volume : number ) : any ; skip ( ) : any ; start ( ) : any ; stop ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/ima.js declare namespace google.ima.AdsManagerLoadedEvent { enum Type { ADS_MANAGER_LOADED = 'ADS_MANAGER_LOADED' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/ima.js declare namespace google.ima { type AdsRequest = { adTagUrl ? : string , adsResponse ? : string } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/ima.js declare namespace google.ima.ImaSdkSettings { enum VpaidMode { DISABLED = 0.0 , ENABLED = 1.0 , INSECURE = 2.0 , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/ima.js declare namespace google.ima { enum ViewMode { FULLSCREEN = 'FULLSCREEN' , NORMAL = 'NORMAL' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/ima.js declare namespace google.ima.dai.api.StreamEvent { enum Type { AD_BREAK_ENDED = 'adBreakEnded' , AD_BREAK_STARTED = 'adBreakStarted' , AD_PERIOD_ENDED = 'adPeriodEnded' , AD_PERIOD_STARTED = 'adPeriodStarted' , AD_PROGRESS = 'adProgress' , CLICK = 'click' , COMPLETE = 'complete' , CUEPOINTS_CHANGED = 'cuepointsChanged' , ERROR = 'error' , FIRST_QUARTILE = 'firstquartile' , LOADED = 'loaded' , MIDPOINT = 'midpoint' , SKIPPABLE_STATE_CHANGED = 'skippableStateChanged' , SKIPPED = 'skip' , STARTED = 'started' , STREAM_INITIALIZED = 'streamInitialized' , THIRD_QUARTILE = 'thirdquartile' , VIDEO_CLICKED = 'videoClicked' , } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/ima.js declare namespace google.ima.dai.api { class StreamManager implements EventTarget { private noStructuralTyping_google_ima_dai_api_StreamManager : any; constructor (videoElement : HTMLMediaElement | null , adUiElement ? : HTMLElement | null , uiSettings ? : google.ima.dai.api.UiSettings | null ) ; addEventListener (type : string | any [] | null , handler : null | object , capture ? : boolean | AddEventListenerOptions , handlerScope ? : object | null ) : any ; contentTimeForStreamTime (streamTime : number ) : any ; dispatchEvent ( ) : any ; onTimedMetadata (metadata : object | null ) : any ; previousCuePointForStreamTime (streamTime : number ) : any ; processMetadata (type : string , data : Uint8Array | null | string , timestamp : number ) : any ; removeEventListener ( ) : any ; replaceAdTagParameters (adTagParameters : object | null ) : any ; requestStream (streamRequest : google.ima.dai.api.StreamRequest | null ) : any ; reset ( ) : any ; setClickElement (clickElement : Element | null ) : any ; streamTimeForContentTime (contentTime : number ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/ima.js declare namespace google.ima { let settings : google.ima.ImaSdkSettings ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/jwk_set.js declare namespace ಠ_ಠ.clutz { /** * A JSON Web Key. */ class JWK { private noStructuralTyping_JWK : any; /** * A key in base 64. Used with kty="oct". */ k : string ; /** * A key ID. Any ASCII string. */ kid : string ; /** * A key type. One of: * 1. "oct" (symmetric key octect sequence) * 2. "RSA" (RSA key) * 3. "EC" (elliptical curve key) * Use "oct" for clearkey. */ kty : string ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/jwk_set.js declare namespace ಠ_ಠ.clutz { /** * A JSON Web Key set. */ class JWKSet { private noStructuralTyping_JWKSet : any; keys : ( JWK | null ) [] | null ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/mdl.js declare namespace ಠ_ಠ.clutz { class MaterialLayout { private noStructuralTyping_MaterialLayout : any; Constant_ : { MENU_ICON : string } ; toggleDrawer ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/mediasession.js declare namespace ಠ_ಠ.clutz { class MediaMetadata { private noStructuralTyping_MediaMetadata : any; constructor (options : any ) ; artist : string ; artwork : object ; title : string ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/mediasession.js declare namespace ಠ_ಠ.clutz { class MediaSession { private noStructuralTyping_MediaSession : any; metadata : MediaMetadata | null ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/mux.js declare namespace muxjs.mp4 { class CaptionParser { private noStructuralTyping_muxjs_mp4_CaptionParser : any; /** * Clear the parsed closed captions data for new data. */ clearParsedCaptions ( ) : any ; /** * Initializes the closed caption parser. */ init ( ) : any ; /** * Return true if a new video track is selected or if the timescale is * changed. * @param videoTrackIds A list of video tracks found in the init segment. * @param timescales The map of track Ids and the tracks' timescales in the init segment. */ isNewInit (videoTrackIds : number [] , timescales : { [ key: number ]: number } ) : boolean ; /** * Parses embedded CEA closed captions and interacts with the underlying * CaptionStream, and return the parsed captions. * @param segment The fmp4 segment containing embedded captions * @param videoTrackIds A list of video tracks found in the init segment. * @param timescales The timescales found in the init segment. */ parse (segment : Uint8Array , videoTrackIds : number [] , timescales : { [ key: number ]: number } ) : muxjs.mp4.ParsedClosedCaptions ; /** * Reset the captions stream. */ resetCaptionStream ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/mux.js declare namespace muxjs.mp4 { type ClosedCaption = { endPts : number , endTime : number , startPts : number , startTime : number , stream : string , text : string } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/mux.js declare namespace muxjs.mp4 { type Metadata = { cueTime : number , data : Uint8Array , dispatchType : string , dts : number , frames : muxjs.mp4.MetadataFrame [] , pts : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/mux.js declare namespace muxjs.mp4 { type MetadataFrame = { data : string , description : string , id : string , key : string , value : string } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/mux.js declare namespace muxjs.mp4 { type ParsedClosedCaptions = { captionStreams : { [ key: string ]: boolean } | null , captions : muxjs.mp4.ClosedCaption [] } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/mux.js declare namespace muxjs.mp4 { class Transmuxer { private noStructuralTyping_muxjs_mp4_Transmuxer : any; constructor (options ? : object | null ) ; /** * Remove all handlers and clean up. */ dispose ( ) : any ; flush ( ) : any ; /** * Remove a handler for a specified event type. * @param type Event name * @param listener The callback to be removed */ off (type : string , listener : Function | null ) : any ; /** * Add a handler for a specified event type. * @param type Event name * @param listener The callback to be invoked */ on (type : string , listener : Function | null ) : any ; push (data : Uint8Array ) : any ; setBaseMediaDecodeTime (time : number ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/mux.js declare namespace muxjs.mp4.Transmuxer { type Segment = { captions : any [] , data : Uint8Array , initSegment : Uint8Array , metadata : any [] } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/prefixed_eme.js declare namespace ಠ_ಠ.clutz { class MediaKeyError { private noStructuralTyping_MediaKeyError : any; code : number ; systemCode : number ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/prefixed_eme.js declare namespace ಠ_ಠ.clutz { class MediaKeyEvent extends Event { private noStructuralTyping_MediaKeyEvent : any; constructor (type : string , eventInitDict ? : object | null ) ; defaultURL : string ; errorCode : MediaKeyError | null ; initData : Uint8Array ; keySystem : string ; message : Uint8Array ; sessionId : string ; systemCode : number ; target : HTMLMediaElement ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/abortable.js declare namespace shaka.extern { /** * A representation of an abortable operation. Note that these are not * cancelable. Cancelation implies undoing what has been done so far, * whereas aborting only means that further work is stopped. */ interface IAbortableOperation < T > { /** * Can be called by anyone holding this object to abort the underlying * operation. This is not cancelation, and will not necessarily result in * any work being undone. abort() should return a Promise which is resolved * when the underlying operation has been aborted. The returned Promise * should never be rejected. */ abort ( ) : Promise < any > ; finally (onFinal : (a : boolean ) => any ) : shaka.extern.IAbortableOperation < T > ; /** * A Promise which represents the underlying operation. It is resolved when * the operation is complete, and rejected if the operation fails or is * aborted. Aborted operations should be rejected with a shaka.util.Error * object using the error code OPERATION_ABORTED. */ promise : Promise < T > ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/abr_manager.js declare namespace shaka.extern { /** * An object which selects Streams from a set of possible choices. This also * watches for system changes to automatically adapt for the current streaming * requirements. For example, when the network slows down, this class is in * charge of telling the Player which streams to switch to in order to reduce * the required bandwidth. * * This class is given a set of streams to choose from when the Player starts * up. This class should store these and use them to make future decisions * about ABR. It is up to this class how those decisions are made. All the * Player will do is tell this class what streams to choose from. */ interface AbrManager { /** * Chooses one variant to switch to. Called by the Player. */ chooseVariant ( ) : shaka.extern.Variant ; /** * Sets the ABR configuration. * * It is the responsibility of the AbrManager implementation to implement the * restrictions behavior described in shaka.extern.AbrConfiguration. */ configure (config : shaka.extern.AbrConfiguration ) : any ; /** * Disables automatic Stream suggestions. After this, the AbrManager may not * call switchCallback(). */ disable ( ) : any ; /** * Enables automatic Variant choices from the last ones passed to setVariants. * After this, the AbrManager may call switchCallback() at any time. */ enable ( ) : any ; /** * Gets an estimate of the current bandwidth in bit/sec. This is used by the * Player to generate stats. */ getBandwidthEstimate ( ) : number ; /** * Initializes the AbrManager. */ init (switchCallback : shaka.extern.AbrManager.SwitchCallback ) : any ; /** * Updates manager playback rate. */ playbackRateChanged (rate : number ) : any ; /** * Notifies the AbrManager that a segment has been downloaded (includes MP4 * SIDX data, WebM Cues data, initialization segments, and media segments). * @param deltaTimeMs The duration, in milliseconds, that the request took to complete. * @param numBytes The total number of bytes transferred. */ segmentDownloaded (deltaTimeMs : number , numBytes : number ) : any ; /** * Updates manager's variants collection. */ setVariants (variants : shaka.extern.Variant [] ) : any ; /** * Stops any background timers and frees any objects held by this instance. * This will only be called after a call to init. */ stop ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/abr_manager.js declare namespace shaka.extern.AbrManager { /** * A factory for creating the abr manager. */ type Factory = ( ) => shaka.extern.AbrManager ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/abr_manager.js declare namespace shaka.extern.AbrManager { /** * A callback into the Player that should be called when the AbrManager decides * it's time to change to a different variant. * * The first argument is a variant to switch to. * * The second argument is an optional boolean. If true, all data will be removed * from the buffer, which will result in a buffering event. Unless a third * argument is passed. * * The third argument in an optional number that specifies how much data (in * seconds) should be retained when clearing the buffer. This can help achieve * a fast switch that doesn't involve a buffering event. A minimum of two video * segments should always be kept buffered to avoid temporary hiccups. */ type SwitchCallback = (a : shaka.extern.Variant , b ? : boolean , c ? : number ) => any ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/ads.js declare namespace shaka.extern { type AdsStats = { loadTimes : number [] , playedCompletely : number , skipped : number , started : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/ads.js declare namespace shaka.extern { /** * Interface for Ad objects. */ interface IAd extends shaka.util.IReleasable { canSkipNow ( ) : boolean ; getDuration ( ) : number ; /** * Gets the minimum suggested duration. Defaults to being equivalent to * getDuration() for server-side ads. */ getMinSuggestedDuration ( ) : number ; getPositionInSequence ( ) : number ; getRemainingTime ( ) : number ; getSequenceLength ( ) : number ; getTimeUntilSkippable ( ) : number ; getVolume ( ) : number ; isMuted ( ) : boolean ; isPaused ( ) : boolean ; isSkippable ( ) : boolean ; pause ( ) : any ; play ( ) : any ; resize (width : number , height : number ) : any ; setMuted (muted : boolean ) : any ; setVolume (volume : number ) : any ; skip ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/ads.js declare namespace shaka.extern { /** * An object that's responsible for all the ad-related logic * in the player. */ interface IAdManager extends EventTarget { /** * Get statistics for the current playback session. If the player is not * playing content, this will return an empty stats object. */ getStats ( ) : any ; initClientSide (adContainer : HTMLElement , video : HTMLMediaElement ) : any ; initServerSide (adContainer : HTMLElement , video : HTMLMediaElement ) : any ; onAssetUnload ( ) : any ; onCueMetadataChange (value : shaka.extern.ID3Metadata ) : any ; onDashTimedMetadata (region : shaka.extern.TimelineRegionInfo ) : any ; onHlsTimedMetadata (metadata : shaka.extern.ID3Metadata , timestampOffset : number ) : any ; release ( ) : any ; replaceServerSideAdTagParameters (adTagParameters : object | null ) : any ; requestClientSideAds (imaRequest : google.ima.AdsRequest ) : any ; requestServerSideStream (imaRequest : google.ima.dai.api.StreamRequest , backupUrl ? : string ) : Promise < string > ; setLocale (locale : string ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/ads.js declare namespace shaka.extern.IAdManager { /** * A factory for creating the ad manager. */ type Factory = ( ) => shaka.extern.IAdManager ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/error.js declare namespace shaka.extern { interface Error { category : shaka.util.Error.Category ; code : shaka.util.Error.Code ; data : any [] ; handled : boolean ; severity : shaka.util.Error.Severity ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/error.js declare namespace shaka.extern { type RestrictionInfo = { hasAppRestrictions : boolean , missingKeys : string [] , restrictedKeyStatuses : string [] } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/manifest.js declare namespace shaka.extern { /** * Creates a SegmentIndex; returns a Promise that resolves after the * SegmentIndex has been created. */ type CreateSegmentIndexFunction = ( ) => Promise < any > ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/manifest.js declare namespace shaka.extern { type DrmInfo = { audioRobustness : string , distinctiveIdentifierRequired : boolean , initData : shaka.extern.InitDataOverride [] | null , keyIds : Set < string > | null , keySystem : string , licenseServerUri : string , persistentStateRequired : boolean , serverCertificate : Uint8Array | null , sessionType : string , videoRobustness : string } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/manifest.js declare namespace shaka.extern { type InitDataOverride = { initData : Uint8Array , initDataType : string , keyId : string | null } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/manifest.js declare namespace shaka.extern { type Manifest = { imageStreams : shaka.extern.Stream [] , minBufferTime : number , offlineSessionIds : string [] , presentationTimeline : shaka.media.PresentationTimeline , textStreams : shaka.extern.Stream [] , variants : shaka.extern.Variant [] } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/manifest.js declare namespace shaka.extern { type Stream = { audioSamplingRate : number | null , bandwidth ? : number , channelsCount : number | null , closedCaptions : Map < string , string > | null , codecs : string , createSegmentIndex : shaka.extern.CreateSegmentIndexFunction , drmInfos : shaka.extern.DrmInfo [] , emsgSchemeIdUris : string [] | null , encrypted : boolean , forced : boolean , frameRate ? : number , hdr ? : string , height ? : number , id : number , keyIds : Set < string > , kind ? : string , label : string | null , language : string , mimeType : string , originalId : string | null , pixelAspectRatio ? : string , primary : boolean , roles : string [] , segmentIndex : shaka.media.SegmentIndex | null , spatialAudio : boolean , tilesLayout ? : string , trickModeVideo : any , type : string , width ? : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/manifest.js declare namespace shaka.extern { type Variant = { allowedByApplication : boolean , allowedByKeySystem : boolean , audio : shaka.extern.Stream | null , bandwidth : number , decodingInfos : ( any | null ) [] , id : number , language : string , primary : boolean , video : shaka.extern.Stream | null } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/manifest_parser.js declare namespace shaka.extern { /** * Parses media manifests and handles manifest updates. * * Given a URI where the initial manifest is found, a parser will request the * manifest, parse it, and return the resulting Manifest object. * * If the manifest requires updates (e.g. for live media), the parser will use * background timers to update the same Manifest object. * * There are many ways for |start| and |stop| to be called. Implementations * should support all cases: * * BASIC * await parser.start(uri, playerInterface); * await parser.stop(); * * INTERRUPTING * const p = parser.start(uri, playerInterface); * await parser.stop(); * await p; * * |p| should be rejected with an OPERATION_ABORTED error. * * STOPPED BEFORE STARTING * await parser.stop(); */ interface ManifestParser { /** * Called by the Player to provide an updated configuration any time the * configuration changes. Will be called at least once before start(). */ configure (config : shaka.extern.ManifestConfiguration ) : any ; /** * Tells the parser that the expiration time of an EME session has changed. * Implementing this is optional. */ onExpirationUpdated (sessionId : string , expiration : number ) : any ; /** * Initialize and start the parser. When |start| resolves, it should return * the initial version of the manifest. |start| will only be called once. If * |stop| is called while |start| is pending, |start| should reject. * @param uri The URI of the manifest. * @param playerInterface The player interface contains the callbacks and members that the parser can use to communicate with the player and outside world. */ start (uri : string , playerInterface : shaka.extern.ManifestParser.PlayerInterface ) : Promise < shaka.extern.Manifest > ; /** * Tell the parser that it must stop and free all internal resources as soon * as possible. Only once all internal resources are stopped and freed will * the promise resolve. Once stopped a parser will not be started again. * * The parser should support having |stop| called multiple times and the * promise should always resolve. */ stop ( ) : Promise < any > ; /** * Tells the parser to do a manual manifest update. Implementing this is * optional. This is only called when 'emsg' boxes are present. */ update ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/manifest_parser.js declare namespace shaka.extern.ManifestParser { /** * A factory for creating the manifest parser. This function is registered with * shaka.media.ManifestParser to create parser instances. */ type Factory = ( ) => shaka.extern.ManifestParser ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/manifest_parser.js declare namespace shaka.extern.ManifestParser { type PlayerInterface = { enableLowLatencyMode : ( ) => any , filter : (a : shaka.extern.Manifest ) => Promise < any > , isAutoLowLatencyMode : ( ) => boolean , isLowLatencyMode : ( ) => boolean , makeTextStreamsForClosedCaptions : (a : shaka.extern.Manifest ) => any , networkingEngine : shaka.net.NetworkingEngine , onError : (a : shaka.util.Error ) => any , onEvent : shaka.util.EventManager.ListenerType , onTimelineRegionAdded : (a : shaka.extern.TimelineRegionInfo ) => any } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/mp4_parser.js declare namespace shaka.extern { type ParsedBox = { flags : number | null , has64BitSize : boolean , parser : shaka.util.Mp4Parser , partialOkay : boolean , reader : shaka.util.DataViewReader , size : number , start : number , version : number | null } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/net.js declare namespace shaka.extern { type ProgressUpdated = (a : number , b : number , c : number ) => any ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/net.js declare namespace shaka.extern { type Request = { allowCrossSiteCredentials : boolean , body : ArrayBuffer | ArrayBufferView | null , headers : { [ key: string ]: string } , licenseRequestType : string | null , method : string , retryParameters : shaka.extern.RetryParameters , sessionId : string | null , streamDataCallback : ( (a : ArrayBuffer | ArrayBufferView ) => Promise < any > ) | null , uris : string [] } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/net.js declare namespace shaka.extern { /** * Defines a filter for requests. This filter takes the request and modifies * it before it is sent to the scheme plugin. * A request filter can run asynchronously by returning a promise; in this case, * the request will not be sent until the promise is resolved. */ type RequestFilter = (a : shaka.net.NetworkingEngine.RequestType , b : shaka.extern.Request ) => Promise < any > | void ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/net.js declare namespace shaka.extern { type Response = { data : ArrayBuffer | ArrayBufferView , fromCache ? : boolean , headers : { [ key: string ]: string } , timeMs ? : number , uri : string } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/net.js declare namespace shaka.extern { /** * Defines a filter for responses. This filter takes the response and modifies * it before it is returned. * A response filter can run asynchronously by returning a promise. */ type ResponseFilter = (a : shaka.net.NetworkingEngine.RequestType , b : shaka.extern.Response ) => Promise < any > | void ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/net.js declare namespace shaka.extern { type RetryParameters = { backoffFactor : number , baseDelay : number , connectionTimeout : number , fuzzFactor : number , maxAttempts : number , stallTimeout : number , timeout : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/net.js declare namespace shaka.extern { type SchemePlugin = (a : string , b : shaka.extern.Request , c : shaka.net.NetworkingEngine.RequestType , d : shaka.extern.ProgressUpdated ) => shaka.extern.IAbortableOperation < shaka.extern.Response > ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline.js declare namespace shaka.extern { type EmeSessionDB = { audioCapabilities : { contentType : string , robustness : string } [] , keySystem : string , licenseUri : string , serverCertificate : Uint8Array | null , sessionId : string , videoCapabilities : { contentType : string , robustness : string } [] } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline.js declare namespace shaka.extern { /** * Similar to storage cells (shaka.extern.StorageCell), an EmeSessionStorageCell * stores data persistently. This only stores the license's session info, not * the license itself. The license itself is stored using EME. */ interface EmeSessionStorageCell { /** * Adds the given sessions to the store. */ add (sessions : shaka.extern.EmeSessionDB [] ) : Promise < any > ; /** * Free all resources used by this cell. This won't affect the stored content. */ destroy ( ) : Promise < any > ; /** * Gets the currently stored sessions. */ getAll ( ) : Promise < shaka.extern.EmeSessionDB [] > ; /** * Removes the given session IDs from the store. */ remove (sessionIds : string [] ) : Promise < any > ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline.js declare namespace shaka.extern { type ManifestDB = { appMetadata : object | null , creationTime : number , drmInfo : shaka.extern.DrmInfo | null , duration : number , expiration : number , originalManifestUri : string , sessionIds : string [] , size : number , streams : shaka.extern.StreamDB [] } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline.js declare namespace shaka.extern { type OfflineSupport = { basic : boolean , encrypted : { [ key: string ]: boolean } } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline.js declare namespace shaka.extern { type SegmentDB = { appendWindowEnd : number , appendWindowStart : number , dataKey : number , endTime : number , initSegmentKey : number | null , startTime : number , timestampOffset : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline.js declare namespace shaka.extern { type SegmentDataDB = { data : ArrayBuffer } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline.js declare namespace shaka.extern { /** * An interface that defines access to collection of segments and manifests. All * methods are designed to be batched operations allowing the implementations to * optimize their operations based on how they store data. * * The storage cell is one of two exposed APIs used to control where and how * offline content is saved. The storage cell is responsible for converting * information between its internal structures and the external (library) * structures. */ interface StorageCell { /** * Add a group of manifests. Will return a promise that resolves with a list * of keys for each manifest. If one manifest fails to be added, all manifests * should fail to be added. */ addManifests (manifests : shaka.extern.ManifestDB [] ) : Promise < number [] > ; /** * Add a group of segments. Will return a promise that resolves with a list * of keys for each segment. If one segment fails to be added, all segments * should fail to be added. */ addSegments (segments : shaka.extern.SegmentDataDB [] ) : Promise < number [] > ; /** * Free all resources used by this cell. This should not affect the stored * content. */ destroy ( ) : Promise < any > ; /** * Get all manifests stored in this cell. Since manifests are small compared * to the asset they describe, it is assumed that it is feasible to have them * all in main memory at one time. */ getAllManifests ( ) : Promise < Map < number , shaka.extern.ManifestDB > > ; /** * Get a group of manifests using their keys to identify them. If any key is * not found, the promise chain will be rejected. */ getManifests (keys : number [] ) : Promise < shaka.extern.ManifestDB [] > ; /** * Get a group of segments using their keys to identify them. If any key is * not found, the promise chain will be rejected. */ getSegments (keys : number [] ) : Promise < shaka.extern.SegmentDataDB [] > ; /** * Check if the cell can support new keys. If a cell has a fixed key space, * then all add-operations will fail as no new keys can be added. All * remove-operations and update-operations should still work. */ hasFixedKeySpace ( ) : boolean ; /** * Remove a group of manifests using their keys to identify them. If a key * is not found, then that removal should be considered successful. * @param onRemove A callback for when a manifest is removed from the cell. The key of the manifest will be passed to the callback. */ removeManifests (keys : number [] , onRemove : (a : number ) => any ) : Promise < any > ; /** * Remove a group of segments using their keys to identify them. If a key * is not found, then that removal should be considered successful. * @param onRemove A callback for when a segment is removed from the cell. The key of the segment will be passed to the callback. */ removeSegments (keys : number [] , onRemove : (a : number ) => any ) : Promise < any > ; /** * Replace the expiration time of the manifest stored under |key| with * |newExpiration|. If no manifest is found under |key| then this should * act as a no-op. */ updateManifestExpiration (key : number , expiration : number ) : Promise < any > ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline.js declare namespace shaka.extern { /** * Storage mechanisms are one of two exported storage APIs. Storage mechanisms * are groups of storage cells (shaka.extern.StorageCell). Storage mechanisms * are responsible for managing the life cycle of resources shared between * storage cells in the same block. * * For example, a storage mechanism may manage a single database connection * while each cell would manage different tables in the database via the same * connection. */ interface StorageMechanism { /** * Free all resources used by the storage mechanism and its cells. This should * not affect the stored content. */ destroy ( ) : Promise < any > ; /** * Erase all content from storage and leave storage in an empty state. Erase * may be called with or without |init|. This allows for storage to be wiped * in case of a version mismatch. * * After calling |erase|, the mechanism will be in an initialized state. */ erase ( ) : Promise < any > ; /** * Get a map of all the cells managed by the storage mechanism. Editing the * map should have no effect on the storage mechanism. The map key is the * cell's address in the mechanism and should be consistent between calls to * |getCells|. */ getCells ( ) : Map < string , shaka.extern.StorageCell > ; /** * Get the current EME session storage cell. */ getEmeSessionCell ( ) : shaka.extern.EmeSessionStorageCell ; /** * Initialize the storage mechanism for first use. This should only be called * once. Calling |init| multiple times has an undefined behaviour. */ init ( ) : Promise < any > ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline.js declare namespace shaka.extern { type StoredContent = { appMetadata : object | null , duration : number , expiration : number , offlineUri : string | null , originalManifestUri : string , size : number , tracks : shaka.extern.TrackList } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline.js declare namespace shaka.extern { type StreamDB = { audioSamplingRate : number | null , channelsCount : number | null , closedCaptions : Map < string , string > | null , codecs : string , encrypted : boolean , forced : boolean , frameRate ? : number , hdr ? : string , height : number | null , id : number , keyIds : Set < string > , kind ? : string , label : string | null , language : string , mimeType : string , originalId : string | null , pixelAspectRatio ? : string , primary : boolean , roles : string [] , segments : shaka.extern.SegmentDB [] , spatialAudio : boolean , tilesLayout ? : string , type : string , variantIds : number [] , width : number | null } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline_compat_v1.js declare namespace shaka.extern { type ManifestDBV1 = { appMetadata : object | null , drmInfo : shaka.extern.DrmInfo | null , duration : number , expiration : number , key : number , originalManifestUri : string , periods : shaka.extern.PeriodDBV1 [] , sessionIds : string [] , size : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline_compat_v1.js declare namespace shaka.extern { type PeriodDBV1 = { startTime : number , streams : shaka.extern.StreamDBV1 [] } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline_compat_v1.js declare namespace shaka.extern { type SegmentDBV1 = { endTime : number , startTime : number , uri : string } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline_compat_v1.js declare namespace shaka.extern { type SegmentDataDBV1 = { data : ArrayBuffer , key : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline_compat_v1.js declare namespace shaka.extern { type StreamDBV1 = { codecs : string , contentType : string , encrypted : boolean , frameRate ? : number , height : number | null , id : number , initSegmentUri : string | null , keyId : string | null , kind ? : string , label : string | null , language : string , mimeType : string , presentationTimeOffset : number , primary : boolean , segments : shaka.extern.SegmentDBV1 [] , variantIds : number [] , width : number | null } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline_compat_v2.js declare namespace shaka.extern { type ManifestDBV2 = { appMetadata : object | null , drmInfo : shaka.extern.DrmInfo | null , duration : number , expiration : number , originalManifestUri : string , periods : shaka.extern.PeriodDBV2 [] , sessionIds : string [] , size : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline_compat_v2.js declare namespace shaka.extern { type PeriodDBV2 = { startTime : number , streams : shaka.extern.StreamDBV2 [] } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline_compat_v2.js declare namespace shaka.extern { type SegmentDBV2 = { dataKey : number , endTime : number , startTime : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline_compat_v2.js declare namespace shaka.extern { type SegmentDataDBV2 = { data : ArrayBuffer } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/offline_compat_v2.js declare namespace shaka.extern { type StreamDBV2 = { codecs : string , contentType : string , encrypted : boolean , frameRate ? : number , height : number | null , id : number , initSegmentKey : number | null , keyId : string | null , kind ? : string , label : string | null , language : string , mimeType : string , originalId : string | null , pixelAspectRatio ? : string , presentationTimeOffset : number , primary : boolean , segments : shaka.extern.SegmentDBV2 [] , variantIds : number [] , width : number | null } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type AbrConfiguration = { bandwidthDowngradeTarget : number , bandwidthUpgradeTarget : number , defaultBandwidthEstimate : number , enabled : boolean , restrictions : shaka.extern.Restrictions , switchInterval : number , useNetworkInformation : boolean } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type AdvancedDrmConfiguration = { audioRobustness : string , distinctiveIdentifierRequired : boolean , individualizationServer : string , persistentStateRequired : boolean , serverCertificate : Uint8Array | null , sessionType : string , videoRobustness : string } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type BufferedInfo = { audio : shaka.extern.BufferedRange [] , text : shaka.extern.BufferedRange [] , total : shaka.extern.BufferedRange [] , video : shaka.extern.BufferedRange [] } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type BufferedRange = { end : number , start : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type DashManifestConfiguration = { autoCorrectDrift : boolean , clockSyncUri : string , disableXlinkProcessing : boolean , ignoreDrmInfo : boolean , ignoreEmptyAdaptationSet : boolean , ignoreMaxSegmentDuration : boolean , ignoreMinBufferTime : boolean , ignoreSuggestedPresentationDelay : boolean , initialSegmentLimit : number , keySystemsByURI : { [ key: string ]: string } , xlinkFailGracefully : boolean } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type DrmConfiguration = { advanced : { [ key: string ]: shaka.extern.AdvancedDrmConfiguration } | null , clearKeys : { [ key: string ]: string } , delayLicenseRequestUntilPlayed : boolean , initDataTransform ? : (a : Uint8Array , b : string , c : shaka.extern.DrmInfo | null ) => Uint8Array , logLicenseExchange : boolean , retryParameters : shaka.extern.RetryParameters , servers : { [ key: string ]: string } , updateExpirationTime : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type DrmSupportType = { persistentState : boolean } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type EmsgInfo = { endTime : number , eventDuration : number , id : number , messageData : Uint8Array | null , presentationTimeDelta : number , schemeIdUri : string , startTime : number , timescale : number , value : string } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type HlsManifestConfiguration = { ignoreTextStreamFailures : boolean , useFullSegmentsForStartTime : boolean } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type ID3Metadata = { [ key: string ]: any } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type LanguageRole = { label : string | null , language : string , role : string } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type ManifestConfiguration = { availabilityWindowOverride : number , dash : shaka.extern.DashManifestConfiguration , defaultPresentationDelay : number , disableAudio : boolean , disableText : boolean , disableThumbnails : boolean , disableVideo : boolean , hls : shaka.extern.HlsManifestConfiguration , retryParameters : shaka.extern.RetryParameters } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type OfflineConfiguration = { downloadSizeCallback : (a : number ) => Promise < boolean > , progressCallback : (a : shaka.extern.StoredContent , b : number ) => any , trackSelectionCallback : (a : shaka.extern.TrackList ) => Promise < shaka.extern.TrackList > , usePersistentLicense : boolean } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type PlayerConfiguration = { abr : shaka.extern.AbrConfiguration , abrFactory : shaka.extern.AbrManager.Factory , drm : shaka.extern.DrmConfiguration , manifest : shaka.extern.ManifestConfiguration , offline : shaka.extern.OfflineConfiguration , playRangeEnd : number , playRangeStart : number , preferForcedSubs : boolean , preferredAudioChannelCount : number , preferredAudioLanguage : string , preferredTextLanguage : string , preferredTextRole : string , preferredVariantRole : string , restrictions : shaka.extern.Restrictions , streaming : shaka.extern.StreamingConfiguration , textDisplayFactory : shaka.extern.TextDisplayer.Factory , useMediaCapabilities : boolean } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type Restrictions = { maxBandwidth : number , maxFrameRate : number , maxHeight : number , maxPixels : number , maxWidth : number , minBandwidth : number , minFrameRate : number , minHeight : number , minPixels : number , minWidth : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type StateChange = { duration : number , state : string , timestamp : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type Stats = { bufferingTime : number , completionPercent : number , corruptedFrames : number , decodedFrames : number , drmTimeSeconds : number , droppedFrames : number , estimatedBandwidth : number , height : number , licenseTime : number , liveLatency : number , loadLatency : number , manifestTimeSeconds : number , maxSegmentDuration : number , pauseTime : number , playTime : number , stateHistory : shaka.extern.StateChange [] , streamBandwidth : number , switchHistory : shaka.extern.TrackChoice [] , width : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type StreamingConfiguration = { alwaysStreamText : boolean , autoLowLatencyMode : boolean , bufferBehind : number , bufferingGoal : number , durationBackoff : number , failureCallback : (a : shaka.util.Error ) => any , forceHTTPS : boolean , forceTransmuxTS : boolean , gapDetectionThreshold : number , ignoreTextStreamFailures : boolean , inaccurateManifestTolerance : number , jumpLargeGaps : boolean , lowLatencyMode : boolean , preferNativeHls : boolean , rebufferingGoal : number , retryParameters : shaka.extern.RetryParameters , safeSeekOffset : number , smallGapLimit : number , stallEnabled : boolean , stallSkip : number , stallThreshold : number , startAtSegmentBoundary : boolean , useNativeHlsOnSafari : boolean } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type SupportType = { drm : { [ key: string ]: shaka.extern.DrmSupportType | null } , manifest : { [ key: string ]: boolean } , media : { [ key: string ]: boolean } } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type Thumbnail = { duration : number , height : number , positionX : number , positionY : number , startTime : number , uris : string [] , width : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type TimelineRegionInfo = { endTime : number , eventElement : Element | null , id : string , schemeIdUri : string , startTime : number , value : string } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type Track = { active : boolean , audioBandwidth : number | null , audioCodec : string | null , audioId : number | null , audioRoles : string [] | null , audioSamplingRate : number | null , bandwidth : number , channelsCount : number | null , codecs : string | null , forced : boolean , frameRate : number | null , hdr : string | null , height : number | null , id : number , kind : string | null , label : string | null , language : string , mimeType : string | null , originalAudioId : string | null , originalImageId : string | null , originalTextId : string | null , originalVideoId : string | null , pixelAspectRatio : string | null , primary : boolean , roles : string [] , spatialAudio : boolean , tilesLayout : string | null , type : string , videoBandwidth : number | null , videoCodec : string | null , videoId : number | null , width : number | null } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type TrackChoice = { bandwidth : number | null , fromAdaptation : boolean , id : number , timestamp : number , type : string } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/player.js declare namespace shaka.extern { type TrackList = shaka.extern.Track [] ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/text.js declare namespace shaka.extern { interface Cue { /** * Text background color as a CSS color, e.g. "#FFFFFF" or "white". */ backgroundColor : string ; /** * The URL of the background image, e.g. "data:[mime type];base64,[data]". */ backgroundImage : string ; /** * The border around this cue as a CSS border. */ border : string ; /** * The number of horizontal and vertical cells into which the Root Container * Region area is divided. */ cellResolution : { columns : number , rows : number } ; /** * Text color as a CSS color, e.g. "#FFFFFF" or "white". */ color : string ; /** * Text direction of the cue. */ direction : shaka.text.Cue.direction ; /** * Vertical alignments of the cues within their extents. * 'BEFORE' means displaying the captions at the top of the text display * container box, 'CENTER' means in the middle, 'AFTER' means at the bottom. */ displayAlign : shaka.text.Cue.displayAlign ; /** * The end time of the cue in seconds, relative to the start of the * presentation. */ endTime : number ; /** * Text font family. */ fontFamily : string ; /** * Text font size in px or em (e.g. '100px'/'100em'). */ fontSize : string ; /** * Text font style. Normal, italic or oblique. */ fontStyle : shaka.text.Cue.fontStyle ; /** * Text font weight. Either normal or bold. */ fontWeight : shaka.text.Cue.fontWeight ; /** * Id of the cue. */ id : string ; /** * If true, this represents a container element that is "above" the main * cues. For example, the <body> and <div> tags that contain the <p> tags * in a TTML file. This controls the flow of the final cues; any nested cues * within an "isContainer" cue will be laid out as separate lines. */ isContainer : boolean ; /** * Text letter spacing as a CSS letter-spacing value. */ letterSpacing : string ; /** * The offset from the display box in either number of lines or * percentage depending on the value of lineInterpretation. */ line : number | null ; /** * Line alignment of the cue box. * Start alignment means the cue box’s top side (for horizontal cues), left * side (for vertical growing right), or right side (for vertical growing * left) is aligned at the line. * Center alignment means the cue box is centered at the line. * End alignment The cue box’s bottom side (for horizontal cues), right side * (for vertical growing right), or left side (for vertical growing left) is * aligned at the line. */ lineAlign : shaka.text.Cue.lineAlign ; /** * Whether or not the cue only acts as a line break between two nested cues. * Should only appear in nested cues. */ lineBreak : boolean ; /** * Separation between line areas inside the cue box in px or em * (e.g. '100px'/'100em'). If not specified, this should be no less than * the largest font size applied to the text in the cue. */ lineHeight : string ; /** * The way to interpret line field. (Either as an integer line number or * percentage from the display box). */ lineInterpretation : shaka.text.Cue.lineInterpretation ; /** * Text line padding as a CSS line-padding value. */ linePadding : string ; /** * Nested cues, which should be laid out horizontally in one block. * Top-level cues are blocks, and nested cues are inline elements. * Cues can be nested arbitrarily deeply. */ nestedCues : shaka.extern.Cue [] ; /** * Opacity of the cue element, from 0-1. */ opacity : number ; /** * The text payload of the cue. If nestedCues is non-empty, this should be * empty. Top-level block containers should have no payload of their own. */ payload : string ; /** * The indent (in percent) of the cue box in the direction defined by the * writing direction. */ position : number | null ; /** * Position alignment of the cue. */ positionAlign : shaka.text.Cue.positionAlign ; /** * The region to render the cue into. Only supported on top-level cues, * because nested cues are inline elements. */ region : shaka.extern.CueRegion | null ; /** * Size of the cue box (in percents), where 0 means "auto". */ size : number ; spacer : boolean ; /** * The start time of the cue in seconds, relative to the start of the * presentation. */ startTime : number ; /** * Alignment of the text inside the cue box. */ textAlign : shaka.text.Cue.textAlign ; /** * Text decoration. A combination of underline, overline * and line through. Empty array means no decoration. */ textDecoration : shaka.text.Cue.textDecoration [] ; /** * Whether or not line wrapping should be applied to the cue. */ wrapLine : boolean ; /** * Text writing mode of the cue. */ writingMode : shaka.text.Cue.writingMode ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/text.js declare namespace shaka.extern { interface CueRegion { /** * The width of the rendering area in heightUnits. */ height : number ; /** * The units (percentage, pixels or lines) the region height is in. */ heightUnits : shaka.text.CueRegion.units ; /** * Region identifier. */ id : string ; /** * The X offset to start the rendering area in percentage (0-100) of this * region width. */ regionAnchorX : number ; /** * The Y offset to start the rendering area in percentage (0-100) of the * region height. */ regionAnchorY : number ; /** * If scroll=UP, it means that cues in the region will be added to the * bottom of the region and will push any already displayed cues in the * region up. Otherwise (scroll=NONE) cues will stay fixed at the location * they were first painted in. */ scroll : shaka.text.CueRegion.scrollMode ; /** * The units (percentage or pixels) the region viewportAnchors are in. */ viewportAnchorUnits : shaka.text.CueRegion.units ; /** * The X offset to start the rendering area in viewportAnchorUnits of the * video width. */ viewportAnchorX : number ; /** * The X offset to start the rendering area in viewportAnchorUnits of the * video height. */ viewportAnchorY : number ; /** * The width of the rendering area in widthUnits. */ width : number ; /** * The units (percentage or pixels) the region width is in. */ widthUnits : shaka.text.CueRegion.units ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/text.js declare namespace shaka.extern { interface TextDisplayer extends shaka.util.IDestroyable { /** * Append given text cues to the list of cues to be displayed. * @param cues Text cues to be appended. */ append (cues : shaka.text.Cue [] ) : any ; destroy ( ) : Promise < any > ; /** * Returns true if text is currently visible. */ isTextVisible ( ) : boolean ; /** * Remove all cues that are fully contained by the given time range (relative * to the presentation). <code>endTime</code> will be greater to equal to * <code>startTime</code>. <code>remove</code> should only return * <code>false</code> if the displayer has been destroyed. If the displayer * has not been destroyed <code>remove</code> should return <code>true</code>. */ remove (startTime : number , endTime : number ) : boolean ; /** * Set text visibility. */ setTextVisibility (on : boolean ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/text.js declare namespace shaka.extern.TextDisplayer { /** * A factory for creating a TextDisplayer. */ type Factory = ( ) => shaka.extern.TextDisplayer ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/text.js declare namespace shaka.extern { /** * An interface for plugins that parse text tracks. */ interface TextParser { /** * Parse an initialization segment. Some formats do not have init * segments so this won't always be called. * @param data The data that makes up the init segment. */ parseInit (data : Uint8Array ) : any ; /** * Parse a media segment and return the cues that make up the segment. * @param data The next section of buffer. * @param timeContext The time information that should be used to adjust the times values for each cue. */ parseMedia (data : Uint8Array , timeContext : shaka.extern.TextParser.TimeContext ) : shaka.extern.Cue [] ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/text.js declare namespace shaka.extern.TextParser { /** * A collection of time offsets used to adjust text cue times. */ type TimeContext = { periodStart : number , segmentEnd : number , segmentStart : number } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/shaka/text.js declare namespace shaka.extern { type TextParserPlugin = ( ) => shaka.extern.TextParser ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/tippy.js declare namespace ಠ_ಠ.clutz { /** * This is the subset of this method that we use in our demo code. */ function tippy (element : Element , config : object ) : any ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/webkitmediakeys.js declare namespace ಠ_ಠ.clutz { class WebKitMediaKeyError { private noStructuralTyping_WebKitMediaKeyError : any; code : number ; systemCode : number ; static MEDIA_KEYERR_CLIENT : number ; static MEDIA_KEYERR_DOMAIN : number ; static MEDIA_KEYERR_HARDWARECHANGE : number ; static MEDIA_KEYERR_OUTPUT : number ; static MEDIA_KEYERR_SERVICE : number ; static MEDIA_KEYERR_UNKNOWN : number ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/webkitmediakeys.js declare namespace ಠ_ಠ.clutz { interface WebKitMediaKeySession extends EventTarget { addEventListener (type : any , listener : any , useCapture : any ) : any ; close ( ) : any ; dispatchEvent (evt : any ) : any ; error : WebKitMediaKeyError | null ; removeEventListener (type : any , listener : any , useCapture : any ) : any ; sessionId : string ; update (message : Uint8Array | null ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/externs/webkitmediakeys.js declare namespace ಠ_ಠ.clutz { class WebKitMediaKeys { private noStructuralTyping_WebKitMediaKeys : any; constructor (keySystem : string ) ; createSession (contentType : string , initData : Uint8Array | null ) : WebKitMediaKeySession ; static isTypeSupported (keySystem : string , contentType : string ) : boolean ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/ui/externs/ui.js declare namespace shaka.extern { /** * Interface for UI elements. UI elements should inherit from the concrete base * class shaka.ui.Element. The members defined in this extern's constructor are * all available from the base class, and are defined here to keep the compiler * from renaming them. */ interface IUIElement extends shaka.util.IReleasable { ad : shaka.extern.IAd | null ; adManager : shaka.extern.IAdManager | null ; controls : shaka.ui.Controls | null ; eventManager : shaka.util.EventManager | null ; localization : shaka.ui.Localization | null ; parent : HTMLElement | null ; player : shaka.Player | null ; video : HTMLMediaElement | null ; release ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/ui/externs/ui.js declare namespace shaka.extern.IUIElement { /** * A factory for creating a UI element. */ interface Factory { create (rootElement : HTMLElement , controls : shaka.ui.Controls ) : shaka.extern.IUIElement ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/ui/externs/ui.js declare namespace shaka.extern { /** * Interface for UI range elements. UI range elements should inherit from the * concrete base class shaka.ui.RangeElement. The members defined in this * extern's constructor are all available from the base class, and are defined * here to keep the compiler from renaming them. */ interface IUIRangeElement extends shaka.extern.IUIElement { bar : HTMLInputElement ; container : HTMLElement ; changeTo (value : number ) : any ; getValue ( ) : number ; /** * Called when a new value is set by user interaction. * To be overridden by subclasses. */ onChange ( ) : any ; /** * Called when user interaction ends. * To be overridden by subclasses. */ onChangeEnd ( ) : any ; /** * Called when user interaction begins. * To be overridden by subclasses. */ onChangeStart ( ) : any ; setRange (min : number , max : number ) : any ; setValue (value : number ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/ui/externs/ui.js declare namespace shaka.extern { /** * Interface for SeekBars. SeekBars should inherit from the concrete base * class shaka.ui.Element. If you do not need to totaly rebuild the * SeekBar, you should consider using shaka.ui.RangeElement or * shaka.ui.SeekBar as your base class. */ interface IUISeekBar extends shaka.extern.IUIRangeElement { getValue ( ) : number ; isShowing ( ) : boolean ; setValue (value : number ) : any ; /** * Called by Controls on a timer to update the state of the seek bar. * Also called internally when the user interacts with the input element. */ update ( ) : any ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/ui/externs/ui.js declare namespace shaka.extern.IUISeekBar { /** * A factory for creating a SeekBar element. */ interface Factory { create (rootElement : HTMLElement , controls : shaka.ui.Controls ) : shaka.extern.IUISeekBar ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/ui/externs/ui.js declare namespace shaka.extern { /** * Interface for UI settings menus. UI settings menus should inherit from the * concrete base class shaka.ui.SettingsMenu. The members defined in this * extern's constructor are all available from the base class, and are defined * here to keep the compiler from renaming them. */ interface IUISettingsMenu extends shaka.extern.IUIElement { backButton : HTMLButtonElement ; backSpan : HTMLElement ; button : HTMLButtonElement ; currentSelection : HTMLElement ; icon : HTMLElement ; menu : HTMLElement ; nameSpan : HTMLElement ; } } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/ui/externs/ui.js declare namespace shaka.extern { type UIConfiguration = { addBigPlayButton : boolean , addSeekBar : boolean , castReceiverAppId : string , clearBufferOnQualityChange : boolean , controlPanelElements : string [] , doubleClickForFullscreen : boolean , enableFullscreenOnRotation : boolean , enableKeyboardPlaybackControls : boolean , fadeDelay : number , forceLandscapeOnFullscreen : boolean , overflowMenuButtons : string [] , seekBarColors : shaka.extern.UISeekBarColors , showUnbufferedStart : boolean , trackLabelFormat : shaka.ui.Overlay.TrackLabelFormat , volumeBarColors : shaka.extern.UIVolumeBarColors } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/ui/externs/ui.js declare namespace shaka.extern { type UISeekBarColors = { adBreaks : string , base : string , buffered : string , played : string } ; } // Generated from /usr/local/google/home/joeyparrish/hacking/shaka/clean/ui/externs/ui.js declare namespace shaka.extern { type UIVolumeBarColors = { base : string , level : string } ; }
cdnjs/cdnjs
ajax/libs/shaka-player/3.1.6/shaka-player.ui.d.ts
TypeScript
mit
198,161
package csc426.ast; import org.beryx.textio.TextTerminal; import csc426.parser.Position; import csc426.semantics.LookupException; import csc426.semantics.SymbolTable; import csc426.semantics.Value; import csc426.semantics.VoidValue; public final class IdExpr extends Expr { public final String id; public IdExpr(String id, Position position) { super(position); this.id = id; } @Override public String toString() { return "Variable " + id + " at " + position; } public String render(String indent) { return indent + "Id " + id + "\n"; } @Override public Value interpret(TextTerminal<?> terminal, SymbolTable<Value> t) { try { return t.lookup(id); } catch (LookupException e) { terminal.println(e.getMessage()); } return VoidValue.INSTANCE; } }
bhoward/CSC426
Demo3/src/main/java/csc426/ast/IdExpr.java
Java
cc0-1.0
785
wcn.view.view = (function() { var views = {}; class view extends whitecrow.control { initialize() { super.initialize(); } static register(name,layoutName){ if(!views[name]){ views[name] = this; this.layoutName = layoutName; return this; } else throw new Error("View with the name '"+name+"' is already registered"); } static resolve(name){ return views[name]; } } return view; })();
kanaxz/video-station
project/lib/whitecrow/namespace/view/view.js
JavaScript
cc0-1.0
473
import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class TelaNotas extends JFrame { private JPanel painelPrincipal; private JPanel painelTopo; private JPanel painelSearch; private JTable tabela; private JPanel painelBotoes; private JScrollPane barraRolagem; private JButton btImprimir; private JButton btVoltar; private JLabel lblNomeCliente; private DefaultTableModel modelo = new DefaultTableModel(); public TelaNotas() { super(" Relatorio de Notas "); painelSearch = new JPanel(); painelPrincipal = new JPanel(); painelTopo = new JPanel(); criaJTable(); criaJanela(); } public void criaJanela() { painelPrincipal.setLayout(new BorderLayout()); painelTopo.setLayout(new FlowLayout(FlowLayout.LEFT)); lblNomeCliente = new JLabel("<Nome do Cliente>"); painelTopo.add(lblNomeCliente); painelTopo.add(BorderLayout.CENTER,painelSearch); //painelSearch.setAlignmentX(LEFT_ALIGNMENT); barraRolagem = new JScrollPane(tabela); painelBotoes= new JPanel(); painelBotoes.setLayout(new FlowLayout(FlowLayout.RIGHT)); btImprimir = new JButton("Imprimir"); btVoltar = new JButton("Voltar"); painelBotoes.add(btImprimir); painelBotoes.add(btVoltar); painelPrincipal.add(BorderLayout.NORTH,painelTopo); painelPrincipal.add(BorderLayout.SOUTH,painelBotoes); painelPrincipal.add(BorderLayout.CENTER,barraRolagem); getContentPane().add(painelPrincipal); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(500, 320); setVisible(true); } private void criaJTable() { tabela = new JTable(modelo); modelo.addColumn(" Nota "); modelo.addColumn(" Quantidade "); tabela.getColumnModel().getColumn(0).setPreferredWidth(120); tabela.getColumnModel().getColumn(1).setPreferredWidth(120); } public static void main(String[] args) { TelaNotas lc = new TelaNotas(); lc.setVisible(true); lc.pack(); } }
JulioCesarMelo/ProjetoIntegrado
Interface/TelaNotas.java
Java
cc0-1.0
2,095
# coding: utf-8 import copy import json import gzip from cStringIO import StringIO from datetime import datetime import arrow import iso8601 from dateutil import tz import ML from ML import operation __author__ = 'czhou <czhou@ilegendsoft.com>' def get_dumpable_types(): return ( operation.BaseOp, ) def encode(value, disallow_objects=False): if isinstance(value, datetime): tzinfo = value.tzinfo if tzinfo is None: tzinfo = tz.tzlocal() return { '__type': 'Date', 'iso': arrow.get(value, tzinfo).to('utc').format('YYYY-MM-DDTHH:mm:ss.SSS') + 'Z', } if isinstance(value, ML.Object): if disallow_objects: raise ValueError('ML.Object not allowed') return value._to_pointer() if isinstance(value, get_dumpable_types()): return value.dump() if isinstance(value, (tuple, list)): return [encode(x, disallow_objects) for x in value] if isinstance(value, dict): return dict([(k, encode(v, disallow_objects)) for k, v in value.iteritems()]) return value def decode(key, value): if isinstance(value, get_dumpable_types()): return value if isinstance(value, (tuple, list)): return [decode(key, x) for x in value] if not isinstance(value, dict): return value if '__type' not in value: return dict([(k, decode(k, v)) for k, v in value.iteritems()]) _type = value['__type'] if _type == 'Pointer': value = copy.deepcopy(value) class_name = value['className'] pointer = ML.Object.create(class_name) if 'createdAt' in value: value.pop('__type') value.pop('className') pointer._finish_fetch(value, True) else: pointer._finish_fetch({'objectId': value['objectId']}, False) return pointer if _type == 'Object': value = copy.deepcopy(value) class_name = value['className'] value.pop('__type') value.pop('class_name') obj = ML.Object.create(class_name) obj._finish_fetch(value, True) return obj if _type == 'Date': return arrow.get(iso8601.parse_date(value['iso'])).to('local').datetime if _type == 'Relation': relation = ML.Relation(None, key) relation.target_class_name = value['className'] return relation def traverse_object(obj, callback, seen=None): seen = seen or set() if isinstance(obj, ML.Object): if obj in seen: return seen.add(obj) traverse_object(obj.attributes, callback, seen) return callback(obj) if isinstance(obj, (ML.Relation )): return callback(obj) if isinstance(obj, (list, tuple)): for idx, child in enumerate(obj): new_child = traverse_object(child, callback, seen) if new_child: obj[idx] = new_child return callback(obj) if isinstance(obj, dict): for key, child in obj.iteritems(): new_child = traverse_object(child, callback, seen) if new_child: obj[key] = new_child return callback(obj) return callback(obj) def response_to_json(response): """ hack for requests in python 2.6 """ if isinstance(response, ML.Response): return json.loads(response.data) content = response.content # hack for requests in python 2.6 if 'application/json' in response.headers.get('Content-Type',''): if content[:2] == '\x1f\x8b': f = StringIO(content) g = gzip.GzipFile(fileobj=f) content = g.read() g.close() f.close() return json.loads(content)
MaxLeap/SDK-CloudCode-Python
ML/utils.py
Python
cc0-1.0
3,771
#!/usr/bin/python import os import time import moveServo import os.path from multiprocessing import Process my_dir = os.path.dirname(__file__) def main(): moveServo.init_candy() moveServo.move_servo_ext(0, 180, 25) print "sleep 5" # time.sleep(1) moveServo.move_servo_ext(180, 90, 25) print "sleep 5" # time.sleep(1) moveServo.move_servo_ext(90, 0, 25) if __name__ == "__main__": try: main() except KeyboardInterrupt: print "Keyboard interrupt received. Cleaning up..." moveServo.del_all_servos() print "Keyboard interrupt Clean up done"
intelmakers/candy_machine
Python/test_servo.py
Python
cc0-1.0
625
from RebotConfig import RebotConfig from Log import Log from exchange.huobi.HuobiUtil import * from exchange.huobi.HuobiService import * import json import time import math '''{1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year }''' PERIOD2TYPE = { 1 : '1min', 5 : '5min', 15 : '15min', 30 : '30min', 60 : '60min', } def PERIOD(period): if period >= 60: return '60min'; return PERIOD2TYPE.get(period); def TIMEHOUR(timestamp): return float(time.strftime("%H", time.localtime(timestamp))); def CreateDefalutKline(): return { 'id' : 0, 'open' : 0, 'high' : 0, 'low' : 999999999, 'close' : 0, 'amount': 0, 'vol' : 0, } def SortCompare(a, b): return a['id'] < b['id']; def Cut(num, c): s = '{:.9f}'.format(num); pos = s.find('.'); if pos > 0: return float(s[0:pos+c+1]); else: return num; def ConvertData(preiod1, data, period2): ndata = []; kcount = period2 / preiod1; datalenght = len(data); nk = None; for key in range(1, datalenght): k = data[datalenght - 1 - key]; prek = data[datalenght - key]; h = TIMEHOUR(k['id']); idx = h % kcount; if idx == 0: if nk != None: nk['close'] = prek['close']; nk['high'] = max(nk['high'], prek['high']); nk['low'] = min(nk['low'], prek['low']); nk['amount']= nk['amount'] + nk['preamount']; nk['vol'] = nk['vol'] + nk['prevol']; nk = CreateDefalutKline(); ndata.append(nk); nk['id'] = k['id']; nk['open'] = k['open']; nk['preamount'] = 0; nk['prevol'] = 0; nk['idx'] = idx; if nk != None: nk['close'] = k['close']; nk['high'] = max(nk['high'], k['high']); nk['low'] = min(nk['low'], k['low']); if nk['idx'] != idx: nk['preamount'] += prek['amount']; nk['prevol'] += prek['vol']; nk['idx'] = idx; nk['amount'] = nk['preamount'] + k['amount']; nk['vol'] = nk['prevol'] + k['vol']; ndata.reverse(); #for k,v in enumerate(ndata): # print v, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(v['id'])); return ndata; def ConvertKlineData(data): ndata = []; lendatadata = len(data); for k in range(0, lendatadata): v = data[lendatadata - 1 - k]; d = [0,1,2,3,4,5,6]; d[0] = v['id']; d[1] = v['open']; d[2] = v['high']; d[3] = v['low']; d[4] = v['close']; d[5] = v['amount']; d[6] = v['vol']; ndata.append(d); return ndata; class huobiEX(): def set(self, access, secret): set_user_key(access, secret); self.orders = {}; self.marketOrders = {}; self.precisions = {}; def createOrder(self, id, market, side, time, price, volume, ext): o = { 'id':id, 'side':side, # sell, buy 'price':price, 'avg_price':price, 'state':'wait', # wait, done, cancel 'market':market, 'created_at':time, 'volume':volume, 'remaining_volume':volume, 'executed_volume':0, 'ext':ext, } self.orders[id] = o; d = self.marketOrders.get(market); if d==None: self.marketOrders[market] = []; d = self.marketOrders.get(market); d.append(o); return id; def getPrice(self, market, price): d = self.precisions[market]; if d != None: return round(price, int(d['price-precision'])); else : return round(price, 0); def getVolume(self, market, vol): d = self.precisions[market]; if d != None: return Cut(vol, int(d['amount-precision'])); else : return Cut(vol, 0); # function def loadData(self, period, timestamp): return None; def prepare(self, period, timestamp): d = get_symbols(); markets = []; for k,v in enumerate(d['data']): if v['quote-currency'] == 'usdt': key = v['base-currency'] + 'usdt'; if key != 'venusdt': self.precisions[key] = v; markets.append({'id':key}); self.markets = markets; def getServerTimestamp(self): return time.time(); def getUser(self): data = get_balance(); nndata = []; if data['status'] != 'ok': return {'accounts':nndata}; if data['data']['state'] != 'working': return {'accounts':nndata}; listdata = data['data']['list']; ndata = {}; for k,v in enumerate(listdata): currency = v['currency']; c = ndata.get(currency); if c == None: c = {'currency': currency}; ndata[currency] = c; if v['type'] == 'trade': c['balance'] = float(v['balance']); if v['type'] == 'frozen': c['locked'] = float(v['balance']); for k,v in enumerate(ndata): d = ndata.get(v); if d['balance'] > 0 or d['locked'] > 0: nndata.append(d); return {'accounts':nndata}; def getMarkets(self): if len(RebotConfig.rebot_trade_markets) > 0: return RebotConfig.rebot_trade_markets; return self.markets; def getK(self, market, limit, period, timestamp=None): data = None; if period > 60: data = get_kline(market, PERIOD(period), limit * period / 60); else: data = get_kline(market, PERIOD(period), limit); if data['status'] != 'ok': return []; datadata = data['data']; if period > 60 : datadata = ConvertData(60, datadata, period); return ConvertKlineData(datadata); def getOrder(self, market): ''' ret = self.marketOrders.get(market); if ret == None: return []; 'remaining_volume':volume, 'executed_volume':0, for k, o in enumerate(ret): data = order_info(o['id']); if data['status'] == 'ok': data = data['data']; o['remaining_volume'] = float(data['amount']) - float(data['field-amount']); o['executed_volume'] = float(data['field-amount']); o['averageprice'] = float(data['field-cash-amount']) / float(data['field-amount']); ''' data = orders_list(market, "pre-submitted,submitted,partial-filled,partial-canceled,filled,canceled"); if data['status'] != 'ok': return []; ret = data['data']; for k, o in enumerate(data['data']): o['id'] = int(o['id']); o['created_at'] = float(o['created-at'])/1000; o['side'] = o['type'][0:3]; if o['side'] != 'buy': o['side'] = 'sell'; o['price'] = float(o['price']); o['market'] = o['symbol']; o['volume'] = float(o['amount']); o['remaining_volume'] = float(o['amount']) - float(o['field-amount']); o['executed_volume'] = float(o['field-amount']); if o['executed_volume'] > 0: o['avg_price'] = float(o['field-cash-amount']) / float(o['field-amount']); else: o['avg_price'] = 0; # pre-submitted,submitted,partial-filled,partial-canceled,filled,canceled if o['state'] == "canceled" or o['state'] == 'partial-canceled': o['state'] = "cancel"; if o['state'] == 'filled': o['state'] = 'compelete'; return ret; def doOrder(self, market, side, price, volume, time=None, ext=None): volume = self.getVolume(market, volume); price = self.getPrice(market, price); if volume <= 0: Log.d("\t\tvolume in precision is nil"); return True, price, volume; nside = 'buy-limit'; if side == 'sell': nside = 'sell-limit'; result = send_order(volume, 'api', market, nside, price); if result['status'] != 'ok': Log.d('\t\tdo order result {0}'.format(result)); return False, price, volume; # self.createOrder(result['data'], market, side, price, volume, time, ext); return True, price, volume; def doOrderCancel(self, orderID, market): data = cancel_order(orderID); if data['status'] != "ok": return False; return True; class huobiEXLocal(): def set(self, access, secret): set_user_key(access, secret) self.accounts = { 'usdt' : {'currency':'usdt', 'balance':'%d' % RebotConfig.user_initamount, 'locked':'0.0'}, }; self.orders = {}; self.marketOrders = {}; self.ORDERID = 0; self.kss = {}; self.allMarkets = None; self.currentMarkets = None; self.poundage = 0;#0.0001; self.precisions = {}; def getPrice(self, market, price): d = self.precisions[market]; if d != None: return round(price, int(d['price-precision'])); else : return round(price, 0); def getVolume(self, market, vol): d = self.precisions[market]; if d != None: return Cut(vol, int(d['amount-precision'])); else : return Cut(vol, 0); def createOrder(self, market, side, time, price, volume, ext): if volume<=0: return None; self.ORDERID += 1; id = self.ORDERID; o = { 'id':id, 'side':side, # sell, buy 'price':price, 'avg_price':price, 'state':'wait', # wait, done, cancel 'market':market, 'created_at':time, 'volume':volume, 'remaining_volume':volume, 'executed_volume':0, 'ext':ext } self.orders[id] = o; d = self.marketOrders.get(market); if d==None: self.marketOrders[market] = []; d = self.marketOrders.get(market); d.append(o); return id; def compeleteOrder(self, id): o = self.orders.get(id); if o==None: return; market = o['market']; currency = market[0:len(market) - len(RebotConfig.base_currency)]; o['remaining_volume']=0; o['executed_volume']=o['volume']; o['state']='done'; if o['side'] == 'sell': c = self.accounts.get(currency); balance = float(c['balance']); c['balance'] = str(balance - o['executed_volume']); ccny = self.accounts.get(RebotConfig.base_currency); ccny['balance'] = str(float(ccny['balance']) + o['executed_volume'] * o['avg_price'] * (1 - self.poundage) ); print '\t\tsell', market, balance, c['balance'] if o['side'] == 'buy': c = self.accounts.get(currency); if c==None: self.accounts[currency] = {'currency':currency, 'balance':'0.0', 'locked':'0.0', 'price':0.0}; c = self.accounts.get(currency); balance = float(c['balance']); price = c['price']; addbalance = o['executed_volume'] * (1 - self.poundage); addprice = o['avg_price']; print '\t\tbuy',market, balance, addbalance c['balance'] = str(balance + addbalance); c['price'] = (balance)/(balance+addbalance)*price + addbalance/(balance+addbalance)*addprice; ccny = self.accounts.get(RebotConfig.base_currency); ccny['balance'] = str(float(ccny['balance']) - addbalance*addprice); # function def loadData(self, period, timestamp): return None; def prepare(self, period, timestamp): d = get_symbols(); markets = [] for k,v in enumerate(d['data']): if v['quote-currency'] == 'usdt': key = v['base-currency'] + 'usdt'; self.precisions[v['base-currency'] + 'usdt'] = v; markets.append({'id':key}); self.markets = markets; def getServerTimestamp(self): return time.time(); def getUser(self): d = {} accounts = []; for k,v in self.accounts.items(): accounts.append(v); d['accounts']=accounts; return d; def getMarkets(self): if len(RebotConfig.rebot_trade_markets) > 0: return RebotConfig.rebot_trade_markets; return self.markets; #return [{'id':'anscny'},{'id':'btccny'}, {'id':'ethcny'}, {'id':'zeccny'}, {'id':'qtumcny'}, {'id':'gxscny'}, {'id':'eoscny'}, {'id':'sccny'}, {'id':'dgdcny'}, {'id':'1stcny'}, {'id':'btscny'}, {'id':'gntcny'}, {'id':'repcny'}, {'id':'etccny'}]; #return [{'id':'anscny'}]; def getK(self, market, limit, period, timestamp=None): if RebotConfig.rebot_is_test == False: data = None; if period > 60: data = get_kline(market, PERIOD(period), limit * period / 60); else: data = get_kline(market, PERIOD(period), limit); if data['status'] != 'ok': return []; datadata = data['data']; if period > 60 : datadata = ConvertData(60, datadata, period); return ConvertKlineData(datadata); ks = self.kss.get(market); if ks==None: data = None; if period > 60: data = get_kline(market, PERIOD(period), RebotConfig.rebot_test_k_count * period / 60); else: data = get_kline(market, PERIOD(period), RebotConfig.rebot_test_k_count); datadata = data['data']; if period > 60 : datadata = ConvertData(60, datadata, period); # print "kline length", len(datadata), RebotConfig.rebot_test_k_count * period / 60, 'xxxxxxxxxxxxxxxxx'; self.kss[market] = ConvertKlineData(datadata); ks = self.kss.get(market); # time.sleep(0.01); # print timestamp, len(ks), ks[-1][0], limit if ks == None or len(ks) == 0: print '%s do not find kline' % market if timestamp > ks[-1][0]: print '{0} k line is over'.format(market); return []; ret = []; for k,v in enumerate(ks): if v[0] >= timestamp: ret.append(v); if len(ret) >= limit: return ret; return ret; def getOrder(self, market): ret = self.marketOrders.get(market); if ret==None: return []; return ret; def doOrder(self, market, side, price, volume, time=None, ext=None): price = self.getPrice(market, price); volume = self.getVolume(market, volume); id = self.createOrder(market, side, time, price, volume, ext) if id: self.compeleteOrder(id); return True, price, volume; def doOrderCancel(self, orderID, market): return None;
WaitGodot/peatio-client-python
exchange/huobiEX.py
Python
cc0-1.0
15,480
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.scripts.tap2rpm}. """ import os from twisted.trial.unittest import TestCase, SkipTest from twisted.python import procutils from twisted.python.failure import Failure from twisted.internet import utils from twisted.scripts import tap2rpm # When we query the RPM metadata, we get back a string we'll have to parse, so # we'll use suitably rare delimiter characters to split on. Luckily, ASCII # defines some for us! RECORD_SEPARATOR = "\x1E" UNIT_SEPARATOR = "\x1F" def _makeRPMs(tapfile=None, maintainer=None, protocol=None, description=None, longDescription=None, setVersion=None, rpmfile=None, type_=None): """ Helper function to invoke tap2rpm with the given parameters. """ args = [] if not tapfile: tapfile = "dummy-tap-file" handle = open(tapfile, "w") handle.write("# Dummy TAP file\n") handle.close() args.extend(["--quiet", "--tapfile", tapfile]) if maintainer: args.extend(["--maintainer", maintainer]) if protocol: args.extend(["--protocol", protocol]) if description: args.extend(["--description", description]) if longDescription: args.extend(["--long_description", longDescription]) if setVersion: args.extend(["--set-version", setVersion]) if rpmfile: args.extend(["--rpmfile", rpmfile]) if type_: args.extend(["--type", type_]) return tap2rpm.run(args) def _queryRPMTags(rpmfile, taglist): """ Helper function to read the given header tags from the given RPM file. Returns a Deferred that fires with dictionary mapping a tag name to a list of the associated values in the RPM header. If a tag has only a single value in the header (like NAME or VERSION), it will be returned as a 1-item list. Run "rpm --querytags" to see what tags can be queried. """ # Build a query format string that will return appropriately delimited # results. Every field is treated as an array field, so single-value tags # like VERSION will be returned as 1-item lists. queryFormat = RECORD_SEPARATOR.join([ "[%%{%s}%s]" % (tag, UNIT_SEPARATOR) for tag in taglist ]) def parseTagValues(output): res = {} for tag, values in zip(taglist, output.split(RECORD_SEPARATOR)): values = values.strip(UNIT_SEPARATOR).split(UNIT_SEPARATOR) res[tag] = values return res def checkErrorResult(failure): # The current rpm packages on Debian and Ubuntu don't properly set up # the RPM database, which causes rpm to print a harmless warning to # stderr. Unfortunately, .getProcessOutput() assumes all warnings are # catastrophic and panics whenever it sees one. # # See also: # http://twistedmatrix.com/trac/ticket/3292#comment:42 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=551669 # http://rpm.org/ticket/106 failure.trap(IOError) # Depending on kernel scheduling, we might read the whole error # message, or only the first few bytes. if str(failure.value).startswith("got stderr: 'error: "): newFailure = Failure(SkipTest("rpm is missing its package " "database. Run 'sudo rpm -qa > /dev/null' to create one.")) else: # Not the exception we were looking for; we should report the # original failure. newFailure = failure # We don't want to raise the exception right away; we want to wait for # the process to exit, otherwise we'll get extra useless errors # reported. d = failure.value.processEnded d.addBoth(lambda _: newFailure) return d d = utils.getProcessOutput("rpm", ("-q", "--queryformat", queryFormat, "-p", rpmfile)) d.addCallbacks(parseTagValues, checkErrorResult) return d class TestTap2RPM(TestCase): def setUp(self): return self._checkForRpmbuild() def _checkForRpmbuild(self): """ tap2rpm requires rpmbuild; skip tests if rpmbuild is not present. """ if not procutils.which("rpmbuild"): raise SkipTest("rpmbuild must be present to test tap2rpm") def _makeTapFile(self, basename="dummy"): """ Make a temporary .tap file and returns the absolute path. """ path = basename + ".tap" handle = open(path, "w") handle.write("# Dummy .tap file") handle.close() return path def _verifyRPMTags(self, rpmfile, **tags): """ Check the given file has the given tags set to the given values. """ d = _queryRPMTags(rpmfile, tags.keys()) d.addCallback(self.assertEqual, tags) return d def test_optionDefaults(self): """ Commandline options should default to sensible values. "sensible" here is defined as "the same values that previous versions defaulted to". """ config = tap2rpm.MyOptions() config.parseOptions([]) self.assertEqual(config['tapfile'], 'twistd.tap') self.assertEqual(config['maintainer'], 'tap2rpm') self.assertEqual(config['protocol'], 'twistd') self.assertEqual(config['description'], 'A TCP server for twistd') self.assertEqual(config['long_description'], 'Automatically created by tap2rpm') self.assertEqual(config['set-version'], '1.0') self.assertEqual(config['rpmfile'], 'twisted-twistd') self.assertEqual(config['type'], 'tap') self.assertEqual(config['quiet'], False) self.assertEqual(config['twistd_option'], 'file') self.assertEqual(config['release-name'], 'twisted-twistd-1.0') def test_protocolCalculatedFromTapFile(self): """ The protocol name defaults to a value based on the tapfile value. """ config = tap2rpm.MyOptions() config.parseOptions(['--tapfile', 'pancakes.tap']) self.assertEqual(config['tapfile'], 'pancakes.tap') self.assertEqual(config['protocol'], 'pancakes') def test_optionsDefaultToProtocolValue(self): """ Many options default to a value calculated from the protocol name. """ config = tap2rpm.MyOptions() config.parseOptions([ '--tapfile', 'sausages.tap', '--protocol', 'eggs', ]) self.assertEqual(config['tapfile'], 'sausages.tap') self.assertEqual(config['maintainer'], 'tap2rpm') self.assertEqual(config['protocol'], 'eggs') self.assertEqual(config['description'], 'A TCP server for eggs') self.assertEqual(config['long_description'], 'Automatically created by tap2rpm') self.assertEqual(config['set-version'], '1.0') self.assertEqual(config['rpmfile'], 'twisted-eggs') self.assertEqual(config['type'], 'tap') self.assertEqual(config['quiet'], False) self.assertEqual(config['twistd_option'], 'file') self.assertEqual(config['release-name'], 'twisted-eggs-1.0') def test_releaseNameDefaultsToRpmfileValue(self): """ The release-name option is calculated from rpmfile and set-version. """ config = tap2rpm.MyOptions() config.parseOptions([ "--rpmfile", "beans", "--set-version", "1.2.3", ]) self.assertEqual(config['release-name'], 'beans-1.2.3') def test_basicOperation(self): """ Calling tap2rpm should produce an RPM and SRPM with default metadata. """ basename = "frenchtoast" # Create RPMs based on a TAP file with this name. rpm, srpm = _makeRPMs(tapfile=self._makeTapFile(basename)) # Verify the resulting RPMs have the correct tags. d = self._verifyRPMTags(rpm, NAME=["twisted-%s" % (basename,)], VERSION=["1.0"], RELEASE=["1"], SUMMARY=["A TCP server for %s" % (basename,)], DESCRIPTION=["Automatically created by tap2rpm"], ) d.addCallback(lambda _: self._verifyRPMTags(srpm, NAME=["twisted-%s" % (basename,)], VERSION=["1.0"], RELEASE=["1"], SUMMARY=["A TCP server for %s" % (basename,)], DESCRIPTION=["Automatically created by tap2rpm"], )) return d def test_protocolOverride(self): """ Setting 'protocol' should change the name of the resulting package. """ basename = "acorn" protocol = "banana" # Create RPMs based on a TAP file with this name. rpm, srpm = _makeRPMs(tapfile=self._makeTapFile(basename), protocol=protocol) # Verify the resulting RPMs have the correct tags. d = self._verifyRPMTags(rpm, NAME=["twisted-%s" % (protocol,)], SUMMARY=["A TCP server for %s" % (protocol,)], ) d.addCallback(lambda _: self._verifyRPMTags(srpm, NAME=["twisted-%s" % (protocol,)], SUMMARY=["A TCP server for %s" % (protocol,)], )) return d def test_rpmfileOverride(self): """ Setting 'rpmfile' should change the name of the resulting package. """ basename = "cherry" rpmfile = "donut" # Create RPMs based on a TAP file with this name. rpm, srpm = _makeRPMs(tapfile=self._makeTapFile(basename), rpmfile=rpmfile) # Verify the resulting RPMs have the correct tags. d = self._verifyRPMTags(rpm, NAME=[rpmfile], SUMMARY=["A TCP server for %s" % (basename,)], ) d.addCallback(lambda _: self._verifyRPMTags(srpm, NAME=[rpmfile], SUMMARY=["A TCP server for %s" % (basename,)], )) return d def test_descriptionOverride(self): """ Setting 'description' should change the SUMMARY tag. """ description = "eggplant" # Create RPMs based on a TAP file with this name. rpm, srpm = _makeRPMs(tapfile=self._makeTapFile(), description=description) # Verify the resulting RPMs have the correct tags. d = self._verifyRPMTags(rpm, SUMMARY=[description], ) d.addCallback(lambda _: self._verifyRPMTags(srpm, SUMMARY=[description], )) return d def test_longDescriptionOverride(self): """ Setting 'longDescription' should change the DESCRIPTION tag. """ longDescription = "fig" # Create RPMs based on a TAP file with this name. rpm, srpm = _makeRPMs(tapfile=self._makeTapFile(), longDescription=longDescription) # Verify the resulting RPMs have the correct tags. d = self._verifyRPMTags(rpm, DESCRIPTION=[longDescription], ) d.addCallback(lambda _: self._verifyRPMTags(srpm, DESCRIPTION=[longDescription], )) return d def test_setVersionOverride(self): """ Setting 'setVersion' should change the RPM's version info. """ version = "123.456" # Create RPMs based on a TAP file with this name. rpm, srpm = _makeRPMs(tapfile=self._makeTapFile(), setVersion=version) # Verify the resulting RPMs have the correct tags. d = self._verifyRPMTags(rpm, VERSION=["123.456"], RELEASE=["1"], ) d.addCallback(lambda _: self._verifyRPMTags(srpm, VERSION=["123.456"], RELEASE=["1"], )) return d def test_tapInOtherDirectory(self): """ tap2rpm handles tapfiles outside the current directory. """ # Make a tapfile outside the current directory. tempdir = self.mktemp() os.mkdir(tempdir) tapfile = self._makeTapFile(os.path.join(tempdir, "bacon")) # Try and make an RPM from that tapfile. _makeRPMs(tapfile=tapfile)
Kagami/kisa
lib/twisted/scripts/test/test_tap2rpm.py
Python
cc0-1.0
12,453
'use strict'; var gulp = require( 'gulp' ); gulp.task( 'build', ['scripts', 'lint', 'test'] );
sebworks/AtomicComponent
gulp/build.js
JavaScript
cc0-1.0
97
package safepoint.fair; import java.lang.management.ManagementFactory; import java.util.concurrent.ThreadLocalRandom; public class SafepointUsingThreadGetInfo extends LoveAtATimeOfSafepoints { @Override protected Object safepointMethod() { long[] threadIds = ManagementFactory.getThreadMXBean().getAllThreadIds(); long tid = threadIds[ThreadLocalRandom.current().nextInt(threadIds.length)]; return ManagementFactory.getThreadMXBean().getThreadInfo(tid, 256); } }
nitsanw/safepoint-experiments
src/main/java/safepoint/fair/SafepointUsingThreadGetInfo.java
Java
cc0-1.0
484
'use strict'; App.factory('PageStateDragClose', [ 'PageStateDragOpen', 'extend', function(PageStateDragOpen, extend) { return extend(function() { this.dragStart = function() { this.getPointer().dragCloseStart(); }; this.drag = function() { this.getPointer().dragClose(); }; this.dragComplete = function() { this.getPointer().dragCloseComplete(); }; }, PageStateDragOpen); }]);
benjah1/christmas2014
app/scripts/factory/book/PageStateDragClose.js
JavaScript
cc0-1.0
407
//! @Alan //! //! Exercise 10.42: //! Reimplement the program that eliminated duplicate words that //! we wrote in § 10.2.3 (p. 383) to use a list instead of a vector. //! #include <iostream> #include <string> #include <list> int main() { std::list<std::string> l = {"aa","aa","aa","aa","aasss","aa"}; l.unique(); for(auto e : l) std::cout << e << " "; return 0; } //! output //! //aa aasss aa
courri/Cpp-Primer
ch10/ex10_42.cpp
C++
cc0-1.0
414
import FWCore.ParameterSet.Config as cms from HeavyIonsAnalysis.JetAnalysis.jets.akPu4PFJetSequence_PbPb_mc_cff import * #PU jets with 15 GeV threshold for subtraction akPu4PFmatch15 = akPu4PFmatch.clone(src = cms.InputTag("akPu4PFJets15")) akPu4PFparton15 = akPu4PFparton.clone(src = cms.InputTag("akPu4PFJets15")) akPu4PFcorr15 = akPu4PFcorr.clone(src = cms.InputTag("akPu4PFJets15")) akPu4PFpatJets15 = akPu4PFpatJets.clone(jetSource = cms.InputTag("akPu4PFJets15"), jetCorrFactorsSource = cms.VInputTag(cms.InputTag("akPu4PFcorr15")), genJetMatch = cms.InputTag("akPu4PFmatch15"), genPartonMatch = cms.InputTag("akPu4PFparton15"), ) akPu4PFJetAnalyzer15 = akPu4PFJetAnalyzer.clone(jetTag = cms.InputTag("akPu4PFpatJets15"), doSubEvent = cms.untracked.bool(True) ) akPu4PFJetSequence15 = cms.Sequence(akPu4PFmatch15 * akPu4PFparton15 * akPu4PFcorr15 * akPu4PFpatJets15 * akPu4PFJetAnalyzer15 )
mverwe/JetRecoValidation
PuThresholdTuning/python/akPu4PFJetSequence15_cff.py
Python
cc0-1.0
1,371
#include <iostream> #include <vector> void carr_func(int * vec) { std::cout << "carr_func - vec: " << vec << std::endl; } int main(void) { std::vector<int> v1 = {-1, 3, 5, -8, 0}; //initialize with list std::vector<int> v2; //don't initialize auto v3(v1); //initialize v3 via copy /** * Managing std::vector capacity */ //Unlike std::array, std::vector has a more sensible empty() function //v2 is currently empty std::cout << "v1.empty(): " << v1.empty() << std::endl; std::cout << "v2.empty(): " << v2.empty() << std::endl; // size() tells you the number of elements std::cout << "v1.size(): " << v1.size() << std::endl; std::cout << "v2.size(): " << v2.size() << std::endl; // max_size() is huuuuuuuuuge for my host machine std::cout << "v1.max_size(): " << v1.max_size() << std::endl; std::cout << "v2.max_size(): " << v2.max_size() << std::endl; // Capacity tells you how many elements can be stored in the currently allocated memory std::cout << "v1.capacity(): " << v1.capacity() << std::endl; std::cout << "v2.capacity(): " << v2.capacity() << std::endl; v2.reserve(10); std::cout << "v2.capacity() after reserve(10): " << v2.capacity() << std::endl; std::cout << "v2.size(): " << v2.size() << std::endl; //If you have reserved space greater than your current needs, you can shrink the buffer v2.shrink_to_fit(); std::cout << "v2.capacity() after shrink_to_fit(): " << v2.capacity() << std::endl; /** * Accessing std::vector elements */ std::cout << "v1.front(): " << v1.front() << std::endl; std::cout << "v1.back(): " << v1.back() << std::endl; std::cout << "v1[0]: " << v1[0] << std::endl; std::cout << "v1.at(4): " << v1.at(4) << std::endl; // Bounds checking will generate exceptions. Try: //auto b = v2.at(10); //However, operator [] is not bounds checked! //This may or may not seg fault //std::cout << "v2[6]: " << v2[6] << std::endl; /* * If you need to interface with legacy code or libraries requiring * a C-style array interface, you can get to the underlying array data ptr */ //Error: //carr_func(v1); //OK: carr_func(v1.data()); /** * Playing around with vectors */ v2 = v1; //copy std::cout << "v2.size() after copy: " << v2.size() << std::endl; v2.clear(); std::cout << "v2.size() after clear: " << v2.size() << std::endl; std::cout << "v2.capacity(): " << v2.capacity() << std::endl; v2.insert(v2.begin(), -1); //insert an element - you need an iterator v2.emplace(v2.end(), int(1000)); //construct and place an element at the iterator int x = 10; v2.push_back(x); //adds element to end v2.emplace_back(10); //constructs an element in place at the end std::cout << std::endl << "v2: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; v2.resize(7); //resize to 7. The new elements will be 0-initialized v2.resize(10, -1); //resize to 10. New elements initialized with -1 v2.pop_back(); //removes last element v2.erase(v2.begin()); //removes first element std::cout << std::endl << "v2 resized: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; v2.resize(4); //shrink and strip off extra elements //Container operations work std::sort(v2.begin(), v2.end()); std::cout << std::endl << "v2 shrunk & sorted: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; std::cout << "std::vector size: " << sizeof(std::vector<char>) << std::endl; return 0; }
phillipjohnston/embedded-resources
examples/cpp/vector.cpp
C++
cc0-1.0
3,513
(function() { // this code can only be used in couchdb. module.exports = { design_docs: { helpers: require('lib/pantheon-helpers-design-docs/helpers'), } }; }).call(this);
Ooblioob/pantheon-helpers
pantheon-helpers.js
JavaScript
cc0-1.0
193
#include "pch.h" /********************************************************************** <BR> This file is part of Crack dot Com's free source code release of Golgotha. <a href="http://www.crack.com/golgotha_release"> <BR> for information about compiling & licensing issues visit this URL</a> <PRE> If that doesn't help, contact Jonathan Clark at golgotha_source@usa.net (Subject should have "GOLG" in it) ***********************************************************************/ #include "sound_man.h" #include "objs/model_id.h" #include "objs/model_draw.h" #include "objs/rocktank.h" #include "objs/base_launcher.h" #include "input.h" #include "math/pi.h" #include "math/angle.h" #include "math/trig.h" #include "objs/buster_rocket.h" #include "resources.h" #include "saver.h" #include "object_definer.h" #include "objs/fire.h" #include "lisp/lisp.h" static g1_object_type stank; void g1_base_launcher_init() { //buster = g1_get_object_type("buster_rocket"); stank = g1_get_object_type("stank"); } g1_object_definer<g1_base_launcher_class> g1_base_launcher_def("base_launcher", g1_object_definition_class::EDITOR_SELECTABLE, g1_base_launcher_init); g1_base_launcher_class::g1_base_launcher_class(g1_object_type id, g1_loader_class * fp) : g1_map_piece_class(id,fp) { defaults = g1_base_launcher_def.defaults; draw_params.setup("rocket_truck_top","rocket_truck_shadow"); first_time=i4_F; w16 ver,data_size; if (fp) { fp->get_version(ver,data_size); if (ver==DATA_VERSION) { fp->end_version(I4_LF); } else { fp->seek(fp->tell() + data_size); } } else { first_time=i4_T; } fire_delay = defaults->fire_delay; health = 1000; //no sound for now radar_type=G1_RADAR_WEAPON; set_flag(AERIAL | HIT_GROUND | SHADOWED | DANGEROUS, 1); } i4_bool g1_base_launcher_class::can_attack(g1_object_class * who) { //bad: was attacking ANY stank. return (who->id == stank && who->player_num!=player_num); } void g1_base_launcher_class::save(g1_saver_class * fp) { g1_map_piece_class::save(fp); fp->start_version(DATA_VERSION); fp->end_version(); } void g1_base_launcher_class::fire() { if (attack_target.valid()) { i4_transform_class o2w; calc_world_transform(1,&o2w); i4_3d_vector local_fire_point; i4_3d_vector world_fire_point, world_fire_dir; o2w.transform(i4_3d_vector(0.4f, 0, 0.2f), world_fire_point); o2w.transform(i4_3d_vector(1,0,0.2f), world_fire_dir); world_fire_dir-=world_fire_point; fire_delay=defaults->fire_delay; //g1_fire(li_get_symbol("buster_rocket"), this, attack_target.get(), // world_fire_point, world_fire_dir); g1_fire(defaults->fire_type,this,attack_target.get(), world_fire_point,world_fire_dir); } } i4_bool g1_base_launcher_class::occupy_location() { if (first_time) { h += 0.9f; //this alone is dangerous: moving the object in //the editor would increase its height beyond limit without //the user actually dragging anything. lh = h; } first_time=i4_F; return g1_map_piece_class::occupy_location(); } void g1_base_launcher_class::think() { find_target(); // can't hurt me.... I'm invincible! (no more) //health = 1000; pitch = 0; //groundpitch;//*cos(theta) - groundroll *sin(theta); roll = 0; //groundroll;// *cos(theta) + groundpitch*sin(theta); if (fire_delay) { fire_delay--; } request_think(); //aim the turet if (attack_target.valid()) { i4_float dx,dy,angle,dangle; //this will obviously only be true if attack_target.ref != NULL dx = (attack_target->x - x); dy = (attack_target->y - y); //aim the turet angle = i4_atan2(dy,dx); //snap it i4_normalize_angle(angle); dangle = i4_rotate_to(theta,angle,defaults->turn_speed); if (dangle<defaults->turn_speed && dangle>-defaults->turn_speed) { if (!fire_delay) { fire(); } } } }
pgrawehr/golgotha
objs__base_launcher.cpp
C++
cc0-1.0
4,079
import OOMP newPart = OOMP.oompItem(9185) newPart.addTag("oompType", "POTE") newPart.addTag("oompSize", "07") newPart.addTag("oompColor", "X") newPart.addTag("oompDesc", "O102") newPart.addTag("oompIndex", "01") OOMP.parts.append(newPart)
oomlout/oomlout-OOMP
old/OOMPpart_POTE_07_X_O102_01.py
Python
cc0-1.0
241
#include<iostream> #include<string> #include<cctype> using std::string; using std::cin; using std::cout; using std::endl; int main(void) { string s("It's a string"); for (auto &c : s) { c = 'x'; } cout << s << endl; return 0; }
akanezorap/CppPrimer
ch03/ex3_06.cpp
C++
cc0-1.0
237
'use strict' /* eslint-env browser, webextensions */ // check if URL includes autoplay token if (decodeURIComponent(window.location.href).includes('autoplay=true')) { console.log('[Google Music Hotkeys] Autoplay token detected') const autoplay = setInterval(async () => { const playbutton = document.getElementById('player-bar-play-pause') // press button only if there is no playback if (playbutton && playbutton.title === 'Play') { clearInterval(autoplay) await browser.runtime.sendMessage({ command: 'toggle-playback' }) console.log('[Google Music Hotkeys] Toggled playback') } }, 1000) }
lidel/google-music-hotkeys
add-on/autoplay.js
JavaScript
cc0-1.0
634
package es.thesinsprods.zagastales.juegozagas.creadornpcs; import java.awt.Color; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.BevelBorder; import es.thesinsprods.resources.font.MorpheusFont; public class InfoAcc3NPC { private JFrame frame; public JFrame getFrame() { return frame; } public void setFrame(JFrame frame) { this.frame = frame; } private final JPanel contentPanel = new JPanel(); private JTextField txtDescripcin; private JTextField txtTipoDeAccesorio; private JTextField textField; MorpheusFont mf = new MorpheusFont(); private JTextField txtposesin; private JTextField textField_4; private JLabel label; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { InfoAcc3NPC window = new InfoAcc3NPC(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public InfoAcc3NPC() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setIconImage(Toolkit.getDefaultToolkit().getImage( ArmasNPC.class .getResource("/images/Historias de Zagas, logo.png"))); frame.setTitle("Historias de Zagas"); frame.setBounds(100, 100, 380, 301); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setResizable(false); frame.getContentPane().setLayout(null); txtDescripcin = new JTextField(); txtDescripcin.setOpaque(false); txtDescripcin.setForeground(Color.WHITE); txtDescripcin.setBackground(new Color(205, 133, 63)); txtDescripcin.setText("Descripci\u00F3n:"); txtDescripcin.setFont(mf.MyFont(0, 13)); txtDescripcin.setEditable(false); txtDescripcin.setColumns(10); txtDescripcin.setBorder(null); txtDescripcin.setBounds(135, 20, 90, 20); frame.getContentPane().add(txtDescripcin); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(135, 51, 221, 99); frame.getContentPane().add(scrollPane); JTextArea textArea = new JTextArea(); textArea.setBackground(Color.WHITE); textArea.setForeground(new Color(0, 0, 0)); textArea.setFont(mf.MyFont(0, 13)); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setEditable(false); scrollPane.setViewportView(textArea); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(135, 153, 221, 99); frame.getContentPane().add(scrollPane_1); JTextArea textArea_1 = new JTextArea(); textArea_1.setBackground(Color.WHITE); textArea_1.setForeground(new Color(0, 0, 0)); textArea_1.setWrapStyleWord(true); textArea_1.setText(""); textArea_1.setLineWrap(true); textArea_1.setFont(mf.MyFont(0, 13)); textArea_1.setEditable(false); scrollPane_1.setViewportView(textArea_1); if (EquipoNPC.accesories3.isPosesion() == true || EquipoNPC.accesories3.isLegendaria() == true) { ArrayList<String> pos = EquipoNPC.accesories3.getPossesion() .getPos(); for (int i = 0; i < pos.size(); i++) { if (pos.get(i) != ("-Propiedad-")) { textArea_1.append(pos.get(i) + "\n"); } } } txtTipoDeAccesorio = new JTextField(); txtTipoDeAccesorio.setOpaque(false); txtTipoDeAccesorio.setForeground(Color.WHITE); txtTipoDeAccesorio.setBackground(new Color(205, 133, 63)); txtTipoDeAccesorio.setText("Tipo de Accesorio:"); txtTipoDeAccesorio.setFont(mf.MyFont(0, 13)); txtTipoDeAccesorio.setEditable(false); txtTipoDeAccesorio.setColumns(10); txtTipoDeAccesorio.setBorder(null); txtTipoDeAccesorio.setBounds(10, 20, 115, 20); frame.getContentPane().add(txtTipoDeAccesorio); textField = new JTextField(); textField.setForeground(new Color(0, 0, 0)); textField.setBackground(Color.WHITE); textField.setEditable(false); textField.setFont(mf.MyFont(0, 11)); textField.setColumns(10); textField.setBounds(10, 51, 115, 20); frame.getContentPane().add(textField); final JButton btnVolver = new JButton(""); btnVolver.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { btnVolver.setIcon(new ImageIcon(InfoAcc3NPC.class .getResource("/images/boton atras2.png"))); } public void mouseReleased(MouseEvent e) { btnVolver.setIcon(new ImageIcon(InfoAcc3NPC.class .getResource("/images/boton atras.png"))); } }); btnVolver.setIcon(new ImageIcon(InfoAcc3NPC.class .getResource("/images/boton atras.png"))); btnVolver.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null)); btnVolver.setForeground(new Color(255, 255, 255)); btnVolver.setBackground(new Color(139, 69, 19)); btnVolver.setBorderPainted(false); btnVolver.setContentAreaFilled(false); btnVolver.setFocusPainted(false); btnVolver.setOpaque(false); btnVolver.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); } }); btnVolver.setFont(mf.MyFont(0, 15)); btnVolver.setBounds(10, 206, 99, 45); frame.getContentPane().add(btnVolver); if (EquipoNPC.accesories3.getClass().getSimpleName().equals("Cloak")) { textField.setText("Capa"); } if (EquipoNPC.accesories3.getClass().getSimpleName().equals("Earrings")) { textField.setText("Pendientes"); } if (EquipoNPC.accesories3.getClass().getSimpleName().equals("Necklace")) { textField.setText("Colgante"); } if (EquipoNPC.accesories3.getClass().getSimpleName().equals("Rings")) { textField.setText("Anillos"); } textArea.setText(EquipoNPC.accesories3.getDescription()); txtposesin = new JTextField(); txtposesin.setOpaque(false); txtposesin.setForeground(Color.WHITE); txtposesin.setBackground(new Color(205, 133, 63)); txtposesin.setText("\u00BFPosesi\u00F3n?"); txtposesin.setFont(mf.MyFont(0, 13)); txtposesin.setEditable(false); txtposesin.setColumns(10); txtposesin.setBorder(null); txtposesin.setBounds(10, 82, 90, 20); frame.getContentPane().add(txtposesin); textField_4 = new JTextField(); textField_4.setForeground(new Color(0, 0, 0)); textField_4.setBackground(Color.WHITE); textField_4.setFont(mf.MyFont(0, 11)); if (EquipoNPC.accesories3.isPosesion() == true) { textField_4.setText("Posesión"); } if (EquipoNPC.accesories3.isPosesion() == false) { textField_4.setText("Normal"); } if (EquipoNPC.accesories3.isLegendaria() == true) { textField_4.setText("Legendario"); } textField_4.setEditable(false); textField_4.setColumns(10); textField_4.setBounds(10, 113, 115, 20); frame.getContentPane().add(textField_4); label = new JLabel(""); label.setIcon(new ImageIcon(InfoAcc3NPC.class .getResource("/images/background-infos.jpg"))); label.setBounds(0, 0, 374, 273); frame.getContentPane().add(label); } }
ZagasTales/HistoriasdeZagas
src Graf/es/thesinsprods/zagastales/juegozagas/creadornpcs/InfoAcc3NPC.java
Java
cc0-1.0
7,548
jsonp({"cep":"87450000","cidade":"Tuneiras do Oeste","uf":"PR","estado":"Paran\u00e1"});
lfreneda/cepdb
api/v1/87450000.jsonp.js
JavaScript
cc0-1.0
89
package org.usfirst.frc.team1977.robot.commands.drive; import org.usfirst.frc.team1977.robot.commands.CommandBase; /** * A simple, non-actuator related command to be mapped to a controller button. * Toggles the speed coefficient for the drive subsystem between high and low * values. * * @author Loveland High Robotics 1977 * @author Evan Stewart */ public class SpeedToggle extends CommandBase { public SpeedToggle() { requires(drive); } // Called just before this Command runs the first time protected void initialize() { drive.setSpeedToggle(!drive.isSpeedToggle()); } // Called repeatedly when this Command is scheduled to run protected void execute() { //Do nothing } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return true; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
LovelandHighRobotics1977/FRC2015
FRC2015/src/org/usfirst/frc/team1977/robot/commands/drive/SpeedToggle.java
Java
cc0-1.0
1,048
using System; using System.Collections.Generic; using System.Reflection; using MSTD; using MSTD.ShBase; namespace CFL_1.CFL_System.MSTD.ShBase { public enum RelationKind { ISMEMBEROF, ISINLIST, HASMEMBER, HASINLIST } public struct BaseRelation { public BaseRelation(Type type, RelationKind kind, Type relationWith) { Type = type; Kind = kind; RelationWith = relationWith; } /// <summary> /// Le type de la class qui déclare cette relation. /// </summary> public Type Type { get; set; } public RelationKind Kind { get; set; } public Type RelationWith { get; set; } } /// <summary> /// <see cref="BaseRelations"/> définit les relations entre un type /// dérivées de <see cref="Base"/> et d'autres types dérivés de <see cref="Base"/>. /// </summary> public class BaseRelations { /// <summary> /// Le type de la classe qui déclare ces relations. /// </summary> public Type Type { get; set; } /// <summary> /// type est le type de la classe qui déclare les relations /// avec les autres types connus par le <see cref="ShContext"/> context. /// </summary> public BaseRelations(Type type) { Type = type; } /// <summary> /// Trouve ou ajoute une liste de <see cref="BaseRelation"/> pour le type /// <see cref="BaseRelation.RelationWith"/> et lui ajoute la relation. /// </summary> public void AddRelation(BaseRelation relation) { List<BaseRelation> _relations = null; if(!__relations.TryGetValue(relation.RelationWith, out _relations)) { _relations = new List<BaseRelation>(); __relations[relation.RelationWith] = _relations; } _relations.Add(relation); } private Dictionary<Type, List<BaseRelation>> __relations = new Dictionary<Type, List<BaseRelation>>(); } /// <summary> /// <see cref="ContextRelations"/> identifie toutes les relations /// entre tous les types connus d'un <see cref="ShContext"/>. /// </summary> public class ContextRelations { /// <summary> /// Se construit en identifiant toutes les relations entre tous les types /// représentés dans le <see cref="ShContext"/> context. /// </summary> public ContextRelations(ShContext context) { Init(context); } /// <summary> /// Trouve ou ajoute la <see cref="BaseRelations"/> pour le Type type /// et lui ajoute la <see cref="BaseRelation"/> relation. /// </summary> public void AddRelation(Type type, BaseRelation relation) { BaseRelations _relations = null; if(!__relations.TryGetValue(type, out _relations)) { _relations = new BaseRelations(type); __relations[type] = _relations; } _relations.AddRelation(relation); } private void Init(ShContext context) { int _i = 1; foreach(Set _set in context.GetSets()) { if(_i < context.SetsCount) { foreach(Set _other in context.GetSets(_i++)) { FindRelationsFromT1ToT2(_set.Type, _other.Type); FindRelationsFromT1ToT2(_other.Type, _set.Type); } } } } private void FindRelationsFromT1ToT2(Type t1, Type t2) { foreach(PropertyInfo _prInfo in t1.GetProperties()) { if(PropertyHelper.IsMappableProperty(_prInfo)) { if(_prInfo.PropertyType == t2) { AddRelation(t1, new BaseRelation(t1, RelationKind.HASMEMBER, t2)); AddRelation(t2, new BaseRelation(t2, RelationKind.ISMEMBEROF, t1)); } else { if(TypeHelper.IsListOf(_prInfo.PropertyType, t2)) { AddRelation(t1, new BaseRelation(t1, RelationKind.HASINLIST, t2)); AddRelation(t2, new BaseRelation(t2, RelationKind.ISINLIST, t1)); } } } } } private Dictionary<Type, BaseRelations> __relations = new Dictionary<Type, BaseRelations>(); } }
CFLShine/CFL
CFLServerData/CFL_System/MSTD/ShBase/BaseRelations.cs
C#
cc0-1.0
4,744
// Filename: WaveFileReader.ava // Reference: http://www.cnblogs.com/liyiwen/archive/2010/04/19/1715715.html // Creator: RobinTang // Time: 2012-09-02 package com.sin.java.media; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; public class WaveFileReader { private String filename = null; private int[][] data = null; private int len = 0; private String chunkdescriptor = null; static private int lenchunkdescriptor = 4; private long chunksize = 0; static private int lenchunksize = 4; private String waveflag = null; static private int lenwaveflag = 4; private String fmtsubchunk = null; static private int lenfmtsubchunk = 4; private long subchunk1size = 0; static private int lensubchunk1size = 4; private int audioformat = 0; static private int lenaudioformat = 2; private int numchannels = 0; static private int lennumchannels = 2; private long samplerate = 0; static private int lensamplerate = 2; private long byterate = 0; static private int lenbyterate = 4; private int blockalign = 0; static private int lenblockling = 2; private int bitspersample = 0; static private int lenbitspersample = 2; private String datasubchunk = null; static private int lendatasubchunk = 4; private long subchunk2size = 0; static private int lensubchunk2size = 4; private FileInputStream fis = null; private BufferedInputStream bis = null; private boolean issuccess = false; public WaveFileReader(String filename) { this.initReader(filename); } // 判断是否创建wav读取器成功 public boolean isSuccess() { return issuccess; } // 获取每个采样的编码长度,8bit或者16bit public int getBitPerSample(){ return this.bitspersample; } // 获取采样率 public long getSampleRate(){ return this.samplerate; } // 获取声道个数,1代表单声道 2代表立体声 public int getNumChannels(){ return this.numchannels; } // 获取数据长度,也就是一共采样多少个 public int getDataLen(){ return this.len; } // 获取数据 // 数据是一个二维数组,[n][m]代表第n个声道的第m个采样值 public int[][] getData(){ return this.data; } private void initReader(String filename){ this.filename = filename; try { fis = new FileInputStream(this.filename); bis = new BufferedInputStream(fis); this.chunkdescriptor = readString(lenchunkdescriptor); if(!chunkdescriptor.endsWith("RIFF")) throw new IllegalArgumentException("RIFF miss, " + filename + " is not a wave file."); this.chunksize = readLong(); this.waveflag = readString(lenwaveflag); if(!waveflag.endsWith("WAVE")) throw new IllegalArgumentException("WAVE miss, " + filename + " is not a wave file."); this.fmtsubchunk = readString(lenfmtsubchunk); if(!fmtsubchunk.endsWith("fmt ")) throw new IllegalArgumentException("fmt miss, " + filename + " is not a wave file."); this.subchunk1size = readLong(); this.audioformat = readInt(); this.numchannels = readInt(); this.samplerate = readLong(); this.byterate = readLong(); this.blockalign = readInt(); this.bitspersample = readInt(); this.datasubchunk = readString(lendatasubchunk); if(!datasubchunk.endsWith("data")) throw new IllegalArgumentException("data miss, " + filename + " is not a wave file."); this.subchunk2size = readLong(); this.len = (int)(this.subchunk2size/(this.bitspersample/8)/this.numchannels); this.data = new int[this.numchannels][this.len]; for(int i=0; i<this.len; ++i){ for(int n=0; n<this.numchannels; ++n){ if(this.bitspersample == 8){ this.data[n][i] = bis.read(); } else if(this.bitspersample == 16){ this.data[n][i] = this.readInt(); } } } issuccess = true; } catch (Exception e) { e.printStackTrace(); } finally{ try{ if(bis != null) bis.close(); if(fis != null) fis.close(); } catch(Exception e1){ e1.printStackTrace(); } } } private String readString(int len){ byte[] buf = new byte[len]; try { if(bis.read(buf)!=len) throw new IOException("no more data!!!"); } catch (IOException e) { e.printStackTrace(); } return new String(buf); } private int readInt(){ byte[] buf = new byte[2]; int res = 0; try { if(bis.read(buf)!=2) throw new IOException("no more data!!!"); res = (buf[0]&0x000000FF) | (((int)buf[1])<<8); } catch (IOException e) { e.printStackTrace(); } return res; } private long readLong(){ long res = 0; try { long[] l = new long[4]; for(int i=0; i<4; ++i){ l[i] = bis.read(); if(l[i]==-1){ throw new IOException("no more data!!!"); } } res = l[0] | (l[1]<<8) | (l[2]<<16) | (l[3]<<24); } catch (IOException e) { e.printStackTrace(); } return res; } private byte[] readBytes(int len){ byte[] buf = new byte[len]; try { if(bis.read(buf)!=len) throw new IOException("no more data!!!"); } catch (IOException e) { e.printStackTrace(); } return buf; } public static int[] readSingleChannel(String filename){ if(filename==null || filename.length()==0){ return null; } try{ WaveFileReader reader = new WaveFileReader(filename); int[] res = reader.getData()[0]; return res; } catch (Exception e){ e.printStackTrace(); } return null; } }
SoLoHiC/chddt
CHDDiagnosticTool/src/com/sin/java/media/WaveFileReader.java
Java
epl-1.0
5,668
''' This is an example how to use PyScanClient library to connect a scan server. It assumes the server running on localhost at port 4810. The scan server is a RESTful based web service, which was developed at SNS. Its binary nightly build could be found at: https://ics-web.sns.ornl.gov/css/nightly/ and source code is managed at github: https://github.com/ControlSystemStudio/cs-studio/tree/master/applications/plugins/org.csstudio.scan The PyScanClient source code is managed at github: https://github.com/PythonScanClient/PyScanClient Created on Apr 17, 2015 @author: shen ''' from scan import ScanClient if __name__ == '__main__': client = ScanClient('localhost') print client # show server information, which is in XML format. print client.serverInfo()
PythonScanClient/PyScanClient
tutorial/1_start.py
Python
epl-1.0
787
/** * <copyright> * </copyright> * * $Id$ */ package gbind.dsl.impl; import gbind.dsl.ConceptFeatureRef; import gbind.dsl.ConceptMetaclass; import gbind.dsl.DslPackage; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Concept Feature Ref</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link gbind.dsl.impl.ConceptFeatureRefImpl#getConceptClass <em>Concept Class</em>}</li> * <li>{@link gbind.dsl.impl.ConceptFeatureRefImpl#getFeatureName <em>Feature Name</em>}</li> * </ul> * * @generated */ public class ConceptFeatureRefImpl extends EObjectImpl implements ConceptFeatureRef { /** * The cached value of the '{@link #getConceptClass() <em>Concept Class</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getConceptClass() * @generated * @ordered */ protected ConceptMetaclass conceptClass; /** * The default value of the '{@link #getFeatureName() <em>Feature Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFeatureName() * @generated * @ordered */ protected static final String FEATURE_NAME_EDEFAULT = null; /** * The cached value of the '{@link #getFeatureName() <em>Feature Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFeatureName() * @generated * @ordered */ protected String featureName = FEATURE_NAME_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ConceptFeatureRefImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return DslPackage.Literals.CONCEPT_FEATURE_REF; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ConceptMetaclass getConceptClass() { if (conceptClass != null && conceptClass.eIsProxy()) { InternalEObject oldConceptClass = (InternalEObject)conceptClass; conceptClass = (ConceptMetaclass)eResolveProxy(oldConceptClass); if (conceptClass != oldConceptClass) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, DslPackage.CONCEPT_FEATURE_REF__CONCEPT_CLASS, oldConceptClass, conceptClass)); } } return conceptClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ConceptMetaclass basicGetConceptClass() { return conceptClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setConceptClass(ConceptMetaclass newConceptClass) { ConceptMetaclass oldConceptClass = conceptClass; conceptClass = newConceptClass; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DslPackage.CONCEPT_FEATURE_REF__CONCEPT_CLASS, oldConceptClass, conceptClass)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getFeatureName() { return featureName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFeatureName(String newFeatureName) { String oldFeatureName = featureName; featureName = newFeatureName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DslPackage.CONCEPT_FEATURE_REF__FEATURE_NAME, oldFeatureName, featureName)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case DslPackage.CONCEPT_FEATURE_REF__CONCEPT_CLASS: if (resolve) return getConceptClass(); return basicGetConceptClass(); case DslPackage.CONCEPT_FEATURE_REF__FEATURE_NAME: return getFeatureName(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case DslPackage.CONCEPT_FEATURE_REF__CONCEPT_CLASS: setConceptClass((ConceptMetaclass)newValue); return; case DslPackage.CONCEPT_FEATURE_REF__FEATURE_NAME: setFeatureName((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case DslPackage.CONCEPT_FEATURE_REF__CONCEPT_CLASS: setConceptClass((ConceptMetaclass)null); return; case DslPackage.CONCEPT_FEATURE_REF__FEATURE_NAME: setFeatureName(FEATURE_NAME_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case DslPackage.CONCEPT_FEATURE_REF__CONCEPT_CLASS: return conceptClass != null; case DslPackage.CONCEPT_FEATURE_REF__FEATURE_NAME: return FEATURE_NAME_EDEFAULT == null ? featureName != null : !FEATURE_NAME_EDEFAULT.equals(featureName); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (featureName: "); result.append(featureName); result.append(')'); return result.toString(); } } //ConceptFeatureRefImpl
jesusc/bento
plugins/genericity.language.gbind/src-gen/gbind/dsl/impl/ConceptFeatureRefImpl.java
Java
epl-1.0
5,771
/** * Copyright (c) 2014-2015 TELECOM ParisTech and AdaCore. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Elie Richa - initial implementation */ package fr.tpt.atlanalyser.atl.ATL.impl; import fr.tpt.atlanalyser.atl.ATL.ATLPackage; import fr.tpt.atlanalyser.atl.ATL.LocatedElement; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EDataTypeEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Located Element</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link fr.tpt.atlanalyser.atl.ATL.impl.LocatedElementImpl#getLocation <em>Location</em>}</li> * <li>{@link fr.tpt.atlanalyser.atl.ATL.impl.LocatedElementImpl#getCommentsBefore <em>Comments Before</em>}</li> * <li>{@link fr.tpt.atlanalyser.atl.ATL.impl.LocatedElementImpl#getCommentsAfter <em>Comments After</em>}</li> * </ul> * </p> * * @generated */ public abstract class LocatedElementImpl extends MinimalEObjectImpl.Container implements LocatedElement { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final String copyright = "Copyright (c) 2014-2015 TELECOM ParisTech and AdaCore.\nAll rights reserved. This program and the accompanying materials\nare made available under the terms of the Eclipse Public License v1.0\nwhich accompanies this distribution, and is available at\nhttp://www.eclipse.org/legal/epl-v10.html\n\nContributors:\n Elie Richa - initial implementation"; /** * The default value of the '{@link #getLocation() <em>Location</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLocation() * @generated * @ordered */ protected static final String LOCATION_EDEFAULT = null; /** * The cached value of the '{@link #getLocation() <em>Location</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLocation() * @generated * @ordered */ protected String location = LOCATION_EDEFAULT; /** * The cached value of the '{@link #getCommentsBefore() <em>Comments Before</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCommentsBefore() * @generated * @ordered */ protected EList<String> commentsBefore; /** * The cached value of the '{@link #getCommentsAfter() <em>Comments After</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCommentsAfter() * @generated * @ordered */ protected EList<String> commentsAfter; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected LocatedElementImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ATLPackage.Literals.LOCATED_ELEMENT; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLocation() { return location; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLocation(String newLocation) { String oldLocation = location; location = newLocation; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ATLPackage.LOCATED_ELEMENT__LOCATION, oldLocation, location)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<String> getCommentsBefore() { if (commentsBefore == null) { commentsBefore = new EDataTypeEList<String>(String.class, this, ATLPackage.LOCATED_ELEMENT__COMMENTS_BEFORE); } return commentsBefore; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<String> getCommentsAfter() { if (commentsAfter == null) { commentsAfter = new EDataTypeEList<String>(String.class, this, ATLPackage.LOCATED_ELEMENT__COMMENTS_AFTER); } return commentsAfter; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ATLPackage.LOCATED_ELEMENT__LOCATION: return getLocation(); case ATLPackage.LOCATED_ELEMENT__COMMENTS_BEFORE: return getCommentsBefore(); case ATLPackage.LOCATED_ELEMENT__COMMENTS_AFTER: return getCommentsAfter(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ATLPackage.LOCATED_ELEMENT__LOCATION: setLocation((String)newValue); return; case ATLPackage.LOCATED_ELEMENT__COMMENTS_BEFORE: getCommentsBefore().clear(); getCommentsBefore().addAll((Collection<? extends String>)newValue); return; case ATLPackage.LOCATED_ELEMENT__COMMENTS_AFTER: getCommentsAfter().clear(); getCommentsAfter().addAll((Collection<? extends String>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ATLPackage.LOCATED_ELEMENT__LOCATION: setLocation(LOCATION_EDEFAULT); return; case ATLPackage.LOCATED_ELEMENT__COMMENTS_BEFORE: getCommentsBefore().clear(); return; case ATLPackage.LOCATED_ELEMENT__COMMENTS_AFTER: getCommentsAfter().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ATLPackage.LOCATED_ELEMENT__LOCATION: return LOCATION_EDEFAULT == null ? location != null : !LOCATION_EDEFAULT.equals(location); case ATLPackage.LOCATED_ELEMENT__COMMENTS_BEFORE: return commentsBefore != null && !commentsBefore.isEmpty(); case ATLPackage.LOCATED_ELEMENT__COMMENTS_AFTER: return commentsAfter != null && !commentsAfter.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (location: "); result.append(location); result.append(", commentsBefore: "); result.append(commentsBefore); result.append(", commentsAfter: "); result.append(commentsAfter); result.append(')'); return result.toString(); } } //LocatedElementImpl
eliericha/atlanalyser
fr.tpt.atlanalyser.atl/src/fr/tpt/atlanalyser/atl/ATL/impl/LocatedElementImpl.java
Java
epl-1.0
8,031
package nju.software.sjy.dao; import java.util.List; import nju.software.sjy.model.xy.TOperation; import nju.software.sjy.model.xy.TResource; import nju.software.sjy.model.xy.TRole; import nju.software.sjy.model.xy.TRoleoperation; import nju.software.sjy.model.xy.TRoleres; public interface RoleDao { List<TRole> getAllRoles(); List<TResource> getResByRole(TRole role); TRole getRoleByRolename(String rolename); List<TOperation> getOperationByRole(TRole role); Integer getMaxRoleBh(); void saveRole(TRole role); void updateRole(TRole role); void deleteRole(TRole role); Integer getMaxRoleoperationBh(); void saveRoleoperation(TRoleoperation ro); void updateRoleoperation(TRoleoperation ro); void deleteRoleoperation(TRoleoperation ro); List<TOperation> getAllOperation(); TOperation getOperationByName(String name); TRole getRoleByRolebh(int rolebh); TRoleoperation getRoByRoleOperation(TRole role, TOperation operation); List<TRoleoperation> getRoByRole(TRole role); TResource getResByName(String resName); List<TRole> getRoleByResource(TResource res); TOperation getOperationByNameRange(String name, String range); List<TResource> getResByType(String type); List<TResource> getAllResource(); TRoleres getRrByRoleRes(TRole role, TResource res); Integer getMaxRoleResBh(); void saveRoleRes(TRoleres roleRes); List<TRoleres> getRrByRole(TRole role); void deleteRoleRes(TRoleres roleRes); List<TOperation> getActiveOperation(); List<TOperation> getOperationByRoleOperationname(TRole role, String operationname); List<TRole> getRoleByRolenamelist(List<String> rolenameList); }
SongyuCHen/SJY
src/nju/software/sjy/dao/RoleDao.java
Java
epl-1.0
1,665
package br.com.exception; public class FoneInvalidoException extends Exception{ /** * */ private static final long serialVersionUID = 1L; public FoneInvalidoException(String msg) { super(msg); } }
yuri4br/Clinica_Vet_POO
src/br/com/exception/FoneInvalidoException.java
Java
epl-1.0
220
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ @FeatureFlag(name = ORIENT_ENABLED) package org.sonatype.nexus.blobstore.restore.raw.internal.orient; import org.sonatype.nexus.common.app.FeatureFlag; import static org.sonatype.nexus.common.app.FeatureFlags.ORIENT_ENABLED;
sonatype/nexus-public
plugins/nexus-restore-raw/src/main/java/org/sonatype/nexus/blobstore/restore/raw/internal/orient/package-info.java
Java
epl-1.0
1,007
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.etherrain.internal.api; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.SocketTimeoutException; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.openhab.binding.etherrain.internal.EtherRainException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link EtherRainCommunication} handles communication with EtherRain * controllers so that the API is all in one place * * @author Joe Inkenbrandt - Initial contribution */ @NonNullByDefault public class EtherRainCommunication { private static final String BROADCAST_DISCOVERY_MESSAGE = "eviro_id_request1"; private static final int BROADCAST_DISCOVERY_PORT = 8089; private static final String ETHERRAIN_USERNAME = "admin"; private static final int HTTP_TIMEOUT = 3; private static final int BROADCAST_TIMEOUT = 80; private static final String RESPONSE_STATUS_PATTERN = "^\\s*(un|ma|ac|os|cs|rz|ri|rn):\\s*([a-zA-Z0-9\\.]*)(\\s*<br>)?"; private static final String BROADCAST_RESPONSE_DISCOVER_PATTERN = "eviro t=(\\S*) n=(\\S*) p=(\\S*) a=(\\S*)"; private static final Pattern broadcastResponseDiscoverPattern = Pattern .compile(BROADCAST_RESPONSE_DISCOVER_PATTERN); private static final Pattern responseStatusPattern = Pattern.compile(RESPONSE_STATUS_PATTERN); private final Logger logger = LoggerFactory.getLogger(EtherRainCommunication.class); private final HttpClient httpClient; private final String address; private final int port; private final String password; public EtherRainCommunication(String address, int port, String password, HttpClient httpClient) { this.address = address; this.port = port; this.password = password; this.httpClient = httpClient; } public static List<EtherRainUdpResponse> autoDiscover() { return updBroadcast(); } public EtherRainStatusResponse commandStatus() throws EtherRainException, IOException { commandLogin(); List<String> responseList = sendGet("result.cgi?xs"); if (responseList.isEmpty()) { throw new EtherRainException("Empty Response"); } EtherRainStatusResponse response = new EtherRainStatusResponse(); for (String line : responseList) { Matcher m = responseStatusPattern.matcher(line); if (m.matches()) { String command = m.replaceAll("$1"); String status = m.replaceAll("$2"); switch (command) { case "un": response.setUniqueName(status); break; case "ma": response.setMacAddress(status); break; case "ac": response.setServiceAccount(status); break; case "os": response.setOperatingStatus(EtherRainOperatingStatus.valueOf(status.toUpperCase())); break; case "cs": response.setLastCommandStatus(EtherRainCommandStatus.valueOf(status.toUpperCase())); break; case "rz": response.setLastCommandResult(EtherRainCommandResult.valueOf(status.toUpperCase())); break; case "ri": response.setLastActiveValue(Integer.parseInt(status)); break; case "rn": response.setRainSensor(Integer.parseInt(status) == 1); break; default: logger.debug("Unknown response: {}", command); } } } return response; } public synchronized boolean commandIrrigate(int delay, int zone1, int zone2, int zone3, int zone4, int zone5, int zone6, int zone7, int zone8) { try { sendGet("result.cgi?xi=" + delay + ":" + zone1 + ":" + zone2 + ":" + zone3 + ":" + zone4 + ":" + zone5 + ":" + zone6 + ":" + zone7 + ":" + zone8); } catch (IOException e) { logger.warn("Could not send irrigate command to etherrain: {}", e.getMessage()); return false; } return true; } public synchronized boolean commandClear() { try { sendGet("/result.cgi?xr"); } catch (IOException e) { logger.warn("Could not send clear command to etherrain: {}", e.getMessage()); return false; } return true; } public synchronized boolean commandLogin() throws EtherRainException { try { sendGet("/ergetcfg.cgi?lu=" + ETHERRAIN_USERNAME + "&lp=" + password); } catch (IOException e) { logger.warn("Could not send clear command to etherrain: {}", e.getMessage()); return false; } return true; } public synchronized boolean commandLogout() { try { sendGet("/ergetcfg.cgi?m=o"); } catch (IOException e) { logger.warn("Could not send logout command to etherrain: {}", e.getMessage()); return false; } return true; } private synchronized List<String> sendGet(String command) throws IOException { String url = "http://" + address + ":" + port + "/" + command; ContentResponse response; try { response = httpClient.newRequest(url).timeout(HTTP_TIMEOUT, TimeUnit.SECONDS).send(); if (response.getStatus() != HttpURLConnection.HTTP_OK) { logger.warn("Etherrain return status other than HTTP_OK : {}", response.getStatus()); return Collections.emptyList(); } } catch (TimeoutException | ExecutionException e) { logger.warn("Could not connect to Etherrain with exception: {}", e.getMessage()); return Collections.emptyList(); } catch (InterruptedException e) { logger.warn("Connect to Etherrain interrupted: {}", e.getMessage()); Thread.currentThread().interrupt(); return Collections.emptyList(); } return new BufferedReader(new StringReader(response.getContentAsString())).lines().collect(Collectors.toList()); } private static List<EtherRainUdpResponse> updBroadcast() { List<EtherRainUdpResponse> rList = new LinkedList<>(); // Find the server using UDP broadcast try (DatagramSocket c = new DatagramSocket()) { c.setSoTimeout(BROADCAST_TIMEOUT); c.setBroadcast(true); byte[] sendData = BROADCAST_DISCOVERY_MESSAGE.getBytes("UTF-8"); // Try the 255.255.255.255 first DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), BROADCAST_DISCOVERY_PORT); c.send(sendPacket); while (true) { // Wait for a response byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket; try { receivePacket = new DatagramPacket(recvBuf, recvBuf.length); c.receive(receivePacket); } catch (SocketTimeoutException e) { return rList; } // Check if the message is correct String message = new String(receivePacket.getData(), "UTF-8").trim(); if (message.length() == 0) { return rList; } String addressBC = receivePacket.getAddress().getHostAddress(); Matcher matcher = broadcastResponseDiscoverPattern.matcher(message); String deviceTypeBC = matcher.replaceAll("$1"); String unqiueNameBC = matcher.replaceAll("$2"); int portBC = Integer.parseInt(matcher.replaceAll("$3")); // NOTE: Version 3.77 of API states that Additional Parameters (a=) are not used // on EtherRain rList.add(new EtherRainUdpResponse(deviceTypeBC, addressBC, portBC, unqiueNameBC, "")); } } catch (IOException ex) { return rList; } } }
paulianttila/openhab2
bundles/org.openhab.binding.etherrain/src/main/java/org/openhab/binding/etherrain/internal/api/EtherRainCommunication.java
Java
epl-1.0
9,421
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Open Source Version is distributed with Sencha Ext JS pursuant to a FLOSS Exception agreed upon * between Sonatype, Inc. and Sencha Inc. Sencha Ext JS is licensed under GPL v3 and cannot be redistributed as part of a * closed source work. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ /*global Ext, NX*/ /** * Maven plugin configuration * * @since 3.15 */ Ext.define('NX.maven.app.PluginConfig', { '@aggregate_priority': 100, controllers: [ { id: 'NX.maven.controller.MavenDependencySnippetController', active: true } ] });
sonatype/nexus-public
plugins/nexus-repository-maven/src/main/resources/static/rapture/NX/maven/app/PluginConfig.js
JavaScript
epl-1.0
1,318
// /******************************************************************************* // * Copyright (c) 2016 by RF77 (https://github.com/RF77) // * All rights reserved. This program and the accompanying materials // * are made available under the terms of the Eclipse Public License v1.0 // * which accompanies this distribution, and is available at // * http://www.eclipse.org/legal/epl-v10.html // * // * Contributors: // * RF77 - initial API and implementation and/or initial documentation // *******************************************************************************/ using System; using System.Threading; namespace FileDb.Impl { public class ReadWritLockable { private readonly TimeSpan _readWriteTimeOut; private readonly ReaderWriterLock _rwl = new ReaderWriterLock(); public ReadWritLockable(TimeSpan readWriteLockTimeOut) { _readWriteTimeOut = readWriteLockTimeOut; } public void WriterLock(Action action) { try { _rwl.AcquireWriterLock(_readWriteTimeOut); action(); } finally { _rwl.ReleaseWriterLock(); } } public T ReaderLock<T>(Func<T> action) { try { _rwl.AcquireReaderLock(_readWriteTimeOut); return action(); } finally { _rwl.ReleaseReaderLock(); } } public T WriterLock<T>(Func<T> action) { try { _rwl.AcquireWriterLock(_readWriteTimeOut); return action(); } finally { _rwl.ReleaseWriterLock(); } } } }
RF77/sharp-tsdb
src/FileDb/Impl/ReadWritLockable.cs
C#
epl-1.0
1,841
using System; using System.Reflection; using System.Resources; 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("CJO-WK_SikuliUI_IDE__Package")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Christopher Olson")] [assembly: AssemblyProduct("CJO-WK_SikuliUI_IDE__Package")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: NeutralResourcesLanguage("en-US")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")]
ChristopherOlson-WK/SikuliUI-IDE
SikuliUI-IDE_Package/Properties/AssemblyInfo.cs
C#
epl-1.0
1,160
/******************************************************************************* * Copyright (c) 2021 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.jpa.tests.spec10.entity.tests; import java.util.HashSet; import java.util.Set; import org.jboss.shrinkwrap.api.ArchivePath; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.runner.RunWith; import org.testcontainers.containers.JdbcDatabaseContainer; import com.ibm.websphere.simplicity.ShrinkHelper; import com.ibm.websphere.simplicity.config.Application; import com.ibm.websphere.simplicity.config.ClassloaderElement; import com.ibm.websphere.simplicity.config.ConfigElementList; import com.ibm.websphere.simplicity.config.ServerConfiguration; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sf.BasicAnnotation_EJB_SF_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sf.DatatypeSupport_EJB_SF_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sf.EmbeddableID_EJB_SF_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sf.Embeddable_EJB_SF_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sf.IDClass_EJB_SF_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sf.MultiTable_EJB_SF_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sf.PKEntity_EJB_SF_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sf.PKGenerator_EJB_SF_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sf.ReadOnly_EJB_SF_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sf.Serializable_EJB_SF_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sf.Versioning_EJB_SF_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sfex.BasicAnnotation_EJB_SFEX_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sfex.DatatypeSupport_EJB_SFEX_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sfex.EmbeddableID_EJB_SFEX_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sfex.Embeddable_EJB_SFEX_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sfex.IDClass_EJB_SFEX_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sfex.MultiTable_EJB_SFEX_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sfex.PKEntity_EJB_SFEX_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sfex.PKGenerator_EJB_SFEX_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sfex.ReadOnly_EJB_SFEX_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sfex.Serializable_EJB_SFEX_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sfex.Versioning_EJB_SFEX_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sl.BasicAnnotation_EJB_SL_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sl.DatatypeSupport_EJB_SL_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sl.EmbeddableID_EJB_SL_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sl.Embeddable_EJB_SL_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sl.IDClass_EJB_SL_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sl.MultiTable_EJB_SL_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sl.PKEntity_EJB_SL_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sl.PKGenerator_EJB_SL_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sl.ReadOnly_EJB_SL_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sl.Serializable_EJB_SL_TestServlet; import com.ibm.ws.jpa.fvt.entity.tests.ejb.sl.Versioning_EJB_SL_TestServlet; import com.ibm.ws.testtooling.database.DatabaseVendor; import com.ibm.ws.testtooling.jpaprovider.JPAPersistenceProvider; import componenttest.annotation.Server; import componenttest.annotation.TestServlet; import componenttest.annotation.TestServlets; import componenttest.custom.junit.runner.FATRunner; import componenttest.custom.junit.runner.Mode; import componenttest.custom.junit.runner.Mode.TestMode; import componenttest.topology.database.container.DatabaseContainerType; import componenttest.topology.database.container.DatabaseContainerUtil; import componenttest.topology.impl.LibertyServer; import componenttest.topology.utils.PrivHelper; @RunWith(FATRunner.class) @Mode(TestMode.FULL) public class Entity_EJB extends JPAFATServletClient { @Rule public static SkipRule skipRule = new SkipRule(); private final static String CONTEXT_ROOT = "Entity10EJB"; private final static String RESOURCE_ROOT = "test-applications/entity/"; private final static String appFolder = "ejb"; private final static String appName = "EntityEJB10"; private final static String appNameEar = appName + ".ear"; private final static Set<String> dropSet = new HashSet<String>(); private final static Set<String> createSet = new HashSet<String>(); private static long timestart = 0; static { dropSet.add("JPA10_ENTITY_${provider}_DROP_${dbvendor}.ddl"); createSet.add("JPA10_ENTITY_${provider}_CREATE_${dbvendor}.ddl"); } @Server("JPA10EJBEntityServer") @TestServlets({ @TestServlet(servlet = BasicAnnotation_EJB_SL_TestServlet.class, path = CONTEXT_ROOT + "/" + "BasicAnnotation_EJB_SL_TestServlet"), @TestServlet(servlet = DatatypeSupport_EJB_SL_TestServlet.class, path = CONTEXT_ROOT + "/" + "DatatypeSupport_EJB_SL_TestServlet"), @TestServlet(servlet = EmbeddableID_EJB_SL_TestServlet.class, path = CONTEXT_ROOT + "/" + "EmbeddableID_EJB_SL_TestServlet"), @TestServlet(servlet = Embeddable_EJB_SL_TestServlet.class, path = CONTEXT_ROOT + "/" + "Embeddable_EJB_SL_TestServlet"), @TestServlet(servlet = IDClass_EJB_SL_TestServlet.class, path = CONTEXT_ROOT + "/" + "IDClass_EJB_SL_TestServlet"), @TestServlet(servlet = MultiTable_EJB_SL_TestServlet.class, path = CONTEXT_ROOT + "/" + "MultiTable_EJB_SL_TestServlet"), @TestServlet(servlet = PKEntity_EJB_SL_TestServlet.class, path = CONTEXT_ROOT + "/" + "PKEntity_EJB_SL_TestServlet"), @TestServlet(servlet = PKGenerator_EJB_SL_TestServlet.class, path = CONTEXT_ROOT + "/" + "PKGenerator_EJB_SL_TestServlet"), @TestServlet(servlet = ReadOnly_EJB_SL_TestServlet.class, path = CONTEXT_ROOT + "/" + "ReadOnly_EJB_SL_TestServlet"), @TestServlet(servlet = Serializable_EJB_SL_TestServlet.class, path = CONTEXT_ROOT + "/" + "Serializable_EJB_SL_TestServlet"), @TestServlet(servlet = Versioning_EJB_SL_TestServlet.class, path = CONTEXT_ROOT + "/" + "Versioning_EJB_SL_TestServlet"), @TestServlet(servlet = BasicAnnotation_EJB_SF_TestServlet.class, path = CONTEXT_ROOT + "/" + "BasicAnnotation_EJB_SF_TestServlet"), @TestServlet(servlet = DatatypeSupport_EJB_SF_TestServlet.class, path = CONTEXT_ROOT + "/" + "DatatypeSupport_EJB_SF_TestServlet"), @TestServlet(servlet = EmbeddableID_EJB_SF_TestServlet.class, path = CONTEXT_ROOT + "/" + "EmbeddableID_EJB_SF_TestServlet"), @TestServlet(servlet = Embeddable_EJB_SF_TestServlet.class, path = CONTEXT_ROOT + "/" + "Embeddable_EJB_SF_TestServlet"), @TestServlet(servlet = IDClass_EJB_SF_TestServlet.class, path = CONTEXT_ROOT + "/" + "IDClass_EJB_SF_TestServlet"), @TestServlet(servlet = MultiTable_EJB_SF_TestServlet.class, path = CONTEXT_ROOT + "/" + "MultiTable_EJB_SF_TestServlet"), @TestServlet(servlet = PKEntity_EJB_SF_TestServlet.class, path = CONTEXT_ROOT + "/" + "PKEntity_EJB_SF_TestServlet"), @TestServlet(servlet = PKGenerator_EJB_SF_TestServlet.class, path = CONTEXT_ROOT + "/" + "PKGenerator_EJB_SF_TestServlet"), @TestServlet(servlet = ReadOnly_EJB_SF_TestServlet.class, path = CONTEXT_ROOT + "/" + "ReadOnly_EJB_SF_TestServlet"), @TestServlet(servlet = Serializable_EJB_SF_TestServlet.class, path = CONTEXT_ROOT + "/" + "Serializable_EJB_SF_TestServlet"), @TestServlet(servlet = Versioning_EJB_SF_TestServlet.class, path = CONTEXT_ROOT + "/" + "Versioning_EJB_SF_TestServlet"), @TestServlet(servlet = BasicAnnotation_EJB_SFEX_TestServlet.class, path = CONTEXT_ROOT + "/" + "BasicAnnotation_EJB_SFEX_TestServlet"), @TestServlet(servlet = DatatypeSupport_EJB_SFEX_TestServlet.class, path = CONTEXT_ROOT + "/" + "DatatypeSupport_EJB_SFEX_TestServlet"), @TestServlet(servlet = EmbeddableID_EJB_SFEX_TestServlet.class, path = CONTEXT_ROOT + "/" + "EmbeddableID_EJB_SFEX_TestServlet"), @TestServlet(servlet = Embeddable_EJB_SFEX_TestServlet.class, path = CONTEXT_ROOT + "/" + "Embeddable_EJB_SFEX_TestServlet"), @TestServlet(servlet = IDClass_EJB_SFEX_TestServlet.class, path = CONTEXT_ROOT + "/" + "IDClass_EJB_SFEX_TestServlet"), @TestServlet(servlet = MultiTable_EJB_SFEX_TestServlet.class, path = CONTEXT_ROOT + "/" + "MultiTable_EJB_SFEX_TestServlet"), @TestServlet(servlet = PKEntity_EJB_SFEX_TestServlet.class, path = CONTEXT_ROOT + "/" + "PKEntity_EJB_SFEX_TestServlet"), @TestServlet(servlet = PKGenerator_EJB_SFEX_TestServlet.class, path = CONTEXT_ROOT + "/" + "PKGenerator_EJB_SFEX_TestServlet"), @TestServlet(servlet = ReadOnly_EJB_SFEX_TestServlet.class, path = CONTEXT_ROOT + "/" + "ReadOnly_EJB_SFEX_TestServlet"), @TestServlet(servlet = Serializable_EJB_SFEX_TestServlet.class, path = CONTEXT_ROOT + "/" + "Serializable_EJB_SFEX_TestServlet"), @TestServlet(servlet = Versioning_EJB_SFEX_TestServlet.class, path = CONTEXT_ROOT + "/" + "Versioning_EJB_SFEX_TestServlet") }) public static LibertyServer server; public static final JdbcDatabaseContainer<?> testContainer = AbstractFATSuite.testContainer; @BeforeClass public static void setUp() throws Exception { PrivHelper.generateCustomPolicy(server, AbstractFATSuite.JAXB_PERMS); bannerStart(Entity_Web.class); timestart = System.currentTimeMillis(); int appStartTimeout = server.getAppStartTimeout(); if (appStartTimeout < (120 * 1000)) { server.setAppStartTimeout(120 * 1000); } int configUpdateTimeout = server.getConfigUpdateTimeout(); if (configUpdateTimeout < (120 * 1000)) { server.setConfigUpdateTimeout(120 * 1000); } server.addEnvVar("repeat_phase", AbstractFATSuite.repeatPhase); //Get driver name server.addEnvVar("DB_DRIVER", DatabaseContainerType.valueOf(testContainer).getDriverName()); //Setup server DataSource properties DatabaseContainerUtil.setupDataSourceProperties(server, testContainer); server.startServer(); setupDatabaseApplication(server, RESOURCE_ROOT + "ddl/"); final Set<String> ddlSet = new HashSet<String>(); System.out.println(Entity_Web.class.getName() + " Setting up database tables..."); DatabaseVendor database = getDbVendor(); JPAPersistenceProvider provider = AbstractFATSuite.provider; ddlSet.clear(); for (String ddlName : dropSet) { ddlSet.add(ddlName.replace("${provider}", provider.name()).replace("${dbvendor}", database.name())); } executeDDL(server, ddlSet, true); ddlSet.clear(); for (String ddlName : createSet) { ddlSet.add(ddlName.replace("${provider}", provider.name()).replace("${dbvendor}", database.name())); } executeDDL(server, ddlSet, false); setupTestApplication(); skipRule.setDatabase(database); skipRule.setProvider(provider); } private static void setupTestApplication() throws Exception { JavaArchive ejbApp = ShrinkWrap.create(JavaArchive.class, appName + ".jar"); ejbApp.addPackages(true, "com.ibm.ws.jpa.fvt.entity.ejblocal"); ejbApp.addPackages(true, "com.ibm.ws.jpa.fvt.entity.entities"); ejbApp.addPackages(true, "com.ibm.ws.jpa.fvt.entity.support"); ejbApp.addPackages(true, "com.ibm.ws.jpa.fvt.entity.testlogic"); ShrinkHelper.addDirectory(ejbApp, RESOURCE_ROOT + appFolder + "/" + appName + ".jar"); WebArchive webApp = ShrinkWrap.create(WebArchive.class, appName + ".war"); webApp.addPackages(true, "com.ibm.ws.jpa.fvt.entity.tests.ejb"); ShrinkHelper.addDirectory(webApp, RESOURCE_ROOT + appFolder + "/" + appName + ".war"); final JavaArchive testApiJar = buildTestAPIJar(); /* * Hibernate 5.2 (JPA 2.1) contains a bug that requires a dialect property to be set * for Oracle platform detection: https://hibernate.atlassian.net/browse/HHH-13184 */ if (AbstractFATSuite.repeatPhase != null && AbstractFATSuite.repeatPhase.contains("21") && DatabaseVendor.ORACLE.equals(getDbVendor())) { ejbApp.move("/META-INF/persistence-oracle-21.xml", "/META-INF/persistence.xml"); } final EnterpriseArchive app = ShrinkWrap.create(EnterpriseArchive.class, appNameEar); app.addAsModule(ejbApp); app.addAsModule(webApp); app.addAsLibrary(testApiJar); ShrinkHelper.addDirectory(app, RESOURCE_ROOT + appFolder, new org.jboss.shrinkwrap.api.Filter<ArchivePath>() { @Override public boolean include(ArchivePath arg0) { if (arg0.get().startsWith("/META-INF/")) { return true; } return false; } }); ShrinkHelper.exportToServer(server, "apps", app); Application appRecord = new Application(); appRecord.setLocation(appNameEar); appRecord.setName(appName); // setup the thirdparty classloader for Hibernate and OpenJPA if (AbstractFATSuite.repeatPhase != null && AbstractFATSuite.repeatPhase.contains("hibernate")) { ConfigElementList<ClassloaderElement> cel = appRecord.getClassloaders(); ClassloaderElement loader = new ClassloaderElement(); loader.getCommonLibraryRefs().add("HibernateLib"); cel.add(loader); } else if (AbstractFATSuite.repeatPhase != null && AbstractFATSuite.repeatPhase.contains("openjpa")) { ConfigElementList<ClassloaderElement> cel = appRecord.getClassloaders(); ClassloaderElement loader = new ClassloaderElement(); loader.getCommonLibraryRefs().add("OpenJPALib"); cel.add(loader); } else if (AbstractFATSuite.repeatPhase != null && AbstractFATSuite.repeatPhase.contains("20") && DatabaseVendor.ORACLE.equals(getDbVendor())) { /* * TODO: OpenJPA 2.2.x (JPA 2.0) has hard dependencies on the Oracle JDBC driver classes and * therefore requires the driver be added to the application classloader * * https://issues.apache.org/jira/projects/OPENJPA/issues/OPENJPA-2602 * https://issues.apache.org/jira/projects/OPENJPA/issues/OPENJPA-2690 */ ConfigElementList<ClassloaderElement> cel = appRecord.getClassloaders(); ClassloaderElement loader = new ClassloaderElement(); loader.getCommonLibraryRefs().add("AnonymousJDBCLib"); cel.add(loader); } server.setMarkToEndOfLog(); ServerConfiguration sc = server.getServerConfiguration(); sc.getApplications().add(appRecord); server.updateServerConfiguration(sc); server.saveServerConfiguration(); HashSet<String> appNamesSet = new HashSet<String>(); appNamesSet.add(appName); server.waitForConfigUpdateInLogUsingMark(appNamesSet, ""); } @AfterClass public static void tearDown() throws Exception { try { // Clean up database try { JPAPersistenceProvider provider = AbstractFATSuite.provider; final Set<String> ddlSet = new HashSet<String>(); for (String ddlName : dropSet) { ddlSet.add(ddlName.replace("${provider}", provider.name()).replace("${dbvendor}", getDbVendor().name())); } executeDDL(server, ddlSet, true); } catch (Throwable t) { t.printStackTrace(); } server.stopServer("CWWJP9991W", // From Eclipselink drop-and-create tables option "WTRN0074E: Exception caught from before_completion synchronization operation" // RuntimeException test, expected ); } finally { try { ServerConfiguration sc = server.getServerConfiguration(); sc.getApplications().clear(); server.updateServerConfiguration(sc); server.saveServerConfiguration(); server.deleteFileFromLibertyServerRoot("apps/" + appNameEar); server.deleteFileFromLibertyServerRoot("apps/DatabaseManagement.war"); } catch (Throwable t) { t.printStackTrace(); } bannerEnd(Entity_Web.class, timestart); } } }
OpenLiberty/open-liberty
dev/com.ibm.ws.jpa.tests.spec10.entity_fat.common/fat/src/com/ibm/ws/jpa/tests/spec10/entity/tests/Entity_EJB.java
Java
epl-1.0
17,783
/** */ package metamodel_bdsl.util; import metamodel_bdsl.BatchProcess; import metamodel_bdsl.BindingAttribute; import metamodel_bdsl.BindingElement; import metamodel_bdsl.Component; import metamodel_bdsl.ConveyorBelt; import metamodel_bdsl.Distribution; import metamodel_bdsl.Flow; import metamodel_bdsl.Gaussian; import metamodel_bdsl.IntermediateElement; import metamodel_bdsl.MetamodelElement; import metamodel_bdsl.MetamodelElementFeature; import metamodel_bdsl.Metamodel_bdslPackage; import metamodel_bdsl.Model; import metamodel_bdsl.NoneElement; import metamodel_bdsl.OrderOnStockThreshold; import metamodel_bdsl.Output; import metamodel_bdsl.Poisson; import metamodel_bdsl.Probability; import metamodel_bdsl.ProcessOutputFlow; import metamodel_bdsl.Query; import metamodel_bdsl.Scalar; import metamodel_bdsl.SiriusTag; import metamodel_bdsl.Storage; import metamodel_bdsl.StorageOutputFlow; import metamodel_bdsl.Supplier; import metamodel_bdsl.Uniform; import metamodel_bdsl.VirtualAttribute; import metamodel_bdsl.deliveredPercentageSupplier; import metamodel_bdsl.descriptionOutput; import metamodel_bdsl.destinationProcessOutputFlow74; import metamodel_bdsl.destinationStorageOutputFlow63; import metamodel_bdsl.durationBatchProcess42; import metamodel_bdsl.durationConveyorBelt132; import metamodel_bdsl.errorQuery; import metamodel_bdsl.initialContentStorage; import metamodel_bdsl.intervalPoisson; import metamodel_bdsl.locationGaussian; import metamodel_bdsl.maximumUniform; import metamodel_bdsl.minimalSeparationBetweenBatchesConveyorBelt; import metamodel_bdsl.minimumUniform; import metamodel_bdsl.nameBatchProcess; import metamodel_bdsl.nameConveyorBelt; import metamodel_bdsl.nameOrderOnStockThreshold; import metamodel_bdsl.nameQuery; import metamodel_bdsl.nameStorage; import metamodel_bdsl.nameSupplier; import metamodel_bdsl.numberOfChainsBatchProcess; import metamodel_bdsl.orderOnStockThresholdStorage22; import metamodel_bdsl.orderQuantityOrderOnStockThreshold; import metamodel_bdsl.orderTypeOrderOnStockThreshold; import metamodel_bdsl.outputConveyorBelt133; import metamodel_bdsl.outputsBatchProcess43; import metamodel_bdsl.overflowStorage; import metamodel_bdsl.percentageOfSuccessBatchProcess; import metamodel_bdsl.periodOrderOnStockThreshold; import metamodel_bdsl.processOutputFlowDelayProcessOutputFlow73; import metamodel_bdsl.processOutputFlowOutput51; import metamodel_bdsl.processOutputFlowStorage23; import metamodel_bdsl.quantityProcessOutputFlow71; import metamodel_bdsl.quantityStorageOutputFlow61; import metamodel_bdsl.refillPolicySupplier31; import metamodel_bdsl.scaleGaussian; import metamodel_bdsl.sizeStorage; import metamodel_bdsl.sourceProcessOutputFlow72; import metamodel_bdsl.sourceStorageOutputFlow62; import metamodel_bdsl.storageOrderOnStockThreshold82; import metamodel_bdsl.storageOutputFlowBatchProcess41; import metamodel_bdsl.storageOutputFlowConveyorBelt131; import metamodel_bdsl.storageOutputFlowStorage21; import metamodel_bdsl.supplierDelaySupplier32; import metamodel_bdsl.supplierOrderOnStockThreshold81; import metamodel_bdsl.systemQuery; import metamodel_bdsl.thresholdOrderOnStockThreshold; import metamodel_bdsl.typeOutput; import metamodel_bdsl.typeQuery; import metamodel_bdsl.valueQuery; import metamodel_bdsl.valueScalar; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see metamodel_bdsl.Metamodel_bdslPackage * @generated */ public class Metamodel_bdslSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static Metamodel_bdslPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Metamodel_bdslSwitch() { if (modelPackage == null) { modelPackage = Metamodel_bdslPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case Metamodel_bdslPackage.MODEL: { Model model = (Model)theEObject; T result = caseModel(model); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.QUERY: { Query query = (Query)theEObject; T result = caseQuery(query); if (result == null) result = caseBindingElement(query); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.STORAGE: { Storage storage = (Storage)theEObject; T result = caseStorage(storage); if (result == null) result = caseComponent(storage); if (result == null) result = caseBindingElement(storage); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.SUPPLIER: { Supplier supplier = (Supplier)theEObject; T result = caseSupplier(supplier); if (result == null) result = caseComponent(supplier); if (result == null) result = caseBindingElement(supplier); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.BATCH_PROCESS: { BatchProcess batchProcess = (BatchProcess)theEObject; T result = caseBatchProcess(batchProcess); if (result == null) result = caseProcess(batchProcess); if (result == null) result = caseBindingElement(batchProcess); if (result == null) result = caseComponent(batchProcess); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.OUTPUT: { Output output = (Output)theEObject; T result = caseOutput(output); if (result == null) result = caseBindingElement(output); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.STORAGE_OUTPUT_FLOW: { StorageOutputFlow storageOutputFlow = (StorageOutputFlow)theEObject; T result = caseStorageOutputFlow(storageOutputFlow); if (result == null) result = caseFlow(storageOutputFlow); if (result == null) result = caseBindingElement(storageOutputFlow); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.PROCESS_OUTPUT_FLOW: { ProcessOutputFlow processOutputFlow = (ProcessOutputFlow)theEObject; T result = caseProcessOutputFlow(processOutputFlow); if (result == null) result = caseFlow(processOutputFlow); if (result == null) result = caseBindingElement(processOutputFlow); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.PROCESS: { metamodel_bdsl.Process process = (metamodel_bdsl.Process)theEObject; T result = caseProcess(process); if (result == null) result = caseComponent(process); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.ORDER_ON_STOCK_THRESHOLD: { OrderOnStockThreshold orderOnStockThreshold = (OrderOnStockThreshold)theEObject; T result = caseOrderOnStockThreshold(orderOnStockThreshold); if (result == null) result = caseBindingElement(orderOnStockThreshold); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.COMPONENT: { Component component = (Component)theEObject; T result = caseComponent(component); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.FLOW: { Flow flow = (Flow)theEObject; T result = caseFlow(flow); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.PROBABILITY: { Probability probability = (Probability)theEObject; T result = caseProbability(probability); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.DISTRIBUTION: { Distribution distribution = (Distribution)theEObject; T result = caseDistribution(distribution); if (result == null) result = caseProbability(distribution); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.SCALAR: { Scalar scalar = (Scalar)theEObject; T result = caseScalar(scalar); if (result == null) result = caseProbability(scalar); if (result == null) result = caseBindingElement(scalar); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.GAUSSIAN: { Gaussian gaussian = (Gaussian)theEObject; T result = caseGaussian(gaussian); if (result == null) result = caseDistribution(gaussian); if (result == null) result = caseBindingElement(gaussian); if (result == null) result = caseProbability(gaussian); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.POISSON: { Poisson poisson = (Poisson)theEObject; T result = casePoisson(poisson); if (result == null) result = caseDistribution(poisson); if (result == null) result = caseBindingElement(poisson); if (result == null) result = caseProbability(poisson); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.UNIFORM: { Uniform uniform = (Uniform)theEObject; T result = caseUniform(uniform); if (result == null) result = caseDistribution(uniform); if (result == null) result = caseBindingElement(uniform); if (result == null) result = caseProbability(uniform); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.CONVEYOR_BELT: { ConveyorBelt conveyorBelt = (ConveyorBelt)theEObject; T result = caseConveyorBelt(conveyorBelt); if (result == null) result = caseProcess(conveyorBelt); if (result == null) result = caseBindingElement(conveyorBelt); if (result == null) result = caseComponent(conveyorBelt); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.STORAGE_OUTPUT_FLOW_STORAGE21: { storageOutputFlowStorage21 storageOutputFlowStorage21 = (storageOutputFlowStorage21)theEObject; T result = casestorageOutputFlowStorage21(storageOutputFlowStorage21); if (result == null) result = caseBindingAttribute(storageOutputFlowStorage21); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.ORDER_ON_STOCK_THRESHOLD_STORAGE22: { orderOnStockThresholdStorage22 orderOnStockThresholdStorage22 = (orderOnStockThresholdStorage22)theEObject; T result = caseorderOnStockThresholdStorage22(orderOnStockThresholdStorage22); if (result == null) result = caseBindingAttribute(orderOnStockThresholdStorage22); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.PROCESS_OUTPUT_FLOW_STORAGE23: { processOutputFlowStorage23 processOutputFlowStorage23 = (processOutputFlowStorage23)theEObject; T result = caseprocessOutputFlowStorage23(processOutputFlowStorage23); if (result == null) result = caseBindingAttribute(processOutputFlowStorage23); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.REFILL_POLICY_SUPPLIER31: { refillPolicySupplier31 refillPolicySupplier31 = (refillPolicySupplier31)theEObject; T result = caserefillPolicySupplier31(refillPolicySupplier31); if (result == null) result = caseBindingAttribute(refillPolicySupplier31); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.SUPPLIER_DELAY_SUPPLIER32: { supplierDelaySupplier32 supplierDelaySupplier32 = (supplierDelaySupplier32)theEObject; T result = casesupplierDelaySupplier32(supplierDelaySupplier32); if (result == null) result = caseBindingAttribute(supplierDelaySupplier32); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.STORAGE_OUTPUT_FLOW_BATCH_PROCESS41: { storageOutputFlowBatchProcess41 storageOutputFlowBatchProcess41 = (storageOutputFlowBatchProcess41)theEObject; T result = casestorageOutputFlowBatchProcess41(storageOutputFlowBatchProcess41); if (result == null) result = caseBindingAttribute(storageOutputFlowBatchProcess41); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.DURATION_BATCH_PROCESS42: { durationBatchProcess42 durationBatchProcess42 = (durationBatchProcess42)theEObject; T result = casedurationBatchProcess42(durationBatchProcess42); if (result == null) result = caseBindingAttribute(durationBatchProcess42); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.OUTPUTS_BATCH_PROCESS43: { outputsBatchProcess43 outputsBatchProcess43 = (outputsBatchProcess43)theEObject; T result = caseoutputsBatchProcess43(outputsBatchProcess43); if (result == null) result = caseBindingAttribute(outputsBatchProcess43); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.PROCESS_OUTPUT_FLOW_OUTPUT51: { processOutputFlowOutput51 processOutputFlowOutput51 = (processOutputFlowOutput51)theEObject; T result = caseprocessOutputFlowOutput51(processOutputFlowOutput51); if (result == null) result = caseBindingAttribute(processOutputFlowOutput51); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.QUANTITY_STORAGE_OUTPUT_FLOW61: { quantityStorageOutputFlow61 quantityStorageOutputFlow61 = (quantityStorageOutputFlow61)theEObject; T result = casequantityStorageOutputFlow61(quantityStorageOutputFlow61); if (result == null) result = caseBindingAttribute(quantityStorageOutputFlow61); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.SOURCE_STORAGE_OUTPUT_FLOW62: { sourceStorageOutputFlow62 sourceStorageOutputFlow62 = (sourceStorageOutputFlow62)theEObject; T result = casesourceStorageOutputFlow62(sourceStorageOutputFlow62); if (result == null) result = caseBindingAttribute(sourceStorageOutputFlow62); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.DESTINATION_STORAGE_OUTPUT_FLOW63: { destinationStorageOutputFlow63 destinationStorageOutputFlow63 = (destinationStorageOutputFlow63)theEObject; T result = casedestinationStorageOutputFlow63(destinationStorageOutputFlow63); if (result == null) result = caseBindingAttribute(destinationStorageOutputFlow63); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.QUANTITY_PROCESS_OUTPUT_FLOW71: { quantityProcessOutputFlow71 quantityProcessOutputFlow71 = (quantityProcessOutputFlow71)theEObject; T result = casequantityProcessOutputFlow71(quantityProcessOutputFlow71); if (result == null) result = caseBindingAttribute(quantityProcessOutputFlow71); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.SOURCE_PROCESS_OUTPUT_FLOW72: { sourceProcessOutputFlow72 sourceProcessOutputFlow72 = (sourceProcessOutputFlow72)theEObject; T result = casesourceProcessOutputFlow72(sourceProcessOutputFlow72); if (result == null) result = caseBindingAttribute(sourceProcessOutputFlow72); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.PROCESS_OUTPUT_FLOW_DELAY_PROCESS_OUTPUT_FLOW73: { processOutputFlowDelayProcessOutputFlow73 processOutputFlowDelayProcessOutputFlow73 = (processOutputFlowDelayProcessOutputFlow73)theEObject; T result = caseprocessOutputFlowDelayProcessOutputFlow73(processOutputFlowDelayProcessOutputFlow73); if (result == null) result = caseBindingAttribute(processOutputFlowDelayProcessOutputFlow73); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.DESTINATION_PROCESS_OUTPUT_FLOW74: { destinationProcessOutputFlow74 destinationProcessOutputFlow74 = (destinationProcessOutputFlow74)theEObject; T result = casedestinationProcessOutputFlow74(destinationProcessOutputFlow74); if (result == null) result = caseBindingAttribute(destinationProcessOutputFlow74); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.SUPPLIER_ORDER_ON_STOCK_THRESHOLD81: { supplierOrderOnStockThreshold81 supplierOrderOnStockThreshold81 = (supplierOrderOnStockThreshold81)theEObject; T result = casesupplierOrderOnStockThreshold81(supplierOrderOnStockThreshold81); if (result == null) result = caseBindingAttribute(supplierOrderOnStockThreshold81); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.STORAGE_ORDER_ON_STOCK_THRESHOLD82: { storageOrderOnStockThreshold82 storageOrderOnStockThreshold82 = (storageOrderOnStockThreshold82)theEObject; T result = casestorageOrderOnStockThreshold82(storageOrderOnStockThreshold82); if (result == null) result = caseBindingAttribute(storageOrderOnStockThreshold82); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.STORAGE_OUTPUT_FLOW_CONVEYOR_BELT131: { storageOutputFlowConveyorBelt131 storageOutputFlowConveyorBelt131 = (storageOutputFlowConveyorBelt131)theEObject; T result = casestorageOutputFlowConveyorBelt131(storageOutputFlowConveyorBelt131); if (result == null) result = caseBindingAttribute(storageOutputFlowConveyorBelt131); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.DURATION_CONVEYOR_BELT132: { durationConveyorBelt132 durationConveyorBelt132 = (durationConveyorBelt132)theEObject; T result = casedurationConveyorBelt132(durationConveyorBelt132); if (result == null) result = caseBindingAttribute(durationConveyorBelt132); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.OUTPUT_CONVEYOR_BELT133: { outputConveyorBelt133 outputConveyorBelt133 = (outputConveyorBelt133)theEObject; T result = caseoutputConveyorBelt133(outputConveyorBelt133); if (result == null) result = caseBindingAttribute(outputConveyorBelt133); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.NAME_QUERY: { nameQuery nameQuery = (nameQuery)theEObject; T result = casenameQuery(nameQuery); if (result == null) result = caseBindingAttribute(nameQuery); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.VALUE_QUERY: { valueQuery valueQuery = (valueQuery)theEObject; T result = casevalueQuery(valueQuery); if (result == null) result = caseBindingAttribute(valueQuery); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.ERROR_QUERY: { errorQuery errorQuery = (errorQuery)theEObject; T result = caseerrorQuery(errorQuery); if (result == null) result = caseBindingAttribute(errorQuery); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.TYPE_QUERY: { typeQuery typeQuery = (typeQuery)theEObject; T result = casetypeQuery(typeQuery); if (result == null) result = caseBindingAttribute(typeQuery); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.SYSTEM_QUERY: { systemQuery systemQuery = (systemQuery)theEObject; T result = casesystemQuery(systemQuery); if (result == null) result = caseBindingAttribute(systemQuery); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.NAME_STORAGE: { nameStorage nameStorage = (nameStorage)theEObject; T result = casenameStorage(nameStorage); if (result == null) result = caseBindingAttribute(nameStorage); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.SIZE_STORAGE: { sizeStorage sizeStorage = (sizeStorage)theEObject; T result = casesizeStorage(sizeStorage); if (result == null) result = caseBindingAttribute(sizeStorage); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.INITIAL_CONTENT_STORAGE: { initialContentStorage initialContentStorage = (initialContentStorage)theEObject; T result = caseinitialContentStorage(initialContentStorage); if (result == null) result = caseBindingAttribute(initialContentStorage); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.OVERFLOW_STORAGE: { overflowStorage overflowStorage = (overflowStorage)theEObject; T result = caseoverflowStorage(overflowStorage); if (result == null) result = caseBindingAttribute(overflowStorage); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.NAME_SUPPLIER: { nameSupplier nameSupplier = (nameSupplier)theEObject; T result = casenameSupplier(nameSupplier); if (result == null) result = caseBindingAttribute(nameSupplier); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.DELIVERED_PERCENTAGE_SUPPLIER: { deliveredPercentageSupplier deliveredPercentageSupplier = (deliveredPercentageSupplier)theEObject; T result = casedeliveredPercentageSupplier(deliveredPercentageSupplier); if (result == null) result = caseBindingAttribute(deliveredPercentageSupplier); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.NAME_BATCH_PROCESS: { nameBatchProcess nameBatchProcess = (nameBatchProcess)theEObject; T result = casenameBatchProcess(nameBatchProcess); if (result == null) result = caseBindingAttribute(nameBatchProcess); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.PERCENTAGE_OF_SUCCESS_BATCH_PROCESS: { percentageOfSuccessBatchProcess percentageOfSuccessBatchProcess = (percentageOfSuccessBatchProcess)theEObject; T result = casepercentageOfSuccessBatchProcess(percentageOfSuccessBatchProcess); if (result == null) result = caseBindingAttribute(percentageOfSuccessBatchProcess); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.NUMBER_OF_CHAINS_BATCH_PROCESS: { numberOfChainsBatchProcess numberOfChainsBatchProcess = (numberOfChainsBatchProcess)theEObject; T result = casenumberOfChainsBatchProcess(numberOfChainsBatchProcess); if (result == null) result = caseBindingAttribute(numberOfChainsBatchProcess); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.TYPE_OUTPUT: { typeOutput typeOutput = (typeOutput)theEObject; T result = casetypeOutput(typeOutput); if (result == null) result = caseBindingAttribute(typeOutput); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.DESCRIPTION_OUTPUT: { descriptionOutput descriptionOutput = (descriptionOutput)theEObject; T result = casedescriptionOutput(descriptionOutput); if (result == null) result = caseBindingAttribute(descriptionOutput); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.PERIOD_ORDER_ON_STOCK_THRESHOLD: { periodOrderOnStockThreshold periodOrderOnStockThreshold = (periodOrderOnStockThreshold)theEObject; T result = caseperiodOrderOnStockThreshold(periodOrderOnStockThreshold); if (result == null) result = caseBindingAttribute(periodOrderOnStockThreshold); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.THRESHOLD_ORDER_ON_STOCK_THRESHOLD: { thresholdOrderOnStockThreshold thresholdOrderOnStockThreshold = (thresholdOrderOnStockThreshold)theEObject; T result = casethresholdOrderOnStockThreshold(thresholdOrderOnStockThreshold); if (result == null) result = caseBindingAttribute(thresholdOrderOnStockThreshold); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.NAME_ORDER_ON_STOCK_THRESHOLD: { nameOrderOnStockThreshold nameOrderOnStockThreshold = (nameOrderOnStockThreshold)theEObject; T result = casenameOrderOnStockThreshold(nameOrderOnStockThreshold); if (result == null) result = caseBindingAttribute(nameOrderOnStockThreshold); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.ORDER_QUANTITY_ORDER_ON_STOCK_THRESHOLD: { orderQuantityOrderOnStockThreshold orderQuantityOrderOnStockThreshold = (orderQuantityOrderOnStockThreshold)theEObject; T result = caseorderQuantityOrderOnStockThreshold(orderQuantityOrderOnStockThreshold); if (result == null) result = caseBindingAttribute(orderQuantityOrderOnStockThreshold); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.ORDER_TYPE_ORDER_ON_STOCK_THRESHOLD: { orderTypeOrderOnStockThreshold orderTypeOrderOnStockThreshold = (orderTypeOrderOnStockThreshold)theEObject; T result = caseorderTypeOrderOnStockThreshold(orderTypeOrderOnStockThreshold); if (result == null) result = caseBindingAttribute(orderTypeOrderOnStockThreshold); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.VALUE_SCALAR: { valueScalar valueScalar = (valueScalar)theEObject; T result = casevalueScalar(valueScalar); if (result == null) result = caseBindingAttribute(valueScalar); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.LOCATION_GAUSSIAN: { locationGaussian locationGaussian = (locationGaussian)theEObject; T result = caselocationGaussian(locationGaussian); if (result == null) result = caseBindingAttribute(locationGaussian); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.SCALE_GAUSSIAN: { scaleGaussian scaleGaussian = (scaleGaussian)theEObject; T result = casescaleGaussian(scaleGaussian); if (result == null) result = caseBindingAttribute(scaleGaussian); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.INTERVAL_POISSON: { intervalPoisson intervalPoisson = (intervalPoisson)theEObject; T result = caseintervalPoisson(intervalPoisson); if (result == null) result = caseBindingAttribute(intervalPoisson); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.MINIMUM_UNIFORM: { minimumUniform minimumUniform = (minimumUniform)theEObject; T result = caseminimumUniform(minimumUniform); if (result == null) result = caseBindingAttribute(minimumUniform); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.MAXIMUM_UNIFORM: { maximumUniform maximumUniform = (maximumUniform)theEObject; T result = casemaximumUniform(maximumUniform); if (result == null) result = caseBindingAttribute(maximumUniform); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.NAME_CONVEYOR_BELT: { nameConveyorBelt nameConveyorBelt = (nameConveyorBelt)theEObject; T result = casenameConveyorBelt(nameConveyorBelt); if (result == null) result = caseBindingAttribute(nameConveyorBelt); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.MINIMAL_SEPARATION_BETWEEN_BATCHES_CONVEYOR_BELT: { minimalSeparationBetweenBatchesConveyorBelt minimalSeparationBetweenBatchesConveyorBelt = (minimalSeparationBetweenBatchesConveyorBelt)theEObject; T result = caseminimalSeparationBetweenBatchesConveyorBelt(minimalSeparationBetweenBatchesConveyorBelt); if (result == null) result = caseBindingAttribute(minimalSeparationBetweenBatchesConveyorBelt); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.NONE_ELEMENT: { NoneElement noneElement = (NoneElement)theEObject; T result = caseNoneElement(noneElement); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.BINDING_ELEMENT: { BindingElement bindingElement = (BindingElement)theEObject; T result = caseBindingElement(bindingElement); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.INTERMEDIATE_ELEMENT: { IntermediateElement intermediateElement = (IntermediateElement)theEObject; T result = caseIntermediateElement(intermediateElement); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.METAMODEL_ELEMENT: { MetamodelElement metamodelElement = (MetamodelElement)theEObject; T result = caseMetamodelElement(metamodelElement); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.METAMODEL_ELEMENT_FEATURE: { MetamodelElementFeature metamodelElementFeature = (MetamodelElementFeature)theEObject; T result = caseMetamodelElementFeature(metamodelElementFeature); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.BINDING_ATTRIBUTE: { BindingAttribute bindingAttribute = (BindingAttribute)theEObject; T result = caseBindingAttribute(bindingAttribute); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.VIRTUAL_ATTRIBUTE: { VirtualAttribute virtualAttribute = (VirtualAttribute)theEObject; T result = caseVirtualAttribute(virtualAttribute); if (result == null) result = defaultCase(theEObject); return result; } case Metamodel_bdslPackage.SIRIUS_TAG: { SiriusTag siriusTag = (SiriusTag)theEObject; T result = caseSiriusTag(siriusTag); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Model</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Model</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseModel(Model object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Query</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Query</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseQuery(Query object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Storage</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Storage</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseStorage(Storage object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Supplier</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Supplier</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseSupplier(Supplier object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Batch Process</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Batch Process</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseBatchProcess(BatchProcess object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Output</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Output</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseOutput(Output object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Storage Output Flow</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Storage Output Flow</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseStorageOutputFlow(StorageOutputFlow object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Process Output Flow</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Process Output Flow</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseProcessOutputFlow(ProcessOutputFlow object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Process</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Process</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseProcess(metamodel_bdsl.Process object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Order On Stock Threshold</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Order On Stock Threshold</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseOrderOnStockThreshold(OrderOnStockThreshold object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Component</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Component</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseComponent(Component object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Flow</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Flow</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFlow(Flow object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Probability</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Probability</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseProbability(Probability object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Distribution</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Distribution</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDistribution(Distribution object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Scalar</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Scalar</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseScalar(Scalar object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Gaussian</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Gaussian</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseGaussian(Gaussian object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Poisson</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Poisson</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casePoisson(Poisson object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Uniform</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Uniform</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseUniform(Uniform object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Conveyor Belt</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Conveyor Belt</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseConveyorBelt(ConveyorBelt object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>storage Output Flow Storage21</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>storage Output Flow Storage21</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casestorageOutputFlowStorage21(storageOutputFlowStorage21 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>order On Stock Threshold Storage22</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>order On Stock Threshold Storage22</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseorderOnStockThresholdStorage22(orderOnStockThresholdStorage22 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>process Output Flow Storage23</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>process Output Flow Storage23</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseprocessOutputFlowStorage23(processOutputFlowStorage23 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>refill Policy Supplier31</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>refill Policy Supplier31</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caserefillPolicySupplier31(refillPolicySupplier31 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>supplier Delay Supplier32</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>supplier Delay Supplier32</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casesupplierDelaySupplier32(supplierDelaySupplier32 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>storage Output Flow Batch Process41</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>storage Output Flow Batch Process41</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casestorageOutputFlowBatchProcess41(storageOutputFlowBatchProcess41 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>duration Batch Process42</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>duration Batch Process42</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casedurationBatchProcess42(durationBatchProcess42 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>outputs Batch Process43</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>outputs Batch Process43</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseoutputsBatchProcess43(outputsBatchProcess43 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>process Output Flow Output51</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>process Output Flow Output51</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseprocessOutputFlowOutput51(processOutputFlowOutput51 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>quantity Storage Output Flow61</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>quantity Storage Output Flow61</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casequantityStorageOutputFlow61(quantityStorageOutputFlow61 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>source Storage Output Flow62</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>source Storage Output Flow62</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casesourceStorageOutputFlow62(sourceStorageOutputFlow62 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>destination Storage Output Flow63</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>destination Storage Output Flow63</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casedestinationStorageOutputFlow63(destinationStorageOutputFlow63 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>quantity Process Output Flow71</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>quantity Process Output Flow71</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casequantityProcessOutputFlow71(quantityProcessOutputFlow71 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>source Process Output Flow72</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>source Process Output Flow72</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casesourceProcessOutputFlow72(sourceProcessOutputFlow72 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>process Output Flow Delay Process Output Flow73</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>process Output Flow Delay Process Output Flow73</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseprocessOutputFlowDelayProcessOutputFlow73(processOutputFlowDelayProcessOutputFlow73 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>destination Process Output Flow74</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>destination Process Output Flow74</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casedestinationProcessOutputFlow74(destinationProcessOutputFlow74 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>supplier Order On Stock Threshold81</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>supplier Order On Stock Threshold81</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casesupplierOrderOnStockThreshold81(supplierOrderOnStockThreshold81 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>storage Order On Stock Threshold82</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>storage Order On Stock Threshold82</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casestorageOrderOnStockThreshold82(storageOrderOnStockThreshold82 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>storage Output Flow Conveyor Belt131</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>storage Output Flow Conveyor Belt131</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casestorageOutputFlowConveyorBelt131(storageOutputFlowConveyorBelt131 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>duration Conveyor Belt132</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>duration Conveyor Belt132</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casedurationConveyorBelt132(durationConveyorBelt132 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>output Conveyor Belt133</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>output Conveyor Belt133</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseoutputConveyorBelt133(outputConveyorBelt133 object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>name Query</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>name Query</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casenameQuery(nameQuery object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>value Query</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>value Query</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casevalueQuery(valueQuery object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>error Query</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>error Query</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseerrorQuery(errorQuery object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>type Query</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>type Query</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casetypeQuery(typeQuery object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>system Query</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>system Query</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casesystemQuery(systemQuery object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>name Storage</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>name Storage</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casenameStorage(nameStorage object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>size Storage</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>size Storage</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casesizeStorage(sizeStorage object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>initial Content Storage</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>initial Content Storage</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseinitialContentStorage(initialContentStorage object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>overflow Storage</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>overflow Storage</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseoverflowStorage(overflowStorage object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>name Supplier</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>name Supplier</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casenameSupplier(nameSupplier object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>delivered Percentage Supplier</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>delivered Percentage Supplier</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casedeliveredPercentageSupplier(deliveredPercentageSupplier object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>name Batch Process</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>name Batch Process</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casenameBatchProcess(nameBatchProcess object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>percentage Of Success Batch Process</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>percentage Of Success Batch Process</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casepercentageOfSuccessBatchProcess(percentageOfSuccessBatchProcess object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>number Of Chains Batch Process</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>number Of Chains Batch Process</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casenumberOfChainsBatchProcess(numberOfChainsBatchProcess object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>type Output</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>type Output</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casetypeOutput(typeOutput object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>description Output</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>description Output</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casedescriptionOutput(descriptionOutput object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>period Order On Stock Threshold</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>period Order On Stock Threshold</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseperiodOrderOnStockThreshold(periodOrderOnStockThreshold object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>threshold Order On Stock Threshold</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>threshold Order On Stock Threshold</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casethresholdOrderOnStockThreshold(thresholdOrderOnStockThreshold object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>name Order On Stock Threshold</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>name Order On Stock Threshold</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casenameOrderOnStockThreshold(nameOrderOnStockThreshold object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>order Quantity Order On Stock Threshold</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>order Quantity Order On Stock Threshold</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseorderQuantityOrderOnStockThreshold(orderQuantityOrderOnStockThreshold object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>order Type Order On Stock Threshold</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>order Type Order On Stock Threshold</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseorderTypeOrderOnStockThreshold(orderTypeOrderOnStockThreshold object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>value Scalar</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>value Scalar</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casevalueScalar(valueScalar object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>location Gaussian</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>location Gaussian</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caselocationGaussian(locationGaussian object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>scale Gaussian</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>scale Gaussian</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casescaleGaussian(scaleGaussian object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>interval Poisson</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>interval Poisson</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseintervalPoisson(intervalPoisson object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>minimum Uniform</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>minimum Uniform</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseminimumUniform(minimumUniform object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>maximum Uniform</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>maximum Uniform</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casemaximumUniform(maximumUniform object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>name Conveyor Belt</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>name Conveyor Belt</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casenameConveyorBelt(nameConveyorBelt object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>minimal Separation Between Batches Conveyor Belt</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>minimal Separation Between Batches Conveyor Belt</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseminimalSeparationBetweenBatchesConveyorBelt(minimalSeparationBetweenBatchesConveyorBelt object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>None Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>None Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseNoneElement(NoneElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Binding Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Binding Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseBindingElement(BindingElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Intermediate Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Intermediate Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseIntermediateElement(IntermediateElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Metamodel Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Metamodel Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMetamodelElement(MetamodelElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Metamodel Element Feature</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Metamodel Element Feature</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMetamodelElementFeature(MetamodelElementFeature object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Binding Attribute</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Binding Attribute</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseBindingAttribute(BindingAttribute object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Virtual Attribute</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Virtual Attribute</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseVirtualAttribute(VirtualAttribute object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Sirius Tag</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Sirius Tag</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseSiriusTag(SiriusTag object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //Metamodel_bdslSwitch
jesusc/bento
tests/test-outputs/bento.sirius.tests.metamodels.output/src/metamodel_bdsl/util/Metamodel_bdslSwitch.java
Java
epl-1.0
76,608
/* * Copyright 2012 PRODYNA AG * * Licensed under the Eclipse Public License (EPL), Version 1.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the License at * * http://www.opensource.org/licenses/eclipse-1.0.php or * http://www.nabucco.org/License.html * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package org.nabucco.business.address.facade.message; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.nabucco.business.address.facade.datatype.PhoneAddress; import org.nabucco.framework.base.facade.datatype.collection.NabuccoCollectionState; import org.nabucco.framework.base.facade.datatype.collection.NabuccoList; import org.nabucco.framework.base.facade.datatype.collection.NabuccoListImpl; import org.nabucco.framework.base.facade.datatype.property.NabuccoProperty; import org.nabucco.framework.base.facade.datatype.property.NabuccoPropertyContainer; import org.nabucco.framework.base.facade.datatype.property.NabuccoPropertyDescriptor; import org.nabucco.framework.base.facade.datatype.property.PropertyAssociationType; import org.nabucco.framework.base.facade.datatype.property.PropertyCache; import org.nabucco.framework.base.facade.datatype.property.PropertyDescriptorSupport; import org.nabucco.framework.base.facade.message.ServiceMessage; import org.nabucco.framework.base.facade.message.ServiceMessageSupport; /** * PhoneAddressListMsg<p/>Default message for list of PhoneAddress datatype<p/> * * @version 1.0 * @author Dominic Trumpfheller, PRODYNA AG, 2010-12-20 */ public class PhoneAddressListMsg extends ServiceMessageSupport implements ServiceMessage { private static final long serialVersionUID = 1L; private static final String[] PROPERTY_CONSTRAINTS = { "m0,n;" }; public static final String PHONEADDRESSLIST = "phoneAddressList"; private NabuccoList<PhoneAddress> phoneAddressList; /** Constructs a new PhoneAddressListMsg instance. */ public PhoneAddressListMsg() { super(); this.initDefaults(); } /** InitDefaults. */ private void initDefaults() { } /** * CreatePropertyContainer. * * @return the NabuccoPropertyContainer. */ protected static NabuccoPropertyContainer createPropertyContainer() { Map<String, NabuccoPropertyDescriptor> propertyMap = new HashMap<String, NabuccoPropertyDescriptor>(); propertyMap.put(PHONEADDRESSLIST, PropertyDescriptorSupport.createCollection(PHONEADDRESSLIST, PhoneAddress.class, 0, PROPERTY_CONSTRAINTS[0], false, PropertyAssociationType.COMPOSITION)); return new NabuccoPropertyContainer(propertyMap); } /** Init. */ public void init() { this.initDefaults(); } @Override public Set<NabuccoProperty> getProperties() { Set<NabuccoProperty> properties = super.getProperties(); properties.add(super.createProperty(PhoneAddressListMsg.getPropertyDescriptor(PHONEADDRESSLIST), this.phoneAddressList)); return properties; } @Override @SuppressWarnings("unchecked") public boolean setProperty(NabuccoProperty property) { if (super.setProperty(property)) { return true; } if ((property.getName().equals(PHONEADDRESSLIST) && (property.getType() == PhoneAddress.class))) { this.phoneAddressList = ((NabuccoList<PhoneAddress>) property.getInstance()); return true; } return false; } @Override public boolean equals(Object obj) { if ((this == obj)) { return true; } if ((obj == null)) { return false; } if ((this.getClass() != obj.getClass())) { return false; } if ((!super.equals(obj))) { return false; } final PhoneAddressListMsg other = ((PhoneAddressListMsg) obj); if ((this.phoneAddressList == null)) { if ((other.phoneAddressList != null)) return false; } else if ((!this.phoneAddressList.equals(other.phoneAddressList))) return false; return true; } @Override public int hashCode() { final int PRIME = 31; int result = super.hashCode(); result = ((PRIME * result) + ((this.phoneAddressList == null) ? 0 : this.phoneAddressList.hashCode())); return result; } @Override public ServiceMessage cloneObject() { return this; } /** * Missing description at method getPhoneAddressList. * * @return the NabuccoList<PhoneAddress>. */ public NabuccoList<PhoneAddress> getPhoneAddressList() { if ((this.phoneAddressList == null)) { this.phoneAddressList = new NabuccoListImpl<PhoneAddress>(NabuccoCollectionState.INITIALIZED); } return this.phoneAddressList; } /** * Getter for the PropertyDescriptor. * * @param propertyName the String. * @return the NabuccoPropertyDescriptor. */ public static NabuccoPropertyDescriptor getPropertyDescriptor(String propertyName) { return PropertyCache.getInstance().retrieve(PhoneAddressListMsg.class).getProperty(propertyName); } /** * Getter for the PropertyDescriptorList. * * @return the List<NabuccoPropertyDescriptor>. */ public static List<NabuccoPropertyDescriptor> getPropertyDescriptorList() { return PropertyCache.getInstance().retrieve(PhoneAddressListMsg.class).getAllProperties(); } }
NABUCCO/org.nabucco.business.address
org.nabucco.business.address.facade.message/src/main/gen/org/nabucco/business/address/facade/message/PhoneAddressListMsg.java
Java
epl-1.0
6,075
/******************************************************************************* * Copyright (c) 1997, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.threading.internal; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import com.ibm.ejs.ras.Tr; import com.ibm.ejs.ras.TraceComponent; import com.ibm.ws.kernel.service.util.CpuInfo; /** * A fixed size FIFO (with expedited) of Objects. Null objects are not allowed in * the buffer. The buffer contains a expedited FIFO buffer, whose objects * will be removed before objects in the main buffer. */ public class BoundedBuffer<T> implements BlockingQueue<T> { // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Implementation Note: the buffer is implemented using a circular // array. Both a "head" and "tail" pointer (array index) are // maintained as well as an overall count of used/empty // slots: // // [TEM]: I do not know why both used and empty slot counts are // maintained given that one can be derived from the other // and the capacity. I suspect it is so that the two // values can vary on independent threads. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // BoundedBuffer's locking model is a little more complicated than it // appears at first glance and the reasons for this are somewhat subtle. // // There are two 'locks' involved: the BoundedBuffer instance itself // and the Object instance named lock. Synchronizing on this i.e. the // BoundedBuffer instance is used to single thread take operations and // the used slots counter. Synchronizing on lock is used to single // thread put operations and the empty slots counter. // // It's easiest to explain the need for two separate locks by explaining // a problem that can arise by only using a single lock. Consider a buffer // with a capacity of two that is currently full - two consecutive put // calls have been made and all threads attempting puts are now in a wait() // call until some space is freed up in the buffer by a take. Another thread // calls the buffer and performs a take which will trigger a notify. If the // thread that is notified is a taking thread another take will occur. This // take will empty the buffer and triggering another notify. If the thread // that is notified here is another taking thread a hang will occur - the // buffer is empty so it and any subsequent take calls will drop into a // wait() until a put occurs. No more notify() calls will be made leaving // the taking threads stuck in wait() awaiting a put and the putting threads // stuck in wait() awaiting a notify from a successful take which can never // occur as the buffer's empty. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // D638088.2 private static TraceComponent tc = Tr.register(BoundedBuffer.class); /* * Maged: * These modifications are for the purpose of: * - increasing concurrency * - reduce latency * - fix a race condition between the expand and put functions * Outline: * - The buffer size is disassociated from the locks * - numberOfUsedSlots is declared AtomicInteger and updated atomically * without locking * - numberOfEmptySlots is not needed * - Wait-notify is replaced with polling * - Lock holding periods are minimized * - Put/Take operations acquire one lock and update numberOfUsedSlots * atomically instead of acquiring two locks * - The expand operation acquires both locks * Christoph: * - queueing putters and getters separately on locks that are different * from 'this' and 'lock' * - benign races on XXQueueLen_ at notify * - spinning with backoff */ // D312598 - begin private static final int SPINS_TAKE_; private static final int SPINS_PUT_; private static final boolean YIELD_TAKE_; private static final boolean YIELD_PUT_; //D638088 - modified the set of WAIT_SLICE parameters private static final long WAIT_SHORT_SLICE_; static { //D638088 - modified spinning defaults to adjust to the number //of physical processors on host system. SPINS_TAKE_ = Integer.getInteger("com.ibm.ws.util.BoundedBuffer.spins_take", CpuInfo.getAvailableProcessors() - 1).intValue(); // D371967 SPINS_PUT_ = Integer.getInteger("com.ibm.ws.util.BoundedBuffer.spins_put", SPINS_TAKE_ / 4).intValue(); // D371967 YIELD_TAKE_ = Boolean.getBoolean("com.ibm.ws.util.BoundedBuffer.yield_take"); YIELD_PUT_ = Boolean.getBoolean("com.ibm.ws.util.BoundedBuffer.yield_put"); //D638088 - created short/long wait periods, based on a multiplication factor. Keeping //default behavior the same. WAIT_SHORT_SLICE_ = Long.getLong("com.ibm.ws.util.BoundedBuffer.wait", 1000).longValue(); // D371967 } private static ConcurrentLinkedQueue<GetQueueLock> waitingThreadLocks = new ConcurrentLinkedQueue<GetQueueLock>(); private static final ThreadLocal<GetQueueLock> threadLocalGetLock = new ThreadLocal<GetQueueLock>() { @Override protected GetQueueLock initialValue() { return new GetQueueLock(); } }; // D371967: An easily-identified marker class used for locking private static class PutQueueLock extends Object {} private final PutQueueLock putQueue_ = new PutQueueLock(); private int putQueueLen_ = 0; // D638088: Added two fields to the getQueueLock for book keeping // D371967: An easily-identified marker class used for locking private static class GetQueueLock extends Object { private boolean notified; public boolean isNotified() { return notified; } public void setNotified(boolean notified) { this.notified = notified; } } private void notifyGet_() { // Notify a waiting thread that work has arrived on the queue. A notification may be lost in some cases - however as none of the // threads wait endlessly, a waiting thread will either be notified, or will eventually wake up. If there are no waiting threads, // the new work will be picked up when an active thread completes its task. GetQueueLock lock = waitingThreadLocks.poll(); if (lock != null) { synchronized (lock) { lock.setNotified(true); lock.notify(); } } } private void waitGet_(long timeout) throws InterruptedException { GetQueueLock getQueueLock = threadLocalGetLock.get(); try { synchronized (getQueueLock) { getQueueLock.setNotified(false); waitingThreadLocks.add(getQueueLock); getQueueLock.wait(timeout == -1 ? 0 : timeout); } } finally { if (!getQueueLock.isNotified()) { // we either timed out or were interrupted, so remove ourselves from the queue... it's okay if a producer already has the // lock because we're going to exit and go try to get more work anyway, so it's okay if we don't get the signal waitingThreadLocks.remove(getQueueLock); } } } private void notifyPut_() { // As in notifyGet_, this notification might be lost. if (putQueueLen_ > 0) { synchronized (putQueue_) { putQueue_.notify(); } } } private void waitPut_(long timeout) throws InterruptedException { synchronized (putQueue_) { try { putQueueLen_++; // D497382 - As in waitGet_, try to avoid lost notifications. if (numberOfUsedSlots.get() >= buffer.length) { // notification through notifyPut_ may be lost here putQueue_.wait(timeout); } // } catch (InterruptedException ex) { // putQueue_.notify(); // throw ex; } finally { putQueueLen_--; } } } // D312598 - end private T[] buffer; // the circular array (buffer) private T[] expeditedBuffer; // the circular expedited array (expedited buffer) private int takeIndex = 0; // the beginning of the buffer private int expeditedTakeIndex = 0; // the beginning of the expedited buffer private int putIndex = 0; // the end of the buffer private int expeditedPutIndex = 0; // the end of the expedited buffer private final AtomicInteger numberOfUsedSlots = new AtomicInteger(0); // D312598 D638088 private final AtomicInteger numberOfUsedExpeditedSlots = new AtomicInteger(0); /** * Helper monitor to handle puts. */ private final BoundedBufferLock lock = new BoundedBufferLock(); //@awisniew DELETED //private ThreadPool threadPool_ = null; // this can be null, only non null when this threadpool supports thread renewal /** * Create a BoundedBuffer with the given capacity. * * @exception IllegalArgumentException if the requested capacity * is less or equal to zero. */ @SuppressWarnings("unchecked") public BoundedBuffer(Class<T> c, int capacity, int expeditedCapacity) throws IllegalArgumentException { if (capacity <= 0 || expeditedCapacity <= 0) { throw new IllegalArgumentException(); } //Initialize buffer array final T[] buffer = (T[]) Array.newInstance(c, capacity); this.buffer = buffer; //Initialize expedited buffer array final T[] expeditedBuffer = (T[]) Array.newInstance(c, expeditedCapacity); this.expeditedBuffer = expeditedBuffer; //enable debug output if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Created bounded buffer: capacity=" + capacity + " expedited capacity=" + expeditedCapacity); } } /** * Return the number of elements in the buffer. * This is only a snapshot value, that may change * immediately after returning. */ // D312598 - remove synchronization and use .get @Override public int size() { return numberOfUsedSlots.get() + numberOfUsedExpeditedSlots.get(); } /** * Returns the overall capacity of the buffer. * Note that this is how much the buffer can hold, * not how much space is unused. */ public int capacity() { return buffer.length + expeditedBuffer.length; } /* * @awisniew - ADDED * * The number of unused slots. * * @see java.util.concurrent.BlockingQueue#remainingCapacity() */ @Override public int remainingCapacity() { return capacity() - size(); } /* * @awisniew - ADDED * * @see java.util.Collection#isEmpty() */ @Override public boolean isEmpty() { if (size() == 0) { return true; } return false; } /** * Peeks at the head of the buffer and returns the first * object (or null if empty). The object remains in the * buffer. */ @Override public T peek() { synchronized (this) { if (numberOfUsedExpeditedSlots.get() > 0) { return expeditedBuffer[expeditedTakeIndex]; } else if (numberOfUsedSlots.get() > 0) { return buffer[takeIndex]; } else { return null; } } } /* * @awisniew - ADDED * * Same as peek, only throws exception if queue is empty * * @see java.util.Queue#element() */ @Override public T element() { T retrievedElement = peek(); if (retrievedElement == null) { throw new NoSuchElementException(); } return retrievedElement; } /** * Puts an object into the buffer. If the buffer is full, * the call will block indefinitely until space is freed up. * * @param x the object being placed in the buffer. * @exception IllegalArgumentException if the object is null. */ @Override public void put(T t) throws InterruptedException { if (t == null) { throw new IllegalArgumentException(); } // D186845 if (Thread.interrupted()) // D186845 throw new InterruptedException(); // D312598 - begin //TODO: Add expedited put/fix waiting logic boolean ret = false; while (true) { synchronized (lock) { if (numberOfUsedSlots.get() < buffer.length) { insert(t); numberOfUsedSlots.getAndIncrement(); ret = true; } } if (ret) { notifyGet_(); return; } int spinctr = SPINS_PUT_; while (numberOfUsedSlots.get() >= buffer.length) { // busy wait if (spinctr > 0) { if (YIELD_PUT_) Thread.yield(); spinctr--; } else { // block on lock waitPut_(WAIT_SHORT_SLICE_); } } } // D312598 - end } /** * Puts an object into the buffer. If the buffer is full, * the call will block for up to the specified timeout * period. * * @param x the object being placed in the buffer. * @param timeoutInMillis the timeout period in milliseconds. * @return the object that was put into the buffer (t) or * null in the event that the request timed out. * @exception IllegalArgumentException if the object is null. */ public T put(T t, long timeoutInMillis) throws InterruptedException { if (t == null) { throw new IllegalArgumentException(); } //TODO: Add expedited put/fix waiting logic long start = (timeoutInMillis <= 0) ? 0 : -1; long waitTime = timeoutInMillis; // D312598 - begin T ret = null; while (true) { synchronized (lock) { if (numberOfUsedSlots.get() < buffer.length) { insert(t); numberOfUsedSlots.getAndIncrement(); ret = t; } } if (ret != null) { notifyGet_(); return ret; } if (start == -1) start = System.currentTimeMillis(); int spinctr = SPINS_PUT_; while (numberOfUsedSlots.get() >= buffer.length) { if (waitTime <= 0) { return null; } // busy wait if (spinctr > 0) { if (YIELD_PUT_) Thread.yield(); spinctr--; } else { // block on lock waitPut_(timeoutInMillis); } waitTime = timeoutInMillis - (System.currentTimeMillis() - start); } } // D312598 - end } /** * Puts an object into the buffer. If the buffer is at or above the * specified maximum capacity, the call will block for up to the * specified timeout period. * * @param x the object being placed in the buffer. * @param timeoutInMillis the timeout period in milliseconds. * @param maximumCapacity the desired maximum capacity of the buffer * @return the object that was put into the buffer (x) or * null in the event that the request timed out. * @exception IllegalArgumentException if the object is null or if the * supplied maximum capacity exceeds the buffer's size. */ public T put(T t, long timeoutInMillis, int maximumCapacity) throws InterruptedException { if ((t == null) || (maximumCapacity > buffer.length)) { throw new IllegalArgumentException(); } long start = (timeoutInMillis <= 0) ? 0 : -1; long waitTime = timeoutInMillis; //TODO: Add expedited put/fix waiting logic // D312598 - begin T ret = null; while (true) { synchronized (lock) { if (numberOfUsedSlots.get() < maximumCapacity) { insert(t); numberOfUsedSlots.getAndIncrement(); ret = t; } } if (ret != null) { notifyGet_(); return ret; } if (start == -1) start = System.currentTimeMillis(); int spinctr = SPINS_PUT_; while (numberOfUsedSlots.get() >= buffer.length) { if (waitTime <= 0) { return null; } // busy wait if (spinctr > 0) { if (YIELD_PUT_) Thread.yield(); spinctr--; } else { // block on lock waitPut_(timeoutInMillis); } waitTime = timeoutInMillis - (System.currentTimeMillis() - start); } } // D312598 - end } /** * Puts an object into the buffer. If the buffer is full, * the call will block for up to the specified amount of * time, waiting for space to be freed up. * * @param x the object being placed into the buffer. * @param timeout the maximum amount of time * that the caller is willing to wait if the buffer is full. * @return true if the object was added to the buffer; false if * it was not added before the timeout expired. */ @Override public boolean offer(T t, long timeout, TimeUnit unit) throws InterruptedException { if (t == null) { throw new IllegalArgumentException(); } //TODO: Add expedited offer/fix waiting logic // D220640: Next two lines pulled out of synchronization block: long timeoutMS = unit.toMillis(timeout); long start = (timeoutMS <= 0) ? 0 : -1; long waitTime = timeoutMS; // D312598 - begin boolean ret = false; while (true) { synchronized (lock) { if (numberOfUsedSlots.get() < buffer.length) { insert(t); numberOfUsedSlots.getAndIncrement(); ret = true; } } if (ret) { notifyGet_(); return true; } if (start == -1) start = System.currentTimeMillis(); int spinctr = SPINS_PUT_; while (numberOfUsedSlots.get() >= buffer.length) { if (waitTime <= 0) { return false; } // busy wait if (spinctr > 0) { if (YIELD_PUT_) Thread.yield(); spinctr--; } else { // block on lock waitPut_(waitTime); } waitTime = timeoutMS - (System.currentTimeMillis() - start); } } // D312598 - end } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.concurrent.BlockingQueue#offer(java.lang.Object) */ @Override public boolean offer(T t) { if (t == null) { throw new IllegalArgumentException(); } boolean ret = false; synchronized (lock) { if (t instanceof QueueItem && ((QueueItem) t).isExpedited()) { if (numberOfUsedExpeditedSlots.get() < expeditedBuffer.length) { expeditedInsert(t); numberOfUsedExpeditedSlots.getAndIncrement(); ret = true; } } else { if (numberOfUsedSlots.get() < buffer.length) { insert(t); numberOfUsedSlots.getAndIncrement(); ret = true; } } } if (ret) { notifyGet_(); return true; } return false; } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.concurrent.BlockingQueue#add(java.lang.Object) */ @Override public boolean add(T t) { if (offer(t)) return true; else throw new IllegalStateException("Queue full"); } /** * Removes an object from the buffer. If the buffer is * empty, then the call blocks until something becomes * available. * * @return Object the next object from the buffer. */ @Override public T take() throws InterruptedException { T old = poll(); while (old == null) { waitGet_(-1); old = poll(); } return old; } /** * Removes an object from the buffer. If the buffer is empty, the call blocks for up to * a specified amount of time before it gives up. * * @param timeout - * the amount of time, that the caller is willing to wait * in the event of an empty buffer. * @param unit - * the unit of time */ @Override public T poll(long timeout, TimeUnit unit) throws InterruptedException { T old = poll(); long endTimeMillis = System.currentTimeMillis() + unit.toMillis(timeout); long timeLeftMillis = endTimeMillis - System.currentTimeMillis(); int spinctr = SPINS_TAKE_; while (old == null && timeLeftMillis > 0) { while (size() <= 0 && timeLeftMillis > 0) { if (spinctr > 0) { // busy wait if (YIELD_TAKE_) Thread.yield(); spinctr--; } else { // block on lock waitGet_(timeLeftMillis); } timeLeftMillis = endTimeMillis - System.currentTimeMillis(); } old = poll(); timeLeftMillis = endTimeMillis - System.currentTimeMillis(); } return old; } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.Queue#poll() */ @Override public T poll() { T old = null; boolean expedited = false; synchronized (this) { if (numberOfUsedExpeditedSlots.get() > 0) { old = expeditedExtract(); numberOfUsedExpeditedSlots.getAndDecrement(); expedited = true; } else if (numberOfUsedSlots.get() > 0) { old = extract(); numberOfUsedSlots.getAndDecrement(); } } if (old != null) { //TODO if expedited is added for put or offer with timeout add notification here if (!expedited) notifyPut_(); } return old; } /* * @awisniew - ADDED * * Same as poll, only throws exception if queue is empty * * @see java.util.Queue#remove() */ @Override public T remove() { T retrievedElement = poll(); if (retrievedElement == null) { throw new NoSuchElementException(); } return retrievedElement; } /** * Inserts an object into the buffer. Note that * since there is no synchronization, it is assumed * that this is done outside the scope of this call. */ private final void insert(T t) { buffer[putIndex] = t; if (++putIndex >= buffer.length) { putIndex = 0; } } /** * Inserts an object into the expeditedBuffer. Note that * since there is no synchronization, it is assumed * that this is done outside the scope of this call. */ private final void expeditedInsert(T t) { expeditedBuffer[expeditedPutIndex] = t; if (++expeditedPutIndex >= expeditedBuffer.length) { expeditedPutIndex = 0; } } /** * Removes an object from the buffer. Note that * since there is no synchronization, it is assumed * that this is done outside the scope of this call. */ private final T extract() { T old = buffer[takeIndex]; buffer[takeIndex] = null; if (++takeIndex >= buffer.length) takeIndex = 0; return old; } /** * Removes an object from the expeditedBuffer. Note that * since there is no synchronization, it is assumed * that this is done outside the scope of this call. */ private final T expeditedExtract() { T old = expeditedBuffer[expeditedTakeIndex]; expeditedBuffer[expeditedTakeIndex] = null; if (++expeditedTakeIndex >= expeditedBuffer.length) expeditedTakeIndex = 0; return old; } /** * Increases the buffer's capacity by the given amount. * * @param additionalCapacity * The amount by which the buffer's capacity should be increased. */ @SuppressWarnings("unchecked") public synchronized void expand(int additionalCapacity) { if (additionalCapacity <= 0) { throw new IllegalArgumentException(); } int capacityBefore = buffer.length; synchronized (lock) { // D312598 int capacityAfter = buffer.length; //Check that no one was expanding while we waited on this lock if (capacityAfter == capacityBefore) { final Object[] newBuffer = new Object[buffer.length + additionalCapacity]; // PK53203 - put() acquires two locks in sequence. First, it acquires // the insert lock to update putIndex. Then, it drops the insert lock // and acquires the extract lock to update numberOfUsedSlots. As a // result, there is a window where putIndex has been updated, but // numberOfUsedSlots has not. Consequently, even though we have // acquired both locks in this method, we cannot rely on the values in // numberOfUsedSlots; we can only rely on putIndex and takeIndex. if (putIndex > takeIndex) { // The contents of the buffer do not wrap round // the end of the array. We can move its contents // into the new expanded buffer in one go. int used = putIndex - takeIndex; System.arraycopy(buffer, takeIndex, newBuffer, 0, used); putIndex = used; // PK53203.1 - If putIndex == takeIndex, then the buffer is either // completely full or completely empty. If it is completely full, then // we need to copy and adjust putIndex. Otherwise, we need to set // putIndex to 0. } else if (putIndex != takeIndex || buffer[takeIndex] != null) { // The contents of the buffer wrap round the end // of the array. We have to perform two copies to // move its contents into the new buffer. int used = buffer.length - takeIndex; System.arraycopy(buffer, takeIndex, newBuffer, 0, used); System.arraycopy(buffer, 0, newBuffer, used, putIndex); putIndex += used; } else { putIndex = 0; } // The contents of the buffer now begin at 0 - update the head pointer. takeIndex = 0; // The buffer's capacity has been increased so update the count of the // empty slots to reflect this. buffer = (T[]) newBuffer; } } // D312598 } /** * Increases the expedited buffer's capacity by the given amount. * * @param additionalCapacity * The amount by which the expedited buffer's capacity should be increased. */ @SuppressWarnings("unchecked") public synchronized void expandExpedited(int additionalCapacity) { if (additionalCapacity <= 0) { throw new IllegalArgumentException(); } int capacityBefore = expeditedBuffer.length; synchronized (lock) { // D312598 int capacityAfter = expeditedBuffer.length; //Check that no one was expanding while we waited on this lock if (capacityAfter == capacityBefore) { final Object[] newBuffer = new Object[expeditedBuffer.length + additionalCapacity]; // PK53203 - put() acquires two locks in sequence. First, it acquires // the insert lock to update putIndex. Then, it drops the insert lock // and acquires the extract lock to update numberOfUsedSlots. As a // result, there is a window where putIndex has been updated, but // numberOfUsedSlots has not. Consequently, even though we have // acquired both locks in this method, we cannot rely on the values in // numberOfUsedSlots; we can only rely on putIndex and takeIndex. if (expeditedPutIndex > expeditedTakeIndex) { // The contents of the buffer do not wrap round // the end of the array. We can move its contents // into the new expanded buffer in one go. int used = expeditedPutIndex - expeditedTakeIndex; System.arraycopy(expeditedBuffer, expeditedTakeIndex, newBuffer, 0, used); expeditedPutIndex = used; // PK53203.1 - If putIndex == takeIndex, then the buffer is either // completely full or completely empty. If it is completely full, then // we need to copy and adjust putIndex. Otherwise, we need to set // putIndex to 0. } else if (expeditedPutIndex != expeditedTakeIndex || expeditedBuffer[expeditedTakeIndex] != null) { // The contents of the buffer wrap round the end // of the array. We have to perform two copies to // move its contents into the new buffer. int used = expeditedBuffer.length - expeditedTakeIndex; System.arraycopy(expeditedBuffer, expeditedTakeIndex, newBuffer, 0, used); System.arraycopy(expeditedBuffer, 0, newBuffer, used, expeditedPutIndex); expeditedPutIndex += used; } else { expeditedPutIndex = 0; } // The contents of the buffer now begin at 0 - update the head pointer. expeditedTakeIndex = 0; // The buffer's capacity has been increased so update the count of the // empty slots to reflect this. expeditedBuffer = (T[]) newBuffer; } } // D312598 } private static class BoundedBufferLock extends Object { // An easily-identified marker class used for locking } // F743-11444 - New method // F743-12896 - Start protected synchronized boolean cancel(Object x) { // First check the expedited buffer synchronized (lock) { if (expeditedPutIndex > expeditedTakeIndex) { for (int i = expeditedTakeIndex; i < expeditedPutIndex; i++) { if (expeditedBuffer[i] == x) { System.arraycopy(expeditedBuffer, i + 1, expeditedBuffer, i, expeditedPutIndex - i - 1); expeditedPutIndex--; expeditedBuffer[expeditedPutIndex] = null; numberOfUsedExpeditedSlots.getAndDecrement(); // D615053 return true; } } } else if (expeditedPutIndex != expeditedTakeIndex || expeditedBuffer[expeditedTakeIndex] != null) { for (int i = expeditedTakeIndex; i < buffer.length; i++) { if (expeditedBuffer[i] == x) { if (i != expeditedBuffer.length - 1) { System.arraycopy(expeditedBuffer, i + 1, expeditedBuffer, i, expeditedBuffer.length - i - 1); } if (expeditedPutIndex != 0) { expeditedBuffer[expeditedBuffer.length - 1] = expeditedBuffer[0]; System.arraycopy(expeditedBuffer, 1, expeditedBuffer, 0, expeditedPutIndex - 1); expeditedPutIndex--; } else { expeditedPutIndex = expeditedBuffer.length - 1; } expeditedBuffer[expeditedPutIndex] = null; numberOfUsedExpeditedSlots.getAndDecrement(); // D615053 return true; } } // D610567 - Scan first section of expedited BoundedBuffer for (int i = 0; i < expeditedPutIndex; i++) { if (expeditedBuffer[i] == x) { System.arraycopy(expeditedBuffer, i + 1, expeditedBuffer, i, expeditedPutIndex - i - 1); expeditedPutIndex--; expeditedBuffer[expeditedPutIndex] = null; numberOfUsedExpeditedSlots.getAndDecrement(); // D615053 return true; } } } // Next check the main buffer if (putIndex > takeIndex) { for (int i = takeIndex; i < putIndex; i++) { if (buffer[i] == x) { System.arraycopy(buffer, i + 1, buffer, i, putIndex - i - 1); putIndex--; buffer[putIndex] = null; numberOfUsedSlots.getAndDecrement(); // D615053 return true; } } } else if (putIndex != takeIndex || buffer[takeIndex] != null) { for (int i = takeIndex; i < buffer.length; i++) { if (buffer[i] == x) { if (i != buffer.length - 1) { System.arraycopy(buffer, i + 1, buffer, i, buffer.length - i - 1); } if (putIndex != 0) { buffer[buffer.length - 1] = buffer[0]; System.arraycopy(buffer, 1, buffer, 0, putIndex - 1); putIndex--; } else { putIndex = buffer.length - 1; } buffer[putIndex] = null; numberOfUsedSlots.getAndDecrement(); // D615053 return true; } } // D610567 - Scan first section of BoundedBuffer for (int i = 0; i < putIndex; i++) { if (buffer[i] == x) { System.arraycopy(buffer, i + 1, buffer, i, putIndex - i - 1); putIndex--; buffer[putIndex] = null; numberOfUsedSlots.getAndDecrement(); // D615053 return true; } } } } return false; } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.Collection#iterator() */ @Override public Iterator<T> iterator() { List<T> bufferAsList = new ArrayList<T>(); synchronized (this) { synchronized (lock) { //First add the items in the expedited buffer //Check if we wrap around the end of the array before iterating if (expeditedPutIndex > expeditedTakeIndex) { for (int i = expeditedTakeIndex; i <= expeditedPutIndex; i++) { bufferAsList.add(expeditedBuffer[i]); } } else { //We wrap around the array. Loop through in two passes(upper and lower) for (int i = expeditedTakeIndex; i < expeditedBuffer.length; i++) { bufferAsList.add(expeditedBuffer[i]); } for (int i = 0; i < expeditedPutIndex; i++) { bufferAsList.add(expeditedBuffer[i]); } } //Next add the items in the main buffer //Check if we wrap around the end of the array before iterating if (putIndex > takeIndex) { for (int i = takeIndex; i <= putIndex; i++) { bufferAsList.add(buffer[i]); } } else { //We wrap around the array. Loop through in two passes(upper and lower) for (int i = takeIndex; i < buffer.length; i++) { bufferAsList.add(buffer[i]); } for (int i = 0; i < putIndex; i++) { bufferAsList.add(buffer[i]); } } } } return bufferAsList.iterator(); } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.Collection#toArray() */ @Override public Object[] toArray() { int size = size(); Object[] retArray; if (size < 1) { retArray = new Object[] {}; } else { retArray = new Object[size]; int retArrayIndex = 0; synchronized (this) { synchronized (lock) { //Add the items in the expedited buffer first //Check if we wrap around the end of the array before iterating if (expeditedPutIndex > expeditedTakeIndex) { for (int i = expeditedTakeIndex; i <= expeditedPutIndex; i++) { retArray[retArrayIndex] = expeditedBuffer[i]; retArrayIndex++; } } else { //We wrap around the array. Loop through in two passes(upper and lower) for (int i = expeditedTakeIndex; i < expeditedBuffer.length; i++) { retArray[retArrayIndex] = expeditedBuffer[i]; retArrayIndex++; } for (int i = 0; i < expeditedPutIndex; i++) { retArray[retArrayIndex] = expeditedBuffer[i]; retArrayIndex++; } } //Next add the items in the main buffer //Check if we wrap around the end of the array before iterating if (putIndex > takeIndex) { for (int i = takeIndex; i <= putIndex; i++) { retArray[retArrayIndex] = buffer[i]; retArrayIndex++; } } else { //We wrap around the array. Loop through in two passes(upper and lower) for (int i = takeIndex; i < buffer.length; i++) { retArray[retArrayIndex] = buffer[i]; retArrayIndex++; } for (int i = 0; i < putIndex; i++) { retArray[retArrayIndex] = buffer[i]; retArrayIndex++; } } } } } return retArray; } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.Collection#toArray(T[]) */ @Override @SuppressWarnings("unchecked") public <E> E[] toArray(E[] a) { if (a.length < size()) { a = (E[]) Array.newInstance(a.getClass().getComponentType(), size()); } int aIndex = 0; synchronized (this) { synchronized (lock) { //First add anything in the expedited buffer //Check if we wrap around the end of the array before iterating if (expeditedPutIndex > expeditedTakeIndex) { for (int i = expeditedTakeIndex; i <= expeditedPutIndex; i++) { a[aIndex] = (E) expeditedBuffer[i]; aIndex++; } } else { //We wrap around the array. Loop through in two passes(upper and lower) for (int i = expeditedTakeIndex; i < expeditedBuffer.length; i++) { a[aIndex] = (E) expeditedBuffer[i]; aIndex++; } for (int i = 0; i < expeditedPutIndex; i++) { a[aIndex] = (E) expeditedBuffer[i]; aIndex++; } } //Now add the items in the main buffer //Check if we wrap around the end of the array before iterating if (putIndex > takeIndex) { for (int i = takeIndex; i <= putIndex; i++) { a[aIndex] = (E) buffer[i]; aIndex++; } } else { //We wrap around the array. Loop through in two passes(upper and lower) for (int i = takeIndex; i < buffer.length; i++) { a[aIndex] = (E) buffer[i]; aIndex++; } for (int i = 0; i < putIndex; i++) { a[aIndex] = (E) buffer[i]; aIndex++; } } } } if (a.length > size()) { a[size()] = null; } return a; } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.concurrent.BlockingQueue#contains(java.lang.Object) */ @Override public boolean contains(Object o) { synchronized (this) { synchronized (lock) { //First check the expedited buffer //Check if we wrap around the end of the array before iterating if (expeditedPutIndex > expeditedTakeIndex) { for (int i = expeditedTakeIndex; i <= expeditedPutIndex; i++) { if (o.equals(expeditedBuffer[i])) { return true; } } } else { //We wrap around the array. Loop through in two passes(upper and lower) for (int i = expeditedTakeIndex; i < expeditedBuffer.length; i++) { if (o.equals(expeditedBuffer[i])) { return true; } } for (int i = 0; i < expeditedPutIndex; i++) { if (o.equals(expeditedBuffer[i])) { return true; } } } //Next check the main buffer //Check if we wrap around the end of the array before iterating if (putIndex > takeIndex) { for (int i = takeIndex; i <= putIndex; i++) { if (o.equals(buffer[i])) { return true; } } } else { //We wrap around the array. Loop through in two passes(upper and lower) for (int i = takeIndex; i < buffer.length; i++) { if (o.equals(buffer[i])) { return true; } } for (int i = 0; i < putIndex; i++) { if (o.equals(buffer[i])) { return true; } } } } } return false; } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.Collection#containsAll(java.util.Collection) */ @Override public boolean containsAll(Collection<?> c) { for (Object e : c) if (!contains(e)) return false; return true; } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.concurrent.BlockingQueue#remove(java.lang.Object) */ @Override public boolean remove(Object o) { if (o == null) { return false; } if (size() == 0) { return false; } synchronized (this) { //First check the expedited buffer synchronized (lock) { //Check if we wrap around the end of the array before iterating if (expeditedPutIndex > expeditedTakeIndex) { for (int i = expeditedTakeIndex; i <= expeditedPutIndex; i++) { if (o.equals(expeditedBuffer[i])) { //Remove element and shift all remaining elements for (int j = i; j < expeditedPutIndex; j++) { expeditedBuffer[j] = expeditedBuffer[j + 1]; } //Null the putIndex expeditedBuffer[expeditedPutIndex] = null; expeditedPutIndex--; //Decrement used slots counter numberOfUsedExpeditedSlots.getAndDecrement(); //TODO if expedited is added for put or offer with timeout add notification here return true; } } } else { //We wrap around the array. Loop through in two passes(upper and lower) for (int i = expeditedTakeIndex; i < expeditedBuffer.length; i++) { if (o.equals(expeditedBuffer[i])) { //Remove element and shift all remaining elements up for (int j = i; j > expeditedTakeIndex; j--) { expeditedBuffer[j] = expeditedBuffer[j - 1]; } //Null the putIndex expeditedBuffer[expeditedTakeIndex] = null; if (expeditedTakeIndex == expeditedBuffer.length - 1) { expeditedTakeIndex = 0; } else { expeditedTakeIndex++; } //Decrement used slots counter numberOfUsedExpeditedSlots.getAndDecrement(); //TODO if expedited is added for put or offer with timeout add notification here return true; } } for (int i = 0; i < expeditedPutIndex; i++) { if (o.equals(expeditedBuffer[i])) { //Remove element and shift all remaining elements down for (int j = i; j < expeditedPutIndex; j++) { expeditedBuffer[j] = expeditedBuffer[j + 1]; } //Null the putIndex expeditedBuffer[expeditedPutIndex] = null; expeditedPutIndex--; //Decrement used slots counter numberOfUsedExpeditedSlots.getAndDecrement(); //TODO if expedited is added for put or offer with timeout add notification here return true; } } } //Next check the main buffer //Check if we wrap around the end of the array before iterating if (putIndex > takeIndex) { for (int i = takeIndex; i <= putIndex; i++) { if (o.equals(buffer[i])) { //Remove element and shift all remaining elements for (int j = i; j < putIndex; j++) { buffer[j] = buffer[j + 1]; } //Null the putIndex buffer[putIndex] = null; putIndex--; //Decrement used slots counter numberOfUsedSlots.getAndDecrement(); //Notify a waiting put thread that space has cleared notifyPut_(); return true; } } } else { //We wrap around the array. Loop through in two passes(upper and lower) for (int i = takeIndex; i < buffer.length; i++) { if (o.equals(buffer[i])) { //Remove element and shift all remaining elements up for (int j = i; j > takeIndex; j--) { buffer[j] = buffer[j - 1]; } //Null the putIndex buffer[takeIndex] = null; if (takeIndex == buffer.length - 1) { takeIndex = 0; } else { takeIndex++; } //Decrement used slots counter numberOfUsedSlots.getAndDecrement(); //Notify a waiting put thread that space has cleared notifyPut_(); return true; } } for (int i = 0; i < putIndex; i++) { if (o.equals(buffer[i])) { //Remove element and shift all remaining elements down for (int j = i; j < putIndex; j++) { buffer[j] = buffer[j + 1]; } //Null the putIndex buffer[putIndex] = null; putIndex--; //Decrement used slots counter numberOfUsedSlots.getAndDecrement(); //Notify a waiting put thread that space has cleared notifyPut_(); return true; } } } } } return false; } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.concurrent.BlockingQueue#drainTo(java.util.Collection) */ @Override public int drainTo(Collection<? super T> c) { return drainTo(c, Integer.MAX_VALUE); } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.concurrent.BlockingQueue#drainTo(java.util.Collection, int) */ @Override public int drainTo(Collection<? super T> c, int maxElements) { //TODO- The elements aren't added to the given collection... if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); int n = Math.min(maxElements, size()); int numRemaining = n; synchronized (this) { synchronized (lock) { //Retrieve and remove at most n elements from the expedited buffer and add them to the passed collection for (int i = 0; i < n; i++) { T retrieved = expeditedExtract(); numRemaining = n - i; if (retrieved != null) { numberOfUsedExpeditedSlots.getAndDecrement(); //TODO if expedited is added for put or offer with timeout add notification here } else { break; //retrieved is null so nothing left in the expedited buffer, move on to the main buffer } } //Retrieve and remove at most numRemaining elements and add them to the passed collection for (int i = 0; i < numRemaining; i++) { T retrieved = extract(); numberOfUsedSlots.getAndDecrement(); if (retrieved != null) { notifyPut_(); } } } } return n; } //---------------------- // Unsupported methods //---------------------- /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.Collection#addAll(java.util.Collection) */ @Override public boolean addAll(Collection<? extends T> c) { //Optional Collection method throw new UnsupportedOperationException(); } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.Collection#removeAll(java.util.Collection) */ @Override public boolean removeAll(Collection<?> c) { //Optional Collection method throw new UnsupportedOperationException(); } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.Collection#retainAll(java.util.Collection) */ @Override public boolean retainAll(Collection<?> c) { //Optional Collection method throw new UnsupportedOperationException(); } /* * @awisniew - ADDED * * (non-Javadoc) * * @see java.util.Collection#clear() */ @Override public void clear() { //Optional Collection method throw new UnsupportedOperationException(); } //@awisniew - DELETED //public void setThreadPool(ThreadPool threadPool) { // threadPool_ = threadPool; //} }
kgibm/open-liberty
dev/com.ibm.ws.threading/src/com/ibm/ws/threading/internal/BoundedBuffer.java
Java
epl-1.0
56,371
import React from 'react'; import PropTypes from 'prop-types'; import {Button, Modal} from 'react-bootstrap'; import FontAwesome from 'react-fontawesome'; import axios from 'axios'; import Server from '../helpers/Server'; import CompareDocs from './CompareDocs'; import {get} from "lodash"; import TreeViewUtils from "../helpers/TreeViewUtils"; /** * Display modal content. */ export class ModalCompareDocs extends React.Component { constructor(props) { super(props); this.state = { showSearchResults: false , message: this.props.labels.msg1 , messageIcon: this.messageIcons.info , data: {values: [{"id": "", "value:": ""}]} , options: { sizePerPage: 30 , sizePerPageList: [5, 15, 30] , onSizePerPageList: this.onSizePerPageList , hideSizePerPage: true , paginationShowsTotal: true } , selectRow: { mode: 'radio' // or checkbox , hideSelectColumn: (this.props.hasCallback ? false : true) , clickToSelect: false , onSelect: this.handleRowSelect , className: "App-row-select" , selected: [] } , showSelectionButtons: false , selectedId: "" , selectedValue: "" , selectedSeq: "" , selectedIdPartsPrompt: "Select one or more ID parts, then click on the search icon:" , selectedIdParts: [ {key: "domain", label: ""}, {key: "topic", label: ""}, {key: "key", label: ""} ] , showIdPartSelector: false , showModalCompareDocs: false , idColumnSize: "80px" , _isMounted: get(this.state,"_isMounted", false) , _requestTokens: get(this.state,"_requestTokens", new Map()) }; this.close = this.close.bind(this); this.open = this.open.bind(this); this.fetchData = this.fetchData.bind(this); this.handleFetchCallback = this.handleFetchCallback.bind(this); this.oldFetchData = this.oldFetchData.bind(this); this.setMessage = this.setMessage.bind(this); this.handleRowSelect = this.handleRowSelect.bind(this); }; componentDidMount = () => { this.setState({_isMounted: true}); }; componentWillUnmount = () => { if (this.state && this.state._requestTokens) { for (let token of this.state._requestTokens.keys()) { try { Server.cancelRequest(token); } catch (error) { // ignore } } } this.setState({_isMounted: false}); }; componentWillMount = () => { this.setState({ showModal: this.props.showModal , domain: "*" , selectedBook: "*" , selectedChapter: "*" , docProp: "id" , matcher: "rx" , query: ".*~" + this.props.selectedIdParts[1].label + "~" + this.props.selectedIdParts[2].label + "$" } , function () { this.fetchData(); } ); }; /** * font-awesome icons for messages * @type {{info: string, warning: string, error: string}} */ messageIcons = { info: "info-circle" , warning: "lightbulb-o" , error: "exclamation-triangle" // , toggleOn: "eye" // , toggleOff: "eye-slash" , toggleOn: "toggle-on" , toggleOff: "toggle-off" , simpleSearch: "minus" , advancedSearch: "bars" , idPatternSearch: "key" }; setMessage(message) { this.setState({ message: message }); } fetchData = () => { let requestTokens = this.state._requestTokens; const requestToken = Server.getRequestToken(); requestTokens.set(requestToken,"live"); this.setState({ message: this.props.labels.msg2 , messageIcon: this.messageIcons.info , _requestTokens: requestTokens }); let parms = "?t=" + encodeURIComponent(this.props.docType) + "&d=" + encodeURIComponent(this.state.domain) + "&b=" + encodeURIComponent(this.state.selectedBook) + "&c=" + encodeURIComponent(this.state.selectedChapter) + "&q=" + encodeURIComponent(this.state.query) + "&p=" + encodeURIComponent(this.state.docProp) + "&m=" + encodeURIComponent(this.state.matcher) ; Server.getTextComparison( this.props.session.restServer , this.props.session.userInfo.username , this.props.session.userInfo.password , parms , this.handleFetchCallback , requestToken ); this.setState({_requestTokens: requestTokens}); }; handleFetchCallback = (response) => { if (this.state._isMounted && response && response.data && response.data.values) { this.state._requestTokens.delete(requestToken); // if one of the values is greek, then make it the selected row let selectedId = ""; let selectedValue = ""; let selectRow = this.state.selectRow; if (response.data.values) { // select the Greek value. If not, if there is only one item, select it let theItem = response.data.values.find(o => o.id.startsWith("gr_")); if (theItem) { selectedId = theItem.id; selectedValue = theItem.value; selectRow.selected = [selectedId]; } else { if (response.data.values.length === 1) { theItem = response.data.values[0]; selectedId = theItem.id; selectedValue = theItem.value; selectRow.selected = [selectedId]; } } } this.setState({ selectRow: selectRow , selectedId: selectedId , selectedValue: selectedValue , data: response.data } ); let resultCount = 0; let message = this.props.labels.foundNone; let found = this.props.labels.foundMany; if (response.data.valueCount) { resultCount = response.data.valueCount; if (resultCount === 0) { message = this.props.labels.foundNone; } else if (resultCount === 1) { message = this.props.labels.foundOne; } else { message = found + " " + resultCount + "."; } } this.setState({ message: message , messageIcon: this.messageIcons.info , showSearchResults: true } ); }; }; oldFetchData() { let requestTokens = this.state._requestTokens; const requestToken = Server.getRequestToken(); requestTokens.set(requestToken,"live"); this.setState({ message: this.props.labels.msg2 , messageIcon: this.messageIcons.info , _requestTokens: requestTokens }); let config = { auth: { username: this.props.session.userInfo.username , password: this.props.session.userInfo.password } }; let parms = "?t=" + encodeURIComponent(this.props.docType) + "&d=" + encodeURIComponent(this.state.domain) + "&b=" + encodeURIComponent(this.state.selectedBook) + "&c=" + encodeURIComponent(this.state.selectedChapter) + "&q=" + encodeURIComponent(this.state.query) + "&p=" + encodeURIComponent(this.state.docProp) + "&m=" + encodeURIComponent(this.state.matcher) ; let path = this.props.session.restServer + Server.getWsServerDbApi() + 'docs' + parms; axios.get(path, config) .then(response => { if (this.state._requestTokens.has(requestToken)) { this.state._requestTokens.delete(requestToken); // if one of the values is greek, then make it the selected row let selectedId = ""; let selectedValue = ""; let selectRow = this.state.selectRow; if (response.data.values) { // select the Greek value. If not, if there is only one item, select it let theItem = response.data.values.find(o => o.id.startsWith("gr_")); if (theItem) { selectedId = theItem.id; selectedValue = theItem.value; selectRow.selected = [selectedId]; } else { if (response.data.values.length === 1) { theItem = response.data.values[0]; selectedId = theItem.id; selectedValue = theItem.value; selectRow.selected = [selectedId]; } } } this.setState({ selectRow: selectRow , selectedId: selectedId , selectedValue: selectedValue , data: response.data } ); let resultCount = 0; let message = this.props.labels.foundNone; let found = this.props.labels.foundMany; if (response.data.valueCount) { resultCount = response.data.valueCount; if (resultCount === 0) { message = this.props.labels.foundNone; } else if (resultCount === 1) { message = this.props.labels.foundOne; } else { message = found + " " + resultCount + "."; } } this.setState({ message: message , messageIcon: this.messageIcons.info , showSearchResults: true } ); } }) .catch((error) => { if (this.state._requestTokens.has(requestToken)) { this.state._requestTokens.delete(requestToken); let message = error.message; let messageIcon = this.messageIcons.error; if (error && error.response && error.response.status === 404) { message = this.props.labels.foundNone; messageIcon = this.messageIcons.warning; this.setState({data: message, message: message, messageIcon: messageIcon}); } } }); } close() { this.setState({showModal: false}); if (this.props.onClose) { this.props.onClose( this.state.selectedId , this.state.selectedValue , this.state.selectedSeq ); } }; open() { this.setState({showModal: true}); }; handleRowSelect = (row, isSelected, e) => { let selectRow = this.state.selectRow; selectRow.selected = [row["id"]]; let idParts = row["id"].split("~"); this.setState({ selectRow: selectRow , selectedId: row["id"] , selectedIdParts: [ {key: "domain", label: idParts[0]}, {key: "topic", label: idParts[1]}, {key: "key", label: idParts[2]} ] , selectedValue: row["value"] , selectedSeq: row["seq"] }); }; render() { return ( <div> <Modal backdrop={"static"} show={this.state.showModal} onHide={this.close}> <Modal.Header closeButton> <Modal.Title>{this.props.title}</Modal.Title> </Modal.Header> <Modal.Body> {this.props.hasCallback && <div className="control-label">{this.props.labels.selectVersion}</div> } <div>{this.props.labels.resultLabel}: <span className="App App-message"><FontAwesome name={this.state.messageIcon}/>{this.state.message}</span> </div> <CompareDocs session={this.props.session} handleRowSelect={this.handleRowSelect} title={this.props.title} docType={this.props.docType} selectedIdParts={this.props.selectedIdParts} labels={this.props.labels} /> </Modal.Body> <Modal.Footer> <Button onClick={this.close}>{this.props.labels.close}</Button> </Modal.Footer> </Modal> </div> ); } } ModalCompareDocs.propTypes = { session: PropTypes.object.isRequired , onClose: PropTypes.func , showModal: PropTypes.bool.isRequired , hasCallback: PropTypes.func , title: PropTypes.string.isRequired , docType: PropTypes.string.isRequired , selectedIdParts: PropTypes.array.isRequired , labels: PropTypes.object.isRequired , instructions: PropTypes.string }; ModalCompareDocs.defaultProps = { }; export default ModalCompareDocs;
OCMC-Translation-Projects/ioc-liturgical-react
src/modules/ModalCompareDocs.js
JavaScript
epl-1.0
12,601
package org.eclipse.graphiti.fx.ga; import java.util.ArrayList; import org.eclipse.emf.common.util.EList; import org.eclipse.graphiti.mm.algorithms.Polyline; import org.eclipse.graphiti.mm.algorithms.styles.Point; public class FxPolyline extends FxGraphicsAlgorithm<javafx.scene.shape.Polyline> { private Polyline polyline; private javafx.scene.shape.Polyline fxPolyline; public FxPolyline(Polyline polyline) { super(polyline, new javafx.scene.shape.Polyline()); this.polyline = polyline; this.fxPolyline = getShape(); initialize(); } @Override protected void initialize() { super.initialize(); // Points EList<Point> points = polyline.getPoints(); ArrayList<Double> list = new ArrayList<>(points.size()); for (Point point : points) { list.add(new Double(point.getX())); list.add(new Double(point.getY())); } fxPolyline.getPoints().addAll(list); } @Override protected void setX(double x) { // Nothing to do } @Override protected void setY(double y) { // Nothing to do } @Override protected void setWidth(double width) { // Nothing to do } @Override protected void setHeight(double height) { // Nothing to do } }
mwenz/graphitiFX
org.eclipse.graphiti.fx/src/org/eclipse/graphiti/fx/ga/FxPolyline.java
Java
epl-1.0
1,234
/** * generated by Xtext */ package org.eclipse.xtext.xtextTest.impl; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; import org.eclipse.xtext.xtextTest.AbstractElement; import org.eclipse.xtext.xtextTest.Group; import org.eclipse.xtext.xtextTest.XtextTestPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Group</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.eclipse.xtext.xtextTest.impl.GroupImpl#getElements <em>Elements</em>}</li> * </ul> * * @generated */ public class GroupImpl extends AbstractElementImpl implements Group { /** * The cached value of the '{@link #getElements() <em>Elements</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getElements() * @generated * @ordered */ protected EList<AbstractElement> elements; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected GroupImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return XtextTestPackage.Literals.GROUP; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<AbstractElement> getElements() { if (elements == null) { elements = new EObjectContainmentEList<AbstractElement>(AbstractElement.class, this, XtextTestPackage.GROUP__ELEMENTS); } return elements; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case XtextTestPackage.GROUP__ELEMENTS: return ((InternalEList<?>)getElements()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case XtextTestPackage.GROUP__ELEMENTS: return getElements(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case XtextTestPackage.GROUP__ELEMENTS: getElements().clear(); getElements().addAll((Collection<? extends AbstractElement>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case XtextTestPackage.GROUP__ELEMENTS: getElements().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case XtextTestPackage.GROUP__ELEMENTS: return elements != null && !elements.isEmpty(); } return super.eIsSet(featureID); } } //GroupImpl
miklossy/xtext-core
org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/xtextTest/impl/GroupImpl.java
Java
epl-1.0
3,661