text
stringlengths
2
1.04M
meta
dict
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>icharate: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.2 / icharate - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> icharate <small> 8.9.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-12 07:16:56 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-12 07:16:56 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.11.2 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.10.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.2 Official release 4.10.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;http://www.labri.fr/perso/anoun/Icharate&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Icharate&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: multimodal categorial grammars&quot; &quot;keyword: syntax/semantics interface&quot; &quot;keyword: higher-order logic&quot; &quot;keyword: meta-linguistics&quot; &quot;category: Computer Science/Formal Languages Theory and Automata&quot; &quot;date: 2003-2006&quot; ] authors: [ &quot;Houda Anoun &lt;[email protected]&gt;&quot; &quot;Pierre Casteran &lt;[email protected]&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/icharate/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/icharate.git&quot; synopsis: &quot;Icharate: A logical Toolkit for Multimodal Categorial Grammars&quot; description: &quot;&quot;&quot; The logical toolkit ICHARATE is built upon a formalization of multimodal categorial grammars in Coq proof assistant. This toolkit aims at facilitating the study of these complicated formalisms by allowing users to build interactively the syntactic derivations of different sentences, compute their semantic interpretations and also prove universal properties of entire classes of grammars using a collection of already established derived rules. Several tactics are defined to ease the interaction with users.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/icharate/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=fe48c0335d136d85a028b467f073194b&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-icharate.8.9.0 coq.8.11.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2). The following dependencies couldn&#39;t be met: - coq-icharate -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-icharate.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "1c33d3a4f5fe5cccc761abbd70332c26", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 159, "avg_line_length": 41.2752808988764, "alnum_prop": 0.5624064243909078, "repo_name": "coq-bench/coq-bench.github.io", "id": "f9100932f4c97642b248369ca5b7aa65113116e5", "size": "7372", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.11.2/icharate/8.9.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php /** * log-to-file * * @file: Decorator.php * @author Ashterix <[email protected]> * * Class - Decorator * @description * * Created by JetBrains PhpStorm. * Date: 18.03.2015 * Time: 13:57 */ namespace LogToFile; class Decorator { const FORMAT_DATE = "Y-m-d"; const FORMAT_TIME = "H:s:i"; /** * @var string Message after wrapping */ private $wrappedMsg = ''; /** * @description Add separator to wrapper * * @param string $separator * @param int $countRepetitions * * @return $this */ public function addSeparator($separator = '*', $countRepetitions = 1) { $this->wrappedMsg .= str_repeat($separator, $countRepetitions); return $this; } /** * @description Add newline * * @return $this */ public function addNewline() { $this->wrappedMsg .= PHP_EOL; return $this; } /** * @description Add date to wrapper * * @return $this */ public function addDate() { $this->wrappedMsg .= date(self::FORMAT_DATE); return $this; } /** * @description Add time to wrapper * * @return $this */ public function addTime() { $this->wrappedMsg .= date(self::FORMAT_TIME); return $this; } /** * @description Add message to wrapper * * @param $msg * * @return $this */ public function addMsg($msg) { $this->wrappedMsg .= $msg; return $this; } /** * @description Return wrapped message * * @return string */ public function getBuildMsg() { $return = $this->wrappedMsg; $this->wrappedMsg = ''; return $return; } }
{ "content_hash": "1e3508cfd652e0665e5c8730b15e5ad5", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 73, "avg_line_length": 16.766355140186917, "alnum_prop": 0.5228539576365663, "repo_name": "Ashterix/log-to-file", "id": "b9459d7f29bda9019b989abaf4f55792d67706a5", "size": "1794", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/LogToFile/Decorator.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "4427" } ], "symlink_target": "" }
var ShowDateModule = Module.Base.extend({ prototype: { _ready: function _ready() { this.element.innerHTML = [ '<div class="module-body">', '<p>Like a long, lost love, I\'ve been waiting for you. *sniff*</p>', '<p>Finally you arrived!</p>', '</div>' ].join(""); } } });
{ "content_hash": "2713afa735133272e000bbd390b63f98", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 74, "avg_line_length": 18.9375, "alnum_prop": 0.5544554455445545, "repo_name": "gburghardt/foundry", "id": "b5ce2f2bea25767c6254c0c2737e2a9026a7405d", "size": "303", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demo/js/modules/show_date_module.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5452" }, { "name": "JavaScript", "bytes": "157809" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "a9db3ddbfbca3c9953f4c91a5053882d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "3120a784472fe95071d379bd56eec2dda0863852", "size": "184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Asparagaceae/Drimia/Drimia elata/ Syn. Idothea elata/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<dom-module id="polyclinic-display"> <style> .polyclinic { margin-left: 58px; min-height: 50px; cursor: pointer; } .name { font-weight: bold; } .desc { color: #333; } </style> <template> <paper-material> <div class="polyclinic" elevation="1" on-mouseover="mouseover" on-mouseout="mouseout" on-click="click"> <div class="name">{{polyclinic.name}}</div> <div class="body"> <span>{{desc}}</span> </div> </paper-material> </template> <script> Polymer({ is: "polyclinic-display", ready: function() { var isClicked = false; }, properties: { polyclinic: { type: Object, computed: "getDesc(polyclinic)" }, desc: { type: String } }, getDesc: function(polyclinic) { return ((polyclinic.waitingNumber) ? ('<div>Number of waiting patients: ' + polyclinic.waitingNumber + '<div><div>Waiting Time: ' + (polyclinic.waitingTime || 0) + ' minutes</div>') : ("Polyclinic is closed!")); }, mouseover: function() { allCustomLayers['Polyclinics'][this.polyclinic.properties.id].openPopup(); }, mouseout: function() { allCustomLayers['Polyclinics'][this.polyclinic.properties.id].closePopup(); }, click: function() { this.isClicked = !this.isClicked; if (isClicked) { mouseover; } else { mouseout; } } }) </script> </dom-module>
{ "content_hash": "198a158f2c5627c38d9b17242ab5c7d9", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 149, "avg_line_length": 29.529411764705884, "alnum_prop": 0.4168326693227092, "repo_name": "kahkhang/hyde", "id": "982bc0d48b10801103285cfcb1fcbe7ffb165ead", "size": "2008", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/custom_polymer_elements/polyclinic-display.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "72375" }, { "name": "HTML", "bytes": "67966" }, { "name": "JavaScript", "bytes": "639416" }, { "name": "Makefile", "bytes": "222" }, { "name": "Shell", "bytes": "1068" } ], "symlink_target": "" }
using Abot.Util; using NUnit.Framework; using System; using System.Threading; namespace Abot.Tests.Unit.Util { [TestFixture] public abstract class ThreadManagerTest { IThreadManager _unitUnderTest; const int MAXTHREADS = 10; protected abstract IThreadManager GetInstance(int maxThreads); [SetUp] public void SetUp() { _unitUnderTest = GetInstance(MAXTHREADS); } [TearDown] public void TearDown() { if (_unitUnderTest != null) _unitUnderTest.Dispose(); } [Test] public void Constructor_CreatesDefaultInstance() { Assert.IsNotNull(_unitUnderTest); Assert.AreEqual(MAXTHREADS, _unitUnderTest.MaxThreads); } [Test] [ExpectedException(typeof(ArgumentException))] public void Constructor_OverMax() { _unitUnderTest = GetInstance(101); } [Test] [ExpectedException(typeof(ArgumentException))] public void Constructor_BelowMinimum() { _unitUnderTest = GetInstance(0); } [Test] public void HasRunningThreads() { //No threads should be running Assert.IsFalse(_unitUnderTest.HasRunningThreads()); //Add word to be run on a thread _unitUnderTest.DoWork(() => System.Threading.Thread.Sleep(300)); System.Threading.Thread.Sleep(20); //Should have 1 running thread Assert.IsTrue(_unitUnderTest.HasRunningThreads()); //Wait for the 1 running thread to finish System.Threading.Thread.Sleep(400); //Should have 0 threads running since the thread should have completed by now Assert.IsFalse(_unitUnderTest.HasRunningThreads()); } [Test] public void DoWork_WorkItemsEqualToThreads_WorkIsCompletedAsync() { int count = 0; for (int i = 0; i < MAXTHREADS; i++) { _unitUnderTest.DoWork(() => { System.Threading.Thread.Sleep(5); Interlocked.Increment(ref count); }); } Assert.IsTrue(count < MAXTHREADS); System.Threading.Thread.Sleep(80);//was 20 but had to bump it up or the TaskThreadManager would fail, its way slower Assert.AreEqual(MAXTHREADS, count); } [Test] public void DoWork_MoreWorkThenThreads_WorkIsCompletedAsync() { int count = 0; for (int i = 0; i < 2 * MAXTHREADS; i++) { _unitUnderTest.DoWork(() => { System.Threading.Thread.Sleep(5); Interlocked.Increment(ref count); }); } //Assert.IsTrue(count < MAXTHREADS);//Manual has completed more then the thread count by the time it gets here System.Threading.Thread.Sleep(80);//was 20 but had to bump it up or the TaskThreadManager would fail, its way slower Assert.AreEqual(2 * MAXTHREADS, count); } [Test] public void DoWork_SingleThreaded_WorkIsCompletedSynchronously() { _unitUnderTest = GetInstance(1); int count = 0; for (int i = 0; i < MAXTHREADS; i++) { _unitUnderTest.DoWork(() => { System.Threading.Thread.Sleep(5); Interlocked.Increment(ref count); }); } Assert.AreEqual(MAXTHREADS, count); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void DoWork_ActionIsNull() { _unitUnderTest.DoWork(null); } [Test] [ExpectedException(typeof(InvalidOperationException))] public void DoWork_CalledAfterAbortAll() { _unitUnderTest.AbortAll(); _unitUnderTest.DoWork(() => System.Threading.Thread.Sleep(10)); } [Test] public void Dispose() { Assert.IsTrue(_unitUnderTest is IDisposable); } [Test] public void Abort_SetsHasRunningThreadsToZero() { for (int i = 0; i < 2 * MAXTHREADS; i++) { _unitUnderTest.DoWork(() => System.Threading.Thread.Sleep(5)); } _unitUnderTest.AbortAll(); Assert.IsFalse(_unitUnderTest.HasRunningThreads()); } } }
{ "content_hash": "0b50e4aeac8539dbb67aba72ddb6bc26", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 128, "avg_line_length": 29.630573248407643, "alnum_prop": 0.5382631126397248, "repo_name": "coveo/abot", "id": "abb35a6e0e06b7691a3783f9f3e2c3267d887e5b", "size": "4654", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "Abot.Tests.Unit/Util/ThreadManagerTest.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "109" }, { "name": "C#", "bytes": "610097" }, { "name": "CSS", "bytes": "979" } ], "symlink_target": "" }
import unittest from sql import For, Table class TestFor(unittest.TestCase): def test_for(self): for_ = For('UPDATE', Table('t1'), Table('t2'), nowait=True) self.assertEqual(str(for_), 'FOR UPDATE OF "t1", "t2" NOWAIT')
{ "content_hash": "81ba9f6e2d50d336edfe6840fda871c3", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 70, "avg_line_length": 27, "alnum_prop": 0.6378600823045267, "repo_name": "shnergle/ShnergleServer", "id": "cf0b940206e6dea8a27195030978dfcf4d44b154", "size": "1853", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site-packages/sql/tests/test_for.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "774901" } ], "symlink_target": "" }
import React, { memo } from 'react'; import Link from 'next/link'; import { Spinner } from 'reactstrap'; import { APP_TITLE } from 'lib/config'; import { ReaderControlsContainer, ReaderControlsWrapper, ReaderControlsInfo, ReaderControlsActions, ReaderControlsLogo, ReaderControlsChapterInfo, ReaderControlsChapters } from './styles'; function ReaderLoading() { return ( <> <div style={{ opacity: 1, visibility: 'visible' }} > <ReaderControlsContainer> <ReaderControlsWrapper> <ReaderControlsInfo> <ReaderControlsLogo> <Link href="/"> <a>{APP_TITLE}</a> </Link> </ReaderControlsLogo> <ReaderControlsChapterInfo> <ReaderControlsChapters></ReaderControlsChapters> </ReaderControlsChapterInfo> </ReaderControlsInfo> <ReaderControlsActions></ReaderControlsActions> </ReaderControlsWrapper> </ReaderControlsContainer> </div> <div style={{ paddingTop: 'calc(40vh)', textAlign: 'center' }}> <Spinner style={{ width: '10rem', height: '10rem' }} type="grow" color="dark" /> </div> </> ); } export default memo(ReaderLoading);
{ "content_hash": "f68cf26fb0be884001bb1919194537a1", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 69, "avg_line_length": 25.98076923076923, "alnum_prop": 0.5692079940784603, "repo_name": "dvaJi/ReaderFront", "id": "27ff51438adc31beb7b7d061270987f5abd8cafa", "size": "1351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/web/src/components/Read/ReaderLoading.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16447" }, { "name": "HTML", "bytes": "23109" }, { "name": "JavaScript", "bytes": "619115" }, { "name": "Shell", "bytes": "1337" }, { "name": "TypeScript", "bytes": "65919" } ], "symlink_target": "" }
import os import csv from person import Person import urllib2 class Members: members = {} def add(self, person): self.members[person.name] = person def parse_tsv(self, string): lines = iter(string.splitlines()) r = csv.DictReader(lines, delimiter='\t') for row in r: person = Person(row) template = os.environ.get('PHOTO_URL_TEMPLATE') if template: person.photo_url = str.replace(os.environ.get('PHOTO_URL_TEMPLATE'), '%NAME%', person.photo) self.add(person) return self def load(self, resource): if (resource.startswith('http')): response = urllib2.urlopen(resource) tsv = response.read() return self.parse_tsv(tsv) else: return self.parse_tsv(open(resource).read())
{ "content_hash": "3a8bf8f7bf6717c4142737a1834b8868", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 108, "avg_line_length": 29.517241379310345, "alnum_prop": 0.5794392523364486, "repo_name": "LandRegistry/team-dashboard", "id": "c67c6cb06ad6d9bec3924a40493a869f38c65cc3", "size": "856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "team/members.py", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1580" }, { "name": "Python", "bytes": "11682" }, { "name": "Shell", "bytes": "429" } ], "symlink_target": "" }
function [D]=chooseDistance(aln) %Display a quest dialog for choosing a genetic distance % Molecular Biology & Evolution Toolbox, (C) 2004, if (isempty(aln)) error('Need aln.'); end switch (aln.seqtype) case (3) ButtonName=questdlg('What genetic distance do you want to use?', ... 'Select genetic distance model', ... 'DayHoff','JTT','WAG','JTT'); switch ButtonName, case 'DayHoff', disp('We''re using DayHoff distance.'); D=dp_dayhoff(aln); case 'JTT', disp('We''re using JTT distance.') D=dp_jtt(aln); case 'WAG', disp('We''re using WAG distance.'); D=dp_wag(aln); otherwise D=[]; end otherwise ButtonName=questdlg('What genetic distance do you want to use?', ... 'Select genetic distance model', ... 'LogDet','JC69','Kimura80','LogDet'); switch ButtonName, case 'LogDet', disp('We''re using LogDet (Lake''s) distance.'); D=dn_logdet(aln); case 'JC69', disp('We''re using Jukes & Cantor (1969) distance.') D=dn_jc(aln,1.0); case 'Kimura80', disp('We''re using Kimura 80 (2-Parameter) distance.'); D=dn_k2p(aln,1.0); otherwise D=[]; end end
{ "content_hash": "639bad47dfa36758574ada31e2f18062", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 69, "avg_line_length": 26.869565217391305, "alnum_prop": 0.5849514563106796, "repo_name": "RiboZones/RiboLab", "id": "3bdf27f202822029286a2530050566d4d3ef4759", "size": "1236", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ToolBoxes/mbetoolbox/private/chooseDistance.m", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "44" }, { "name": "C", "bytes": "1338856" }, { "name": "C++", "bytes": "22920" }, { "name": "HTML", "bytes": "136590" }, { "name": "M", "bytes": "4853" }, { "name": "Makefile", "bytes": "15751" }, { "name": "Mathematica", "bytes": "6010" }, { "name": "Matlab", "bytes": "2496907" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Search</title> <link rel="stylesheet" href="_static/basic.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="_static/bootstrap-3.1.0/css/bootstrap.min.css" type="text/css" /> <link rel="stylesheet" href="_static/bootstrap-3.1.0/css/bootstrap-theme.min.css" type="text/css" /> <link rel="stylesheet" href="_static/bootstrap-sphinx.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '0.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="_static/searchtools.js"></script> <script type="text/javascript" src="_static/js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="_static/js/jquery-fix.js"></script> <script type="text/javascript" src="_static/bootstrap-3.1.0/js/bootstrap.min.js"></script> <script type="text/javascript" src="_static/bootstrap-sphinx.js"></script> <script src="http://sagecell.sagemath.org/static/jquery.min.js"></script> <script src="http://sagecell.sagemath.org/static/embedded_sagecell.js"></script> <script>sagecell.makeSagecell({inputLocation: ".sage"});</script> <style type="text/css"> .sagecell .CodeMirror-scroll { overflow-y: hidden; overflow-x: auto; } .sagecell .CodeMirror { height: auto; } </style> <link rel="top" title="mechpy Documentation" href="index.html" /> <script type="text/javascript"> jQuery(function() { Search.loadIndex("searchindex.js"); }); </script> <script type="text/javascript" id="searchindexloader"></script> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'> <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'> <meta name="apple-mobile-web-app-capable" content="yes"> <style type="text/css"> div.admonition { background-color: whiteSmoke; border: 1px solid #bababa; } </style> </head> <body role="document"> <div id="navbar" class="navbar navbar-inverse navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <!-- .btn-navbar is used as the toggle for collapsed navbar content --> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.html"> mechpy Documentation</a> <span class="navbar-text navbar-version pull-left"><b>0.1</b></span> </div> <div class="collapse navbar-collapse nav-collapse"> <ul class="nav navbar-nav"> <li class="divider-vertical"></li> <li class="dropdown globaltoc-container"> <a role="button" id="dLabelGlobalToc" data-toggle="dropdown" data-target="#" href="index.html">Site <b class="caret"></b></a> <ul class="dropdown-menu globaltoc" role="menu" aria-labelledby="dLabelGlobalToc"><ul> <li class="toctree-l1"><a class="reference internal" href="mechpy.html">mechpy Documentation</a></li> <li class="toctree-l1"><a class="reference internal" href="mechpy.html#introduction">Introduction</a></li> <li class="toctree-l1"><a class="reference internal" href="mechpy.html#mechpy-modules">mechpy Modules</a><ul> <li class="toctree-l2"><a class="reference internal" href="mechpy.html#abaqus-and-abaqus-report">abaqus and abaqus_report</a></li> <li class="toctree-l2"><a class="reference internal" href="mechpy.html#catia">catia</a></li> <li class="toctree-l2"><a class="reference internal" href="mechpy.html#composites">composites</a></li> <li class="toctree-l2"><a class="reference internal" href="mechpy.html#design">design</a></li> <li class="toctree-l2"><a class="reference internal" href="mechpy.html#fem">fem</a></li> <li class="toctree-l2"><a class="reference internal" href="mechpy.html#math">math</a></li> <li class="toctree-l2"><a class="reference internal" href="mechpy.html#statics">statics</a></li> <li class="toctree-l2"><a class="reference internal" href="mechpy.html#units">units</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="mechpy.html#tutorials">Tutorials</a><ul> <li class="toctree-l2"><a class="reference internal" href="mechpy.html#importing-python-modules">Importing Python Modules</a></li> <li class="toctree-l2"><a class="reference internal" href="mechpy.html#converting-an-ipython-notebook-to-an-html-document">Converting an ipython notebook to an html document</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="mechpy.html#references">References</a></li> <li class="toctree-l1"><a class="reference internal" href="mechpy.html#sundries">Sundries</a><ul> <li class="toctree-l2"><a class="reference internal" href="mechpy.html#running-jupyter-notebook-in-windows">Running jupyter notebook in windows</a><ul> <li class="toctree-l3"><a class="reference internal" href="mechpy.html#python-engineering-libraries">===== Python Engineering Libraries</a><ul> <li class="toctree-l4"><a class="reference internal" href="mechpy.html#id3">Units</a></li> <li class="toctree-l4"><a class="reference internal" href="mechpy.html#dynamics-and-control-systems">Dynamics and Control Systems</a></li> <li class="toctree-l4"><a class="reference internal" href="mechpy.html#fluids-aero">Fluids/Aero</a></li> <li class="toctree-l4"><a class="reference internal" href="mechpy.html#mechanics-composites-materials">Mechanics/Composites/Materials</a></li> <li class="toctree-l4"><a class="reference internal" href="mechpy.html#fem-math">FEM / Math</a></li> <li class="toctree-l4"><a class="reference internal" href="mechpy.html#plotting-and-visualization">Plotting and Visualization</a></li> <li class="toctree-l4"><a class="reference internal" href="mechpy.html#general-numeric-python">General Numeric Python</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="mechpy.html#general-engineering-software">General Engineering Software</a></li> <li class="toctree-l3"><a class="reference internal" href="mechpy.html#python-engineering-tutorials-and-classes">Python Engineering Tutorials and Classes</a></li> <li class="toctree-l3"><a class="reference internal" href="mechpy.html#random-links">Random Links</a></li> <li class="toctree-l3"><a class="reference internal" href="mechpy.html#microsoft-excel">Microsoft Excel</a></li> </ul> </li> </ul> </li> </ul> </ul> </li> <li class="dropdown"> <a role="button" id="dLabelLocalToc" data-toggle="dropdown" data-target="#" href="#">Page <b class="caret"></b></a> <ul class="dropdown-menu localtoc" role="menu" aria-labelledby="dLabelLocalToc"></ul> </li> </ul> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-md-12"> <h1 id="search-documentation">Search</h1> <div id="fallback" class="admonition warning"> <script type="text/javascript">$('#fallback').hide();</script> <p> Please activate JavaScript to enable the search functionality. </p> </div> <p> From here you can search these documents. Enter your search words into the box below and click "search". Note that the search function will automatically search for all of the words. Pages containing fewer words won't appear in the result list. </p> <form class="form-inline" action="" method="get"> <div class="form-group"> <input type="text" class="form-control" name="q" value="" /> </div> <input type="submit" class="btn btn-default" value="search" /> <span id="search-progress" style="padding-left: 10px"></span> </form> <div id="search-results"> </div> </div> </div> </div> <footer class="footer"> <div class="container"> <p class="pull-right"> <a href="#">Back to top</a> <br/> </p> <p> &copy; Copyright 2016, Neal Gordon.<br/> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.4.1.<br/> </p> </div> </footer> </body> </html>
{ "content_hash": "f1a3ba8ead6602a222765ea32f32f1c8", "timestamp": "", "source": "github", "line_count": 230, "max_line_length": 182, "avg_line_length": 40.41304347826087, "alnum_prop": 0.6358257127487896, "repo_name": "nagordon/mechpy", "id": "a4ec25212cd697b3dcc05c9da00bd3b716c5345a", "size": "9295", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/sphinx/_build/html/search.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "689" }, { "name": "Jupyter Notebook", "bytes": "4625752" }, { "name": "Python", "bytes": "197781" } ], "symlink_target": "" }
from huxley.api.tests import (DestroyAPITestCase, ListAPITestCase, PartialUpdateAPITestCase, RetrieveAPITestCase) from huxley.core.models import School from huxley.utils.test import TestSchools, TestUsers class SchoolDetailGetTestCase(RetrieveAPITestCase): url_name = 'api:school_detail' def test_anonymous_user(self): '''It should reject request from an anonymous user.''' school = TestSchools.new_school() response = self.get_response(school.id) self.assertNotAuthenticated(response) def test_self(self): '''It should allow the get request from the user.''' school = TestSchools.new_school() self.client.login(username=school.advisor.username, password='test') response = self.get_response(school.id) self.assertEqual(response.data, { 'id': school.id, 'registered': school.registered.isoformat(), 'name': school.name, 'address': school.address, 'city': school.city, 'state': school.state, 'zip_code': school.zip_code, 'country': school.country, 'primary_name': school.primary_name, 'primary_gender': school.primary_gender, 'primary_email': school.primary_email, 'primary_phone': school.primary_phone, 'primary_type': school.primary_type, 'secondary_name': school.secondary_name, 'secondary_gender': school.secondary_gender, 'secondary_email': school.secondary_email, 'secondary_phone': school.secondary_phone, 'secondary_type': school.secondary_type, 'program_type': school.program_type, 'times_attended': school.times_attended, 'international': school.international, 'waitlist': school.waitlist, 'beginner_delegates':school.beginner_delegates, 'intermediate_delegates': school.intermediate_delegates, 'advanced_delegates': school.advanced_delegates, 'spanish_speaking_delegates': school.spanish_speaking_delegates, 'country_preferences': school.country_preference_ids, 'committeepreferences': list(school.committeepreferences.all()), 'registration_comments': school.registration_comments, 'fees_owed': float(school.fees_owed), 'fees_paid': float(school.fees_paid), }) def test_other_user(self): '''it should not allow a get request from another user.''' school = TestSchools.new_school() TestUsers.new_user(username='user2', password='user2') self.client.login(username='user2', password='user2') response = self.get_response(school.id) self.assertPermissionDenied(response) def test_superuser(self): '''it should allow a get request from a superuser.''' school = TestSchools.new_school() TestUsers.new_superuser(username='user1', password='user1') self.client.login(username='user1', password='user1') response = self.get_response(school.id) self.assertEqual(response.data, { 'id': school.id, 'registered': school.registered.isoformat(), 'name': school.name, 'address': school.address, 'city': school.city, 'state': school.state, 'zip_code': school.zip_code, 'country': school.country, 'primary_name': school.primary_name, 'primary_gender': school.primary_gender, 'primary_email': school.primary_email, 'primary_phone': school.primary_phone, 'primary_type': school.primary_type, 'secondary_name': school.secondary_name, 'secondary_gender': school.secondary_gender, 'secondary_email': school.secondary_email, 'secondary_phone': school.secondary_phone, 'secondary_type': school.secondary_type, 'program_type': school.program_type, 'times_attended': school.times_attended, 'international': school.international, 'waitlist': school.waitlist, 'beginner_delegates': school.beginner_delegates, 'intermediate_delegates': school.intermediate_delegates, 'advanced_delegates': school.advanced_delegates, 'spanish_speaking_delegates': school.spanish_speaking_delegates, 'country_preferences': school.country_preference_ids, 'committeepreferences': list(school.committeepreferences.all()), 'registration_comments': school.registration_comments, 'fees_owed': float(school.fees_owed), 'fees_paid': float(school.fees_paid), }) class SchoolDetailPatchTestCase(PartialUpdateAPITestCase): url_name = 'api:school_detail' params = {'name': 'name', 'city': 'city'} def setUp(self): self.school = TestSchools.new_school() self.user = self.school.advisor def test_anonymous_user(self): '''Should not be able to update with an anonymous user.''' response = self.get_response(self.school.id) updated_school = School.objects.get(id=self.school.id) self.assertNotAuthenticated(response) self.assertEqual(updated_school.name, self.school.name) self.assertEqual(updated_school.city, self.school.city) def test_self(self): '''You should be able to update with an anonymous user.''' self.client.login(username=self.user.username, password='test') response = self.get_response(self.school.id, params=self.params) self.school = School.objects.get(id=self.school.id) self.assertEqual(response.data['name'], self.school.name) self.assertEqual(response.data['city'], self.school.city) def test_other_user(self): '''Should not allow another user to change a school's data''' TestUsers.new_user(username='user2', password='user2') self.client.login(username='user2', password='user2') response = self.get_response(self.school.id, params=self.params) updated_school = School.objects.get(id=self.school.id) self.assertPermissionDenied(response) self.assertEqual(updated_school.name, self.school.name) self.assertEqual(updated_school.city, self.school.city) def test_superuser(self): '''This should allow a superuser to change school data.''' TestUsers.new_superuser(username='user2', password='user2') self.client.login(username='user2', password='user2') response = self.get_response(self.school.id, params=self.params) self.school = School.objects.get(id=self.school.id) self.assertEqual(response.data['name'], self.school.name) self.assertEqual(response.data['city'], self.school.city) class SchoolDetailDeleteTestCase(DestroyAPITestCase): url_name = 'api:school_detail' def setUp(self): self.school = TestSchools.new_school() self.user = self.school.advisor def test_anonymous_user(self): '''Should not be able to delete anonymously.''' response = self.get_response(self.school.id) self.assertNotAuthenticated(response) self.assertTrue(School.objects.filter(id=self.school.id).exists()) def test_self(self): '''One user should be able to delete their own account.''' self.client.login(username=self.user.username, password='test') response = self.get_response(self.school.id) self.assertEqual(response.data, None) self.assertFalse(School.objects.filter(id=self.school.id).exists()) def test_other_user(self): '''One user should not be able to delete another user.''' TestUsers.new_user(username='user2', password='user2') self.client.login(username='user2', password='user2') response = self.get_response(self.school.id) self.assertPermissionDenied(response) self.assertTrue(School.objects.filter(id=self.school.id).exists()) def test_superuser(self): '''A superuser should not be able to delete an account.''' TestUsers.new_user(username='user2', password='user2') self.client.login(username='user2', password='user2') response = self.get_response(self.school.id) self.assertPermissionDenied(response) self.assertTrue(School.objects.filter(id=self.school.id).exists()) class SchoolListGetTestCase(ListAPITestCase): url_name = 'api:school_list' def setUp(self): self.school = TestSchools.new_school() self.user = self.school.advisor def test_anonymous_user(self): '''It should reject an anonymous user.''' response = self.get_response() self.assertMethodNotAllowed(response, 'GET') def test_self(self): '''It should reject a request from an unauthorized user.''' self.client.login(username='testuser', password='test') response = self.get_response() self.assertMethodNotAllowed(response, 'GET') def test_superuser(self): '''It should reject a request from a superuser.''' TestUsers.new_superuser(username='user', password='user') self.client.login(username='user', password='user') response = self.get_response() self.assertMethodNotAllowed(response, 'GET')
{ "content_hash": "70c50a2bb9ff4a638907a2b7f7905817", "timestamp": "", "source": "github", "line_count": 226, "max_line_length": 76, "avg_line_length": 41.80530973451327, "alnum_prop": 0.6436282811176969, "repo_name": "ctmunwebmaster/huxley", "id": "a4d3d780b0f9688df842cda599cc6feb58a73ab7", "size": "9597", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "huxley/api/tests/school/test_school.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "20631" }, { "name": "HTML", "bytes": "5628" }, { "name": "JavaScript", "bytes": "87792" }, { "name": "Python", "bytes": "191860" }, { "name": "Shell", "bytes": "2855" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { using Workspace = Microsoft.CodeAnalysis.Workspace; [Obsolete("This is a compatibility shim for TypeScript and Live Unit Testing; please do not use it.")] internal abstract partial class AbstractProject : ForegroundThreadAffinitizedObject, IVisualStudioHostProject { internal const string ProjectGuidPropertyName = "ProjectGuid"; internal static object RuleSetErrorId = new object(); private string _displayName; private readonly VisualStudioWorkspace _visualStudioWorkspace; private readonly DiagnosticDescriptor _errorReadingRulesetRule = new DiagnosticDescriptor( id: IDEDiagnosticIds.ErrorReadingRulesetId, title: ServicesVSResources.ErrorReadingRuleset, messageFormat: ServicesVSResources.Error_reading_ruleset_file_0_1, category: FeaturesResources.Roslyn_HostError, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); public AbstractProject( VisualStudioProjectTracker projectTracker, Func<ProjectId, IVsReportExternalErrors> reportExternalErrorCreatorOpt, string projectSystemName, string projectFilePath, IVsHierarchy hierarchy, string language, Guid projectGuid, IServiceProvider serviceProviderNotUsed, // not used, but left for compat with TypeScript VisualStudioWorkspaceImpl workspace, HostDiagnosticUpdateSource hostDiagnosticUpdateSourceOpt, ICommandLineParserService commandLineParserServiceOpt = null) : base(projectTracker.ThreadingContext) { Hierarchy = hierarchy; Guid = projectGuid; Language = language; ProjectTracker = projectTracker; _visualStudioWorkspace = workspace; this.DisplayName = hierarchy != null && hierarchy.TryGetName(out var name) ? name : projectSystemName; ProjectSystemName = projectSystemName; HostDiagnosticUpdateSource = hostDiagnosticUpdateSourceOpt; // Set the default value for last design time build result to be true, until the project system lets us know that it failed. LastDesignTimeBuildSucceeded = true; if (projectFilePath != null && File.Exists(projectFilePath)) { ProjectFilePath = projectFilePath; } if (ProjectFilePath != null) { Version = VersionStamp.Create(File.GetLastWriteTimeUtc(ProjectFilePath)); } else { Version = VersionStamp.Create(); } if (reportExternalErrorCreatorOpt != null) { ExternalErrorReporter = reportExternalErrorCreatorOpt(Id); } } /// <summary> /// A full path to the project bin output binary, or null if the project doesn't have an bin output binary. /// </summary> // FYI: this can't be made virtual because there are calls to this where a 'call' instead of 'callvirt' is being used to call // the method. internal string BinOutputPath => GetOutputFilePath(); protected virtual string GetOutputFilePath() { return VisualStudioProject.OutputFilePath; } protected IVsReportExternalErrors ExternalErrorReporter { get; } internal HostDiagnosticUpdateSource HostDiagnosticUpdateSource { get; } public virtual ProjectId Id => VisualStudioProject?.Id ?? ExplicitId; internal ProjectId ExplicitId { get; set; } public string Language { get; } public VisualStudioProjectTracker ProjectTracker { get; } /// <summary> /// The <see cref="IVsHierarchy"/> for this project. NOTE: May be null in Deferred Project Load cases. /// </summary> public IVsHierarchy Hierarchy { get; } /// <summary> /// Guid of the project /// /// it is not readonly since it can be changed while loading project /// </summary> public Guid Guid { get; protected set; } public Workspace Workspace { get; } public VersionStamp Version { get; } public IProjectCodeModel ProjectCodeModel { get; protected set; } /// <summary> /// The containing directory of the project. Null if none exists (consider Venus.) /// </summary> protected string ContainingDirectoryPathOpt { get { var projectFilePath = this.ProjectFilePath; if (projectFilePath != null) { return Path.GetDirectoryName(projectFilePath); } else { return null; } } } /// <summary> /// The full path of the project file. Null if none exists (consider Venus.) /// Note that the project file path might change with project file rename. /// If you need the folder of the project, just use <see cref="ContainingDirectoryPathOpt" /> which doesn't change for a project. /// </summary> public string ProjectFilePath { get; private set; } /// <summary> /// The public display name of the project. This name is not unique and may be shared /// between multiple projects, especially in cases like Venus where the intellisense /// projects will match the name of their logical parent project. /// </summary> public string DisplayName { get => _displayName; set { _displayName = value; UpdateVisualStudioProjectProperties(); } } internal string AssemblyName { get; private set; } /// <summary> /// The name of the project according to the project system. In "regular" projects this is /// equivalent to <see cref="DisplayName"/>, but in Venus cases these will differ. The /// ProjectSystemName is the 2_Default.aspx project name, whereas the regular display name /// matches the display name of the project the user actually sees in the solution explorer. /// These can be assumed to be unique within the Visual Studio workspace. /// </summary> public string ProjectSystemName { get; } /// <summary> /// Flag indicating if the latest design time build has succeeded for current project state. /// </summary> /// <remarks>Default value is true.</remarks> protected bool LastDesignTimeBuildSucceeded { get; private set; } #nullable enable public VisualStudioProject? VisualStudioProject { get; internal set; } #nullable restore internal void UpdateVisualStudioProjectProperties() { if (VisualStudioProject != null) { VisualStudioProject.DisplayName = this.DisplayName; } } [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] protected void UpdateProjectDisplayName(string displayName) { this.DisplayName = displayName; } [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal void AddDocument(IVisualStudioHostDocument document, bool isCurrentContext, bool hookupHandlers) { var shimDocument = (DocumentProvider.ShimDocument)document; VisualStudioProject.AddSourceFile(shimDocument.FilePath, shimDocument.SourceCodeKind); } [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal void RemoveDocument(IVisualStudioHostDocument document) { var containedDocument = ContainedDocument.TryGetContainedDocument(document.Id); if (containedDocument != null) { VisualStudioProject.RemoveSourceTextContainer(containedDocument.SubjectBuffer.AsTextContainer()); containedDocument.Dispose(); } else { var shimDocument = (DocumentProvider.ShimDocument)document; VisualStudioProject.RemoveSourceFile(shimDocument.FilePath); } } [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal IVisualStudioHostDocument GetCurrentDocumentFromPath(string filePath) { var id = _visualStudioWorkspace.CurrentSolution.GetDocumentIdsWithFilePath(filePath).FirstOrDefault(d => d.ProjectId == Id); if (id != null) { return new DocumentProvider.ShimDocument(this, id, filePath); } else { return null; } } [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal ImmutableArray<IVisualStudioHostDocument> GetCurrentDocuments() { return _visualStudioWorkspace.CurrentSolution.GetProject(Id).Documents.SelectAsArray( d => (IVisualStudioHostDocument)new DocumentProvider.ShimDocument(this, d.Id, d.FilePath, d.SourceCodeKind)); } } }
{ "content_hash": "1bb8e5e31dde62687a385a09a2fb5878", "timestamp": "", "source": "github", "line_count": 258, "max_line_length": 137, "avg_line_length": 39.86821705426357, "alnum_prop": 0.643787672564651, "repo_name": "abock/roslyn", "id": "d3a763cd63195233887c0d21406a80f42c278d51", "size": "10288", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/VisualStudio/Core/Def/Implementation/ProjectSystem/AbstractProject.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "289100" }, { "name": "Batchfile", "bytes": "9059" }, { "name": "C#", "bytes": "126276814" }, { "name": "C++", "bytes": "5602" }, { "name": "CMake", "bytes": "8276" }, { "name": "Dockerfile", "bytes": "2450" }, { "name": "F#", "bytes": "549" }, { "name": "PowerShell", "bytes": "236203" }, { "name": "Shell", "bytes": "94929" }, { "name": "Visual Basic .NET", "bytes": "70520200" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "c892e21b82e0a18ee2b791e26bc31a88", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "65c6fa81f0750f1bdb70eb21781c839660cc06b7", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Myrtus/Myrtus tijucana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="40dp" android:height="40dp" android:viewportWidth="40" android:viewportHeight="40" android:tint="?attr/colorControlNormal"> <path android:fillColor="@android:color/white" android:pathData="M9,25.125 L20,8.583 31,25.125ZM8.583,31.5V28.875H31.417V31.5Z"/> </vector>
{ "content_hash": "6e5d2f185ba1624f056e75e51e8afdff", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 88, "avg_line_length": 38, "alnum_prop": 0.7052631578947368, "repo_name": "google/material-design-icons", "id": "10071ef445fa3b2e7cef10045e1f1f0960c550a6", "size": "380", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "symbols/android/eject/materialsymbolssharp/eject_gradN25fill1_40px.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.frameworkset.commons.pool; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Timer; import java.util.TimerTask; /** * This class consists exclusively of static methods that operate on or return keyedPool related interfaces. * * @author Sandy McArthur * @version $Revision: 385296 $ $Date: 2006-03-12 10:28:08 -0500 (Sun, 12 Mar 2006) $ * @since Pool 1.3 */ public final class PoolUtils { /** * Timer used to periodically check pools idle object count. * Because a {@link Timer} creates a {@link Thread} this is lazily instantiated. */ private static Timer MIN_IDLE_TIMER; /** * PoolUtils instances should NOT be constructed in standard programming. * Instead, the class should be used procedurally: PoolUtils.adapt(aPool);. * This constructor is public to permit tools that require a JavaBean instance to operate. */ public PoolUtils() { } /** * Adapt a <code>KeyedPoolableObjectFactory</code> instance to work where a <code>PoolableObjectFactory</code> is * needed. This method is the equivalent of calling * {@link #adapt(KeyedPoolableObjectFactory, Object) PoolUtils.adapt(aKeyedPoolableObjectFactory, new Object())}. * * @param keyedFactory the {@link KeyedPoolableObjectFactory} to delegate to. * @return a {@link PoolableObjectFactory} that delegates to <code>keyedFactory</code> with an internal key. * @throws IllegalArgumentException when <code>keyedFactory</code> is <code>null</code>. * @see #adapt(KeyedPoolableObjectFactory, Object) * @since Pool 1.3 */ public static PoolableObjectFactory adapt(final KeyedPoolableObjectFactory keyedFactory) throws IllegalArgumentException { return adapt(keyedFactory, new Object()); } /** * Adapt a <code>KeyedPoolableObjectFactory</code> instance to work where a <code>PoolableObjectFactory</code> is * needed using the specified <code>key</code> when delegating. * * @param keyedFactory the {@link KeyedPoolableObjectFactory} to delegate to. * @param key the key to use when delegating. * @return a {@link PoolableObjectFactory} that delegates to <code>keyedFactory</code> with the specified key. * @throws IllegalArgumentException when <code>keyedFactory</code> or <code>key</code> is <code>null</code>. * @see #adapt(KeyedPoolableObjectFactory) * @since Pool 1.3 */ public static PoolableObjectFactory adapt(final KeyedPoolableObjectFactory keyedFactory, final Object key) throws IllegalArgumentException { return new PoolableObjectFactoryAdaptor(keyedFactory, key); } /** * Adapt a <code>PoolableObjectFactory</code> instance to work where a <code>KeyedPoolableObjectFactory</code> is * needed. The key is ignored. * * @param factory the {@link PoolableObjectFactory} to delegate to. * @return a {@link KeyedPoolableObjectFactory} that delegates to <code>factory</code> ignoring the key. * @throws IllegalArgumentException when <code>factory</code> is <code>null</code>. * @since Pool 1.3 */ public static KeyedPoolableObjectFactory adapt(final PoolableObjectFactory factory) throws IllegalArgumentException { return new KeyedPoolableObjectFactoryAdaptor(factory); } /** * Adapt a <code>KeyedObjectPool</code> instance to work where an <code>ObjectPool</code> is needed. This is the * equivalent of calling {@link #adapt(KeyedObjectPool, Object) PoolUtils.adapt(aKeyedObjectPool, new Object())}. * * @param keyedPool the {@link KeyedObjectPool} to delegate to. * @return an {@link ObjectPool} that delegates to <code>keyedPool</code> with an internal key. * @throws IllegalArgumentException when <code>keyedPool</code> is <code>null</code>. * @see #adapt(KeyedObjectPool, Object) * @since Pool 1.3 */ public static ObjectPool adapt(final KeyedObjectPool keyedPool) throws IllegalArgumentException { return adapt(keyedPool, new Object()); } /** * Adapt a <code>KeyedObjectPool</code> instance to work where an <code>ObjectPool</code> is needed using the * specified <code>key</code> when delegating. * * @param keyedPool the {@link KeyedObjectPool} to delegate to. * @param key the key to use when delegating. * @return an {@link ObjectPool} that delegates to <code>keyedPool</code> with the specified key. * @throws IllegalArgumentException when <code>keyedPool</code> or <code>key</code> is <code>null</code>. * @see #adapt(KeyedObjectPool) * @since Pool 1.3 */ public static ObjectPool adapt(final KeyedObjectPool keyedPool, final Object key) throws IllegalArgumentException { return new ObjectPoolAdaptor(keyedPool, key); } /** * Adapt an <code>ObjectPool</code> to work where an <code>KeyedObjectPool</code> is needed. * The key is ignored. * * @param pool the {@link ObjectPool} to delegate to. * @return a {@link KeyedObjectPool} that delegates to <code>keyedPool</code> ignoring the key. * @throws IllegalArgumentException when <code>keyedPool</code> is <code>null</code>. * @since Pool 1.3 */ public static KeyedObjectPool adapt(final ObjectPool pool) throws IllegalArgumentException { return new KeyedObjectPoolAdaptor(pool); } /** * Wraps an <code>ObjectPool</code> and dynamically checks the type of objects borrowed and returned to the keyedPool. * If an object is passed to the keyedPool that isn't of type <code>type</code> a {@link ClassCastException} will be thrown. * * @param pool the keyedPool to enforce type safety on * @return an <code>ObjectPool</code> that will only allow objects of <code>type</code> * @since Pool 1.3 */ public static ObjectPool checkedPool(final ObjectPool pool, final Class type) { if (pool == null) { throw new IllegalArgumentException("pool must not be null."); } if (type == null) { throw new IllegalArgumentException("type must not be null."); } return new CheckedObjectPool(pool, type); } /** * Wraps an <code>KeyedObjectPool</code> and dynamically checks the type of objects borrowed and returned to the keyedPool. * If an object is passed to the keyedPool that isn't of type <code>type</code> a {@link ClassCastException} will be thrown. * * @param keyedPool the keyedPool to enforce type safety on * @return an <code>KeyedObjectPool</code> that will only allow objects of <code>type</code> * @since Pool 1.3 */ public static KeyedObjectPool checkedPool(final KeyedObjectPool keyedPool, final Class type) { if (keyedPool == null) { throw new IllegalArgumentException("keyedPool must not be null."); } if (type == null) { throw new IllegalArgumentException("type must not be null."); } return new CheckedKeyedObjectPool(keyedPool, type); } /** * Periodically check the idle object count for the keyedPool. At most one idle object will be added per period. * If there is an exception when calling {@link ObjectPool#addObject()} then no more checks will be performed. * * @param pool the keyedPool to check periodically. * @param minIdle if the {@link ObjectPool#getNumIdle()} is less than this then add an idle object. * @param period the frequency to check the number of idle objects in a keyedPool, see * {@link Timer#schedule(TimerTask, long, long)}. * @return the {@link TimerTask} that will periodically check the pools idle object count. * @throws IllegalArgumentException when <code>keyedPool</code> is <code>null</code> or * when <code>minIdle</code> is negative or when <code>period</code> isn't * valid for {@link Timer#schedule(TimerTask, long, long)}. * @since Pool 1.3 */ public static TimerTask checkMinIdle(final ObjectPool pool, final int minIdle, final long period) throws IllegalArgumentException { if (pool == null) { throw new IllegalArgumentException("keyedPool must not be null."); } if (minIdle < 0) { throw new IllegalArgumentException("minIdle must be non-negative."); } final TimerTask task = new ObjectPoolMinIdleTimerTask(pool, minIdle); getMinIdleTimer().schedule(task, 0L, period); return task; } /** * Periodically check the idle object count for the key in the keyedPool. At most one idle object will be added per period. * If there is an exception when calling {@link KeyedObjectPool#addObject(Object)} then no more checks for that key * will be performed. * * @param keyedPool the keyedPool to check periodically. * @param key the key to check the idle count of. * @param minIdle if the {@link KeyedObjectPool#getNumIdle(Object)} is less than this then add an idle object. * @param period the frequency to check the number of idle objects in a keyedPool, see * {@link Timer#schedule(TimerTask, long, long)}. * @return the {@link TimerTask} that will periodically check the pools idle object count. * @throws IllegalArgumentException when <code>keyedPool</code>, <code>key</code> is <code>null</code> or * when <code>minIdle</code> is negative or when <code>period</code> isn't * valid for {@link Timer#schedule(TimerTask, long, long)}. * @since Pool 1.3 */ public static TimerTask checkMinIdle(final KeyedObjectPool keyedPool, final Object key, final int minIdle, final long period) throws IllegalArgumentException { if (keyedPool == null) { throw new IllegalArgumentException("keyedPool must not be null."); } if (key == null) { throw new IllegalArgumentException("key must not be null."); } if (minIdle < 0) { throw new IllegalArgumentException("minIdle must be non-negative."); } final TimerTask task = new KeyedObjectPoolMinIdleTimerTask(keyedPool, key, minIdle); getMinIdleTimer().schedule(task, 0L, period); return task; } /** * Periodically check the idle object count for each key in the <code>Collection</code> <code>keys</code> in the keyedPool. * At most one idle object will be added per period. * * @param keyedPool the keyedPool to check periodically. * @param keys a collection of keys to check the idle object count. * @param minIdle if the {@link KeyedObjectPool#getNumIdle(Object)} is less than this then add an idle object. * @param period the frequency to check the number of idle objects in a keyedPool, see * {@link Timer#schedule(TimerTask, long, long)}. * @return a {@link Map} of key and {@link TimerTask} pairs that will periodically check the pools idle object count. * @throws IllegalArgumentException when <code>keyedPool</code>, <code>keys</code>, or any of the values in the * collection is <code>null</code> or when <code>minIdle</code> is negative or when <code>period</code> isn't * valid for {@link Timer#schedule(TimerTask, long, long)}. * @see #checkMinIdle(KeyedObjectPool, Object, int, long) * @since Pool 1.3 */ public static Map checkMinIdle(final KeyedObjectPool keyedPool, final Collection keys, final int minIdle, final long period) throws IllegalArgumentException { if (keys == null) { throw new IllegalArgumentException("keys must not be null."); } final Map tasks = new HashMap(keys.size()); final Iterator iter = keys.iterator(); while (iter.hasNext()) { final Object key = iter.next(); final TimerTask task = checkMinIdle(keyedPool, key, minIdle, period); tasks.put(key, task); } return tasks; } /** * Call <code>addObject()</code> on <code>keyedPool</code> <code>count</code> number of times. * * @param pool the keyedPool to prefill. * @param count the number of idle objects to add. * @throws Exception when {@link ObjectPool#addObject()} fails. * @throws IllegalArgumentException when <code>keyedPool</code> is <code>null</code>. * @since Pool 1.3 */ public static void prefill(final ObjectPool pool, final int count) throws Exception, IllegalArgumentException { if (pool == null) { throw new IllegalArgumentException("keyedPool must not be null."); } for (int i = 0; i < count; i++) { pool.addObject(); } } /** * Call <code>addObject(Object)</code> on <code>keyedPool</code> with <code>key</code> <code>count</code> * number of times. * * @param keyedPool the keyedPool to prefill. * @param key the key to add objects for. * @param count the number of idle objects to add for <code>key</code>. * @throws Exception when {@link KeyedObjectPool#addObject(Object)} fails. * @throws IllegalArgumentException when <code>keyedPool</code> or <code>key</code> is <code>null</code>. * @since Pool 1.3 */ public static void prefill(final KeyedObjectPool keyedPool, final Object key, final int count) throws Exception, IllegalArgumentException { if (keyedPool == null) { throw new IllegalArgumentException("keyedPool must not be null."); } if (key == null) { throw new IllegalArgumentException("key must not be null."); } for (int i = 0; i < count; i++) { keyedPool.addObject(key); } } /** * Call <code>addObject(Object)</code> on <code>keyedPool</code> with each key in <code>keys</code> for * <code>count</code> number of times. This has the same effect as calling * {@link #prefill(KeyedObjectPool, Object, int)} for each key in the <code>keys</code> collection. * * @param keyedPool the keyedPool to prefill. * @param keys {@link Collection} of keys to add objects for. * @param count the number of idle objects to add for each <code>key</code>. * @throws Exception when {@link KeyedObjectPool#addObject(Object)} fails. * @throws IllegalArgumentException when <code>keyedPool</code>, <code>keys</code>, or * any value in <code>keys</code> is <code>null</code>. * @see #prefill(KeyedObjectPool, Object, int) * @since Pool 1.3 */ public static void prefill(final KeyedObjectPool keyedPool, final Collection keys, final int count) throws Exception, IllegalArgumentException { if (keys == null) { throw new IllegalArgumentException("keys must not be null."); } final Iterator iter = keys.iterator(); while (iter.hasNext()) { prefill(keyedPool, iter.next(), count); } } /** * Returns a synchronized (thread-safe) ObjectPool backed by the specified ObjectPool. * * @param pool the ObjectPool to be "wrapped" in a synchronized ObjectPool. * @return a synchronized view of the specified ObjectPool. * @since Pool 1.3 */ public static ObjectPool synchronizedPool(final ObjectPool pool) { return new SynchronizedObjectPool(pool); } /** * Returns a synchronized (thread-safe) KeyedObjectPool backed by the specified KeyedObjectPool. * * @param keyedPool the KeyedObjectPool to be "wrapped" in a synchronized KeyedObjectPool. * @return a synchronized view of the specified KeyedObjectPool. * @since Pool 1.3 */ public static KeyedObjectPool synchronizedPool(final KeyedObjectPool keyedPool) { return new SynchronizedKeyedObjectPool(keyedPool); } /** * Returns a synchronized (thread-safe) PoolableObjectFactory backed by the specified PoolableObjectFactory. * * @param factory the PoolableObjectFactory to be "wrapped" in a synchronized PoolableObjectFactory. * @return a synchronized view of the specified PoolableObjectFactory. * @since Pool 1.3 */ public static PoolableObjectFactory synchronizedPoolableFactory(final PoolableObjectFactory factory) { return new SynchronizedPoolableObjectFactory(factory); } /** * Returns a synchronized (thread-safe) KeyedPoolableObjectFactory backed by the specified KeyedPoolableObjectFactory. * * @param keyedFactory the KeyedPoolableObjectFactory to be "wrapped" in a synchronized KeyedPoolableObjectFactory. * @return a synchronized view of the specified KeyedPoolableObjectFactory. * @since Pool 1.3 */ public static KeyedPoolableObjectFactory synchronizedPoolableFactory(final KeyedPoolableObjectFactory keyedFactory) { return new SynchronizedKeyedPoolableObjectFactory(keyedFactory); } /** * Get the <code>Timer</code> for checking keyedPool's idle count. Lazily create the {@link Timer} as needed. * * @return the {@link Timer} for checking keyedPool's idle count. * @since Pool 1.3 */ private static synchronized Timer getMinIdleTimer() { if (MIN_IDLE_TIMER == null) { MIN_IDLE_TIMER = new Timer(true); } return MIN_IDLE_TIMER; } private static class PoolableObjectFactoryAdaptor implements PoolableObjectFactory { private final Object key; private final KeyedPoolableObjectFactory keyedFactory; PoolableObjectFactoryAdaptor(final KeyedPoolableObjectFactory keyedFactory, final Object key) throws IllegalArgumentException { if (keyedFactory == null) { throw new IllegalArgumentException("keyedFactory must not be null."); } if (key == null) { throw new IllegalArgumentException("key must not be null."); } this.keyedFactory = keyedFactory; this.key = key; } public Object makeObject() throws Exception { return keyedFactory.makeObject(key); } public void destroyObject(final Object obj) throws Exception { keyedFactory.destroyObject(key, obj); } public boolean validateObject(final Object obj) { return keyedFactory.validateObject(key, obj); } public void activateObject(final Object obj) throws Exception { keyedFactory.activateObject(key, obj); } public void passivateObject(final Object obj) throws Exception { keyedFactory.passivateObject(key, obj); } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("PoolableObjectFactoryAdaptor"); sb.append("{key=").append(key); sb.append(", keyedFactory=").append(keyedFactory); sb.append('}'); return sb.toString(); } } private static class KeyedPoolableObjectFactoryAdaptor implements KeyedPoolableObjectFactory { private final PoolableObjectFactory factory; KeyedPoolableObjectFactoryAdaptor(final PoolableObjectFactory factory) throws IllegalArgumentException { if (factory == null) { throw new IllegalArgumentException("factory must not be null."); } this.factory = factory; } public Object makeObject(final Object key) throws Exception { return factory.makeObject(); } public void destroyObject(final Object key, final Object obj) throws Exception { factory.destroyObject(obj); } public boolean validateObject(final Object key, final Object obj) { return factory.validateObject(obj); } public void activateObject(final Object key, final Object obj) throws Exception { factory.activateObject(obj); } public void passivateObject(final Object key, final Object obj) throws Exception { factory.passivateObject(obj); } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("KeyedPoolableObjectFactoryAdaptor"); sb.append("{factory=").append(factory); sb.append('}'); return sb.toString(); } } private static class ObjectPoolAdaptor implements ObjectPool { private final Object key; private final KeyedObjectPool keyedPool; ObjectPoolAdaptor(final KeyedObjectPool keyedPool, final Object key) throws IllegalArgumentException { if (keyedPool == null) { throw new IllegalArgumentException("keyedPool must not be null."); } if (key == null) { throw new IllegalArgumentException("key must not be null."); } this.keyedPool = keyedPool; this.key = key; } public Object borrowObject() throws Exception, NoSuchElementException, IllegalStateException { return keyedPool.borrowObject(key); } public void returnObject(final Object obj) throws Exception { keyedPool.returnObject(key, obj); } public void invalidateObject(final Object obj) throws Exception { keyedPool.invalidateObject(key, obj); } public void addObject() throws Exception, IllegalStateException { keyedPool.addObject(key); } public int getNumIdle() throws UnsupportedOperationException { return keyedPool.getNumIdle(key); } public int getNumActive() throws UnsupportedOperationException { return keyedPool.getNumActive(key); } public void clear() throws Exception, UnsupportedOperationException { keyedPool.clear(); } public void close() throws Exception { keyedPool.close(); } public void setFactory(final PoolableObjectFactory factory) throws IllegalStateException, UnsupportedOperationException { keyedPool.setFactory(adapt(factory)); } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("ObjectPoolAdaptor"); sb.append("{key=").append(key); sb.append(", keyedPool=").append(keyedPool); sb.append('}'); return sb.toString(); } } private static class KeyedObjectPoolAdaptor implements KeyedObjectPool { private final ObjectPool pool; KeyedObjectPoolAdaptor(final ObjectPool pool) throws IllegalArgumentException { if (pool == null) { throw new IllegalArgumentException("keyedPool must not be null."); } this.pool = pool; } public Object borrowObject(final Object key) throws Exception, NoSuchElementException, IllegalStateException { return pool.borrowObject(); } public void returnObject(final Object key, final Object obj) throws Exception { pool.returnObject(obj); } public void invalidateObject(final Object key, final Object obj) throws Exception { pool.invalidateObject(obj); } public void addObject(final Object key) throws Exception, IllegalStateException { pool.addObject(); } public int getNumIdle(final Object key) throws UnsupportedOperationException { return pool.getNumIdle(); } public int getNumActive(final Object key) throws UnsupportedOperationException { return pool.getNumActive(); } public int getNumIdle() throws UnsupportedOperationException { return pool.getNumIdle(); } public int getNumActive() throws UnsupportedOperationException { return pool.getNumActive(); } public void clear() throws Exception, UnsupportedOperationException { pool.clear(); } public void clear(final Object key) throws Exception, UnsupportedOperationException { pool.clear(); } public void close() throws Exception { pool.close(); } public void setFactory(final KeyedPoolableObjectFactory factory) throws IllegalStateException, UnsupportedOperationException { pool.setFactory(adapt(factory)); } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("KeyedObjectPoolAdaptor"); sb.append("{keyedPool=").append(pool); sb.append('}'); return sb.toString(); } } private static class CheckedObjectPool implements ObjectPool { private final Class type; private final ObjectPool pool; CheckedObjectPool(final ObjectPool pool, final Class type) { if (pool == null) { throw new IllegalArgumentException("pool must not be null."); } if (type == null) { throw new IllegalArgumentException("type must not be null."); } this.pool = pool; this.type = type; } public Object borrowObject() throws Exception, NoSuchElementException, IllegalStateException { final Object obj = pool.borrowObject(); if (type.isInstance(obj)) { return obj; } else { throw new ClassCastException("Borrowed object is not of type: " + type.getName() + " was: " + obj); } } public void returnObject(final Object obj) throws Exception { if (type.isInstance(obj)) { pool.returnObject(obj); } else { throw new ClassCastException("Returned object is not of type: " + type.getName() + " was: " + obj); } } public void invalidateObject(final Object obj) throws Exception { if (type.isInstance(obj)) { pool.invalidateObject(obj); } else { throw new ClassCastException("Invalidated object is not of type: " + type.getName() + " was: " + obj); } } public void addObject() throws Exception, IllegalStateException, UnsupportedOperationException { pool.addObject(); } public int getNumIdle() throws UnsupportedOperationException { return pool.getNumIdle(); } public int getNumActive() throws UnsupportedOperationException { return pool.getNumActive(); } public void clear() throws Exception, UnsupportedOperationException { pool.clear(); } public void close() throws Exception { pool.close(); } public void setFactory(final PoolableObjectFactory factory) throws IllegalStateException, UnsupportedOperationException { pool.setFactory(factory); } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("CheckedObjectPool"); sb.append("{type=").append(type); sb.append(", keyedPool=").append(pool); sb.append('}'); return sb.toString(); } } private static class CheckedKeyedObjectPool implements KeyedObjectPool { private final Class type; private final KeyedObjectPool keyedPool; CheckedKeyedObjectPool(final KeyedObjectPool keyedPool, final Class type) { if (keyedPool == null) { throw new IllegalArgumentException("keyedPool must not be null."); } if (type == null) { throw new IllegalArgumentException("type must not be null."); } this.keyedPool = keyedPool; this.type = type; } public Object borrowObject(final Object key) throws Exception, NoSuchElementException, IllegalStateException { Object obj = keyedPool.borrowObject(key); if (type.isInstance(obj)) { return obj; } else { throw new ClassCastException("Borrowed object for key: " + key + " is not of type: " + type.getName() + " was: " + obj); } } public void returnObject(final Object key, final Object obj) throws Exception { if (type.isInstance(obj)) { keyedPool.returnObject(key, obj); } else { throw new ClassCastException("Returned object for key: " + key + " is not of type: " + type.getName() + " was: " + obj); } } public void invalidateObject(final Object key, final Object obj) throws Exception { if (type.isInstance(obj)) { keyedPool.invalidateObject(key, obj); } else { throw new ClassCastException("Invalidated object for key: " + key + " is not of type: " + type.getName() + " was: " + obj); } } public void addObject(final Object key) throws Exception, IllegalStateException, UnsupportedOperationException { keyedPool.addObject(key); } public int getNumIdle(final Object key) throws UnsupportedOperationException { return keyedPool.getNumIdle(key); } public int getNumActive(final Object key) throws UnsupportedOperationException { return keyedPool.getNumActive(key); } public int getNumIdle() throws UnsupportedOperationException { return keyedPool.getNumIdle(); } public int getNumActive() throws UnsupportedOperationException { return keyedPool.getNumActive(); } public void clear() throws Exception, UnsupportedOperationException { keyedPool.clear(); } public void clear(final Object key) throws Exception, UnsupportedOperationException { keyedPool.clear(key); } public void close() throws Exception { keyedPool.close(); } public void setFactory(final KeyedPoolableObjectFactory factory) throws IllegalStateException, UnsupportedOperationException { keyedPool.setFactory(factory); } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("CheckedKeyedObjectPool"); sb.append("{type=").append(type); sb.append(", keyedPool=").append(keyedPool); sb.append('}'); return sb.toString(); } } private static class ObjectPoolMinIdleTimerTask extends TimerTask { private final int minIdle; private final ObjectPool pool; ObjectPoolMinIdleTimerTask(final ObjectPool pool, final int minIdle) throws IllegalArgumentException { if (pool == null) { throw new IllegalArgumentException("poll must not be null."); } this.pool = pool; this.minIdle = minIdle; } public void run() { boolean success = false; try { if (pool.getNumIdle() < minIdle) { pool.addObject(); } success = true; } catch (Exception e) { cancel(); } finally { // detect other types of Throwable and cancel this Timer if (!success) { cancel(); } } } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("ObjectPoolMinIdleTimerTask"); sb.append("{minIdle=").append(minIdle); sb.append(", keyedPool=").append(pool); sb.append('}'); return sb.toString(); } } private static class KeyedObjectPoolMinIdleTimerTask extends TimerTask { private final int minIdle; private final Object key; private final KeyedObjectPool pool; KeyedObjectPoolMinIdleTimerTask(final KeyedObjectPool pool, final Object key, final int minIdle) throws IllegalArgumentException { if (pool == null) { throw new IllegalArgumentException("keyedPool must not be null."); } this.pool = pool; this.key = key; this.minIdle = minIdle; } public void run() { boolean success = false; try { if (pool.getNumIdle(key) < minIdle) { pool.addObject(key); } success = true; } catch (Exception e) { cancel(); } finally { // detect other types of Throwable and cancel this Timer if (!success) { cancel(); } } } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("KeyedObjectPoolMinIdleTimerTask"); sb.append("{minIdle=").append(minIdle); sb.append(", key=").append(key); sb.append(", keyedPool=").append(pool); sb.append('}'); return sb.toString(); } } private static class SynchronizedObjectPool implements ObjectPool { private final Object lock; private final ObjectPool pool; SynchronizedObjectPool(final ObjectPool pool) throws IllegalArgumentException { if (pool == null) { throw new IllegalArgumentException("keyedPool must not be null."); } this.pool = pool; lock = new Object(); } public Object borrowObject() throws Exception, NoSuchElementException, IllegalStateException { synchronized (lock) { return pool.borrowObject(); } } public void returnObject(final Object obj) throws Exception { synchronized (lock) { pool.returnObject(obj); } } public void invalidateObject(final Object obj) throws Exception { synchronized (lock) { pool.invalidateObject(obj); } } public void addObject() throws Exception, IllegalStateException, UnsupportedOperationException { synchronized (lock) { pool.addObject(); } } public int getNumIdle() throws UnsupportedOperationException { synchronized (lock) { return pool.getNumIdle(); } } public int getNumActive() throws UnsupportedOperationException { synchronized (lock) { return pool.getNumActive(); } } public void clear() throws Exception, UnsupportedOperationException { synchronized (lock) { pool.clear(); } } public void close() throws Exception { synchronized (lock) { pool.close(); } } public void setFactory(final PoolableObjectFactory factory) throws IllegalStateException, UnsupportedOperationException { synchronized (lock) { pool.setFactory(factory); } } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SynchronizedObjectPool"); sb.append("{keyedPool=").append(pool); sb.append('}'); return sb.toString(); } } private static class SynchronizedKeyedObjectPool implements KeyedObjectPool { private final Object lock; private final KeyedObjectPool keyedPool; SynchronizedKeyedObjectPool(final KeyedObjectPool keyedPool) throws IllegalArgumentException { if (keyedPool == null) { throw new IllegalArgumentException("keyedPool must not be null."); } this.keyedPool = keyedPool; lock = new Object(); } public Object borrowObject(final Object key) throws Exception, NoSuchElementException, IllegalStateException { synchronized (lock) { return keyedPool.borrowObject(key); } } public void returnObject(final Object key, final Object obj) throws Exception { synchronized (lock) { keyedPool.returnObject(key, obj); } } public void invalidateObject(final Object key, final Object obj) throws Exception { synchronized (lock) { keyedPool.invalidateObject(key, obj); } } public void addObject(final Object key) throws Exception, IllegalStateException, UnsupportedOperationException { synchronized (lock) { keyedPool.addObject(key); } } public int getNumIdle(final Object key) throws UnsupportedOperationException { synchronized (lock) { return keyedPool.getNumIdle(key); } } public int getNumActive(final Object key) throws UnsupportedOperationException { synchronized (lock) { return keyedPool.getNumActive(key); } } public int getNumIdle() throws UnsupportedOperationException { synchronized (lock) { return keyedPool.getNumIdle(); } } public int getNumActive() throws UnsupportedOperationException { synchronized (lock) { return keyedPool.getNumActive(); } } public void clear() throws Exception, UnsupportedOperationException { synchronized (lock) { keyedPool.clear(); } } public void clear(final Object key) throws Exception, UnsupportedOperationException { synchronized (lock) { keyedPool.clear(key); } } public void close() throws Exception { synchronized (lock) { keyedPool.close(); } } public void setFactory(final KeyedPoolableObjectFactory factory) throws IllegalStateException, UnsupportedOperationException { synchronized (lock) { keyedPool.setFactory(factory); } } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SynchronizedKeyedObjectPool"); sb.append("{keyedPool=").append(keyedPool); sb.append('}'); return sb.toString(); } } private static class SynchronizedPoolableObjectFactory implements PoolableObjectFactory { private final Object lock; private final PoolableObjectFactory factory; SynchronizedPoolableObjectFactory(final PoolableObjectFactory factory) throws IllegalArgumentException { if (factory == null) { throw new IllegalArgumentException("factory must not be null."); } this.factory = factory; lock = new Object(); } public Object makeObject() throws Exception { synchronized (lock) { return factory.makeObject(); } } public void destroyObject(final Object obj) throws Exception { synchronized (lock) { factory.destroyObject(obj); } } public boolean validateObject(final Object obj) { synchronized (lock) { return factory.validateObject(obj); } } public void activateObject(final Object obj) throws Exception { synchronized (lock) { factory.activateObject(obj); } } public void passivateObject(final Object obj) throws Exception { synchronized (lock) { factory.passivateObject(obj); } } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SynchronizedPoolableObjectFactory"); sb.append("{factory=").append(factory); sb.append('}'); return sb.toString(); } } private static class SynchronizedKeyedPoolableObjectFactory implements KeyedPoolableObjectFactory { private final Object lock; private final KeyedPoolableObjectFactory keyedFactory; SynchronizedKeyedPoolableObjectFactory(final KeyedPoolableObjectFactory keyedFactory) throws IllegalArgumentException { if (keyedFactory == null) { throw new IllegalArgumentException("keyedFactory must not be null."); } this.keyedFactory = keyedFactory; lock = new Object(); } public Object makeObject(final Object key) throws Exception { synchronized (lock) { return keyedFactory.makeObject(key); } } public void destroyObject(final Object key, final Object obj) throws Exception { synchronized (lock) { keyedFactory.destroyObject(key, obj); } } public boolean validateObject(final Object key, final Object obj) { synchronized (lock) { return keyedFactory.validateObject(key, obj); } } public void activateObject(final Object key, final Object obj) throws Exception { synchronized (lock) { keyedFactory.activateObject(key, obj); } } public void passivateObject(final Object key, final Object obj) throws Exception { synchronized (lock) { keyedFactory.passivateObject(key, obj); } } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SynchronizedKeyedPoolableObjectFactory"); sb.append("{keyedFactory=").append(keyedFactory); sb.append('}'); return sb.toString(); } } }
{ "content_hash": "d3b881031b2451a69ee76d70180c6ced", "timestamp": "", "source": "github", "line_count": 1092, "max_line_length": 163, "avg_line_length": 39.92490842490842, "alnum_prop": 0.603972659296298, "repo_name": "bbossgroups/bboss", "id": "64569bfc1e7523032272813cfc2199c877120510", "size": "44227", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bboss-persistent/src-jdk5/com/frameworkset/commons/pool/PoolUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2144" }, { "name": "C", "bytes": "227968" }, { "name": "CSS", "bytes": "1961" }, { "name": "FreeMarker", "bytes": "13875" }, { "name": "HTML", "bytes": "151852" }, { "name": "Java", "bytes": "19726045" }, { "name": "JavaScript", "bytes": "73606" }, { "name": "PLSQL", "bytes": "2684" }, { "name": "Shell", "bytes": "2970" } ], "symlink_target": "" }
#ifndef __LINUX_USB_SERIAL_VISOR_H #define __LINUX_USB_SERIAL_VISOR_H #define HANDSPRING_VENDOR_ID 0x082d #define HANDSPRING_VISOR_ID 0x0100 #define HANDSPRING_TREO_ID 0x0200 #define HANDSPRING_TREO600_ID 0x0300 #define PALM_VENDOR_ID 0x0830 #define PALM_M500_ID 0x0001 #define PALM_M505_ID 0x0002 #define PALM_M515_ID 0x0003 #define PALM_I705_ID 0x0020 #define PALM_M125_ID 0x0040 #define PALM_M130_ID 0x0050 #define PALM_TUNGSTEN_T_ID 0x0060 #define PALM_TREO_650 0x0061 #define PALM_TUNGSTEN_Z_ID 0x0031 #define PALM_ZIRE_ID 0x0070 #define PALM_M100_ID 0x0080 #define GSPDA_VENDOR_ID 0x115e #define GSPDA_XPLORE_M68_ID 0xf100 #define SONY_VENDOR_ID 0x054C #define SONY_CLIE_3_5_ID 0x0038 #define SONY_CLIE_4_0_ID 0x0066 #define SONY_CLIE_S360_ID 0x0095 #define SONY_CLIE_4_1_ID 0x009A #define SONY_CLIE_NX60_ID 0x00DA #define SONY_CLIE_NZ90V_ID 0x00E9 #define SONY_CLIE_UX50_ID 0x0144 #define SONY_CLIE_TJ25_ID 0x0169 #define ACER_VENDOR_ID 0x0502 #define ACER_S10_ID 0x0001 #define SAMSUNG_VENDOR_ID 0x04E8 #define SAMSUNG_SCH_I330_ID 0x8001 #define SAMSUNG_SPH_I500_ID 0x6601 #define TAPWAVE_VENDOR_ID 0x12EF #define TAPWAVE_ZODIAC_ID 0x0100 #define GARMIN_VENDOR_ID 0x091E #define GARMIN_IQUE_3600_ID 0x0004 #define ACEECA_VENDOR_ID 0x4766 #define ACEECA_MEZ1000_ID 0x0001 #define KYOCERA_VENDOR_ID 0x0C88 #define KYOCERA_7135_ID 0x0021 #define FOSSIL_VENDOR_ID 0x0E67 #define FOSSIL_ABACUS_ID 0x0002 /**************************************************************************** * Handspring Visor Vendor specific request codes (bRequest values) * A big thank you to Handspring for providing the following information. * If anyone wants the original file where these values and structures came * from, send email to <[email protected]>. ****************************************************************************/ /**************************************************************************** * VISOR_REQUEST_BYTES_AVAILABLE asks the visor for the number of bytes that * are available to be transferred to the host for the specified endpoint. * Currently this is not used, and always returns 0x0001 ****************************************************************************/ #define VISOR_REQUEST_BYTES_AVAILABLE 0x01 /**************************************************************************** * VISOR_CLOSE_NOTIFICATION is set to the device to notify it that the host * is now closing the pipe. An empty packet is sent in response. ****************************************************************************/ #define VISOR_CLOSE_NOTIFICATION 0x02 /**************************************************************************** * VISOR_GET_CONNECTION_INFORMATION is sent by the host during enumeration to * get the endpoints used by the connection. ****************************************************************************/ #define VISOR_GET_CONNECTION_INFORMATION 0x03 /**************************************************************************** * VISOR_GET_CONNECTION_INFORMATION returns data in the following format ****************************************************************************/ struct visor_connection_info { __le16 num_ports; struct { __u8 port_function_id; __u8 port; } connections[2]; }; /* struct visor_connection_info.connection[x].port defines: */ #define VISOR_ENDPOINT_1 0x01 #define VISOR_ENDPOINT_2 0x02 /* struct visor_connection_info.connection[x].port_function_id defines: */ #define VISOR_FUNCTION_GENERIC 0x00 #define VISOR_FUNCTION_DEBUGGER 0x01 #define VISOR_FUNCTION_HOTSYNC 0x02 #define VISOR_FUNCTION_CONSOLE 0x03 #define VISOR_FUNCTION_REMOTE_FILE_SYS 0x04 /**************************************************************************** * PALM_GET_SOME_UNKNOWN_INFORMATION is sent by the host during enumeration to * get some information from the M series devices, that is currently unknown. ****************************************************************************/ #define PALM_GET_EXT_CONNECTION_INFORMATION 0x04 /** * struct palm_ext_connection_info - return data from a PALM_GET_EXT_CONNECTION_INFORMATION request * @num_ports: maximum number of functions/connections in use * @endpoint_numbers_different: will be 1 if in and out endpoints numbers are * different, otherwise it is 0. If value is 1, then * connections.end_point_info is non-zero. If value is 0, then * connections.port contains the endpoint number, which is the same for in * and out. * @port_function_id: contains the creator id of the application that opened * this connection. * @port: contains the in/out endpoint number. Is 0 if in and out endpoint * numbers are different. * @end_point_info: high nubbe is in endpoint and low nibble will indicate out * endpoint. Is 0 if in and out endpoints are the same. * * The maximum number of connections currently supported is 2 */ struct palm_ext_connection_info { __u8 num_ports; __u8 endpoint_numbers_different; __le16 reserved1; struct { __u32 port_function_id; __u8 port; __u8 end_point_info; __le16 reserved; } connections[2]; }; #endif
{ "content_hash": "8e705eb421ca10aa6725ddd4f688e9b1", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 99, "avg_line_length": 35.12244897959184, "alnum_prop": 0.6178578345922913, "repo_name": "lokeshjindal15/pd-gem5", "id": "4c456dd69ce54c5df0ba791770a239984aa4a52d", "size": "5622", "binary": false, "copies": "2157", "ref": "refs/heads/master", "path": "kernel_dvfs/linux-linaro-tracking-gem5/drivers/usb/serial/visor.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "10138943" }, { "name": "Awk", "bytes": "19269" }, { "name": "C", "bytes": "469972635" }, { "name": "C++", "bytes": "18163034" }, { "name": "CMake", "bytes": "2202" }, { "name": "Clojure", "bytes": "333" }, { "name": "Emacs Lisp", "bytes": "1969" }, { "name": "Groff", "bytes": "63956" }, { "name": "HTML", "bytes": "136898" }, { "name": "Hack", "bytes": "2489" }, { "name": "Java", "bytes": "3096" }, { "name": "Jupyter Notebook", "bytes": "1231954" }, { "name": "Lex", "bytes": "59257" }, { "name": "M4", "bytes": "52982" }, { "name": "Makefile", "bytes": "1453704" }, { "name": "Objective-C", "bytes": "1315749" }, { "name": "Perl", "bytes": "716374" }, { "name": "Perl6", "bytes": "3727" }, { "name": "Protocol Buffer", "bytes": "3246" }, { "name": "Python", "bytes": "4102365" }, { "name": "Scilab", "bytes": "21433" }, { "name": "Shell", "bytes": "512873" }, { "name": "SourcePawn", "bytes": "4687" }, { "name": "UnrealScript", "bytes": "10556" }, { "name": "Visual Basic", "bytes": "2884" }, { "name": "XS", "bytes": "1239" }, { "name": "Yacc", "bytes": "121715" } ], "symlink_target": "" }
<?php if($_POST) { $serverrootpath = $_SERVER['DOCUMENT_ROOT']; $includepath = $_SERVER['DOCUMENT_ROOT'] . "/portal/includes"; $rootpath = "/portal"; include("$serverrootpath/includes/db.inc.php"); include("$includepath/common.php"); page_protect(); $user_id = $_SESSION['user_id']; $id = str_replace( "'", "''", stripslashes($_POST["commentid"]) ); if($id) { $result3 = QueryWS1("SELECT PostID FROM PPComments WHERE CommentID = $id"); list($postid) = mssql_fetch_row($result3); $result4 = QueryWS1("UPDATE PPPosts SET CommentCount = CommentCount - 1 WHERE PostID = $postid"); $result = QueryWS1("DELETE FROM PPComments WHERE CommentID = $id"); $result2 = QueryWS1("DELETE FROM PPCommentVotes WHERE CommentID = $id"); echo json_encode(array('success' => true, 'message' => 'Success!')); } else { echo json_encode(array('success' => false, 'message' => 'Error!')); } } ?>
{ "content_hash": "20fcf954278ed05e92deb10e703a59a3", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 100, "avg_line_length": 30.483870967741936, "alnum_prop": 0.6232804232804233, "repo_name": "frodesigns/helbreath-player-portal", "id": "823c28671794b4b92879eda24d09e40dd1c4d909", "size": "945", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/deleteComment.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10183" }, { "name": "JavaScript", "bytes": "78324" }, { "name": "PHP", "bytes": "767419" } ], "symlink_target": "" }
package org.apache.jmeter.testbeans.gui; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.beans.PropertyEditorSupport; import javax.swing.JPasswordField; /** * This class implements a property editor for non-null String properties that * supports custom editing (i.e.: provides a GUI component) based on a text * field. * <p> * The provided GUI is a simple password field. * */ public class PasswordEditor extends PropertyEditorSupport implements ActionListener, FocusListener { private JPasswordField textField; /** * Value on which we started the editing. Used to avoid firing * PropertyChanged events when there's not been such change. */ private String initialValue = ""; protected PasswordEditor() { super(); textField = new JPasswordField(); textField.addActionListener(this); textField.addFocusListener(this); } @Override public String getAsText() { return new String(textField.getPassword()); } @Override public void setAsText(String value) { initialValue = value; textField.setText(value); } @Override public Object getValue() { return getAsText(); } @Override public void setValue(Object value) { if (value instanceof String) { setAsText((String) value); } else { throw new IllegalArgumentException(); } } /** * {@inheritDoc} */ @Override public Component getCustomEditor() { return textField; } @Override public boolean supportsCustomEditor() { return true; } /** * Avoid needlessly firing PropertyChanged events. * <p> * {@inheritDoc} */ @Override public void firePropertyChange() { String newValue = getAsText(); if (initialValue.equals(newValue)) { return; } initialValue = newValue; super.firePropertyChange(); } /** * {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { firePropertyChange(); } /** * {@inheritDoc} */ @Override public void focusGained(FocusEvent e) { } /** * {@inheritDoc} */ @Override public void focusLost(FocusEvent e) { firePropertyChange(); } }
{ "content_hash": "749dca087170d2f44f6017122808427f", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 100, "avg_line_length": 22.5, "alnum_prop": 0.5934865900383142, "repo_name": "yuyupapa/OpenSource", "id": "e69ba21705fd84fe35733558cb2e7a53fe8d8531", "size": "3424", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "apache-jmeter-3.0/src/core/org/apache/jmeter/testbeans/gui/PasswordEditor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "71892" }, { "name": "CSS", "bytes": "26064" }, { "name": "Groff", "bytes": "8383" }, { "name": "HTML", "bytes": "3089620" }, { "name": "Java", "bytes": "29561111" }, { "name": "JavaScript", "bytes": "128607" }, { "name": "NSIS", "bytes": "41068" }, { "name": "Scala", "bytes": "722545" }, { "name": "Shell", "bytes": "90291" }, { "name": "XSLT", "bytes": "105761" } ], "symlink_target": "" }
// Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.launcher; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.security.CodeSource; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** Main class for a JAR file to run code from "WEB-INF/lib". */ public final class GerritLauncher { private static final String pkg = "com.google.gerrit.pgm"; public static final String NOT_ARCHIVED = "NOT_ARCHIVED"; public static void main(final String argv[]) throws Exception { System.exit(mainImpl(argv)); } private static int mainImpl(final String argv[]) throws Exception { if (argv.length == 0) { File me; try { me = getDistributionArchive(); } catch (FileNotFoundException e) { me = null; } String jar = me != null ? me.getName() : "gerrit.war"; System.err.println("Gerrit Code Review " + getVersion(me)); System.err.println("usage: java -jar " + jar + " command [ARG ...]"); System.err.println(); System.err.println("The most commonly used commands are:"); System.err.println(" init Initialize a Gerrit installation"); System.err.println(" reindex Rebuild the secondary index"); System.err.println(" daemon Run the Gerrit network daemons"); System.err.println(" gsql Run the interactive query console"); System.err.println(" version Display the build version number"); System.err.println(); System.err.println(" ls List files available for cat"); System.err.println(" cat FILE Display a file from the archive"); System.err.println(); return 1; } // Special cases, a few global options actually are programs. // if ("-v".equals(argv[0]) || "--version".equals(argv[0])) { argv[0] = "version"; } else if ("-p".equals(argv[0]) || "--cat".equals(argv[0])) { argv[0] = "cat"; } else if ("-l".equals(argv[0]) || "--ls".equals(argv[0])) { argv[0] = "ls"; } // Run the application class // final ClassLoader cl = libClassLoader(); Thread.currentThread().setContextClassLoader(cl); return invokeProgram(cl, argv); } private static String getVersion(final File me) { if (me == null) { return ""; } try { final JarFile jar = new JarFile(me); try { Manifest mf = jar.getManifest(); Attributes att = mf.getMainAttributes(); String val = att.getValue(Attributes.Name.IMPLEMENTATION_VERSION); return val != null ? val : ""; } finally { jar.close(); } } catch (IOException e) { return ""; } } private static int invokeProgram(final ClassLoader loader, final String[] origArgv) throws Exception { String name = origArgv[0]; final String[] argv = new String[origArgv.length - 1]; System.arraycopy(origArgv, 1, argv, 0, argv.length); Class<?> clazz; try { try { String cn = name; if (cn.equals(cn.toLowerCase())) { StringBuilder buf = new StringBuilder(); buf.append(Character.toUpperCase(cn.charAt(0))); for (int i = 1; i < cn.length(); i++) { if (cn.charAt(i) == '-' && i + 1 < cn.length()) { i++; buf.append(Character.toUpperCase(cn.charAt(i))); } else { buf.append(cn.charAt(i)); } } cn = buf.toString(); } clazz = Class.forName(pkg + "." + cn, true, loader); } catch (ClassNotFoundException cnfe) { if (name.equals(name.toLowerCase())) { clazz = Class.forName(pkg + "." + name, true, loader); } else { throw cnfe; } } } catch (ClassNotFoundException cnfe) { System.err.println("fatal: unknown command " + name); System.err.println(" (no " + pkg + "." + name + ")"); return 1; } final Method main; try { main = clazz.getMethod("main", argv.getClass()); } catch (SecurityException | NoSuchMethodException e) { System.err.println("fatal: unknown command " + name); return 1; } final Object res; try { if ((main.getModifiers() & Modifier.STATIC) == Modifier.STATIC) { res = main.invoke(null, new Object[] {argv}); } else { res = main.invoke(clazz.newInstance(), new Object[] {argv}); } } catch (InvocationTargetException ite) { if (ite.getCause() instanceof Exception) { throw (Exception) ite.getCause(); } else if (ite.getCause() instanceof Error) { throw (Error) ite.getCause(); } else { throw ite; } } if (res instanceof Number) { return ((Number) res).intValue(); } else { return 0; } } private static ClassLoader libClassLoader() throws IOException { final File path; try { path = getDistributionArchive(); } catch (FileNotFoundException e) { if (NOT_ARCHIVED.equals(e.getMessage())) { return useDevClasspath(); } throw e; } final SortedMap<String, URL> jars = new TreeMap<String, URL>(); try { final ZipFile zf = new ZipFile(path); try { final Enumeration<? extends ZipEntry> e = zf.entries(); while (e.hasMoreElements()) { final ZipEntry ze = e.nextElement(); if (ze.isDirectory()) { continue; } else if (ze.getName().startsWith("WEB-INF/lib/")) { extractJar(zf, ze, jars); } else if (ze.getName().startsWith("WEB-INF/pgm-lib/")) { extractJar(zf, ze, jars); } } } finally { zf.close(); } } catch (IOException e) { throw new IOException("Cannot obtain libraries from " + path, e); } if (jars.isEmpty()) { return GerritLauncher.class.getClassLoader(); } // The extension API needs to be its own ClassLoader, along // with a few of its dependencies. Try to construct this first. List<URL> extapi = new ArrayList<URL>(); move(jars, "gerrit-extension-api-", extapi); move(jars, "guice-", extapi); move(jars, "javax.inject-1.jar", extapi); move(jars, "aopalliance-1.0.jar", extapi); move(jars, "guice-servlet-", extapi); move(jars, "tomcat-servlet-api-", extapi); ClassLoader parent = ClassLoader.getSystemClassLoader(); if (!extapi.isEmpty()) { parent = new URLClassLoader( extapi.toArray(new URL[extapi.size()]), parent); } return new URLClassLoader( jars.values().toArray(new URL[jars.size()]), parent); } private static void extractJar(ZipFile zf, ZipEntry ze, SortedMap<String, URL> jars) throws IOException { File tmp = createTempFile(safeName(ze), ".jar"); FileOutputStream out = new FileOutputStream(tmp); try { InputStream in = zf.getInputStream(ze); try { byte[] buf = new byte[4096]; int n; while ((n = in.read(buf, 0, buf.length)) > 0) { out.write(buf, 0, n); } } finally { in.close(); } } finally { out.close(); } String name = ze.getName(); jars.put( name.substring(name.lastIndexOf('/'), name.length()), tmp.toURI().toURL()); } private static void move(SortedMap<String, URL> jars, String prefix, List<URL> extapi) { SortedMap<String, URL> matches = jars.tailMap(prefix); if (!matches.isEmpty()) { String first = matches.firstKey(); if (first.startsWith(prefix)) { extapi.add(jars.remove(first)); } } } private static String safeName(final ZipEntry ze) { // Try to derive the name of the temporary file so it // doesn't completely suck. Best if we can make it // match the name it was in the archive. // String name = ze.getName(); if (name.contains("/")) { name = name.substring(name.lastIndexOf('/') + 1); } if (name.contains(".")) { name = name.substring(0, name.lastIndexOf('.')); } if (name.isEmpty()) { name = "code"; } return name; } private volatile static File myArchive; private volatile static File myHome; /** * Locate the JAR/WAR file we were launched from. * * @return local path of the Gerrit WAR file. * @throws FileNotFoundException if the code cannot guess the location. */ public static File getDistributionArchive() throws FileNotFoundException { if (myArchive == null) { myArchive = locateMyArchive(); } return myArchive; } private static File locateMyArchive() throws FileNotFoundException { final ClassLoader myCL = GerritLauncher.class.getClassLoader(); final String myName = GerritLauncher.class.getName().replace('.', '/') + ".class"; final URL myClazz = myCL.getResource(myName); if (myClazz == null) { throw new FileNotFoundException("Cannot find JAR: no " + myName); } // ZipFile may have the path of our JAR hiding within itself. // try { Field nameField = ZipFile.class.getDeclaredField("name"); nameField.setAccessible(true); JarFile jar = ((JarURLConnection) myClazz.openConnection()).getJarFile(); File path = new File((String) nameField.get(jar)); if (path.isFile()) { return path; } } catch (Exception e) { // Nope, that didn't work. Try a different method. // } // Maybe this is a local class file, running under a debugger? // if ("file".equals(myClazz.getProtocol())) { final File path = new File(myClazz.getPath()); if (path.isFile() && path.getParentFile().isDirectory()) { throw new FileNotFoundException(NOT_ARCHIVED); } } // The CodeSource might be able to give us the source as a stream. // If so, copy it to a local file so we have random access to it. // final CodeSource src = GerritLauncher.class.getProtectionDomain().getCodeSource(); if (src != null) { try { final InputStream in = src.getLocation().openStream(); try { final File tmp = createTempFile("gerrit_", ".zip"); final FileOutputStream out = new FileOutputStream(tmp); try { final byte[] buf = new byte[4096]; int n; while ((n = in.read(buf, 0, buf.length)) > 0) { out.write(buf, 0, n); } } finally { out.close(); } return tmp; } finally { in.close(); } } catch (IOException e) { // Nope, that didn't work. // } } throw new FileNotFoundException("Cannot find local copy of JAR"); } private static boolean temporaryDirectoryFound; private static File temporaryDirectory; /** * Creates a temporary file within the application's unpack location. * <p> * The launcher unpacks the nested JAR files into a temporary directory, * allowing the classes to be loaded from local disk with standard Java APIs. * This method constructs a new temporary file in the same directory. * <p> * The method first tries to create {@code prefix + suffix} within the * directory under the assumption that a given {@code prefix + suffix} * combination is made at most once per JVM execution. If this fails (e.g. the * named file already exists) a mangled unique name is used and returned * instead, with the unique string appearing between the prefix and suffix. * <p> * Files created by this method will be automatically deleted by the JVM when * it terminates. If the returned file is converted into a directory by the * caller, the caller must arrange for the contents to be deleted before the * directory is. * <p> * If supported by the underlying operating system, the temporary directory * which contains these temporary files is accessible only by the user running * the JVM. * * @param prefix prefix of the file name. * @param suffix suffix of the file name. * @return the path of the temporary file. The returned object exists in the * filesystem as a file; caller may need to delete and recreate as a * directory if a directory was preferred. * @throws IOException the file could not be created. */ public static synchronized File createTempFile(String prefix, String suffix) throws IOException { if (!temporaryDirectoryFound) { final File d = File.createTempFile("gerrit_", "_app", tmproot()); if (d.delete() && d.mkdir()) { // Try to lock the directory down to be accessible by us. // We first have to remove all permissions, then add back // only the owner permissions. // d.setWritable(false, false /* all */); d.setReadable(false, false /* all */); d.setExecutable(false, false /* all */); d.setWritable(true, true /* owner only */); d.setReadable(true, true /* owner only */); d.setExecutable(true, true /* owner only */); d.deleteOnExit(); temporaryDirectory = d; } temporaryDirectoryFound = true; } if (temporaryDirectory != null) { // If we have a private directory and this name has not yet // been used within the private directory, create it as-is. // final File tmp = new File(temporaryDirectory, prefix + suffix); if (tmp.createNewFile()) { tmp.deleteOnExit(); return tmp; } } if (!prefix.endsWith("_")) { prefix += "_"; } final File tmp = File.createTempFile(prefix, suffix, temporaryDirectory); tmp.deleteOnExit(); return tmp; } /** * Provide path to a working directory * * @return local path of the working directory or null if cannot be determined */ public static File getHomeDirectory() { if (myHome == null) { myHome = locateHomeDirectory(); } return myHome; } private static File tmproot() { File tmp; String gerritTemp = System.getenv("GERRIT_TMP"); if (gerritTemp != null && gerritTemp.length() > 0) { tmp = new File(gerritTemp); } else { tmp = new File(getHomeDirectory(), "tmp"); } if (!tmp.exists() && !tmp.mkdirs()) { System.err.println("warning: cannot create " + tmp.getAbsolutePath()); System.err.println("warning: using system temporary directory instead"); return null; } // Try to clean up any stale empty directories. Assume any empty // directory that is older than 7 days is one of these dead ones // that we can clean up. // final File[] tmpEntries = tmp.listFiles(); if (tmpEntries != null) { final long now = System.currentTimeMillis(); final long expired = now - MILLISECONDS.convert(7, DAYS); for (final File tmpEntry : tmpEntries) { if (tmpEntry.isDirectory() && tmpEntry.lastModified() < expired) { final String[] all = tmpEntry.list(); if (all == null || all.length == 0) { tmpEntry.delete(); } } } } try { return tmp.getCanonicalFile(); } catch (IOException e) { return tmp; } } private static File locateHomeDirectory() { // Try to find the user's home directory. If we can't find it // return null so the JVM's default temporary directory is used // instead. This is probably /tmp or /var/tmp. // String userHome = System.getProperty("user.home"); if (userHome == null || "".equals(userHome)) { userHome = System.getenv("HOME"); if (userHome == null || "".equals(userHome)) { System.err.println("warning: cannot determine home directory"); System.err.println("warning: using system temporary directory instead"); return null; } } // Ensure the home directory exists. If it doesn't, try to make it. // final File home = new File(userHome); if (!home.exists()) { if (home.mkdirs()) { System.err.println("warning: created " + home.getAbsolutePath()); } else { System.err.println("warning: " + home.getAbsolutePath() + " not found"); System.err.println("warning: using system temporary directory instead"); return null; } } // Use $HOME/.gerritcodereview/tmp for our temporary file area. // final File gerrithome = new File(home, ".gerritcodereview"); if (!gerrithome.exists() && !gerrithome.mkdirs()) { System.err.println("warning: cannot create " + gerrithome.getAbsolutePath()); System.err.println("warning: using system temporary directory instead"); return null; } try { return gerrithome.getCanonicalFile(); } catch (IOException e) { return gerrithome; } } /** * Locate the path of the {@code buck-out} directory in a source tree. * * @throws FileNotFoundException if the directory cannot be found. */ public static File getDeveloperBuckOut() throws FileNotFoundException { // Find ourselves in the CLASSPATH, we should be a loose class file. Class<GerritLauncher> self = GerritLauncher.class; URL u = self.getResource(self.getSimpleName() + ".class"); if (u == null) { throw new FileNotFoundException("Cannot find class " + self.getName()); } else if (!"file".equals(u.getProtocol())) { throw new FileNotFoundException("Cannot find extract path from " + u); } // Pop up to the top level classes folder that contains us. File dir = new File(u.getPath()); String myName = self.getName(); for (;;) { int dot = myName.lastIndexOf('.'); if (dot < 0) { dir = dir.getParentFile(); break; } myName = myName.substring(0, dot); dir = dir.getParentFile(); } dir = popdir(u, dir, "classes"); dir = popdir(u, dir, "eclipse"); if ("buck-out".equals(dir.getName())) { return dir; } throw new FileNotFoundException("Cannot find buck-out from " + u); } private static File popdir(URL u, File dir, String name) throws FileNotFoundException { if (dir.getName().equals(name)) { return dir.getParentFile(); } throw new FileNotFoundException("Cannot find buck-out from " + u); } private static ClassLoader useDevClasspath() throws MalformedURLException, FileNotFoundException { File out = getDeveloperBuckOut(); List<URL> dirs = new ArrayList<URL>(); dirs.add(new File(new File(out, "eclipse"), "classes").toURI().toURL()); ClassLoader cl = GerritLauncher.class.getClassLoader(); for (URL u : ((URLClassLoader) cl).getURLs()) { if (includeJar(u)) { dirs.add(u); } } return new URLClassLoader( dirs.toArray(new URL[dirs.size()]), ClassLoader.getSystemClassLoader().getParent()); } private static boolean includeJar(URL u) { String path = u.getPath(); return path.endsWith(".jar") && !path.endsWith("-src.jar") && !path.contains("/buck-out/gen/lib/gwt/"); } private GerritLauncher() { } }
{ "content_hash": "79b4dfa54a4d92af85ed8baaebb21a08", "timestamp": "", "source": "github", "line_count": 621, "max_line_length": 83, "avg_line_length": 32.966183574879224, "alnum_prop": 0.6161098085189527, "repo_name": "bpollack/gerrit", "id": "ef87395b0320159ab5d2b8de45539611c52c6d92", "size": "20472", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "gerrit-launcher/src/main/java/com/google/gerrit/launcher/GerritLauncher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "53024" }, { "name": "Go", "bytes": "1865" }, { "name": "Java", "bytes": "7417702" }, { "name": "JavaScript", "bytes": "1590" }, { "name": "Perl", "bytes": "27655" }, { "name": "Python", "bytes": "13891" }, { "name": "Shell", "bytes": "36064" } ], "symlink_target": "" }
<?php /** * Adds geospatial search to SolrSearch * * @author <[email protected]> * @license BSD License http://www.silverstripe.org/bsd-license */ class SolrGeoExtension extends DataExtension{ public static $db = array( // geo spatial options 'GeoRestrictionField' => 'Varchar(64)', 'GeoCentre' => 'SolrGeoPoint', 'GeoRadius' => 'Double', 'DistanceSort' => "Enum(',asc,desc','asc')", ); public function updateSolrCMSFields(\FieldList $fields) { // geo spatial field stuff $fields->addFieldToTab('Root.Main', $geoHeader = new HeaderField('GeoHeader', _t('SolrSearch.GEO_HEADER', 'Geospatial Settings')), 'Content'); $fields->addFieldToTab('Root.Main', new GeoCoordinateField('GeoCentre', _t('SolrSearch.GEO_CENTRE', 'Centre for geo restriction')), 'Content' ); $geoFields = $this->getGeoSelectableFields(); $geoFields = array_merge(array('' => ''), $geoFields); $fields->addFieldToTab('Root.Main', $geoField = new DropdownField('GeoRestrictionField', _t('SolrSearch.RESTRICT_BY', 'Geo field to restrict within radius'), $geoFields), 'Content' ); $geoField->setRightTitle('Leave the geo field blank and no geospatial restriction will be used'); $fields->addFieldToTab('Root.Main', new NumericField('GeoRadius', _t('SolrSearch.RESTRICT_RADIUS', 'Restrict results within radius (in km)')), 'Content' ); $distanceOpts = array( '' => 'None', 'asc' => 'Nearest to furthest', 'desc' => 'Furthest to nearest', ); $fields->addFieldToTab('Root.Main', new DropdownField('DistanceSort', _t('SolrSearch.SORT_BY_DISTANCE', 'Sort by distance from point'), $distanceOpts), 'Content' ); } /** * Get a list of geopoint fields that are selectable */ public function getGeoSelectableFields() { $all = $this->owner->getSelectableFields(null, false); $listTypes = $this->owner->searchableTypes('Page'); $geoFields = array(); foreach ($listTypes as $classType) { $db = Config::inst()->get($classType, 'db'); foreach ($db as $name => $type) { if (is_subclass_of($type, 'SolrGeoPoint') || $type == 'SolrGeoPoint') { $geoFields[$name] = $name; } } } ksort($geoFields); return $geoFields; } public function updateQueryBuilder(SolrQueryBuilder $builder) { // geo fields if ($this->owner->GeoRestrictionField) { $mappedField = $this->getSolr()->getSolrFieldName($this->owner->GeoRestrictionField, $types); $radius = $this->owner->GeoRadius ? $this->owner->GeoRadius : 5; $centre = $this->owner->GeoCentre instanceof SolrGeoPoint ? $this->owner->GeoCentre->latLon() : null; // allow an extension to decide how to geosearch if (!$centre && $this->owner->hasMethod('updateGeoSearch')) { $this->owner->extend('updateGeoSearch', $builder, $builder->getUserQuery(), $mappedField, $radius); } else if ($centre && $mappedField) { $builder->restrictNearPoint($centre, $mappedField, $radius); if ($this->owner->DistanceSort) { $builder->sortBy('geodist()', strtolower($this->owner->DistanceSort)); } } } } }
{ "content_hash": "ba1b0ff550d2f305d90703c9d08a3f37", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 144, "avg_line_length": 33.40860215053763, "alnum_prop": 0.6598004505954297, "repo_name": "nyeholt/silverstripe-solr", "id": "fe9b4e97f4b10ec03aadf51323ac051aa37e4d65", "size": "3107", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "code/extensions/SolrGeoExtension.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "358" }, { "name": "CSS", "bytes": "3675" }, { "name": "HTML", "bytes": "8757" }, { "name": "JavaScript", "bytes": "21691" }, { "name": "PHP", "bytes": "119553" }, { "name": "Scheme", "bytes": "1935" }, { "name": "Shell", "bytes": "6807" }, { "name": "XSLT", "bytes": "48649" } ], "symlink_target": "" }
 using System; namespace ClipperLib { public enum Intersection { None, Colinear, Intersect } public static class IntPointExtensions { public static bool CalcIntersection(IntPoint a1, IntPoint a2, IntPoint b1, IntPoint b2, out IntPoint position) { position = default(IntPoint); long intersection_epsilon = 1; long num = (a1.Y - b1.Y) * (b2.X - b1.X) - (a1.X - b1.X) * (b2.Y - b1.Y); long den = (a2.X - a1.X) * (b2.Y - b1.Y) - (a2.Y - a1.Y) * (b2.X - b1.X); if (Math.Abs(den) < intersection_epsilon) { return false; } position.X = a1.X + (a2.X - a1.X) * num / den; position.Y = a1.Y + (a2.Y - a1.Y) * num / den; return true; } public static long Cross(this IntPoint left, IntPoint right) { return left.X * right.Y - left.Y * right.X; } public static bool DoIntersect(IntPoint startA, IntPoint endA, IntPoint startB, IntPoint endB) { return GetIntersection(startA, endA, startB, endB) != Intersection.None; } public static long Dot(this IntPoint point1, IntPoint point2) { return point1.X * point2.X + point1.Y * point2.Y; } public static Intersection GetIntersection(IntPoint startA, IntPoint endA, IntPoint startB, IntPoint endB) { // Find the four orientations needed for general and // special cases int o1 = Orientation(startA, endA, startB); int o2 = Orientation(startA, endA, endB); int o3 = Orientation(startB, endB, startA); int o4 = Orientation(startB, endB, endA); // Special Cases // startA, endA and startB are collinear and startB lies on segment startA endA if (o1 == 0 && startB.OnSegment(startA, endA)) return Intersection.Colinear; // startA, endA and startB are collinear and endB lies on segment startA-endA if (o2 == 0 && endB.OnSegment(startA, endA)) return Intersection.Colinear; // startB, endB and startA are collinear and startA lies on segment startB-endB if (o3 == 0 && startA.OnSegment(startB, endB)) return Intersection.Colinear; // startB, endB and endA are collinear and endA lies on segment startB-endB if (o4 == 0 && endA.OnSegment(startB, endB)) return Intersection.Colinear; // General case if (o1 != o2 && o3 != o4) { return Intersection.Intersect; } return Intersection.None; // Doesn't fall in any of the above cases } public static IntPoint GetLength(this IntPoint pointToSet, long len) { long _len = pointToSet.Length(); if (_len < 1) { return new IntPoint(len, 0); } return pointToSet * len / _len; } public static IntPoint GetPerpendicularLeft(this IntPoint startingDirection) { return new IntPoint(-startingDirection.Y, startingDirection.X); } public static IntPoint GetPerpendicularRight(this IntPoint startingDirection) { return new IntPoint(startingDirection.Y, -startingDirection.X); } public static IntPoint GetRotated(this IntPoint thisPoint, double radians) { double cos = (double)Math.Cos(radians); double sin = (double)Math.Sin(radians); IntPoint output; output.X = (long)(Math.Round(thisPoint.X * cos - thisPoint.Y * sin)); output.Y = (long)(Math.Round(thisPoint.Y * cos + thisPoint.X * sin)); return output; } public static double GetTurnAmount(this IntPoint currentPoint, IntPoint prevPoint, IntPoint nextPoint) { if (prevPoint != currentPoint && currentPoint != nextPoint && nextPoint != prevPoint) { prevPoint = currentPoint - prevPoint; nextPoint -= currentPoint; double prevAngle = Math.Atan2(prevPoint.Y, prevPoint.X); IntPoint rotatedPrev = prevPoint.GetRotated(-prevAngle); // undo the rotation nextPoint = nextPoint.GetRotated(-prevAngle); double angle = Math.Atan2(nextPoint.Y, nextPoint.X); return angle; } return 0; } public static bool IsShorterThen(this IntPoint pointToCheck, long len) { if (pointToCheck.X > len || pointToCheck.X < -len) { return false; } if (pointToCheck.Y > len || pointToCheck.Y < -len) { return false; } return pointToCheck.LengthSquared() <= len * len; } public static long Length(this IntPoint pointToMeasure) { return (long)Math.Sqrt(pointToMeasure.LengthSquared()); } public static long LengthSquared(this IntPoint pointToMeasure) { return pointToMeasure.X * pointToMeasure.X + pointToMeasure.Y * pointToMeasure.Y; } public static bool OnSegment(this IntPoint testPosition, IntPoint start, IntPoint end) { if (start == end) { if (testPosition == start) { return true; } return false; } IntPoint segmentDelta = end - start; long segmentLength = segmentDelta.Length(); IntPoint pointRelStart = testPosition - start; long distanceFromStart = segmentDelta.Dot(pointRelStart) / segmentLength; if (distanceFromStart >= 0 && distanceFromStart <= segmentLength) { IntPoint segmentDeltaLeft = segmentDelta.GetPerpendicularLeft(); long distanceFromStartLeft = segmentDeltaLeft.Dot(pointRelStart) / segmentLength; if (distanceFromStartLeft == 0) { return true; } } return false; } // To find orientation of ordered triplet (p, q, r). // The function returns following values // 0 --> p, q and r are collinear // 1 --> Clockwise // 2 --> Counterclockwise public static int Orientation(IntPoint start, IntPoint end, IntPoint test) { // See http://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. long val = (end.Y - start.Y) * (test.X - end.X) - (end.X - start.X) * (test.Y - end.Y); if (val == 0) { return 0; } return (val > 0) ? 1 : 2; // clockwise or counterclockwise } } }
{ "content_hash": "2e57097320b4017f1c31729e51b49b79", "timestamp": "", "source": "github", "line_count": 215, "max_line_length": 114, "avg_line_length": 33.15813953488372, "alnum_prop": 0.5371019778370038, "repo_name": "larsbrubaker/agg-sharp", "id": "611e819c0ebd7e5fccd080d0396ad3868055ceaa", "size": "8649", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "clipper_library/IntPointExtensions.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C#", "bytes": "11774071" }, { "name": "Smalltalk", "bytes": "4964" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `XKB_KEY_Hangul_J_Phieuf` constant in crate `wayland_kbd`."> <meta name="keywords" content="rust, rustlang, rust-lang, XKB_KEY_Hangul_J_Phieuf"> <title>wayland_kbd::keysyms::XKB_KEY_Hangul_J_Phieuf - Rust</title> <link rel="stylesheet" type="text/css" href="../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <p class='location'><a href='../index.html'>wayland_kbd</a>::<wbr><a href='index.html'>keysyms</a></p><script>window.sidebarCurrent = {name: 'XKB_KEY_Hangul_J_Phieuf', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press 'S' to search, '?' for more options..." type="search"> </div> </form> </nav> <section id='main' class="content constant"> <h1 class='fqn'><span class='in-band'><a href='../index.html'>wayland_kbd</a>::<wbr><a href='index.html'>keysyms</a>::<wbr><a class='constant' href=''>XKB_KEY_Hangul_J_Phieuf</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-4382' class='srclink' href='../../src/wayland_kbd/ffi/keysyms.rs.html#1760' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const XKB_KEY_Hangul_J_Phieuf: <a href='http://doc.rust-lang.org/nightly/std/primitive.u32.html'>u32</a><code> = </code><code>0x0eed</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div class="shortcuts"> <h1>Keyboard shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>typedef</code> (or <code>tdef</code>). </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> <script> window.rootPath = "../../"; window.currentCrate = "wayland_kbd"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script async src="../../search-index.js"></script> </body> </html>
{ "content_hash": "01e6975f5567ab2fceb899cf7d86e184", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 260, "avg_line_length": 38.32673267326733, "alnum_prop": 0.5329372255231206, "repo_name": "mcanders/bevy", "id": "223d144d46dadcd646599d3f820ae393af21c347", "size": "3871", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/wayland_kbd/keysyms/constant.XKB_KEY_Hangul_J_Phieuf.html", "mode": "33188", "license": "mit", "language": [ { "name": "Rust", "bytes": "316751" } ], "symlink_target": "" }
FROM balenalib/jetson-tx1-fedora:35-build # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 RUN dnf install -y \ python3-pip \ python3-dbus \ && dnf clean all # install "virtualenv", since the vast majority of users of this image will want it RUN pip3 install -U --no-cache-dir --ignore-installed pip setuptools \ && pip3 install --no-cache-dir virtualenv RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/python-deprecation-warning CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@python" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 35 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.9.10, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "445ea9ec73e2457c6a30f4d7d8655aa3", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 708, "avg_line_length": 77.96774193548387, "alnum_prop": 0.7335539925527513, "repo_name": "resin-io-library/base-images", "id": "447dc0a93c075f4b6918c8606f8faaac101a24c1", "size": "2438", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/python/jetson-tx1/fedora/35/3.9.10/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :null_session respond_to :json before_action :configure_permitted_parameters, if: :devise_controller? def angular render 'layouts/application' end def fb response.headers['X-Frame-Options'] = 'ALLOW-FROM https://apps.facebook.com' render 'layouts/application' end private def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) << :username end end
{ "content_hash": "ef5939089b006d92a8616ce81e6a91ed", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 80, "avg_line_length": 24.916666666666668, "alnum_prop": 0.7341137123745819, "repo_name": "chmen/scharwerk", "id": "588ad38d249f7a4e16ab1585c74a8329a9b9f8ab", "size": "634", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/controllers/application_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4674" }, { "name": "HTML", "bytes": "33280" }, { "name": "JavaScript", "bytes": "8777" }, { "name": "Ruby", "bytes": "77604" } ], "symlink_target": "" }
package gin.edit.modifynode; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.expr.UnaryExpr; import com.github.javaparser.ast.expr.UnaryExpr.Operator; import gin.edit.ModifyNode; public class UnaryOperatorReplacement extends ModifyNode { private final Operator source; private final Operator replacement; // the following list is not perfect! needs refinement, if not total replacement with a better way to do this // also missing removal/insertion of these - e.g. where we have a complement, there isn't a "no-complement" operator, // so instead we have to look for nodes with/without a complement and possibly delete/insert private static final Map<Operator, List<Operator>> REPLACEMENTS = new LinkedHashMap<>(); static { REPLACEMENTS.put(Operator.BITWISE_COMPLEMENT, Arrays.asList(Operator.LOGICAL_COMPLEMENT, Operator.MINUS, Operator.PLUS)); REPLACEMENTS.put(Operator.LOGICAL_COMPLEMENT, Arrays.asList(Operator.BITWISE_COMPLEMENT, Operator.MINUS, Operator.PLUS)); REPLACEMENTS.put(Operator.MINUS, Arrays.asList(Operator.BITWISE_COMPLEMENT, Operator.LOGICAL_COMPLEMENT, Operator.PLUS)); REPLACEMENTS.put(Operator.PLUS, Arrays.asList(Operator.BITWISE_COMPLEMENT, Operator.LOGICAL_COMPLEMENT, Operator.MINUS)); REPLACEMENTS.put(Operator.POSTFIX_DECREMENT, Arrays.asList(Operator.POSTFIX_INCREMENT, Operator.PREFIX_DECREMENT, Operator.PREFIX_INCREMENT)); REPLACEMENTS.put(Operator.POSTFIX_INCREMENT, Arrays.asList(Operator.POSTFIX_DECREMENT, Operator.PREFIX_DECREMENT, Operator.PREFIX_INCREMENT)); REPLACEMENTS.put(Operator.PREFIX_DECREMENT, Arrays.asList(Operator.POSTFIX_DECREMENT, Operator.POSTFIX_INCREMENT, Operator.PREFIX_INCREMENT)); REPLACEMENTS.put(Operator.PREFIX_INCREMENT, Arrays.asList(Operator.POSTFIX_DECREMENT, Operator.POSTFIX_INCREMENT, Operator.PREFIX_DECREMENT)); } /** * @param sourceNodes is the list of possible nodes for modification; these won't be * modified, just used for reference * @param r is needed to choose a node and a suitable replacement * (keeps this detail out of Patch class) */ public UnaryOperatorReplacement(List<Node> sourceNodes, UnaryOperatorReplacementFactory factory, Random r) { super(sourceNodes, factory, r); UnaryExpr sourceNode = (UnaryExpr)(this.sourceNodes.get(sourceNodeIndex)); this.source = sourceNode.getOperator(); this.replacement = chooseRandomReplacement(source, r); } @Override public boolean apply(CompilationUnit cu) { // first, get the list of nodes from the new cu List<Node> nodes = this.factory.appliesToNodes(cu); Node node = nodes.get(sourceNodeIndex); ((UnaryExpr)node).setOperator(replacement); return true; } private static Operator chooseRandomReplacement(Operator original, Random r) { Operator replacement; /* do { replacement = Operator.values()[r.nextInt(Operator.values().length)]; } while (replacement.equals(original)); */ List<Operator> l = REPLACEMENTS.get(original); replacement = l.get(r.nextInt(l.size())); return replacement; } @Override public String toString() { return super.toString() + " [" + source + " -> " + replacement + "]"; } }
{ "content_hash": "c83ff4d1cf1e04c9c9ac6f3483395680", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 146, "avg_line_length": 42.0875, "alnum_prop": 0.7650727650727651, "repo_name": "drdrwhite/gin", "id": "f0672ed6b5858154a78b9f5f857f681f82b2630b", "size": "3367", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/gin/edit/modifynode/UnaryOperatorReplacement.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "48585" } ], "symlink_target": "" }
package dto.staticdata.item; import java.util.List; public class ItemTree { private String header; private List<String> tags; public String getHeader() { return header; } public List<String> getTags() { return tags; } }
{ "content_hash": "a288b7e6ab5b8a3e9c16339d118282e0", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 35, "avg_line_length": 14.052631578947368, "alnum_prop": 0.6254681647940075, "repo_name": "a64adam/ulti", "id": "2f9414e83cf1d8d775a9a73cd6ff793e68f27ad4", "size": "1402", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/dto/staticdata/item/ItemTree.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "318949" } ], "symlink_target": "" }
#ifndef MITKIMAGEREADACCESSOR_H #define MITKIMAGEREADACCESSOR_H #include "mitkImageAccessorBase.h" namespace mitk { class Image; class ImageDataItem; /** * @brief ImageReadAccessor class to get locked read access for a particular image part * @ingroup Data */ class MITK_CORE_EXPORT ImageReadAccessor : public ImageAccessorBase { friend class Image; template <class TPixel, unsigned int VDimension> friend class ImagePixelReadAccessor; public: typedef itk::SmartPointer<Image> ImagePointer; /** \brief Orders read access for a slice, volume or 4D-Image * \param Image::Pointer specifies the associated Image * \param ImageDataItem* specifies the allocated image part * \param OptionFlags properties from mitk::ImageAccessorBase::Options can be chosen and assembled with bitwise unification. * \throws mitk::Exception if the Constructor was created inappropriately * \throws mitk::MemoryIsLockedException if requested image area is exclusively locked and mitk::ImageAccessorBase::ExceptionIfLocked is set in OptionFlags */ ImageReadAccessor( ImageConstPointer image, const ImageDataItem* iDI = NULL, int OptionFlags = ImageAccessorBase::DefaultBehavior ); ImageReadAccessor( ImagePointer image, const ImageDataItem* iDI = NULL, int OptionFlags = ImageAccessorBase::DefaultBehavior ); ImageReadAccessor(const Image* image, const ImageDataItem* iDI = NULL); /** Destructor informs Image to unlock memory. */ virtual ~ImageReadAccessor(); protected: virtual const Image* GetImage() const; private: /** \brief manages a consistent read access and locks the ordered image part */ void OrganizeReadAccess(); ImageReadAccessor& operator=(const ImageReadAccessor&); // Not implemented on purpose. ImageReadAccessor(const ImageReadAccessor&); ImageConstPointer m_Image; }; } #endif // MITKIMAGEACCESSOR_H
{ "content_hash": "345c75ffd5a96fd54605c8aa93746131", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 158, "avg_line_length": 26.397260273972602, "alnum_prop": 0.7509081473793461, "repo_name": "danielknorr/MITK", "id": "3555550852c733e6d09c6ae75fa2d96c1cab6b80", "size": "2425", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Core/Code/DataManagement/mitkImageReadAccessor.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "2396657" }, { "name": "C++", "bytes": "25415939" }, { "name": "CSS", "bytes": "34746" }, { "name": "Java", "bytes": "350330" }, { "name": "JavaScript", "bytes": "47395" }, { "name": "Makefile", "bytes": "788" }, { "name": "Objective-C", "bytes": "512812" }, { "name": "Perl", "bytes": "982" }, { "name": "Python", "bytes": "7545" }, { "name": "Shell", "bytes": "6507" }, { "name": "TeX", "bytes": "1204" }, { "name": "XSLT", "bytes": "15769" } ], "symlink_target": "" }
Wallet Tools --------------------- ### [BitRPC](/contrib/bitrpc) ### Allows for sending of all standard Moneta commands via RPC rather than as command line args. ### [SpendFrom](/contrib/spendfrom) ### Use the raw transactions API to send coins received on a particular address (or addresses). Repository Tools --------------------- ### [Developer tools](/contrib/devtools) ### Specific tools for developers working on this repository. Contains the script `github-merge.sh` for merging github pull requests securely and signing them using GPG. ### [Linearize](/contrib/linearize) ### Construct a linear, no-fork, best version of the blockchain. ### [Qos](/contrib/qos) ### A Linux bash script that will set up traffic control (tc) to limit the outgoing bandwidth for connections to the Moneta network. This means one can have an always-on monetad instance running, and another local monetad/moneta-qt instance which connects to this node and receives blocks from it. ### [Seeds](/contrib/seeds) ### Utility to generate the pnSeed[] array that is compiled into the client. Build Tools and Keys --------------------- ### [Debian](/contrib/debian) ### Contains files used to package monetad/moneta-qt for Debian-based Linux systems. If you compile monetad/moneta-qt yourself, there are some useful files here. ### [Gitian-descriptors](/contrib/gitian-descriptors) ### Gavin's notes on getting gitian builds up and running using KVM. ### [Gitian-downloader](/contrib/gitian-downloader) Various PGP files of core developers. ### [MacDeploy](/contrib/macdeploy) ### Scripts and notes for Mac builds. Test and Verify Tools --------------------- ### [TestGen](/contrib/testgen) ### Utilities to generate test vectors for the data-driven Moneta tests. ### [Test Patches](/contrib/test-patches) ### These patches are applied when the automated pull-tester tests each pull and when master is tested using jenkins. ### [Verify SF Binaries](/contrib/verifysfbinaries) ### This script attempts to download and verify the signature file SHA256SUMS.asc from SourceForge.
{ "content_hash": "2d7a1338fbe368081acebf70651141c7", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 293, "avg_line_length": 37.07142857142857, "alnum_prop": 0.7249518304431599, "repo_name": "moneta-develop/moneta", "id": "c0de61d163e091802703bcc2deb710f83d4ea1da", "size": "2076", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "contrib/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "7639" }, { "name": "C", "bytes": "388529" }, { "name": "C++", "bytes": "3518396" }, { "name": "CSS", "bytes": "1127" }, { "name": "Groff", "bytes": "17983" }, { "name": "HTML", "bytes": "50621" }, { "name": "Java", "bytes": "2099" }, { "name": "Makefile", "bytes": "61678" }, { "name": "Objective-C", "bytes": "2020" }, { "name": "Objective-C++", "bytes": "7244" }, { "name": "Protocol Buffer", "bytes": "2304" }, { "name": "Python", "bytes": "211715" }, { "name": "QMake", "bytes": "2018" }, { "name": "Shell", "bytes": "40427" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Diagnostics; namespace MGR.CommandLineParser.Command.Lambda { [DebuggerDisplay("Dictionary value assigner (currently {Values.Count} values)")] internal class LambdaBasedCommandOptionDictionaryValueAssigner : ILambdaBasedCommandOptionValueAssigner { internal Dictionary<object, object> Values { get; } = new Dictionary<object, object>(); public object GetValue() => Values; public void AssignValue(object value) { var kvp = (KeyValuePair<object, object>) value; Values.Add(kvp.Key, kvp.Value); } } }
{ "content_hash": "53fe5251d7493039685e913a60aab92b", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 107, "avg_line_length": 34.888888888888886, "alnum_prop": 0.6926751592356688, "repo_name": "mgrosperrin/commandlineparser", "id": "84c77d06bddb5446f2d120d11d1fa391359f236b", "size": "630", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/MGR.CommandLineParser.Command.Lambda/LambdaBasedCommandOptionDictionaryValueAssigner.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "454041" }, { "name": "PowerShell", "bytes": "756" } ], "symlink_target": "" }
package org.elasticsearch.xpack.core.ml.inference.trainedmodel.metadata; import org.elasticsearch.Version; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.core.ml.AbstractBWCSerializationTestCase; import org.junit.Before; import java.io.IOException; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; public class TotalFeatureImportanceTests extends AbstractBWCSerializationTestCase<TotalFeatureImportance> { private boolean lenient; @SuppressWarnings("unchecked") public static TotalFeatureImportance randomInstance() { Supplier<Object> classNameGenerator = randomFrom( () -> randomAlphaOfLength(10), ESTestCase::randomBoolean, () -> randomIntBetween(0, 10) ); return new TotalFeatureImportance( randomAlphaOfLength(10), randomBoolean() ? null : randomImportance(), randomBoolean() ? null : Stream.generate(() -> new TotalFeatureImportance.ClassImportance(classNameGenerator.get(), randomImportance())) .limit(randomIntBetween(1, 10)) .collect(Collectors.toList()) ); } private static TotalFeatureImportance.Importance randomImportance() { return new TotalFeatureImportance.Importance(randomDouble(), randomDouble(), randomDouble()); } @Before public void chooseStrictOrLenient() { lenient = randomBoolean(); } @Override protected TotalFeatureImportance createTestInstance() { return randomInstance(); } @Override protected Writeable.Reader<TotalFeatureImportance> instanceReader() { return TotalFeatureImportance::new; } @Override protected TotalFeatureImportance doParseInstance(XContentParser parser) throws IOException { return TotalFeatureImportance.fromXContent(parser, lenient); } @Override protected boolean supportsUnknownFields() { return lenient; } @Override protected TotalFeatureImportance mutateInstanceForVersion(TotalFeatureImportance instance, Version version) { return instance; } }
{ "content_hash": "c457a6aba0ac9b1d2c07a51df5276953", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 127, "avg_line_length": 32.44444444444444, "alnum_prop": 0.7059075342465754, "repo_name": "robin13/elasticsearch", "id": "5e9925891ac822aff0fedac479c024d0d82033eb", "size": "2588", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/metadata/TotalFeatureImportanceTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "11082" }, { "name": "Batchfile", "bytes": "14049" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "315863" }, { "name": "HTML", "bytes": "3399" }, { "name": "Java", "bytes": "40107206" }, { "name": "Perl", "bytes": "7271" }, { "name": "Python", "bytes": "54437" }, { "name": "Shell", "bytes": "108937" } ], "symlink_target": "" }
/////////////////////////////////////////////////////////// // The Henge3D Physics Engine // // Found at https://github.com/bretternst/Henge3D // //////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace Henge3D { /// <summary> /// Represents a line that intersects with a given point and proceeds infinitely in the given direction and the negative of /// the given direction. /// </summary> public struct Line { public Vector3 P; public Vector3 Direction; /// <summary> /// Construct a line. /// </summary> /// <param name="p">A point intersecting the line.</param> /// <param name="direction">The direction of the line.</param> public Line(Vector3 p, Vector3 direction) { P = p; Direction = direction; } } }
{ "content_hash": "047368cffa57bf05e1aa17197b56940e", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 124, "avg_line_length": 26.176470588235293, "alnum_prop": 0.5865168539325842, "repo_name": "ASzot/Wumpus-XNA-Game-Engine", "id": "599862cbb2a0fc9608098ca24246569a6440a915", "size": "892", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "HTW Game Engine/Game Physics Editor/Physics/Geometry/Primitives/Line.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2506144" }, { "name": "HLSL", "bytes": "166647" }, { "name": "RPC", "bytes": "69838301" } ], "symlink_target": "" }
<?php namespace Acme\Mypkg\Command; /** * MockBCommandController Fixture */ class MockBCommandController extends \TYPO3\CMS\Extbase\Mvc\Controller\CommandController { /** * funcBCommand */ public function funcBCommand() { } }
{ "content_hash": "d6743b5efac93daefeb20f46d5cdc731", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 88, "avg_line_length": 15.117647058823529, "alnum_prop": 0.6770428015564203, "repo_name": "ahmedRguei/blogTypo", "id": "43503c292c09e01dcc5170d173e5db2a29c6350c", "size": "677", "binary": false, "copies": "16", "ref": "refs/heads/master", "path": "typo3/sysext/extbase/Tests/Unit/Scheduler/Fixtures/MockBCommandController.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "3425" }, { "name": "CSS", "bytes": "1591892" }, { "name": "HTML", "bytes": "617019" }, { "name": "JavaScript", "bytes": "3011598" }, { "name": "PHP", "bytes": "25967799" }, { "name": "PLpgSQL", "bytes": "3957" }, { "name": "Shell", "bytes": "7244" }, { "name": "Smarty", "bytes": "302" }, { "name": "TypeScript", "bytes": "122147" }, { "name": "XSLT", "bytes": "27654" } ], "symlink_target": "" }
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://[email protected] class: org.apache.http.impl.cookie.RFC2965DiscardAttributeHandler ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ORG_APACHE_HTTP_IMPL_COOKIE_RFC2965DISCARDATTRIBUTEHANDLER_HPP_DECL #define J2CPP_ORG_APACHE_HTTP_IMPL_COOKIE_RFC2965DISCARDATTRIBUTEHANDLER_HPP_DECL namespace j2cpp { namespace org { namespace apache { namespace http { namespace cookie { class CookieAttributeHandler; } } } } } namespace j2cpp { namespace org { namespace apache { namespace http { namespace cookie { class SetCookie; } } } } } namespace j2cpp { namespace org { namespace apache { namespace http { namespace cookie { class CookieOrigin; } } } } } namespace j2cpp { namespace org { namespace apache { namespace http { namespace cookie { class Cookie; } } } } } namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace lang { class Object; } } } #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <org/apache/http/cookie/Cookie.hpp> #include <org/apache/http/cookie/CookieAttributeHandler.hpp> #include <org/apache/http/cookie/CookieOrigin.hpp> #include <org/apache/http/cookie/SetCookie.hpp> namespace j2cpp { namespace org { namespace apache { namespace http { namespace impl { namespace cookie { class RFC2965DiscardAttributeHandler; class RFC2965DiscardAttributeHandler : public object<RFC2965DiscardAttributeHandler> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) explicit RFC2965DiscardAttributeHandler(jobject jobj) : object<RFC2965DiscardAttributeHandler>(jobj) { } operator local_ref<org::apache::http::cookie::CookieAttributeHandler>() const; operator local_ref<java::lang::Object>() const; RFC2965DiscardAttributeHandler(); void parse(local_ref< org::apache::http::cookie::SetCookie > const&, local_ref< java::lang::String > const&); void validate(local_ref< org::apache::http::cookie::Cookie > const&, local_ref< org::apache::http::cookie::CookieOrigin > const&); jboolean match(local_ref< org::apache::http::cookie::Cookie > const&, local_ref< org::apache::http::cookie::CookieOrigin > const&); }; //class RFC2965DiscardAttributeHandler } //namespace cookie } //namespace impl } //namespace http } //namespace apache } //namespace org } //namespace j2cpp #endif //J2CPP_ORG_APACHE_HTTP_IMPL_COOKIE_RFC2965DISCARDATTRIBUTEHANDLER_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ORG_APACHE_HTTP_IMPL_COOKIE_RFC2965DISCARDATTRIBUTEHANDLER_HPP_IMPL #define J2CPP_ORG_APACHE_HTTP_IMPL_COOKIE_RFC2965DISCARDATTRIBUTEHANDLER_HPP_IMPL namespace j2cpp { org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::operator local_ref<org::apache::http::cookie::CookieAttributeHandler>() const { return local_ref<org::apache::http::cookie::CookieAttributeHandler>(get_jobject()); } org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::RFC2965DiscardAttributeHandler() : object<org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler>( call_new_object< org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::J2CPP_CLASS_NAME, org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::J2CPP_METHOD_NAME(0), org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::J2CPP_METHOD_SIGNATURE(0) >() ) { } void org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::parse(local_ref< org::apache::http::cookie::SetCookie > const &a0, local_ref< java::lang::String > const &a1) { return call_method< org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::J2CPP_CLASS_NAME, org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::J2CPP_METHOD_NAME(1), org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::J2CPP_METHOD_SIGNATURE(1), void >(get_jobject(), a0, a1); } void org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::validate(local_ref< org::apache::http::cookie::Cookie > const &a0, local_ref< org::apache::http::cookie::CookieOrigin > const &a1) { return call_method< org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::J2CPP_CLASS_NAME, org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::J2CPP_METHOD_NAME(2), org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::J2CPP_METHOD_SIGNATURE(2), void >(get_jobject(), a0, a1); } jboolean org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::match(local_ref< org::apache::http::cookie::Cookie > const &a0, local_ref< org::apache::http::cookie::CookieOrigin > const &a1) { return call_method< org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::J2CPP_CLASS_NAME, org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::J2CPP_METHOD_NAME(3), org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler::J2CPP_METHOD_SIGNATURE(3), jboolean >(get_jobject(), a0, a1); } J2CPP_DEFINE_CLASS(org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler,"org/apache/http/impl/cookie/RFC2965DiscardAttributeHandler") J2CPP_DEFINE_METHOD(org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler,0,"<init>","()V") J2CPP_DEFINE_METHOD(org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler,1,"parse","(Lorg/apache/http/cookie/SetCookie;Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler,2,"validate","(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V") J2CPP_DEFINE_METHOD(org::apache::http::impl::cookie::RFC2965DiscardAttributeHandler,3,"match","(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z") } //namespace j2cpp #endif //J2CPP_ORG_APACHE_HTTP_IMPL_COOKIE_RFC2965DISCARDATTRIBUTEHANDLER_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
{ "content_hash": "bbbba13aac6b2b7c66475443a62f21b3", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 201, "avg_line_length": 44.227586206896554, "alnum_prop": 0.725557461406518, "repo_name": "hyEvans/ph-open", "id": "ec50140f5c51b18d67d7d52744b8498f263fe02d", "size": "6413", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "proj.android/jni/puzzleHero/platforms/android-8/org/apache/http/impl/cookie/RFC2965DiscardAttributeHandler.hpp", "mode": "33261", "license": "mit", "language": [], "symlink_target": "" }
package dev.jeka.core.api.depmanagement; import dev.jeka.core.api.depmanagement.publication.JkMavenMetadata; import org.junit.Assert; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; @SuppressWarnings("javadoc") public class JkMavenMetadataTest { @Test public void testupdateSnapshot() throws UnsupportedEncodingException { final JkMavenMetadata mavenMetadata = JkMavenMetadata.of(JkModuleId.of("dev.jeka", "core") .withVersion("0.1-SNAPSHOT"), "11111111.222222"); mavenMetadata.updateSnapshot("20151023145532"); mavenMetadata.addSnapshotVersion("jar", "source"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); mavenMetadata.output(outputStream); final String string = outputStream.toString("UTF-8"); final ByteArrayInputStream inputStream = new ByteArrayInputStream(string.getBytes()); final JkMavenMetadata readData = JkMavenMetadata.of(inputStream); outputStream = new ByteArrayOutputStream(); readData.output(outputStream); final String string2 = outputStream.toString("UTF-8"); System.out.println(string2); Assert.assertEquals(string, string2); } @Test public void testAddRelease() throws UnsupportedEncodingException { final JkMavenMetadata mavenMetadata = JkMavenMetadata.of(JkModuleId.of("dev.jeka", "core")); mavenMetadata.addVersion("1.3.2", "20151023145532"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); mavenMetadata.output(outputStream); final String string = outputStream.toString("UTF-8"); final ByteArrayInputStream inputStream = new ByteArrayInputStream(string.getBytes()); final JkMavenMetadata readData = JkMavenMetadata.of(inputStream); outputStream = new ByteArrayOutputStream(); readData.output(outputStream); final String string2 = outputStream.toString("UTF-8"); System.out.println(string2); Assert.assertEquals(string, string2); } @Test public void testAddSnapshot() throws UnsupportedEncodingException { final JkMavenMetadata mavenMetadata = JkMavenMetadata.of(JkModuleId.of("dev.jeka", "core")); mavenMetadata.addVersion("1.3.2-SNAPSHOT", "20151023145532"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); mavenMetadata.output(outputStream); final String string = outputStream.toString("UTF-8"); final ByteArrayInputStream inputStream = new ByteArrayInputStream(string.getBytes()); final JkMavenMetadata readData = JkMavenMetadata.of(inputStream); outputStream = new ByteArrayOutputStream(); readData.output(outputStream); final String string2 = outputStream.toString("UTF-8"); System.out.println(string2); Assert.assertEquals(string, string2); } }
{ "content_hash": "8afee231a5fd54c76a4e1628a1df0fe7", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 100, "avg_line_length": 45.92307692307692, "alnum_prop": 0.7206030150753768, "repo_name": "jerkar/jerkar", "id": "0e393e23d120ac80d0f0eb421522fb39bec76af1", "size": "2985", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dev.jeka.core/src/test/java/dev/jeka/core/api/depmanagement/JkMavenMetadataTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "539" }, { "name": "CSS", "bytes": "9341" }, { "name": "HTML", "bytes": "639" }, { "name": "Java", "bytes": "1129999" }, { "name": "Shell", "bytes": "4597" } ], "symlink_target": "" }
@interface ZXAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
{ "content_hash": "e3ad00695db73067786fbb77bb099a46", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 62, "avg_line_length": 23.6, "alnum_prop": 0.7966101694915254, "repo_name": "urmyfaith/roadofios", "id": "6efd2bb9bdd9e50a158ea67e8a4871ffd091661e", "size": "266", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "advancedUI/0121_week12_day3/MyMagazine/MyMagazine/ZXAppDelegate.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "386126" }, { "name": "C++", "bytes": "43787" }, { "name": "Groff", "bytes": "6292" }, { "name": "HTML", "bytes": "7690" }, { "name": "Objective-C", "bytes": "6979812" }, { "name": "Objective-C++", "bytes": "9575" }, { "name": "Python", "bytes": "19494" }, { "name": "Shell", "bytes": "6" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.ops4j.pax.exam</groupId> <artifactId>pax-exam-samples</artifactId> <version>4.6.0-SNAPSHOT</version> </parent> <groupId>org.ops4j.pax.exam.samples</groupId> <artifactId>pax-exam-sample10-derby</artifactId> <packaging>pom</packaging> <name>OPS4J Pax Exam Sample10 JBoss Module</name> <dependencies> <dependency> <groupId>org.apache.derby</groupId> <artifactId>derby</artifactId> <scope>compile</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <configuration> <descriptor>src/main/assembly/assembly.xml</descriptor> <attach>true</attach> </configuration> <executions> <execution> <id>all</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "0de9a4f8dff75ba7c213e1673c2812a9", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 204, "avg_line_length": 35.906976744186046, "alnum_prop": 0.5297927461139896, "repo_name": "bimargulies/org.ops4j.pax.exam2", "id": "2c442d4d671329f6d4c063d35c7b8d5468ea317f", "size": "1544", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/pax-exam-sample10-derby/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1271799" }, { "name": "Shell", "bytes": "198" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `router` mod in crate `tokio_http2`."> <meta name="keywords" content="rust, rustlang, rust-lang, router"> <title>tokio_http2::router - Rust</title> <link rel="stylesheet" type="text/css" href="../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../main.css"> <link rel="shortcut icon" href="https://lambdastackio.github.io/static/images/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../../tokio_http2/index.html'><img src='https://lambdastackio.github.io/static/images/lambdastack-200x200.png' alt='logo' width='100'></a> <p class='location'><a href='../index.html'>tokio_http2</a></p><script>window.sidebarCurrent = {name: 'router', ty: 'mod', relpath: '../'};</script><script defer src="../sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content mod"> <h1 class='fqn'><span class='in-band'>Module <a href='../index.html'>tokio_http2</a>::<wbr><a class='mod' href=''>router</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-612' class='srclink' href='../../src/tokio_http2/src/router/mod.rs.html#15-122' title='goto source code'>[src]</a></span></h1> <h2 id='modules' class='section-header'><a href="#modules">Modules</a></h2> <table> <tr class=' module-item'> <td><a class='mod' href='builder/index.html' title='tokio_http2::router::builder'>builder</a></td> <td class='docblock-short'> </td> </tr> <tr class=' module-item'> <td><a class='mod' href='handlers/index.html' title='tokio_http2::router::handlers'>handlers</a></td> <td class='docblock-short'> </td> </tr> <tr class=' module-item'> <td><a class='mod' href='path/index.html' title='tokio_http2::router::path'>path</a></td> <td class='docblock-short'> </td> </tr> <tr class=' module-item'> <td><a class='mod' href='route/index.html' title='tokio_http2::router::route'>route</a></td> <td class='docblock-short'> </td> </tr></table><h2 id='structs' class='section-header'><a href="#structs">Structs</a></h2> <table> <tr class=' module-item'> <td><a class='struct' href='struct.Router.html' title='tokio_http2::router::Router'>Router</a></td> <td class='docblock-short'> <p>This is the one. The router.</p> </td> </tr></table><h2 id='types' class='section-header'><a href="#types">Type Definitions</a></h2> <table> <tr class=' module-item'> <td><a class='type' href='type.HttpResult.html' title='tokio_http2::router::HttpResult'>HttpResult</a></td> <td class='docblock-short'> </td> </tr></table></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../"; window.currentCrate = "tokio_http2"; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script defer src="../../search-index.js"></script> </body> </html>
{ "content_hash": "ad2b08055c029b7db6714eae649a4ee6", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 205, "avg_line_length": 42.152866242038215, "alnum_prop": 0.44620731338773045, "repo_name": "lambdastackio/tokio-http2", "id": "9b71432054c8e15c281ac6bacdc4c5f2547ece21", "size": "6628", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/tokio_http2/router/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Rust", "bytes": "221396" }, { "name": "Shell", "bytes": "696" } ], "symlink_target": "" }
#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_BASE_COLLECTIVE_EXECUTOR_H_ #define TENSORFLOW_CORE_COMMON_RUNTIME_BASE_COLLECTIVE_EXECUTOR_H_ #include <memory> #include <string> #include "tensorflow/core/common_runtime/buf_rendezvous.h" #include "tensorflow/core/framework/collective.h" #include "tensorflow/core/framework/device_attributes.pb.h" namespace tensorflow { class CollectiveImplementation; class DeviceMgr; class Device; // Helper interface that aliases regular subfields of a Tensor as separate // Tensors for in-place update. class CollectiveAdapter { public: virtual ~CollectiveAdapter() {} // Move the backing tensor to 'output' with its original storage and // shape. After this call this CollectiveAdapter object should be // deleted immediately without calling any of its other methods. virtual void ConsumeFinalValue(Tensor* output) = 0; // const access to entire intermediate value for debugging virtual const Tensor& Value() const = 0; // Returns tensor for chunk i which aliases the backing buffer. virtual Tensor ChunkAlias(int i) = 0; // Returns tensor allocated on the same device but with its own // separate backing buffer. Will have same type and size as // chunk i. virtual Tensor TempChunk(int i) const = 0; // Bytes in chunk i virtual int64 ChunkBytes(int i) const = 0; // Generate a CPU RAM scalar tensor of the same DataType as the // backing tensor with the given integer value. virtual Tensor Scalar(int v) const = 0; // Generate a scalar tensor of same DataType and on the same device // as the backing tensor. virtual Tensor Scalar(Allocator* a) const = 0; // Debugging string describing buffer location virtual string TBounds(const Tensor& t) const = 0; virtual string DebugString() const = 0; // Computes the number of elements per alias chunk tensor. // // A CHECK in tensor.cc expects that the memory buffer backing a // Tensor will be aligned according to EIGEN_MAX_ALIGN_BYTES. To // ensure that all chunk aliasing Tensors maintain this alignment we // need to pick a chunk size that preserves it. Note than in extreme // cases (impractical, but possible with very small tensors) one or // more tail chunks can end up emptby. static int64 AlignedChunkElts(int64 elt_bytes, int64 total_elts, int64 num_chunks); }; // Create a CollectiveAdaptor wrapping 'output', specialized to its // data-type and shape. CollectiveAdapter* MakeCollectiveAdapter(Tensor* output, int num_chunks, Allocator* allocator); // Default implementation of CollectiveExecutor. Delegates the actual // work of moving data to a class specialized for the operation type, // arguments and device+interconnect topology. class BaseCollectiveExecutor : public CollectiveExecutor { public: BaseCollectiveExecutor(CollectiveExecutorMgrInterface* cem, PerStepCollectiveRemoteAccess* remote_access, int64 step_id, const DeviceMgr* dev_mgr) : CollectiveExecutor(cem), step_id_(step_id), dev_mgr_(dev_mgr), remote_access_(remote_access) {} ~BaseCollectiveExecutor() override; void StartAbort(const Status& s) override; void ExecuteAsync(OpKernelContext* ctx, const CollectiveParams& col_params, const string& exec_key, StatusCallback done) override; PerStepCollectiveRemoteAccess* remote_access() override { return remote_access_.get(); } void RecvFromPeer(const string& peer_device, const string& peer_task, bool peer_is_local, const string& key, Device* to_device, DeviceContext* to_device_ctx, const AllocatorAttributes& to_alloc_attr, Tensor* to_tensor, const DeviceLocality& client_locality, int stream_index, const StatusCallback& done) override { remote_access_->RecvFromPeer( peer_device, peer_task, peer_is_local, key, to_device, to_device_ctx, to_alloc_attr, to_tensor, client_locality, stream_index, done); } void PostToPeer(const string& peer_device, const string& peer_task, const string& key, Device* from_device, DeviceContext* from_device_ctx, const AllocatorAttributes& from_alloc_attr, const Tensor* from_tensor, const DeviceLocality& client_locality, const StatusCallback& done) override { remote_access_->PostToPeer(peer_device, peer_task, key, from_device, from_device_ctx, from_alloc_attr, from_tensor, client_locality, done); } protected: const int64 step_id_; const DeviceMgr* dev_mgr_; // Not owned. std::unique_ptr<PerStepCollectiveRemoteAccess> remote_access_; private: Status CreateCollective(const CollectiveParams& col_params, CollectiveImplementationInterface** col_impl); }; } // namespace tensorflow #endif // TENSORFLOW_CORE_COMMON_RUNTIME_BASE_COLLECTIVE_EXECUTOR_H_
{ "content_hash": "eba019b17b94747856842ea38f736099", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 80, "avg_line_length": 39.43076923076923, "alnum_prop": 0.6896215372610223, "repo_name": "girving/tensorflow", "id": "360ce4db7bdab16d38872722540f2fe08a1b143f", "size": "5794", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "tensorflow/core/common_runtime/base_collective_executor.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "3325" }, { "name": "Batchfile", "bytes": "10132" }, { "name": "C", "bytes": "343258" }, { "name": "C#", "bytes": "8446" }, { "name": "C++", "bytes": "50036869" }, { "name": "CMake", "bytes": "196127" }, { "name": "Dockerfile", "bytes": "36386" }, { "name": "Go", "bytes": "1254086" }, { "name": "HTML", "bytes": "4681865" }, { "name": "Java", "bytes": "867313" }, { "name": "Jupyter Notebook", "bytes": "2604735" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "58787" }, { "name": "Objective-C", "bytes": "15650" }, { "name": "Objective-C++", "bytes": "99243" }, { "name": "PHP", "bytes": "1357" }, { "name": "Perl", "bytes": "7536" }, { "name": "PureBasic", "bytes": "25356" }, { "name": "Python", "bytes": "42041620" }, { "name": "Ruby", "bytes": "553" }, { "name": "Shell", "bytes": "477299" }, { "name": "Smarty", "bytes": "6976" } ], "symlink_target": "" }
module Interface.LpSolve where -- standard modules -- local modules import Helpful.Process --import Data.Time.Clock (diffUTCTime, getCurrentTime) --import Debug.Trace zeroObjective :: String -> Maybe Bool zeroObjective p = case head answer of "This problem is infeasible" -> Nothing "This problem is unbounded" -> Just False otherwise -> do let (chattering, value) = splitAt 29 (answer!!1) if chattering == "Value of objective function: " then if (read value :: Float) == 0.0 then Just True else Just False else error $ "lp_solve answered in an unexpected way.\n" ++ "Expected Answer: \"Value of objective function: " ++ "NUMBER\"\nActual Answer: " ++ lpAnswer where lpAnswer = unsafeReadProcess "lp_solve" [] p answer = lines lpAnswer -- old version --zeroObjective :: String -> Maybe Bool --zeroObjective p = unsafePerformIO $ do ---- start <- getCurrentTime -- (_, clpAnswer, _) <- readProcessWithExitCode "lp_solve" [] p -- let answer = lines clpAnswer ---- end <- getCurrentTime ---- print $ (show (end `diffUTCTime` start) ++ " elapsed. ") ++ clpAnswer -- case head answer of -- "This problem is infeasible" -> return Nothing -- "This problem is unbounded" -> return $ Just False -- otherwise -> do -- let (chattering, value) = splitAt 29 (answer!!1) -- if chattering == "Value of objective function: " then -- if (read value :: Float) == 0.0 then -- return $ Just True -- else -- return $ Just False -- else -- error $ "lp_solve answered in an unexpected way.\n" ++ -- "Expected Answer: \"Value of objective function: " ++ -- "NUMBER\"\nActual Answer: " ++ clpAnswer --{-# NOINLINE zeroObjective #-}
{ "content_hash": "16605b4a8907b13b5d9e73aeeba6e7f6", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 77, "avg_line_length": 36.83018867924528, "alnum_prop": 0.5712090163934426, "repo_name": "spatial-reasoning/zeno", "id": "4a2c6d5722e8903afa8d2465a13e934d1dc6884e", "size": "1952", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Interface/LpSolve.hs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Haskell", "bytes": "3390262" } ], "symlink_target": "" }
module.exports = { Soldier: require("./lib/Soldier.js") }
{ "content_hash": "eafd7c9cdec49f7fa68c80c53fe840eb", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 40, "avg_line_length": 20.333333333333332, "alnum_prop": 0.639344262295082, "repo_name": "nherment/node-infantry", "id": "f016aa42a018706878bbec27c9cad15d216b38d1", "size": "63", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "9409" } ], "symlink_target": "" }
import u2f from "@ledgerhq/hw-transport-u2f"; export declare type TransportCreator = { create: () => Promise<u2f.Transport>; }; export declare const transports: { [name: string]: TransportCreator; }; //# sourceMappingURL=ledger-transport.d.ts.map
{ "content_hash": "935488466cf59231fcff9f8423ef7876", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 46, "avg_line_length": 31.75, "alnum_prop": 0.7244094488188977, "repo_name": "ethers-io/ethers.js", "id": "e4b0fcaa717dbc6446fb7ca7e7372ef9f9cecf22", "size": "254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/hardware-wallets/lib.esm/ledger-transport.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3638" }, { "name": "Java", "bytes": "6255" }, { "name": "JavaScript", "bytes": "400367" }, { "name": "Objective-C", "bytes": "4451" }, { "name": "Python", "bytes": "8828" }, { "name": "Ruby", "bytes": "817" }, { "name": "Shell", "bytes": "840" }, { "name": "Solidity", "bytes": "3691" }, { "name": "Starlark", "bytes": "602" }, { "name": "TypeScript", "bytes": "1208900" }, { "name": "Yacc", "bytes": "6161" } ], "symlink_target": "" }
<?php $_SERVER['SCRIPT_FILENAME'] = FRONTEND_ENTRY_FILE; $_SERVER['SCRIPT_NAME'] = FRONTEND_ENTRY_URL; /** * Application configuration for frontend functional tests */ return yii\helpers\ArrayHelper::merge( require(YII_APP_BASE_PATH . '/_application/common/config/main.php'), require(YII_APP_BASE_PATH . '/_application/common/config/main-local.php'), require(YII_APP_BASE_PATH . '/_application/frontend/config/main.php'), require(YII_APP_BASE_PATH . '/_application/frontend/config/main-local.php'), require(dirname(__DIR__) . '/config.php'), require(dirname(__DIR__) . '/functional.php'), require(__DIR__ . '/config.php'), [ ] );
{ "content_hash": "bc1e61321ac97f2b2fa4f76cedaf6317", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 80, "avg_line_length": 37.166666666666664, "alnum_prop": 0.6681614349775785, "repo_name": "uran1980/yii2-advanced-template-custom", "id": "bedd0e9d940512af7c80a7fdb9293ca3a7649c48", "size": "669", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_application/tests/codeception/config/frontend/functional.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "2461" }, { "name": "Batchfile", "bytes": "1552" }, { "name": "CSS", "bytes": "45764" }, { "name": "JavaScript", "bytes": "11045" }, { "name": "PHP", "bytes": "441977" }, { "name": "Ruby", "bytes": "156" } ], "symlink_target": "" }
// All HloInstruction subclasses are put in this file. #ifndef TENSORFLOW_COMPILER_XLA_SERVICE_HLO_INSTRUCTIONS_H_ #define TENSORFLOW_COMPILER_XLA_SERVICE_HLO_INSTRUCTIONS_H_ #include "absl/memory/memory.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" namespace xla { class HloBatchNormInstruction : public HloInstruction { public: // Returns feature_index field associated with the instruction. The index // represents the index of the feature dimension. int64 feature_index() const { return feature_index_; } // Returns a epsilon value associated with the instruction. The is a small // number added to the variance to avoid divide-by-zero error. float epsilon() const { return epsilon_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; protected: explicit HloBatchNormInstruction(HloOpcode opcode, const Shape& shape, HloInstruction* operand, HloInstruction* scale, float epsilon, int64 feature_index); private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // A small float number added to the variance to avoid divide-by-zero error. float epsilon_ = 0.0f; // An integer value representing the index of the feature dimension. int64 feature_index_ = -1; }; class HloBatchNormTrainingInstruction : public HloBatchNormInstruction { public: explicit HloBatchNormTrainingInstruction(const Shape& shape, HloInstruction* operand, HloInstruction* scale, HloInstruction* offset, float epsilon, int64 feature_index); private: // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; }; class HloBatchNormInferenceInstruction : public HloBatchNormInstruction { public: explicit HloBatchNormInferenceInstruction( const Shape& shape, HloInstruction* operand, HloInstruction* scale, HloInstruction* offset, HloInstruction* mean, HloInstruction* variance, float epsilon, int64 feature_index); private: // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; }; class HloBatchNormGradInstruction : public HloBatchNormInstruction { public: explicit HloBatchNormGradInstruction( const Shape& shape, HloInstruction* operand, HloInstruction* scale, HloInstruction* mean, HloInstruction* variance, HloInstruction* grad_output, float epsilon, int64 feature_index); private: // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; }; class HloFftInstruction : public HloInstruction { public: explicit HloFftInstruction(const Shape& shape, HloInstruction* operand, FftType fft_type, absl::Span<const int64> fft_length); FftType fft_type() const { return fft_type_; } const std::vector<int64>& fft_length() const { return fft_length_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // Describes FFT type for an FFT instruction. FftType fft_type_ = FftType::FFT; // Indicates the FFT length for an FFT instruction. std::vector<int64> fft_length_; }; class HloSendRecvInstruction : public HloInstruction { public: // Returns the channel id associated with the instruction. The id is // shared between each Send/Recv pair and is globally unique to identify each // channel. int64 channel_id() const { return channel_id_; } // Returns whether this send/recv instruction sends data to/from the host. bool is_host_transfer() const { return is_host_transfer_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; protected: explicit HloSendRecvInstruction(HloOpcode opcode, const Shape& shape, int64 channel_id, bool is_host_transfer); private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Represents a unique identifier for each Send/Recv instruction pair. int64 channel_id_; // Whether this send/recv instruction sends data to/from the host. bool is_host_transfer_; }; class HloSendInstruction : public HloSendRecvInstruction { public: explicit HloSendInstruction(HloInstruction* operand, HloInstruction* token, int64 channel_id, bool is_host_transfer); private: // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; }; class HloSendDoneInstruction : public HloSendRecvInstruction { public: explicit HloSendDoneInstruction(HloSendInstruction* operand, bool is_host_transfer); private: // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; }; class HloRecvInstruction : public HloSendRecvInstruction { public: explicit HloRecvInstruction(const Shape& shape, HloInstruction* token, int64 channel_id, bool is_host_transfer); private: // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; }; class HloRecvDoneInstruction : public HloSendRecvInstruction { public: explicit HloRecvDoneInstruction(HloRecvInstruction* operand, bool is_host_transfer); private: // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; }; class HloCollectiveInstruction : public HloInstruction { public: const std::vector<ReplicaGroup>& replica_groups() const { return replica_groups_; } protected: explicit HloCollectiveInstruction( HloOpcode opcode, const Shape& shape, absl::Span<HloInstruction* const> operands, const std::vector<ReplicaGroup>& replica_groups); HloInstructionProto ToProto() const override; std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; std::vector<ReplicaGroup> replica_groups_; }; class HloAllReduceInstruction : public HloCollectiveInstruction { public: explicit HloAllReduceInstruction( const Shape& shape, absl::Span<HloInstruction* const> operands, HloComputation* reduce_computation, const std::vector<ReplicaGroup>& replica_groups, absl::string_view barrier, const absl::optional<int64>& all_reduce_id); // Returns the barrier config used for the AllReduce implementation of // each backend. string all_reduce_barrier() const { return all_reduce_barrier_; } void set_all_reduce_barrier(string barrier) { all_reduce_barrier_ = barrier; } absl::optional<int64> all_reduce_id() const { return all_reduce_id_; } void set_all_reduce_id(const absl::optional<int64>& all_reduce_id); // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; // Returns true if the AllReduce does no communication, so it's equivalent // to a mem copy. bool IsNoop() const; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // The string representation of the barrier config used for AllReduce. string all_reduce_barrier_; // For Allreduce nodes from different modules, if they have the same // all_reduce_id, they will be 'Allreduce'd. If empty, Allreduce will not be // applied cross modules. absl::optional<int64> all_reduce_id_; }; class HloAllToAllInstruction : public HloCollectiveInstruction { public: explicit HloAllToAllInstruction( const Shape& shape, absl::Span<HloInstruction* const> operands, const std::vector<ReplicaGroup>& replica_groups); private: // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; }; class HloCollectivePermuteInstruction : public HloInstruction { public: explicit HloCollectivePermuteInstruction( const Shape& shape, HloInstruction* operand, const std::vector<std::pair<int64, int64>>& source_target_pairs); const std::vector<std::pair<int64, int64>>& source_target_pairs() const { return source_target_pairs_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; const std::vector<std::pair<int64, int64>> source_target_pairs_; }; class HloReverseInstruction : public HloInstruction { public: explicit HloReverseInstruction(const Shape& shape, HloInstruction* operand, absl::Span<const int64> dimensions); // Returns the dimension sizes or numbers associated with this instruction. const std::vector<int64>& dimensions() const override { return dimensions_; } int64 dimensions(int64 index) const override { return dimensions()[index]; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; std::vector<int64> dimensions_; }; class HloConcatenateInstruction : public HloInstruction { public: explicit HloConcatenateInstruction(const Shape& shape, absl::Span<HloInstruction* const> operands, int64 dimension); // Returns the dimension sizes or numbers associated with this instruction. const std::vector<int64>& dimensions() const override { return dimensions_; } int64 dimensions(int64 index) const override { return dimensions()[index]; } // Accessor for the dimension in which a concatenate HLO should occur. int64 concatenate_dimension() const { return dimensions(0); } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; std::vector<int64> dimensions_; }; class HloReduceInstruction : public HloInstruction { public: explicit HloReduceInstruction(const Shape& shape, absl::Span<HloInstruction* const> args, absl::Span<const int64> dimensions_to_reduce, HloComputation* reduce_computation); // Returns the dimension sizes or numbers associated with this instruction. const std::vector<int64>& dimensions() const override { return dimensions_; } int64 dimensions(int64 index) const override { return dimensions()[index]; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; // Returns the number of input arrays (and, consequentially, the number of // init values) this reduce has. int64 input_count() const { return operand_count() / 2; } // Returns the input tensors to be reduced. absl::Span<HloInstruction* const> inputs() const { return absl::MakeSpan(operands()).subspan(0, input_count()); } // Returns the init values of the reduction. absl::Span<HloInstruction* const> init_values() const { return absl::MakeSpan(operands()).subspan(input_count(), operand_count()); } private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; std::vector<int64> dimensions_; }; class HloSortInstruction : public HloInstruction { public: explicit HloSortInstruction(const Shape& shape, int64 dimension, HloInstruction* keys, absl::Span<HloInstruction* const> values = {}); // Returns the dimension sizes or numbers associated with this instruction. const std::vector<int64>& dimensions() const override { return dimensions_; } int64 dimensions(int64 index) const override { return dimensions()[index]; } // Returns the sort dimension for this instruction int64 sort_dimension() const { return dimensions(0); } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; // Returns the key operand to this instruction. const HloInstruction* keys() const { return operand(0); } HloInstruction* mutable_keys() { return mutable_operand(0); } // Returns the number of value operands. int64 values_count() const { return operand_count() - 1; } private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; std::vector<int64> dimensions_; }; class HloTransposeInstruction : public HloInstruction { public: explicit HloTransposeInstruction(const Shape& shape, HloInstruction* operand, absl::Span<const int64> dimensions); // Returns the dimension sizes or numbers associated with this instruction. const std::vector<int64>& dimensions() const override { return dimensions_; } int64 dimensions(int64 index) const override { return dimensions()[index]; } // Returns whether this instruction does a rank-2 transposition. bool IsRank2Transpose() const; // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; std::vector<int64> dimensions_; }; class HloBroadcastInstruction : public HloInstruction { public: explicit HloBroadcastInstruction(const Shape& shape, HloInstruction* operand, absl::Span<const int64> broadcast_dimension); // Returns the dimension sizes or numbers associated with this instruction. const std::vector<int64>& dimensions() const override { return dimensions_; } int64 dimensions(int64 index) const override { return dimensions()[index]; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; std::vector<int64> dimensions_; }; class HloMapInstruction : public HloInstruction { public: explicit HloMapInstruction(const Shape& shape, absl::Span<HloInstruction* const> operands, HloComputation* map_computation); // Returns the dimension sizes or numbers associated with this instruction. const std::vector<int64>& dimensions() const override { return dimensions_; } int64 dimensions(int64 index) const override { return dimensions()[index]; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: bool IsElementwiseImpl( const absl::optional<int64>& operand_idx) const override; std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; std::vector<int64> dimensions_; }; class HloSliceInstruction : public HloInstruction { public: explicit HloSliceInstruction(const Shape& shape, HloInstruction* operand, absl::Span<const int64> start_indices, absl::Span<const int64> limit_indices, absl::Span<const int64> strides); HloInstructionProto ToProto() const override; // Returns the start index in the given dimension for a slice node. int64 slice_starts(int64 dimension) const { return slice_starts_[dimension]; } const std::vector<int64>& slice_starts() const { return slice_starts_; } // Returns the (exclusive) limit index in the given dimension for a slice // node. int64 slice_limits(int64 dimension) const { return slice_limits_[dimension]; } const std::vector<int64>& slice_limits() const { return slice_limits_; } // Returns the stride in the given dimension for a slice node. int64 slice_strides(int64 dimension) const { return slice_strides_[dimension]; } const std::vector<int64>& slice_strides() const { return slice_strides_; } private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // Describes the [begin, end) index range for a slice. std::vector<int64> slice_starts_; std::vector<int64> slice_limits_; std::vector<int64> slice_strides_; }; class HloConstantInstruction : public HloInstruction { public: explicit HloConstantInstruction(Literal literal); // Used when the literal is too large and dropped. explicit HloConstantInstruction(const Shape& shape); // Returns the literal associated with this instruction. const Literal& literal() const { return *literal_; } // Returns whether there is literal associated with this instruction. bool HasLiteral() const { return literal_.has_value(); } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; // Change the layout for an Constant Hlo instruction to match new_layout. For // tuple shaped constants shape_index is the path to the internal array // subshape whose layout needs to be changed. void RelayoutConstant(const Layout& new_layout, const ShapeIndex& shape_index = {}); private: bool IsElementwiseImpl( const absl::optional<int64>& operand_idx) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; string OperandsToStringWithCanonicalNameMap( const HloPrintOptions& options, CanonicalNameMap* canonical_name_map) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; absl::optional<Literal> literal_; }; class HloTraceInstruction : public HloInstruction { public: explicit HloTraceInstruction(const string& tag, HloInstruction* operand); // Returns a tag to be used in tracing. string TracingTag() const { return literal_.GetR1U8AsString(); } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; Literal literal_; }; class HloFusionInstruction : public HloInstruction { public: explicit HloFusionInstruction(const Shape& shape, FusionKind fusion_kind, HloInstruction* fused_root); explicit HloFusionInstruction(const Shape& shape, FusionKind fusion_kind, absl::Span<HloInstruction* const> operands, HloComputation* fusion_computation); string ToCategory() const override; // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; // Adds a new operand the fusion instruction. HloInstruction* AddFusionOperand(HloInstruction* new_operand); // Merges the fused instructions from 'instruction_to_merge' into the // fused instruction set of 'this', updating operands as necessary. // // Predondition: 'instruction_to_merge' must be an operand of 'this'. void MergeFusionInstruction(HloFusionInstruction* instruction_to_merge); // Merges the fused instructions from instruction_to_merge into the fused // instruction set of 'this' and generates multioutput fusion instructions. // All the users of instruction_to_merge will be redirected to 'this' // instruction. instruction_to_merge will be removed from its parent // computation. void MergeFusionInstructionIntoMultiOutput( HloFusionInstruction* instruction_to_merge); // Fuses the given instruction in this fusion instruction. instruction_to_fuse // is cloned and the clone is placed in the fusion // instruction. instruction_to_fuse is unchanged. Instruction is cloned rather // than moved to cleanly handle the case where the instruction has a use // outside the fusion instruction. Moving such an instruction into a fusion // instruction would violate the single-result invariant of HLO instructions // and significantly complicate code generation. HloInstruction* FuseInstruction(HloInstruction* instruction_to_fuse) { return FuseInstructionInternal(instruction_to_fuse); } // Fuses the given instruction in this fusion instruction and generate // multioutput fusion instruction. A clone of the instruction_to_fuse will // be part of the output of fusion instructions. The users of // instruction_to_fuse will be redirected to this fusion instructions. // instruction_to_fuse will be removed from its parent computation. HloInstruction* FuseInstructionIntoMultiOutput( HloInstruction* instruction_to_fuse) { return FuseInstructionInternal(instruction_to_fuse, /* add_output */ true); } // Returns the computation for this fused instruction. HloComputation* fused_instructions_computation() const; // Returns the root instruction of the fused expression contained within this // fusion instruction. HloInstruction* fused_expression_root() const; // Returns the list of fused instructions inside this fusion instruction. The // returned type is a range of HloInstruction*s. const tensorflow::gtl::iterator_range<UnwrappingIterator< std::list<std::unique_ptr<HloInstruction>>::const_iterator>> fused_instructions() const; const tensorflow::gtl::iterator_range< UnwrappingIterator<std::list<std::unique_ptr<HloInstruction>>::iterator>> fused_instructions(); // Gets the number of instructions inside this fusion instruction. int64 fused_instruction_count() const; // Returns the fused parameter instruction in this fusion instruction // corresponding to the given parameter number. HloInstruction* fused_parameter(int64 parameter_number) const; // Returns the vector of fused parameters inside this fusion instruction. const std::vector<HloInstruction*>& fused_parameters() const; // Returns true if this instruction is a fusion instruction that generates // multiple outputs. const bool IsMultiOutputFusion() const { return fused_expression_root()->opcode() == HloOpcode::kTuple; } FusionKind fusion_kind() const { return fusion_kind_; } void set_fusion_kind(FusionKind kind) { fusion_kind_ = kind; } // If multiple operands are the same instruction, keeps only one of them. Status DeduplicateFusionOperands(); private: // Fuses the given instruction into this fusion instruction. When add_output // is false (which is the default), instruction_to_fuse is cloned and the // clone is placed in the fusion instruction. instruction_to_fuse is // unchanged. // // When add_output is true, a clone of the instruction_to_fuse will be part // of the output of fusion instructions. The users of instruction_to_fuse // will be redirected to this fusion instructions. instruction_to_fuse will // be removed from its parent computation. HloInstruction* FuseInstructionInternal(HloInstruction* instruction_to_fuse, bool add_output = false); // Clones the given instruction_to_fuse and insert the clone into this fusion // instruction. If add_output is true, a clone of instruction_to_fuse will // be in the output of the this fusion instruction (part of the tuple of the // fusion root). HloInstruction* CloneAndFuseInternal(HloInstruction* instruction_to_fuse, bool add_output = false); bool IsElementwiseImpl( const absl::optional<int64>& operand_idx) const override; std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; uint64 InnerHash() const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // The type of the fusion. Used by kFusion only. FusionKind fusion_kind_; }; class HloRngInstruction : public HloInstruction { public: explicit HloRngInstruction(const Shape& shape, RandomDistribution distribution, absl::Span<HloInstruction* const> parameters); // Returns the random distribution for this rng node. RandomDistribution random_distribution() const { return distribution_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: bool IsElementwiseImpl( const absl::optional<int64>& operand_idx) const override; std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // The distribution requested for random number generation. RandomDistribution distribution_; }; class HloParameterInstruction : public HloInstruction { public: explicit HloParameterInstruction(int64 parameter_number, const Shape& shape, const string& name); int64 parameter_number() const { return parameter_number_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; string OperandsToStringWithCanonicalNameMap( const HloPrintOptions& options, CanonicalNameMap* canonical_name_map) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; int64 parameter_number_ = 0; }; class HloGetTupleElementInstruction : public HloInstruction { public: explicit HloGetTupleElementInstruction(const Shape& shape, HloInstruction* operand, int64 index); // Returns the tuple index associated with this instruction. int64 tuple_index() const { return tuple_index_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; int64 tuple_index_ = -1; }; class HloReducePrecisionInstruction : public HloInstruction { public: explicit HloReducePrecisionInstruction(const Shape& shape, HloInstruction* operand, const int exponent_bits, const int mantissa_bits); // Returns the number of exponent bits for a reduce-precision node. int32 exponent_bits() const { return exponent_bits_; } // Returns the number of mantissa bits for a reduce-precision node. int32 mantissa_bits() const { return mantissa_bits_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // The bit sizes for a reduce-precision operation. int32 exponent_bits_ = 0; int32 mantissa_bits_ = 0; }; class HloInfeedInstruction : public HloInstruction { public: explicit HloInfeedInstruction(const Shape& infeed_shape, HloInstruction* token_operand, const string& config); // Returns the infeed configuration string. The infeed configuration includes // any metadata needed for the backend compiler (e.g., infeed buffer address) // and is target-dependent. string infeed_config() const { return infeed_config_; } void set_infeed_config(const string& config) { infeed_config_ = config; } // Returns the shape of the data received by the infeed. This is not the same // as the shape of the infeed instruction which produces a tuple containing // the infeed data shape and a TOKEN. const Shape& infeed_shape() const { TF_DCHECK_OK(ShapeUtil::ValidateShapeWithOptionalLayout(shape())); return ShapeUtil::GetSubshape(shape(), {0}); } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // The string representation of the infeed configuration. string infeed_config_; }; class HloOutfeedInstruction : public HloInstruction { public: explicit HloOutfeedInstruction(const Shape& outfeed_shape, HloInstruction* operand, HloInstruction* token_operand, absl::string_view outfeed_config); // Returns the shape for the Outfeed instruction. const Shape& outfeed_shape() const { return outfeed_shape_; } // Returns the config for the Outfeed instruction. const string& outfeed_config() const { return outfeed_config_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // Shape of outfeed request. Shape outfeed_shape_; // Outfeed configuration information, only present for kOutfeed. string outfeed_config_; }; class HloConvolutionInstruction : public HloInstruction { public: explicit HloConvolutionInstruction( const Shape& shape, HloInstruction* lhs, HloInstruction* rhs, int64 feature_group_count, int64 batch_group_count, const Window& window, const ConvolutionDimensionNumbers& dimension_numbers, const PrecisionConfig& precision_config); const Window& window() const override { return window_; } void set_window(const Window& window) override { window_ = window; } const ConvolutionDimensionNumbers& convolution_dimension_numbers() const { return convolution_dimension_numbers_; } void set_convolution_dimension_numbers( const ConvolutionDimensionNumbers& dnums) { convolution_dimension_numbers_ = dnums; } // The number of feature groups. Must be a divisor of the input feature // dimension and output feature dimension. int64 feature_group_count() const { return feature_group_count_; } // The number of feature groups. Must be a divisor of the input batch // dimension. int64 batch_group_count() const { return batch_group_count_; } // Returns the information used to tell the implementation information about // what sort of precision is requested. The meaning of the field is backend // specific. At the moment, it is only supported for kConvolution and kDot. // Transformations on one kDot or kConvolution to another will preserve this // information. Transformations to other HLOs will not preserve this // information but it is presumed that the alternate lowering is strictly // superior. const PrecisionConfig& precision_config() const { return precision_config_; } PrecisionConfig* mutable_precision_config() { return &precision_config_; } string ToCategory() const override; // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // The number of feature groups. Must be a divisor of the input feature // dimension and output feature dimension. int64 feature_group_count_; // The number of feature groups. Must be a divisor of the input batch // dimension. int64 batch_group_count_; // Describes the window used for a convolution. Window window_; // Describes the dimension numbers used for a convolution. ConvolutionDimensionNumbers convolution_dimension_numbers_; // Information used to communicate to the implementation about the algorithm // used to produce results. See the documentation on precision_config(). PrecisionConfig precision_config_; }; class HloReduceWindowInstruction : public HloInstruction { public: explicit HloReduceWindowInstruction(const Shape& shape, HloInstruction* operand, HloInstruction* init_value, const Window& window, HloComputation* reduce_computation); const Window& window() const override { return window_; } void set_window(const Window& window) override { window_ = window; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; Window window_; }; class HloSelectAndScatterInstruction : public HloInstruction { public: explicit HloSelectAndScatterInstruction( const Shape& shape, HloInstruction* operand, HloComputation* select, const Window& window, HloInstruction* source, HloInstruction* init_value, HloComputation* scatter); const Window& window() const override { return window_; } void set_window(const Window& window) override { window_ = window; } // Gets/sets the select or scatter HloComputation for SelectAndScatter. The // setters should only be called by HloModule or HloComputation methods. HloComputation* select() const { return called_computations()[kSelectComputationIndex]; } HloComputation* scatter() const { return called_computations()[kScatterComputationIndex]; } void set_select(HloComputation* computation) { // Don't allow changing the computation for fused instructions so we don't // have to recompute called_instructions for the entire fusion instruction. CHECK(!IsFused()); set_called_computation(kSelectComputationIndex, computation); } void set_scatter(HloComputation* computation) { // Don't allow changing the computation for fused instructions so we don't // have to recompute called_instructions for the entire fusion instruction. CHECK(!IsFused()); set_called_computation(kScatterComputationIndex, computation); } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; Window window_; }; class HloCustomCallInstruction : public HloInstruction { public: HloCustomCallInstruction(const Shape& shape, absl::Span<HloInstruction* const> operands, absl::string_view custom_call_target, absl::string_view opaque); // Constructor for a custom call with constrained layout. 'shape' and // 'operands_with_layout' must all have layouts. HloCustomCallInstruction(const Shape& shape, absl::Span<HloInstruction* const> operands, absl::string_view custom_call_target, absl::string_view opaque, absl::Span<const Shape> operand_shapes_with_layout); const Window& window() const override { CHECK(window_ != nullptr); return *window_; } void set_window(const Window& window) override { window_ = absl::make_unique<Window>(window); } const ConvolutionDimensionNumbers& convolution_dimension_numbers() const { CHECK(convolution_dimension_numbers_ != nullptr); return *convolution_dimension_numbers_; } void set_convolution_dimension_numbers( const ConvolutionDimensionNumbers& dnums) { convolution_dimension_numbers_ = absl::make_unique<ConvolutionDimensionNumbers>(dnums); } const string& opaque() const { return opaque_; } const string& custom_call_target() const { return custom_call_target_; } void set_feature_group_count(int64 feature_group_count) { feature_group_count_ = feature_group_count; } void set_batch_group_count(int64 batch_group_count) { batch_group_count_ = batch_group_count; } int64 feature_group_count() const { return feature_group_count_; } int64 batch_group_count() const { return batch_group_count_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; // Returns whether the result and operand layouts are constrained. bool layout_constrained() const { return layout_constrained_; } // Returns the shapes (with layout) of the operands. CHECKs if this custom // call does not have constrained layouts. const std::vector<Shape>& operand_shapes_with_layout() const { CHECK(layout_constrained()); return operand_shapes_with_layout_; } private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // Name of a global symbol to call. string custom_call_target_; // Opaque string interpreted by the backend. string opaque_; // Describes the window in a windowed operation such as convolution. std::unique_ptr<Window> window_; // Describes the dimension numbers used for a convolution. std::unique_ptr<ConvolutionDimensionNumbers> convolution_dimension_numbers_; // The number of feature groups. This is used for grouped convolutions. int64 feature_group_count_; int64 batch_group_count_; // Whether the result and operand layouts are constrained. bool layout_constrained_; // For layout-constrained custom calls, this vector holds the shape with // layout for each operand. std::vector<Shape> operand_shapes_with_layout_; }; class HloPadInstruction : public HloInstruction { public: explicit HloPadInstruction(const Shape& shape, HloInstruction* operand, HloInstruction* padding_value, const PaddingConfig& padding_config); // Returns the padding configuration for a pad node. const PaddingConfig& padding_config() const { return padding_config_; } // Returns the padding value. const HloInstruction* padding_value() const { return operand(1); } HloInstruction* mutable_padding_value() { return mutable_operand(1); } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // The padding configuration that describes the edge padding and interior // padding of this pad instruction. PaddingConfig padding_config_; }; class HloDynamicIndexInstruction : public HloInstruction { public: explicit HloDynamicIndexInstruction(HloOpcode opcode, const Shape& shape) : HloInstruction(opcode, shape) {} virtual int64 first_index_operand_number() const = 0; // Returns a subspan of operands which represent the start indices. absl::Span<HloInstruction* const> index_operands() const { return absl::MakeSpan(operands()).subspan(first_index_operand_number()); } // Returns the shapes of the index operands. std::vector<Shape> index_shapes() const { std::vector<Shape> shapes; auto indices = index_operands(); for (const HloInstruction* index : indices) { shapes.push_back(index->shape()); } return shapes; } }; class HloDynamicSliceInstruction : public HloDynamicIndexInstruction { public: explicit HloDynamicSliceInstruction(const Shape& shape, HloInstruction* operand, HloInstruction* start_indices, absl::Span<const int64> slice_sizes); explicit HloDynamicSliceInstruction( const Shape& shape, HloInstruction* operand, absl::Span<HloInstruction* const> start_indices, absl::Span<const int64> slice_sizes); // Old methods kept for smooth subclassing transition END. // Returns the size of the slice in the given dimension for a dynamic // slice node. int64 slice_sizes(int64 dimension) const { return dynamic_slice_sizes_[dimension]; } const std::vector<int64>& dynamic_slice_sizes() const { return dynamic_slice_sizes_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; int64 first_index_operand_number() const override { return 1; } private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // Describes the [start, start + size) range size for a dynamic slice // ('start' is specified dynamically in the second operand of the operation). std::vector<int64> dynamic_slice_sizes_; }; class HloDynamicUpdateSliceInstruction : public HloDynamicIndexInstruction { public: explicit HloDynamicUpdateSliceInstruction(const Shape& shape, HloInstruction* operand, HloInstruction* update, HloInstruction* start_indices); explicit HloDynamicUpdateSliceInstruction( const Shape& shape, HloInstruction* operand, HloInstruction* update, absl::Span<HloInstruction* const> start_indices); int64 first_index_operand_number() const override { return 2; } }; class HloGatherInstruction : public HloInstruction { public: explicit HloGatherInstruction( const Shape& shape, HloInstruction* operand, HloInstruction* start_indices, const GatherDimensionNumbers& gather_dim_numbers, absl::Span<const int64> slice_sizes); const GatherDimensionNumbers& gather_dimension_numbers() const { CHECK(gather_dimension_numbers_ != nullptr); return *gather_dimension_numbers_; } absl::Span<const int64> gather_slice_sizes() const { return gather_slice_sizes_; } // Returns the dump string of the gather dimension numbers. string GatherDimensionNumbersToString() const; // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; // Creates an instance of GatherDimensionNumbers. static GatherDimensionNumbers MakeGatherDimNumbers( absl::Span<const int64> offset_dims, absl::Span<const int64> collapsed_slice_dims, absl::Span<const int64> start_index_map, int64 index_vector_dim); private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; std::unique_ptr<GatherDimensionNumbers> gather_dimension_numbers_; std::vector<int64> gather_slice_sizes_; }; class HloScatterInstruction : public HloInstruction { public: explicit HloScatterInstruction( const Shape& shape, HloInstruction* operand, HloInstruction* scatter_indices, HloInstruction* updates, HloComputation* update_computation, const ScatterDimensionNumbers& scatter_dim_numbers); const ScatterDimensionNumbers& scatter_dimension_numbers() const { CHECK(scatter_dimension_numbers_ != nullptr); return *scatter_dimension_numbers_; } // Returns the dump string of the scatter dimension numbers. string ScatterDimensionNumbersToString() const; // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; // Creates an instance of ScatterDimensionNumbers. static ScatterDimensionNumbers MakeScatterDimNumbers( absl::Span<const int64> update_window_dims, absl::Span<const int64> inserted_window_dims, absl::Span<const int64> scatter_dims_to_operand_dims, int64 index_vector_dim); private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; std::unique_ptr<ScatterDimensionNumbers> scatter_dimension_numbers_; }; class HloIotaInstruction : public HloInstruction { public: explicit HloIotaInstruction(const Shape& shape, int64 iota_dimension); // Returns the dimension sizes or numbers associated with this instruction. int64 iota_dimension() const { return iota_dimension_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; const int64 iota_dimension_; }; class HloDotInstruction : public HloInstruction { public: // Creates a dot op with operands 'lhs' and 'rhs' with contracting and batch // dimensions specified in 'dimension_numbers'. explicit HloDotInstruction(const Shape& shape, HloInstruction* lhs, HloInstruction* rhs, const DotDimensionNumbers& dimension_numbers, const PrecisionConfig& precision_config); // Returns data on the dimension numbers used for a dot operation. const DotDimensionNumbers& dot_dimension_numbers() const { return dot_dimension_numbers_; } // Returns the information used to tell the implementation information about // what sort of precision is requested. The meaning of the field is backend // specific. At the moment, it is only supported for kConvolution and kDot. // Transformations on one kDot or kConvolution to another will preserve this // information. Transformations to other HLOs will not preserve this // information but it is presumed that the alternate lowering is strictly // superior. const PrecisionConfig& precision_config() const { return precision_config_; } PrecisionConfig* mutable_precision_config() { return &precision_config_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; // Returns the dump string of the dot dimension numbers. string DotDimensionNumbersToString() const; // Describes the dimension numbers used for a dot. DotDimensionNumbers dot_dimension_numbers_; // Information used to communicate to the implementation about the algorithm // used to produce results. See the documentation on precision_config(). PrecisionConfig precision_config_; }; class HloDomainInstruction : public HloInstruction { public: explicit HloDomainInstruction( const Shape& shape, HloInstruction* operand, std::unique_ptr<DomainMetadata> operand_side_metadata, std::unique_ptr<DomainMetadata> user_side_metadata); // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; // Retrieves the operand side metadata of a kDomain instruction. const DomainMetadata& operand_side_metadata() const { return *operand_side_metadata_; } // Retrieves the user side metadata of a kDomain instruction. const DomainMetadata& user_side_metadata() const { return *user_side_metadata_; } private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; std::unique_ptr<DomainMetadata> operand_side_metadata_; std::unique_ptr<DomainMetadata> user_side_metadata_; }; class HloGetDimensionSizeInstruction : public HloInstruction { public: explicit HloGetDimensionSizeInstruction(const Shape& shape, HloInstruction* operand, int64 dimension); // Returns the dimension sizes or numbers associated with this instruction. int64 dimension() const { return dimension_; } // Returns a serialized representation of this instruction. HloInstructionProto ToProto() const override; private: std::vector<string> ExtraAttributesToStringImpl( const HloPrintOptions& options) const override; bool IdenticalSlowPath( const HloInstruction& other, const std::function<bool(const HloComputation*, const HloComputation*)>& eq_computations) const override; // Implementation for non-common logic of CloneWithNewOperands. std::unique_ptr<HloInstruction> CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const override; int64 dimension_; }; } // namespace xla #endif // TENSORFLOW_COMPILER_XLA_SERVICE_HLO_INSTRUCTIONS_H_
{ "content_hash": "79de1580b83e3c12c06d615e51e979df", "timestamp": "", "source": "github", "line_count": 1462, "max_line_length": 80, "avg_line_length": 42.9781121751026, "alnum_prop": 0.7259445523124423, "repo_name": "apark263/tensorflow", "id": "1b4a94753cda8aba8d50836b9d51b7c3fd5807f6", "size": "63502", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow/compiler/xla/service/hlo_instructions.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "2867" }, { "name": "Batchfile", "bytes": "14734" }, { "name": "C", "bytes": "561314" }, { "name": "C#", "bytes": "8446" }, { "name": "C++", "bytes": "54581021" }, { "name": "CMake", "bytes": "207169" }, { "name": "Dockerfile", "bytes": "39024" }, { "name": "Go", "bytes": "1373561" }, { "name": "HTML", "bytes": "4680118" }, { "name": "Java", "bytes": "899393" }, { "name": "Jupyter Notebook", "bytes": "2618454" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "75994" }, { "name": "Objective-C", "bytes": "16140" }, { "name": "Objective-C++", "bytes": "102889" }, { "name": "PHP", "bytes": "14340" }, { "name": "Pascal", "bytes": "399" }, { "name": "Perl", "bytes": "7536" }, { "name": "PureBasic", "bytes": "25356" }, { "name": "Python", "bytes": "44616385" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Ruby", "bytes": "838" }, { "name": "Shell", "bytes": "504099" }, { "name": "Smarty", "bytes": "10072" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="GradleSettings"> <option name="linkedExternalProjectsSettings"> <GradleProjectSettings> <option name="distributionType" value="LOCAL" /> <option name="externalProjectPath" value="$PROJECT_DIR$" /> <option name="gradleHome" value="D:\develop\Android\studio\gradle\gradle-2.14.1" /> <option name="modules"> <set> <option value="$PROJECT_DIR$" /> <option value="$PROJECT_DIR$/app" /> </set> </option> <option name="resolveModulePerSourceSet" value="false" /> </GradleProjectSettings> </option> </component> </project>
{ "content_hash": "2fc617af782c0fe68846154812b6a0b5", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 91, "avg_line_length": 37.26315789473684, "alnum_prop": 0.6087570621468926, "repo_name": "zengerdev/homeweather", "id": "fe234dcf4b7050d2b80c472a1eef27230e9a5bcc", "size": "708", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/gradle.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "32865" } ], "symlink_target": "" }
package com.github.davidmoten.rx.jdbc; import static com.github.davidmoten.rx.Functions.constant; import static com.github.davidmoten.rx.RxUtil.log; import static com.github.davidmoten.rx.RxUtil.toEmpty; import static com.github.davidmoten.rx.jdbc.DatabaseCreator.connectionProvider; import static com.github.davidmoten.rx.jdbc.DatabaseCreator.createDatabase; import static com.github.davidmoten.rx.jdbc.DatabaseCreator.nextUrl; import static com.github.davidmoten.rx.jdbc.TestingUtil.countDown; import static java.util.Arrays.asList; import static org.easymock.EasyMock.createMock; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static rx.Observable.just; import java.io.IOException; import java.io.Reader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.easymock.EasyMock; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.davidmoten.rx.RxUtil; import com.github.davidmoten.rx.jdbc.annotations.Column; import com.github.davidmoten.rx.jdbc.annotations.Index; import com.github.davidmoten.rx.jdbc.annotations.Query; import com.github.davidmoten.rx.jdbc.exceptions.TransactionAlreadyOpenException; import com.github.davidmoten.rx.jdbc.tuple.Tuple2; import com.github.davidmoten.rx.jdbc.tuple.Tuple3; import com.github.davidmoten.rx.jdbc.tuple.Tuple4; import com.github.davidmoten.rx.jdbc.tuple.Tuple5; import com.github.davidmoten.rx.jdbc.tuple.Tuple6; import com.github.davidmoten.rx.jdbc.tuple.Tuple7; import com.github.davidmoten.rx.jdbc.tuple.TupleN; import com.zaxxer.hikari.HikariDataSource; import rx.Observable; import rx.Observable.Operator; import rx.Observer; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func1; import rx.observables.MathObservable; import rx.observers.TestSubscriber; public abstract class DatabaseTestBase { /** * <p> * Timeout used for latch.await() and similar. If too short then short * machine lockups on build server (which is known to happen on CloudBees * Jenkins infrastructure) will cause undesired test failures. * </p> * * <p> * While your test is still failing use a lower value of course so that you * get rapid turnaround. However, once passing switch the timeout to this * standard timeout value. * </p> */ private static final int TIMEOUT_SECONDS = 3; private static final Logger log = LoggerFactory.getLogger(DatabaseTestBase.class); private final boolean async; public DatabaseTestBase(boolean async) { this.async = async; } Database db() { if (async) return DatabaseCreator.db().asynchronous(); else return DatabaseCreator.db(); } @Test public void testSimpleExample() { Observable<String> names = db().select("select name from person order by name") .getAs(String.class); // convert the names to a list for unit test List<String> list = names.toList().toBlocking().single(); log.debug("list=" + list); assertEquals(asList("FRED", "JOSEPH", "MARMADUKE"), list); } @Test public void testCountQuery() { int count = db() // select names .select("select name from person where name >?") // set name parameter .parameter("ALEX") // count results .count() // get count .first() // block till finished .toBlocking().single(); assertEquals(3, count); } @Test public void testTransactionUsingCount() { Database db = db(); Func1<? super Integer, Boolean> isZero = new Func1<Integer, Boolean>() { @Override public Boolean call(Integer t1) { return t1 == 0; } }; Observable<Integer> existingRows = db // select names .select("select name from person where name=?") // set name parameter .parameter("FRED") // is part of transaction .dependsOn(db.beginTransaction()) // get result count .count() // return empty if count = 0 .filter(isZero); Observable<Integer> update = db // insert record if does not exist .update("insert into person(name,score) values(?,0)") // get parameters from last query .parameters(existingRows.map(constant("FRED"))) // return num rows affected .count(); boolean committed = db.commit(update).toBlocking().single(); assertTrue(committed); } @Test public void testTransactionOnCommit() { Database db = db(); Observable<Boolean> begin = db.beginTransaction(); Observable<Integer> updateCount = db // set everyones score to 99 .update("update person set score=?") // is within transaction .dependsOn(begin) // new score .parameter(99) // execute .count(); Observable<Boolean> commit = db.commit(updateCount); long count = db.select("select count(*) from person where score=?") // set score .parameter(99) // depends on .dependsOn(commit) // return as Long .getAs(Long.class) // log .doOnEach(RxUtil.log()) // get answer .toBlocking().single(); assertEquals(3, count); } @Test public void testSelectErrorResetsTransactionContextInDatabaseClass() { Database db = db(); Observable<Integer> select = db // select names .select("select namez from person where name=?") // set name parameter .parameter("FRED") // is part of transaction .dependsOn(db.beginTransaction()) // get result count .count(); final AtomicBoolean transactionClosed = new AtomicBoolean(true); db.commit(select).doOnError(new Action1<Throwable>() { @Override public void call(Throwable t) { System.out.println(t.getMessage()); if (t instanceof TransactionAlreadyOpenException) transactionClosed.set(false); } }).retry(1).subscribe(ignore()); assertTrue(transactionClosed.get()); } @Test public void testUpdateErrorResetsTransactionContextInDatabaseClass() { Database db = db(); Observable<Integer> update = db // select names .update("zzz") // set name parameter .parameter("FRED") // is part of transaction .dependsOn(db.beginTransaction()) // get result count .count(); final AtomicBoolean transactionClosed = new AtomicBoolean(true); db.commit(update).doOnError(new Action1<Throwable>() { @Override public void call(Throwable t) { System.out.println(t.getMessage()); if (t instanceof TransactionAlreadyOpenException) transactionClosed.set(false); } }).retry(1).subscribe(ignore()); assertTrue(transactionClosed.get()); } private static <T> Observer<T> ignore() { return new Observer<T>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(T t) { } }; } @Test public void testPushEmptyList() { Database db = db(); Observable<Integer> rowsAffected = Observable // generate two integers .range(1, 2) // replace the integers with empty lists .map(toEmpty()) // execute the update .lift(db.update("update person set score = score + 1").parameterListOperator()) // flatten .lift(RxUtil.<Integer> flatten()) // total the affected records .lift(SUM_INTEGER); assertIs(6, rowsAffected); } @Test public void testRunScript() { Observable<String> commands = just("create table temp1(id integer)", "drop table temp1"); db().run(commands).count().toBlocking().single(); } @Test public void testTransactionOnCommitDoesntOccurUnlessSubscribedTo() { Database db = db(); Observable<Boolean> begin = db.beginTransaction(); Observable<Integer> u = db.update("update person set score=?").dependsOn(begin) .parameter(99).count(); db.commit(u); // note that last transaction was not listed as a dependency of the next // query long count = db.select("select count(*) from person where score=?").parameter(99) .getAs(Long.class).toBlocking().single(); assertEquals(0, count); } @Test public void testTransactionOnRollback() { Database db = db(); Observable<Boolean> begin = db.beginTransaction(); Observable<Integer> updateCount = db.update("update person set score=?").dependsOn(begin) .parameter(99).count(); db.rollback(updateCount); long count = db.select("select count(*) from person where score=?").parameter(99) .dependsOnLastTransaction().getAs(Long.class).toBlocking().single(); assertEquals(0, count); } @Test public void testUpdateAndSelectWithTransaction() { Database db = db(); Observable<Boolean> begin = db.beginTransaction(); Observable<Integer> updateCount = db // update everyone's score to 99 .update("update person set score=?") // in transaction .dependsOn(begin) // new score .parameter(99) // execute .count(); long count = db.select("select count(*) from person where score=?") // where score = 99 .parameter(99) // depends on .dependsOn(updateCount) // as long value .getAs(Long.class).toBlocking().single(); assertEquals(3, count); } @Test public void testUseParameterObservable() { int count = db().select("select name from person where name >?") .parameters(Observable.just("ALEX")).count().toBlocking().single(); assertEquals(3, count); } @Test public void testTwoParameters() { List<String> list = db().select("select name from person where name > ? and name < ?") .parameter("ALEX").parameter("LOUIS").getAs(String.class).toList().toBlocking() .single(); assertEquals(asList("FRED", "JOSEPH"), list); } @Test public void testTakeFewerThanAvailable() { int count = db().select("select name from person where name >?").parameter("ALEX") .get(new ResultSetMapper<Integer>() { @Override public Integer call(ResultSet rs) throws SQLException { return 1; } }).take(2).count().first().toBlocking().single(); assertEquals(2, count); } @Test public void testJdbcObservableCountLettersInAllNames() { int count = MathObservable .sumInteger(db() // select .select("select name from person where name >?") // set name .parameter("ALEX") // count letters .get(COUNT_LETTERS_IN_NAME)) // first result .first() // block and get result .toBlocking().single(); assertEquals(19, count); } private static final ResultSetMapper<Integer> COUNT_LETTERS_IN_NAME = new ResultSetMapper<Integer>() { @Override public Integer call(ResultSet rs) throws SQLException { return rs.getString("name").length(); } }; @Test public void testTransformToTuple2AndTestActionsPrintln() { Tuple2<String, Integer> tuple = db() .select("select name,score from person where name >? order by name") .parameter("ALEX").getAs(String.class, Integer.class).last().toBlocking().single(); assertEquals("MARMADUKE", tuple.value1()); assertEquals(25, (int) tuple.value2()); } @Test public void testTransformToTupleN() { TupleN<String> tuple = db().select("select name, lower(name) from person order by name") .getTupleN(String.class).first().toBlocking().single(); assertEquals("FRED", tuple.values().get(0)); assertEquals("fred", tuple.values().get(1)); } @Test public void testMultipleSetsOfParameters() { List<Integer> list = db().select("select score from person where name=?") // first param .parameter("FRED") // second param .parameter("JOSEPH") // score as integer .getAs(Integer.class) // log .doOnEach(log()) // sort .toSortedList() // block and get .toBlocking().single(); assertEquals(asList(21, 34), list); } @Test public void testNoParams() { List<Tuple2<String, Integer>> tuples = db() .select("select name, score from person where name=? order by name") .getAs(String.class, Integer.class).toList().toBlocking().single(); assertEquals(0, tuples.size()); } @Test public void testCreateFromScript() { Database db = Database.from(DatabaseCreator.nextUrl()); Observable<Integer> create = db .run(DatabaseTestBase.class.getResourceAsStream("/db-creation-script.sql"), ";"); Observable<Integer> count = db.select("select name from person").dependsOn(create) .getAs(String.class).count(); assertIs(3, count); } @Test public void testComposition2() { log.debug("running testComposition2"); Func1<Integer, Boolean> isZero = new Func1<Integer, Boolean>() { @Override public Boolean call(Integer count) { return count == 0; } }; Database db = db(); Observable<Integer> existingRows = db.select("select name from person where name=?") .parameter("FRED").getAs(String.class).count().filter(isZero); List<Integer> counts = db.update("insert into person(name,score) values(?,?)") .parameters(existingRows).count().toList().toBlocking().single(); assertEquals(0, counts.size()); } @Test public void testEmptyResultSet() { int count = db().select("select name from person where name >?") .parameters(Observable.just("ZZTOP")).count().first().toBlocking().single(); assertEquals(0, count); } @Test public void testMixingExplicitAndObservableParameters() { String name = db() .select("select name from person where name > ? and score < ? order by name") .parameter("BARRY").parameters(Observable.just(100)).getAs(String.class).first() .toBlocking().single(); assertEquals("FRED", name); } @Test public void testInstantiateDatabaseWithUrl() throws SQLException { Database db = Database.from("jdbc:h2:mem:testa1"); Connection con = db.queryContext().connectionProvider().get(); con.close(); } @Test public void testComposition() { // use composition to find the first person alphabetically with // a score less than the person with the last name alphabetically // whose name is not XAVIER. Two threads and connections will be used. Database db = db(); Observable<Integer> score = db .select("select score from person where name <> ? order by name") .parameter("XAVIER").getAs(Integer.class).last(); Observable<String> name = db.select("select name from person where score < ? order by name") .parameters(score).getAs(String.class).first(); assertIs("FRED", name); } @Test public void testCompositionUsingLift() { // use composition to find the first person alphabetically with // a score less than the person with the last name alphabetically // whose name is not XAVIER. Two threads and connections will be used. Database db = db(); Observable<String> name = db .select("select score from person where name <> ? order by name") .parameter("XAVIER").getAs(Integer.class).last() .lift(db.select("select name from person where score < ? order by name") .parameterOperator().getAs(String.class)) .first(); assertIs("FRED", name); } @Test public void testCompositionTwoLevels() { Database db = db(); Observable<String> names = db.select("select name from person order by name") .getAs(String.class); Observable<String> names2 = db.select("select name from person where name<>? order by name") .parameters(names).parameters(names).getAs(String.class); List<String> list = db.select("select name from person where name>?").parameters(names2) .getAs(String.class).toList().toBlocking().single(); System.out.println(list); assertEquals(12, list.size()); } @Test(expected = RuntimeException.class) public void testSqlProblem() { String name = db().select("select name from pperson where name >?").parameter("ALEX") .getAs(String.class).first().toBlocking().single(); log.debug(name); } @Test(expected = ClassCastException.class) public void testException() { Integer name = db().select("select name from person where name >?").parameter("ALEX") .getAs(Integer.class).first().toBlocking().single(); log.debug("name=" + name); } @Test public void testAutoMapWillMapStringToStringAndIntToDouble() { Person person = db().select("select name,score,dob,registered from person order by name") .autoMap(Person.class).first().toBlocking().single(); assertEquals("FRED", person.getName()); assertEquals(21, person.getScore(), 0.001); assertNull(person.getDateOfBirth()); } @Test(expected = RuntimeException.class) public void testAutoMapCannotFindConstructorWithEnoughParameters() { db().select("select name,score,dob,registered,name from person order by name") .autoMap(Person.class).first().toBlocking().single(); } @Test public void testGetTimestamp() { Database db = db(); java.sql.Timestamp registered = new java.sql.Timestamp(100); Observable<Integer> u = db.update("update person set registered=? where name=?") .parameter(registered).parameter("FRED").count(); Date regTime = db.select("select registered from person order by name").dependsOn(u) .getAs(Date.class).first().toBlocking().single(); assertEquals(100, regTime.getTime()); } @Test public void insertClobAndReadAsString() throws SQLException { Database db = db(); insertClob(db); // read clob as string String text = db.select("select document from person_clob").getAs(String.class).first() .toBlocking().single(); assertTrue(text.contains("about Fred")); } @Test public void insertNullClobAndReadAsString() throws SQLException { Database db = db(); insertClob(db, null); // read clob as string String text = db.select("select document from person_clob").getAs(String.class).first() .toBlocking().single(); assertNull(text); } @Test public void insertNullBlobAndReadAsByteArray() throws SQLException { Database db = db(); insertBlob(db, null); // read clob as string byte[] bytes = db.select("select document from person_blob").getAs(byte[].class).first() .toBlocking().single(); assertNull(bytes); } private static void insertClob(Database db) { insertClob(db, "A description about Fred that is rather long and needs a Clob to store it"); } private static void insertClob(Database db, String value) { Observable<Integer> count = db.update("insert into person_clob(name,document) values(?,?)") .parameter("FRED").parameterClob(value).count(); assertIs(1, count); } private static void insertBlob(Database db, byte[] bytes) { Observable<Integer> count = db.update("insert into person_blob(name,document) values(?,?)") .parameter("FRED").parameterBlob(bytes).count(); assertIs(1, count); } @Test public void insertClobAndReadAsReader() throws SQLException, IOException { Database db = db(); insertClob(db); // read clob as Reader String text = db.select("select document from person_clob").getAs(Reader.class) .map(Util.READER_TO_STRING).first().toBlocking().single(); assertTrue(text.contains("about Fred")); } @Test public void insertBlobAndReadAsByteArray() throws SQLException { Database db = db(); insertBlob(db); // read clob as string byte[] bytes = db.select("select document from person_blob").getAs(byte[].class).first() .toBlocking().single(); assertTrue(new String(bytes).contains("about Fred")); } @Test public void testInsertNull() { Observable<Integer> count = db().update("insert into person(name,score,dob) values(?,?,?)") .parameters("JACK", 42, null).count(); assertIs(1, count); } @Test public void testRC4() { Observable.<Object> empty().concatWith(just(10, 20, 30)).buffer(3) .concatMap(new Func1<List<Object>, Observable<Object>>() { @Override public Observable<Object> call(List<Object> list) { return Observable.from(list); } }).count().toBlocking().single(); // Observable<Integer> count = db() // .update("insert into person(name,score,dob) values(?,?,?)") // .parameters("JACK", 42, null).count(); // assertIs(1, count); } @Test public void testAutoMap() { TimeZone current = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("AEST")); Database db = db(); Date dob = new Date(100); long now = System.currentTimeMillis(); java.sql.Timestamp registered = new java.sql.Timestamp(now); Observable<Integer> u = db.update("update person set dob=?, registered=? where name=?") .parameter(dob).parameter(registered).parameter("FRED").count(); Person person = db.select("select name,score,dob,registered from person order by name") .dependsOn(u).autoMap(Person.class).first().toBlocking().single(); assertEquals("FRED", person.getName()); assertEquals(21, person.getScore(), 0.001); // Dates are truncated to start of day assertEquals(0, (long) person.getDateOfBirth()); assertEquals(now, (long) person.getRegistered()); } finally { TimeZone.setDefault(current); } } @Test public void testLastTransactionWithoutTransaction() { assertIs(0, db().lastTransactionResult().count()); } @Test public void testTuple3() { Tuple3<String, Integer, String> tuple = db() .select("select name,1,lower(name) from person order by name") .getAs(String.class, Integer.class, String.class).first().toBlocking().single(); assertEquals("FRED", tuple.value1()); assertEquals(1, (int) tuple.value2()); assertEquals("fred", tuple.value3()); } @Test public void testTuple4() { Tuple4<String, Integer, String, Integer> tuple = db() .select("select name,1,lower(name),2 from person order by name") .getAs(String.class, Integer.class, String.class, Integer.class).first() .toBlocking().single(); assertEquals("FRED", tuple.value1()); assertEquals(1, (int) tuple.value2()); assertEquals("fred", tuple.value3()); assertEquals(2, (int) tuple.value4()); } @Test public void testTuple5() { Tuple5<String, Integer, String, Integer, String> tuple = db() .select("select name,1,lower(name),2,name from person order by name") .getAs(String.class, Integer.class, String.class, Integer.class, String.class) .first().toBlocking().single(); assertEquals("FRED", tuple.value1()); assertEquals(1, (int) tuple.value2()); assertEquals("fred", tuple.value3()); assertEquals(2, (int) tuple.value4()); assertEquals("FRED", tuple.value5()); } @Test public void testTuple6() { Tuple6<String, Integer, String, Integer, String, Integer> tuple = db() .select("select name,1,lower(name),2,name,3 from person order by name") .getAs(String.class, Integer.class, String.class, Integer.class, String.class, Integer.class) .first().toBlocking().single(); assertEquals("FRED", tuple.value1()); assertEquals(1, (int) tuple.value2()); assertEquals("fred", tuple.value3()); assertEquals(2, (int) tuple.value4()); assertEquals("FRED", tuple.value5()); assertEquals(3, (int) tuple.value6()); } @Test public void testTuple7() { Tuple7<String, Integer, String, Integer, String, Integer, Integer> tuple = db() .select("select name,1,lower(name),2,name,3,4 from person order by name") .getAs(String.class, Integer.class, String.class, Integer.class, String.class, Integer.class, Integer.class) .first().toBlocking().single(); assertEquals("FRED", tuple.value1()); assertEquals(1, (int) tuple.value2()); assertEquals("fred", tuple.value3()); assertEquals(2, (int) tuple.value4()); assertEquals("FRED", tuple.value5()); assertEquals(3, (int) tuple.value6()); assertEquals(4, (int) tuple.value7()); } @Test public void testAutoMapClob() { Database db = db(); insertClob(db); List<PersonClob> list = db.select("select name, document from person_clob") .autoMap(PersonClob.class).toList().toBlocking().single(); assertEquals(1, list.size()); assertEquals("FRED", list.get(0).getName()); assertTrue(list.get(0).getDocument().contains("rather long")); } @Test public void testAutoMapBlob() { Database db = db(); insertBlob(db); List<PersonBlob> list = db.select("select name, document from person_blob") .autoMap(PersonBlob.class).toList().toBlocking().single(); assertEquals(1, list.size()); assertEquals("FRED", list.get(0).getName()); assertTrue(new String(list.get(0).getDocument()).contains("rather long")); } private void insertBlob(Database db) { insertBlob(db, "A description about Fred that is rather long and needs a Clob to store it" .getBytes()); } @Test public void testCalendarParameter() throws SQLException { Database db = db(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); Observable<Integer> update = db.update("update person set registered=? where name=?") .parameters(cal, "FRED").count(); Timestamp t = db.select("select registered from person where name=?").parameter("FRED") .dependsOn(update).getAs(Timestamp.class).first().toBlocking().single(); assertEquals(0, t.getTime()); } @Test public void testDatabaseBuilder() { Database.builder().connectionProvider(connectionProvider()) .nonTransactionalSchedulerOnCurrentThread().build(); } @Test public void testConnectionPool() { ConnectionProviderPooled cp = new ConnectionProviderPooled(nextUrl(), 0, 10); Database db = createDatabase(cp); int count = db.select("select name from person order by name").count().toBlocking() .single(); assertEquals(3, count); cp.close(); // and again to test idempotentcy cp.close(); } @Test(expected = RuntimeException.class) public void testConnectionPoolWhenExceptionThrown() throws SQLException { HikariDataSource pool = new HikariDataSource(); pool.setJdbcUrl("invalid"); new ConnectionProviderPooled(pool).get(); } @Test public void testConnectionPoolDoesNotRunOutOfConnectionsWhenQueryRunRepeatedly() throws SQLException { ConnectionProviderPooled cp = new ConnectionProviderPooled(nextUrl(), 0, 1); Database db = new Database(cp); Connection con = cp.get(); DatabaseCreator.createDatabase(con); con.close(); assertIs(100, db.select("select name from person where name=?") .parameters(Observable.range(0, 100).map(constant("FRED"))).count()); } // TODO add unit test to check that resources closed (connection etc) before // onComplete or onError called on either select or update @Test public void testDatabaseBuilderWithPool() { Database.builder().url(nextUrl()).pool(0, 5).build().close(); } @Test public void testOneConnectionOpenAndClosedAfterOneSelect() throws InterruptedException { CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1); Database db = new Database(cp); db.select("select name from person").count().toBlocking().single(); cp.closesLatch().await(); cp.getsLatch().await(); } @Test public void testOneConnectionOpenAndClosedAfterOneUpdate() throws InterruptedException { CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1); Database db = new Database(cp); db.update("update person set score=? where name=?").parameters(23, "FRED").count() .toBlocking().single(); cp.closesLatch().await(TIMEOUT_SECONDS, TimeUnit.SECONDS); cp.getsLatch().await(TIMEOUT_SECONDS, TimeUnit.SECONDS); } @Test public void testLiftWithParameters() { int score = just("FRED").lift(db().select("select score from person where name=?") .parameterOperator().getAs(Integer.class)).toBlocking().single(); assertEquals(21, score); } @Test public void testLiftWithManyParameters() { int score = Observable // range .range(1, 3) // log .doOnEach(log()) // to parameter .map(constant("FRED")) .lift(db() // select .select("select score from person where name=?") // push parameters .parameterOperator() // get score as integer .getAs(Integer.class)) // sum values .lift(SUM_INTEGER) // block and get .toBlocking().single(); assertEquals(3 * 21, score); } private final Operator<Integer, Integer> SUM_INTEGER = RxUtil .toOperator(new Func1<Observable<Integer>, Observable<Integer>>() { @Override public Observable<Integer> call(Observable<Integer> source) { return MathObservable.sumInteger(source); } }); @Test public void testDetector() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Observable.range(1, 10).doOnUnsubscribe(countDown(latch)).take(1).toBlocking().single(); assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); } @Test public void testUnsubscribeOfBufferAndFlatMap() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Observable.interval(10, TimeUnit.MILLISECONDS).doOnUnsubscribe(countDown(latch)).buffer(2) .flatMap(constant(just(1L))).take(6).toList().toBlocking().single(); assertTrue(latch.await(3, TimeUnit.SECONDS)); } @Test public void testParametersAreUnsubscribedIfUnsubscribedPostParameterOperatorLift() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Observable.interval(100, TimeUnit.MILLISECONDS).doOnEach(log()).map(constant("FRED")) .doOnUnsubscribe(countDown(latch)) .lift(db().select("select score from person where name=?").parameterOperator() .getAs(Integer.class)) .take(1).subscribe(log()); assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); } @Test public void testParametersAreUnsubscribed() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Observable<String> params = Observable.interval(100, TimeUnit.MILLISECONDS).doOnEach(log()) .map(constant("FRED")).doOnUnsubscribe(countDown(latch)); db().select("select score from person where name=?").parameters(params).getAs(Integer.class) .take(1).subscribe(log()); assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); } @Test public void testTakeShouldNotHang() { assertEquals(1, (int) Observable.<Integer> empty().concatWith(Observable.just(1)).take(1) .toBlocking().single()); } @Test public void testLiftSelectWithDependencies() { Database db = db(); Observable<Integer> count = db.update("update person set score=? where name=?") .parameters(4, "FRED").count() .lift(db.select("select score from person where name=?").parameters("FRED") .dependsOnOperator().getAs(Integer.class)); assertIs(4, count); } @Test public void testLiftUpdateWithParameters() { Database db = db(); Observable<Integer> count = just(4, "FRED") .lift(db.update("update person set score=? where name=?").parameterOperator()); assertIs(1, count); } @Test public void testLiftUpdateWithDependencies() { Database db = db(); Observable<Integer> score = Observable // parameters for coming update .just(4, "FRED") // update Fred's score to 4 .lift(db.update("update person set score=? where name=?").parameterOperator()) // update everyone with score of 4 to 14 .lift(db.update("update person set score=? where score=?").parameters(14, 4) .dependsOnOperator()) // get Fred's score .lift(db.select("select score from person where name=?").parameters("FRED") .dependsOnOperator().getAs(Integer.class)); assertIs(14, score); } static <T> void assertIs(T t, Observable<T> observable) { assertEquals(t, observable.toBlocking().single()); } @Test public void testTwoConnectionsOpenedAndClosedAfterTwoSelects() throws InterruptedException { CountDownConnectionProvider cp = new CountDownConnectionProvider(2, 2); Database db = new Database(cp); db.select("select name from person").count().toBlocking().single(); db.select("select name from person").count().toBlocking().single(); assertTrue(cp.getsLatch().await(60, TimeUnit.SECONDS)); assertTrue(cp.closesLatch().await(60, TimeUnit.SECONDS)); } @Test public void testTwoConnectionsOpenedAndClosedAfterTwoUpdates() throws InterruptedException { CountDownConnectionProvider cp = new CountDownConnectionProvider(2, 2); Database db = new Database(cp); db.update("update person set score=? where name=?").parameters(23, "FRED").count() .toBlocking().single(); db.update("update person set score=? where name=?").parameters(25, "JOHN").count() .toBlocking().single(); assertTrue(cp.getsLatch().await(60, TimeUnit.SECONDS)); assertTrue(cp.closesLatch().await(60, TimeUnit.SECONDS)); } @Test public void testOneConnectionOpenedAndClosedAfterTwoSelectsWithinTransaction() throws InterruptedException { CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1); Database db = new Database(cp); Observable<Boolean> begin = db.beginTransaction(); Observable<Integer> count = db.select("select name from person").dependsOn(begin).count(); Observable<Integer> count2 = db.select("select name from person").dependsOn(count).count(); int result = db.commit(count2).count().toBlocking().single(); log.info("committed " + result); cp.getsLatch().await(); log.info("gets ok"); cp.closesLatch().await(); log.info("closes ok"); } @Test public void testOneConnectionOpenedAndClosedAfterTwoUpdatesWithinTransaction() throws InterruptedException { CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1); Database db = new Database(cp); Observable<Boolean> begin = db.beginTransaction(); Observable<Integer> count = db.update("update person set score=? where name=?") .dependsOn(begin).parameters(23, "FRED").count(); Observable<Integer> count2 = db.update("update person set score=? where name=?") .dependsOn(count).parameters(25, "JOHN").count(); int result = db.commit(count2).count().toBlocking().single(); log.info("committed " + result); cp.getsLatch().await(); log.info("gets ok"); cp.closesLatch().await(); log.info("closes ok"); } @Test public void testCloseDatabaseClosesConnectionProvider() { ConnectionProvider cp = createMock(ConnectionProvider.class); cp.close(); EasyMock.expectLastCall().once(); EasyMock.replay(cp); new Database(cp).close(); EasyMock.verify(cp); } @Test public void testCloseAutoCommittingConnectionProviderClosesInternalConnectionProvider() { ConnectionProvider cp = createMock(ConnectionProvider.class); cp.close(); EasyMock.expectLastCall().once(); EasyMock.replay(cp); new ConnectionProviderAutoCommitting(cp).close(); EasyMock.verify(cp); } @Test public void testCloseSingletonManualCommitConnectionProviderClosesInternalConnectionProvider() { ConnectionProvider cp = createMock(ConnectionProvider.class); cp.close(); EasyMock.expectLastCall().once(); EasyMock.replay(cp); new ConnectionProviderSingletonManualCommit(cp).close(); EasyMock.verify(cp); } @Test public void testCloseConnectionProviderFromUrlClosesInternalConnectionProvider() { db().close(); } @Test(expected = RuntimeException.class) public void testCannotPassObservableAsSingleParameter() { db().select("anything").parameter(Observable.just(123)); } @Test public void testConnectionsReleasedByUpdateStatementBeforeOnNext() throws InterruptedException { final CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1); Database db = new Database(cp); Observable<Integer> result = db.update("update person set score = 1 where name=?") .parameter("FRED").count(); checkConnectionsReleased(cp, result); } @Test public void testConnectionsReleasedByCommitBeforeOnNext() throws InterruptedException { final CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1); Database db = new Database(cp); Observable<Boolean> begin = db.beginTransaction(); Observable<Integer> result = db.update("update person set score = 1 where name=?") .dependsOn(begin).parameter("FRED").count(); checkConnectionsReleased(cp, db.commit(result)); } @Test public void testConnectionsReleasedByRollbackBeforeOnNext() throws InterruptedException { final CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1); Database db = new Database(cp); Observable<Boolean> begin = db.beginTransaction(); Observable<Integer> result = db.update("update person set score = 1 where name=?") .dependsOn(begin).parameter("FRED").count(); checkConnectionsReleased(cp, db.rollback(result)); } private void checkConnectionsReleased(final CountDownConnectionProvider cp, Observable<?> result) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); result.subscribe(new Action1<Object>() { @Override public void call(Object obj) { try { if (cp.closesLatch().await(TIMEOUT_SECONDS, TimeUnit.SECONDS)) latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }); assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); } @Test public void testCanChainUpdateStatementsWithinTransaction() { Database db = db(); Observable<Boolean> begin = db.beginTransaction(); Observable<Integer> updates = Observable // set name parameter .just("FRED") // push into update .lift(db.update("update person set score=1 where name=?").dependsOn(begin) .parameterOperator()) // map num rows affected to JOHN .map(constant("JOHN")) // push into second update .lift(db.update("update person set score=2 where name=?").parameterOperator()); db.commit(updates).toBlocking().single(); } @Test public void testCommitOperator() { Database db = db(); Observable<Boolean> begin = db.beginTransaction(); String name = Observable // set name parameter .just("FRED") // push into update .lift(db.update("update person set score=1 where name=?").dependsOn(begin) .parameterOperator()) // map num rows affected to JOHN .lift(db.commitOperator()) // select query .lift(db.select("select name from person where score=1") // depends on commit .dependsOnOperator() // return names .getAs(String.class)) // return first name .first() // block to get make everything run .toBlocking().single(); assertEquals("FRED", name); } @Test public void testTryCatch() { try (Connection con = DatabaseCreator.nextConnection(); PreparedStatement ps = con.prepareStatement( "select name from person where name > ? order by name");) { ps.setObject(1, "ALEX"); List<String> list = new ArrayList<String>(); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { list.add(rs.getString(1)); } } System.out.println(list); } catch (SQLException e) { throw new RuntimeException(e); } } @Test public void testChainSelectUsingOperators() { Database db = db(); List<Integer> scores = db.select("select name from person") // get name .getAs(String.class) // push name as parameter to next select .lift(db // select scores .select("select score from person where name=?") // parameters are pushed .parameterOperator() // get score as integer .getAs(Integer.class)) // sort scores .toSortedList() // block to get result .toBlocking().single(); assertEquals(asList(21, 25, 34), scores); } @Test public void testBeginTransactionEmitsOneItem() { Database db = db(); Boolean value = db.beginTransaction().toBlocking().single(); assertTrue(value); } @Test public void testCommitOnLastOperator() { Database db = db(); long count = db // start transaction .beginTransaction() // push parameters .concatMap(constant(just(99, 88))) // log .doOnEach(log()) // update twice .lift(db.update("update person set score=?") // push parameters .parameterOperator()) // commit on last .lift(db.commitOnCompleteOperator()) // get count of 88s .lift(db.select("select count(*) from person where score=88") // depends on previous .dependsOnOperator() // count as Long .getAs(Long.class)) // block and get result .toBlocking().single(); assertEquals(3, count); } @Test public void testRollbackOnLastOperator() { Database db = db(); long count = db // start transaction .beginTransaction() // push parameters .concatMap(constant(just(99, 88))) // log .doOnEach(log()) // update twice .lift(db.update("update person set score=?") // push parameters .parameterOperator()) // commit on last .lift(db.rollbackOnCompleteOperator()) // get count of 88s .lift(db.select("select count(*) from person where score=88") // depends on previous .dependsOnOperator() // count as Long .getAs(Long.class)) // block and get result .toBlocking().single(); assertEquals(0, count); } @Test public void testBeginTransactionOnNextForThreePasses() { Database db = db(); Observable<Integer> min = Observable // do 3 times .just(11, 12, 13) // begin transaction for each item .lift(db.beginTransactionOnNextOperator()) // update all scores to the item .lift(db.update("update person set score=?").parameterOperator()) // to empty parameter list .map(toEmpty()) // increase score .lift(db.update("update person set score=score + 5").parameterListOperator()) // only expect one result so can flatten .lift(RxUtil.<Integer> flatten()) // commit transaction .lift(db.commitOnNextOperator()) // to empty lists .map(toEmpty()) // return count .lift(db.select("select min(score) from person").dependsOnOperator() .getAs(Integer.class)); assertIs(18, min); } @Test public void testParameterListOperator() { Database db = db(); @SuppressWarnings("unchecked") int count = // parameters grouped in lists objects(objects(1), objects(2)) // log .doOnEach(log()) // begin trans .lift(db.<Observable<Object>> beginTransactionOnNextOperator()) // log .doOnEach(log()) // update .lift(db.update("update person set score = ?") // push lists of parameters .parameterListOperator()) // log .doOnEach(log()) // commit .lift(db.<Integer> commitOnNextListOperator()) // total rows affected .count() // block and get result .toBlocking().single(); assertEquals(2, count); } @Test public void testParameterListOperatorWhenQueryNeedsTwoParameters() { Database db = db(); @SuppressWarnings("unchecked") int count = // parameters grouped in lists objects(objects(1, "FRED", 3, "JOHN"), objects(2, "JOSEPH")) // log .doOnEach(log()) // begin trans .lift(db.<Observable<Object>> beginTransactionOnNextOperator()) // log .doOnEach(log()) // update .lift(db.update("update person set score = ? where name=?") // push lists of parameters .parameterListOperator()) // log .doOnEach(log()) // commit .lift(db.<Integer> commitOnNextListOperator()) // total rows affected .count() // block and get result .toBlocking().single(); assertEquals(2, count); } @Test public void testCanExecuteCreateSchema() { Database db = db(); int count = db.update("create schema if not exists special_user").count().toBlocking() .single(); assertEquals(0, count); } @Test public void testCanExecuteCreateTable() { Database db = db(); int count = db.update("create table mytemp(name varchar2(100) primary key)").count() .toBlocking().single(); assertEquals(0, count); } private static Observable<Object> objects(Object... objects) { return Observable.from(objects); } private static Observable<Observable<Object>> objects( @SuppressWarnings("unchecked") Observable<Object>... objects) { return Observable.from(objects); } @Test public void testDatabaseFromConnectionCanUseConnectionTwiceWithoutItBeingClosedInReality() throws SQLException { ConnectionProvider cp = DatabaseCreator.connectionProvider(); DatabaseCreator.createDatabase(cp); Connection con = cp.get(); Database db = Database.from(con); Observable<Integer> count = db // get names .select("select name from person") // as string .getAs(String.class) // count names .count() // do something else .lift(db // get max score .select("select max(score) from person") // run the previous statement first .dependsOnOperator() // as integer .getAs(Integer.class)); assertIs(34, count); con.close(); } @Test public void testNonTransactionalMultipleQueries() { // get a synchronous database Database db = DatabaseCreator.db(); final Set<String> set = Collections.newSetFromMap(new HashMap<String, Boolean>()); Observable<Integer> count = Observable.just(1, 2, 3, 4, 5) // select .lift(db.select("select name from person where score >?") // push parameters to this query .parameterOperator() // get name as string .getAs(String.class)) // record thread name .doOnNext(new Action1<String>() { @Override public void call(String name) { set.add(Thread.currentThread().getName()); } }) // count .count(); assertIs(5 * 3, count); System.out.println("threads=" + set); assertEquals(1, set.size()); } @Test public void testTransaction() { Database db = db(); Observable<Boolean> begin = db.beginTransaction(); Observable<Integer> count = Observable // generate 1,2,3 .just(1, 2, 3) // update score with that value .lift(db.update("update person set score = ?") // participates in a transaction .dependsOn(begin) // parameters are pushed to this update statement .parameterOperator()) // commit transaction .lift(db.commitOnCompleteOperator()) // count names with score 3 .lift(db.select("select count(name) from person where score=3") // must commit first .dependsOnOperator().getAs(Integer.class)); assertIs(3, count); } @Test public void testTwoConnectionsOpenedAndClosedWhenTakeOneUsedWithSelectThatReturnsOneRow() throws InterruptedException { Action0 completed = new Action0() { @Override public void call() { System.out.println("completed"); } }; CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1); Database db = new Database(cp); db.select("select count(*) from person").getAs(Long.class).doOnCompleted(completed).take(1) .toBlocking().single(); assertTrue(cp.getsLatch().await(6, TimeUnit.SECONDS)); assertTrue(cp.closesLatch().await(6, TimeUnit.SECONDS)); } @Test public void testAutoMapInterface() { // test dynamic proxying List<NameScore> list = db().select("select name, score from person order by name") .autoMap(NameScore.class).toList().toBlocking().single(); assertEquals(3, list.size()); assertEquals("FRED", list.get(0).name()); assertEquals(21, list.get(0).score()); assertEquals("JOSEPH", list.get(1).name()); assertEquals(34, list.get(1).score()); } static interface NameScore { @Index(1) String name(); @Column("score") int score(); } @Test public void testAutoMapConvertsCamelCaseToUnderscoreColumnNames() { // test dynamic proxying List<Address> list = db().select("select address_id, full_address from address") .autoMap(Address.class).toList().toBlocking().single(); assertEquals(1, list.size()); assertEquals(1, list.get(0).addressId()); assertTrue(list.get(0).fullAddress().contains("Something")); } static interface Address { @Column int addressId(); @Column String fullAddress(); } @Test public void testAutoMapWithQueryAnnotation() { List<NameScore2> list = db().select().autoMap(NameScore2.class).toList().toBlocking() .single(); assertEquals(3, list.size()); assertEquals("FRED", list.get(0).name()); assertEquals(21, list.get(0).score()); assertEquals("JOSEPH", list.get(1).name()); assertEquals(34, list.get(1).score()); } @Query("select name, score from person order by name") static interface NameScore2 { @Index(1) String name(); @Column("score") int score(); } @Test(expected = RuntimeException.class) public void testAutoMapThrowsExceptionIfMappedInterfaceColumnMethodHasParameters() { // test dynamic proxying db().select("select address_id, full_address from address").autoMap(Address2.class).toList() .toBlocking().single(); } static interface Address2 { @Column int addressId(String suburb); @Column String fullAddress(); } @Test public void testCustomMapper() { String name = db().select("select name from person order by name") .get(new ResultSetMapper<String>() { @Override public String call(ResultSet rs) throws SQLException { return rs.getString(1); } }).first().toBlocking().single(); assertEquals("FRED", name); } @Test public void testReturnGeneratedKeysForOneInsertedValue() { // h2 only returns the last generated key List<Integer> list = db() // .update("insert into note(text) values(?)") // .parameters("something") // .returnGeneratedKeys() // .getAs(Integer.class) // .toList().toBlocking().single(); assertEquals(Arrays.asList(1), list); } @Test public void testReturnGeneratedKeysForMultipleInsertedValuesInOneStatement() { // h2 only returns the last generated key List<Integer> list = db() // .update("insert into note(text) values(?),(?)") // .parameters("something", "again") // .returnGeneratedKeys() // .getAs(Integer.class) // .toList().toBlocking().single(); assertEquals(Arrays.asList(2), list); } @Test public void testReturnGeneratedKeysForMultipleCallsOfInsert() { // h2 only returns the last generated key List<Integer> list = db() // .update("insert into note(text) values(?)") // .parameters("something", "again") // .returnGeneratedKeys() // .getAs(Integer.class) // .toList().toBlocking().single(); assertEquals(Arrays.asList(1, 2), list); } @Test public void testNamedParameters() { String name = db() // .select("select name from person where score >= :min and score <=:max") // .parameter("min", 24) // .parameter("max", 26) // .getAs(String.class).toBlocking().single(); assertEquals("MARMADUKE", name); } @Test public void testNamedParametersWithMapParameter() { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("min", 24); map.put("max", 26); String name = db() // .select("select name from person where score >= :min and score <=:max") // .parameters(map) // .getAs(String.class).toBlocking().single(); assertEquals("MARMADUKE", name); } @Test public void testNamedParametersWithMapParameterInObservable() { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("min", 24); map.put("max", 26); String name = db() // .select("select name from person where score >= :min and score <=:max") // .parameters(Observable.just(map)) // .getAs(String.class).toBlocking().single(); assertEquals("MARMADUKE", name); } @Test public void testNamedParametersWithUpdateStatement() { int count = db() // .update("update person set score = :newScore where score >= :min and score <=:max") // .parameter("newScore", 25) // .parameter("min", 24) // .parameter("max", 26) // .count().toBlocking().single(); assertEquals(1, count); } @Test(expected = RuntimeException.class) public void testNamedParametersOneMissingParameterShouldThrowException() { db().select("select name from person where name = :name and score = :score") .parameter("name", "FRED").count().toBlocking().single(); } @Test(expected = RuntimeException.class) public void testNamedParametersWithMapParameterNoNamesInSql() { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("min", 24); map.put("max", 26); db() // .select("select name from person where score >= ? and score <= ?") // .parameters(Observable.just(map)) // .getAs(String.class).toBlocking().single(); } @Test public void testNoParameters() { int count = db().select("select name from person").count().toBlocking().single(); assertEquals(3, count); } @Test public void testAutoMapInterfaceWithPrimitives() { List<NameScorePrimitive> list = db() .select("select name, score from person where name='FRED'") .autoMap(NameScorePrimitive.class).toList().toBlocking().single(); assertEquals(21, list.get(0).score()); } static interface NameScorePrimitive { @Column String name(); @Column int score(); } @Test public void testResultSetTransformSetOnDatabase() { final AtomicInteger count = new AtomicInteger(); Func1<ResultSet, ? extends ResultSet> transform = new Func1<ResultSet, ResultSet>() { @Override public ResultSet call(ResultSet rs) { count.incrementAndGet(); return rs; } }; TestSubscriber<Integer> ts = TestSubscriber.create(); Database db = Database.builder().connectionProvider(db().connectionProvider()) .resultSetTransform(transform).build(); db.select("select name from person").count().subscribe(ts); ts.awaitTerminalEvent(); assertEquals(1, (int) count.get()); } @Test public void testResultSetTransformSetOnQuery() { final AtomicInteger count = new AtomicInteger(); Func1<ResultSet, ? extends ResultSet> transform = new Func1<ResultSet, ResultSet>() { @Override public ResultSet call(ResultSet rs) { count.incrementAndGet(); return rs; } }; TestSubscriber<Integer> ts = TestSubscriber.create(); db().select("select name from person").resultSetTransform(transform).count().subscribe(ts); ts.awaitTerminalEvent(10, TimeUnit.SECONDS); assertEquals(1, (int) count.get()); } @Test public void testResultSetTransformSetOnQueryCompoundsWithDatabaseTransform() { final List<Integer> list = new CopyOnWriteArrayList<>(); Func1<ResultSet, ? extends ResultSet> transform1 = new Func1<ResultSet, ResultSet>() { @Override public ResultSet call(ResultSet rs) { list.add(1); return rs; } }; Func1<ResultSet, ? extends ResultSet> transform2 = new Func1<ResultSet, ResultSet>() { @Override public ResultSet call(ResultSet rs) { list.add(2); return rs; } }; Database db = Database.builder().connectionProvider(db().connectionProvider()) .resultSetTransform(transform1).build(); TestSubscriber<Integer> ts = TestSubscriber.create(); db.select("select name from person").resultSetTransform(transform2).count().subscribe(ts); ts.awaitTerminalEvent(10, TimeUnit.SECONDS); assertEquals(Arrays.asList(1, 2), list); } /******************************************************** ** Utility classes ********************************************************/ private static class CountDownConnectionProvider implements ConnectionProvider { private final ConnectionProvider cp; private final CountDownLatch closesLatch; private final CountDownLatch getsLatch; CountDownConnectionProvider(int expectedGets, int expectedCloses) { this.cp = connectionProvider(); DatabaseCreator.createDatabase(cp.get()); this.closesLatch = new CountDownLatch(expectedCloses); this.getsLatch = new CountDownLatch(expectedGets); } CountDownLatch closesLatch() { return closesLatch; } CountDownLatch getsLatch() { return getsLatch; } @Override public Connection get() { getsLatch.countDown(); Connection inner = cp.get(); return new CountingConnection(inner, closesLatch); } @Override public void close() { cp.close(); } } static class PersonClob { private final String name; private final String document; public PersonClob(String name, String document) { this.name = name; this.document = document; } public String getName() { return name; } public String getDocument() { return document; } } static class PersonBlob { private final String name; private final byte[] document; public PersonBlob(String name, byte[] document) { this.name = name; this.document = document; } public String getName() { return name; } public byte[] getDocument() { return document; } } static class Person { private final String name; private final double score; private final Long dateOfBirthEpochMs; private final Long registered; Person(String name, double score, Long dateOfBirthEpochMs, Long registered) { this.name = name; this.score = score; this.dateOfBirthEpochMs = dateOfBirthEpochMs; this.registered = registered; } public String getName() { return name; } public double getScore() { return score; } public Long getDateOfBirth() { return dateOfBirthEpochMs; } public Long getRegistered() { return registered; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Pair [name="); builder.append(name); builder.append(", score="); builder.append(score); builder.append("]"); return builder.toString(); } } }
{ "content_hash": "3b21f9b4df21bffc4aaafdabda73fd70", "timestamp": "", "source": "github", "line_count": 1866, "max_line_length": 106, "avg_line_length": 37.40943193997856, "alnum_prop": 0.5693493395983154, "repo_name": "vtsyryuk/rxjava-jdbc", "id": "90b8b9d76ae639d18e3bf772a0fde969d7393259", "size": "69806", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/com/github/davidmoten/rx/jdbc/DatabaseTestBase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "322649" }, { "name": "Shell", "bytes": "168" } ], "symlink_target": "" }
FROM nginx:1.7 MAINTAINER Levi Bostian <[email protected]> # NginX Configuration ADD nginx.conf /etc/nginx/nginx.conf ADD mime.types /etc/nginx/mime.types ADD web-http.conf /etc/nginx/web-http.conf ADD web-https.conf /etc/nginx/web-https.conf # forward request and error logs to docker log collector RUN ln -sf /dev/stdout /var/log/nginx/access.log RUN ln -sf /dev/stderr /var/log/nginx/error.log # Install taiga-front-dist RUN mkdir -p /usr/local/taiga COPY taiga-front-dist/ /usr/local/taiga/taiga-front-dist # Configuration and Start scripts ADD ./configure /usr/local/taiga/configure ADD ./start /usr/local/taiga/start RUN chmod +x /usr/local/taiga/configure /usr/local/taiga/start EXPOSE 80 443 CMD ["/usr/local/taiga/start"]
{ "content_hash": "8a43d228859911704645ae4fedad41a8", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 62, "avg_line_length": 28.53846153846154, "alnum_prop": 0.7654986522911051, "repo_name": "curiosityio/taiga-docker", "id": "2222718aaf22771531d769ad29fc3c75bbc100c5", "size": "742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "taiga-front-dist/Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "186988" }, { "name": "JavaScript", "bytes": "2007" }, { "name": "Nginx", "bytes": "4140" }, { "name": "Python", "bytes": "2793020" }, { "name": "Shell", "bytes": "1392" } ], "symlink_target": "" }
#include <propagate_const.h> #else #include <experimental/propagate_const> #endif namespace utils { template <typename T> using PropagateConst = std::experimental::propagate_const<T>; } // namespace utils
{ "content_hash": "a1a4fd5ad795920dcb657cf8469c4c94", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 61, "avg_line_length": 23.333333333333332, "alnum_prop": 0.7523809523809524, "repo_name": "antaljanosbenjamin/miscellaneous", "id": "96f908f8c02065a37f522f17a199ee417d6456a4", "size": "238", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects/utils/include/utils/PropagateConst.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "3190279" }, { "name": "CMake", "bytes": "48708" }, { "name": "Python", "bytes": "1752" } ], "symlink_target": "" }
using namespace oclgrind; using namespace std; THREAD_LOCAL RaceDetector::WorkerState RaceDetector::m_state = {NULL}; #define STATE(workgroup) (m_state.groups->at(workgroup)) // Use a bank of mutexes to reduce unnecessary synchronisation #define NUM_GLOBAL_MUTEXES 4096 // Must be power of two #define GLOBAL_MUTEX(buffer,offset) \ m_globalMutexes[buffer][offset & (NUM_GLOBAL_MUTEXES-1)] RaceDetector::RaceDetector(const Context *context) : Plugin(context) { m_kernelInvocation = NULL; m_allowUniformWrites = !checkEnv("OCLGRIND_UNIFORM_WRITES"); } void RaceDetector::kernelBegin(const KernelInvocation *kernelInvocation) { m_kernelInvocation = kernelInvocation; } void RaceDetector::kernelEnd(const KernelInvocation *kernelInvocation) { // Clear all global memory accesses for (auto buffer = m_globalAccesses.begin(); buffer != m_globalAccesses.end(); buffer++) { size_t sz = buffer->second.size(); buffer->second.clear(); buffer->second.resize(sz); } m_kernelInvocation = NULL; } void RaceDetector::memoryAllocated(const Memory *memory, size_t address, size_t size, cl_mem_flags flags, const uint8_t *initData) { size_t buffer = memory->extractBuffer(address); if (memory->getAddressSpace() == AddrSpaceGlobal) { m_globalAccesses[buffer].resize(size); m_globalMutexes[buffer] = new mutex[NUM_GLOBAL_MUTEXES]; } } void RaceDetector::memoryAtomicLoad(const Memory *memory, const WorkItem *workItem, AtomicOp op, size_t address, size_t size) { registerAccess(memory, workItem->getWorkGroup(), workItem, address, size, true); } void RaceDetector::memoryAtomicStore(const Memory *memory, const WorkItem *workItem, AtomicOp op, size_t address, size_t size) { registerAccess(memory, workItem->getWorkGroup(), workItem, address, size, true, (const uint8_t*)memory->getPointer(address)); } void RaceDetector::memoryDeallocated(const Memory *memory, size_t address) { size_t buffer = memory->extractBuffer(address); if (memory->getAddressSpace() == AddrSpaceGlobal) { m_globalAccesses.erase(buffer); delete[] m_globalMutexes.at(buffer); m_globalMutexes.erase(buffer); } } void RaceDetector::memoryLoad(const Memory *memory, const WorkItem *workItem, size_t address, size_t size) { registerAccess(memory, workItem->getWorkGroup(), workItem, address, size, false, NULL); } void RaceDetector::memoryLoad(const Memory *memory, const WorkGroup *workGroup, size_t address, size_t size) { registerAccess(memory, workGroup, NULL, address, size, false); } void RaceDetector::memoryStore(const Memory *memory, const WorkItem *workItem, size_t address, size_t size, const uint8_t *storeData) { registerAccess(memory, workItem->getWorkGroup(), workItem, address, size, false, storeData); } void RaceDetector::memoryStore(const Memory *memory, const WorkGroup *workGroup, size_t address, size_t size, const uint8_t *storeData) { registerAccess(memory, workGroup, NULL, address, size, false, storeData); } void RaceDetector::workGroupBarrier(const WorkGroup *workGroup, uint32_t flags) { if (flags & CLK_LOCAL_MEM_FENCE) { syncWorkItems(workGroup->getLocalMemory(), STATE(workGroup), STATE(workGroup).wiLocal); } if (flags & CLK_GLOBAL_MEM_FENCE) { syncWorkItems(m_context->getGlobalMemory(), STATE(workGroup), STATE(workGroup).wiGlobal); } } void RaceDetector::workGroupBegin(const WorkGroup *workGroup) { // Create worker state if haven't already if (!m_state.groups) { m_state.groups = new unordered_map<const WorkGroup*,WorkGroupState>; } // Initialize work-group state WorkGroupState& state = (*m_state.groups)[workGroup]; Size3 wgsize = workGroup->getGroupSize(); state.numWorkItems = wgsize.x*wgsize.y*wgsize.z; // Re-use pool allocator for all access maps AccessMap tmp(0, AccessMap::hasher(), AccessMap::key_equal(), state.wgGlobal.get_allocator()); state.wiGlobal.resize(state.numWorkItems+1, tmp); state.wiLocal.resize(state.numWorkItems+1, tmp); } void RaceDetector::workGroupComplete(const WorkGroup *workGroup) { WorkGroupState& state = STATE(workGroup); syncWorkItems(workGroup->getLocalMemory(), state, state.wiLocal); syncWorkItems(m_context->getGlobalMemory(), state, state.wiGlobal); // Merge global accesses across kernel invocation RaceList races; size_t group = workGroup->getGroupIndex(); for (auto record = state.wgGlobal.begin(); record != state.wgGlobal.end(); record++) { size_t address = record->first; size_t buffer = m_context->getGlobalMemory()->extractBuffer(address); size_t offset = m_context->getGlobalMemory()->extractOffset(address); lock_guard<mutex> lock(GLOBAL_MUTEX(buffer, offset)); AccessRecord& a = record->second; AccessRecord& b = m_globalAccesses.at(buffer)[offset]; // Check for races with previous accesses if (check(a.load, b.store) && getAccessWorkGroup(b.store) != group) insertRace(races, {AddrSpaceGlobal, address, a.load, b.store}); if (check(a.store, b.load) && getAccessWorkGroup(b.load) != group) insertRace(races, {AddrSpaceGlobal, address, a.store, b.load}); if (check(a.store, b.store) && getAccessWorkGroup(b.store) != group) insertRace(races, {AddrSpaceGlobal, address, a.store, b.store}); // Insert accesses if (a.load.isSet()) insert(b, a.load); if (a.store.isSet()) insert(b, a.store); } state.wgGlobal.clear(); // Log races for (auto race = races.begin(); race != races.end(); race++) logRace(*race); // Clean-up work-group state m_state.groups->erase(workGroup); if (m_state.groups->empty()) { delete m_state.groups; m_state.groups = NULL; } } bool RaceDetector::check(const MemoryAccess& a, const MemoryAccess& b) const { // Ensure both accesses are valid if (!a.isSet() || !b.isSet()) return false; // No race if same work-item if (a.isWorkItem() && b.isWorkItem() && (a.getEntity() == b.getEntity())) return false; // No race if both operations are atomics if (a.isAtomic() && b.isAtomic()) return false; // Potential race if at least one store if (a.isStore() || b.isStore()) { // Read-write race if one is a load if (a.isLoad() || b.isLoad()) return true; // Write-write race if not uniform if (!m_allowUniformWrites || (a.getStoreData() != b.getStoreData())) return true; } return false; } size_t RaceDetector::getAccessWorkGroup(const MemoryAccess& access) const { if (access.isWorkItem()) { const Size3& wgsize = m_kernelInvocation->getLocalSize(); return access.getEntity() / (wgsize.x*wgsize.y*wgsize.z); } else return access.getEntity(); } void RaceDetector::insert(AccessRecord& record, const MemoryAccess& access) const { if (access.isLoad()) { if (!record.load.isSet() || record.load.isAtomic()) record.load = access; } else if (access.isStore()) { if (!record.store.isSet() || record.store.isAtomic()) record.store = access; } } void RaceDetector::insertRace(RaceList& races, const Race& race) const { // Check list for duplicates for (auto x = races.begin(); x != races.end(); x++) { // Check if races are equal modulo address if ((race.a.getInstruction() == x->a.getInstruction()) && (race.b.getInstruction() == x->b.getInstruction()) && (race.a.isLoad() == x->a.isLoad()) && (race.b.isLoad() == x->b.isLoad()) && (race.a.isWorkItem() == x->a.isWorkItem()) && (race.b.isWorkItem() == x->b.isWorkItem()) && (race.a.getEntity() == x->a.getEntity()) && (race.b.getEntity() == x->b.getEntity())) { // If they match, keep the one with the lowest address if (race.address < x->address) { races.erase(x); races.push_back(race); return; } else return; } } races.push_back(race); } void RaceDetector::logRace(const Race& race) const { const char *raceType; if (race.a.isLoad() || race.b.isLoad()) raceType = "Read-write"; else raceType = "Write-write"; Context::Message msg(ERROR, m_context); msg << raceType << " data race at " << getAddressSpaceName(race.addrspace) << " memory address 0x" << hex << race.address << endl << msg.INDENT << "Kernel: " << msg.CURRENT_KERNEL << endl << endl << "First entity: "; if (race.a.isWorkItem()) { Size3 wgsize = m_kernelInvocation->getLocalSize(); Size3 global(race.a.getEntity(), m_kernelInvocation->getGlobalSize()); Size3 local(global.x%wgsize.x, global.y%wgsize.y, global.z%wgsize.z); Size3 group(global.x/wgsize.x, global.y/wgsize.y, global.z/wgsize.z); msg << "Global" << global << " Local" << local << " Group" << group; } else { msg << "Group" << Size3(race.a.getEntity(), m_kernelInvocation->getLocalSize()); } msg << endl << race.a.getInstruction() << endl << endl << "Second entity: "; // Show details of other entity involved in race if (race.b.isWorkItem()) { Size3 wgsize = m_kernelInvocation->getLocalSize(); Size3 global(race.b.getEntity(), m_kernelInvocation->getGlobalSize()); Size3 local(global.x%wgsize.x, global.y%wgsize.y, global.z%wgsize.z); Size3 group(global.x/wgsize.x, global.y/wgsize.y, global.z/wgsize.z); msg << "Global" << global << " Local" << local << " Group" << group; } else { msg << "Group" << Size3(race.b.getEntity(), m_kernelInvocation->getLocalSize()); } msg << endl << race.b.getInstruction() << endl; msg.send(); } void RaceDetector::registerAccess(const Memory *memory, const WorkGroup *workGroup, const WorkItem *workItem, size_t address, size_t size, bool atomic, const uint8_t *storeData) { unsigned addrSpace = memory->getAddressSpace(); if (addrSpace == AddrSpacePrivate || addrSpace == AddrSpaceConstant) return; if (!memory->isAddressValid(address, size)) return; // Construct access MemoryAccess access(workGroup, workItem, storeData != NULL, atomic); size_t index; if (workItem) { Size3 wgsize = workGroup->getGroupSize(); Size3 lid = workItem->getLocalID(); index = lid.x + (lid.y + lid.z*wgsize.y)*wgsize.x; } else { index = STATE(workGroup).wiLocal.size() - 1; } AccessMap& accesess = (addrSpace == AddrSpaceGlobal) ? STATE(workGroup).wiGlobal[index] : STATE(workGroup).wiLocal[index]; for (size_t i = 0; i < size; i++) { if (storeData) access.setStoreData(storeData[i]); insert(accesess[address+i], access); } } void RaceDetector::syncWorkItems(const Memory *memory, WorkGroupState& state, vector<AccessMap>& accesses) { AccessMap wgAccesses(0, AccessMap::hasher(), AccessMap::key_equal(), state.wgGlobal.get_allocator()); for (size_t i = 0; i < state.numWorkItems + 1; i++) { RaceList races; for (auto record = accesses[i].begin(); record != accesses[i].end(); record++) { size_t address = record->first; AccessRecord& a = record->second; AccessRecord& b = wgAccesses[address]; if (check(a.load, b.store)) insertRace(races, {memory->getAddressSpace(),address,a.load,b.store}); if (check(a.store, b.load)) insertRace(races, {memory->getAddressSpace(),address,a.store,b.load}); if (check(a.store, b.store)) insertRace(races, {memory->getAddressSpace(),address,a.store,b.store}); if (a.load.isSet()) { insert(b, a.load); if (memory->getAddressSpace() == AddrSpaceGlobal) insert(state.wgGlobal[address], a.load); } if (a.store.isSet()) { insert(b, a.store); if (memory->getAddressSpace() == AddrSpaceGlobal) insert(state.wgGlobal[address], a.store); } } accesses[i].clear(); // Log races for (auto race = races.begin(); race != races.end(); race++) logRace(*race); } } RaceDetector::MemoryAccess::MemoryAccess() { this->info = 0; this->instruction = NULL; } RaceDetector::MemoryAccess::MemoryAccess(const WorkGroup *workGroup, const WorkItem *workItem, bool store, bool atomic) { this->info = 0; this->info |= 1 << SET_BIT; this->info |= store << STORE_BIT; this->info |= atomic << ATOMIC_BIT; if (workItem) { this->entity = workItem->getGlobalIndex(); this->instruction = workItem->getCurrentInstruction(); } else { this->info |= (1<<WG_BIT); this->entity = workGroup->getGroupIndex(); this->instruction = NULL; // TODO? } } void RaceDetector::MemoryAccess::clear() { this->info = 0; this->instruction = NULL; } bool RaceDetector::MemoryAccess::isSet() const { return this->info & (1<<SET_BIT); } bool RaceDetector::MemoryAccess::isAtomic() const { return this->info & (1<<ATOMIC_BIT); } bool RaceDetector::MemoryAccess::isLoad() const { return !isStore(); } bool RaceDetector::MemoryAccess::isStore() const { return this->info & (1<<STORE_BIT); } bool RaceDetector::MemoryAccess::isWorkGroup() const { return this->info & (1<<WG_BIT); } bool RaceDetector::MemoryAccess::isWorkItem() const { return !isWorkGroup(); } size_t RaceDetector::MemoryAccess::getEntity() const { return this->entity; } const llvm::Instruction* RaceDetector::MemoryAccess::getInstruction() const { return this->instruction; } uint8_t RaceDetector::MemoryAccess::getStoreData() const { return this->storeData; } void RaceDetector::MemoryAccess::setStoreData(uint8_t data) { this->storeData = data; }
{ "content_hash": "25cacfdd03ebaf3f596bc9bd87508a53", "timestamp": "", "source": "github", "line_count": 508, "max_line_length": 80, "avg_line_length": 28.559055118110237, "alnum_prop": 0.6211745244003308, "repo_name": "bitfusionio/Oclgrind", "id": "812fa3dd7a16fb57a4d8a65c56617b9f75a5d1ff", "size": "15005", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/plugins/RaceDetector.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "593" }, { "name": "C", "bytes": "214152" }, { "name": "C++", "bytes": "568662" }, { "name": "CMake", "bytes": "13124" }, { "name": "Python", "bytes": "4887" }, { "name": "Shell", "bytes": "4696" } ], "symlink_target": "" }
package com.zhouyuanchao.android.draganddraw; import android.graphics.Point; import android.graphics.PointF; public class Box { private PointF mOrigin; private PointF mCurrent; public Box(PointF origin) { mOrigin = origin; } public void setCurrent(PointF current) { mCurrent = current; } public PointF getCurrent() { return mCurrent; } public PointF getOrigin() { return mOrigin; } }
{ "content_hash": "5470c9bb2efe13e1d7a1966f01141ea7", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 45, "avg_line_length": 15.37037037037037, "alnum_prop": 0.7228915662650602, "repo_name": "yjwx0017/LearnAndroid", "id": "0bca3ed22ed9e5ed20bc2590930303810da3c9f8", "size": "415", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DragAndDraw/src/com/zhouyuanchao/android/draganddraw/Box.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "101530" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "82961a6488716cf2e6104574c561a4dc", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "6e1d8fc82391ad6af734f53e03a62518a514cf10", "size": "201", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Boraginales/Boraginaceae/Heliotropium/Heliotropium coromandelianum/Heliotropium coromandelianum oblongifolium/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
This R script plots the relationships between an author of a tweet and the retweeters. The nodes represent the author and the retweeters, whereas the directed edges represent possible paths the tweet can "take" to reach a certain user. ## Requirements RtGraph was written and tested using R 3.4.1 (Single Candle). The script requires the following packages: twitteR and igraph. The consumer key, consumer secret, access token, and access secret for the Twitter API are required and need to be stored in the *auth.txt* file. Each string must be on a separate line and in the following order: 1. Consumer key 2. Consumer secret 3. Access token 4. Access secret The file *auth.txt* must be in the same directory as the *rtgraph.R* file to access the API. You can run the *rtgraph.R* script from an interactive session or from the terminal with Rscript: ```bash Rscript rtGraph.R ``` ## Input The script asks for a tweet number (ID), which is found in the tweet's URL: ```html https://twitter.com/username/status/[TweetID] ``` ## Output Saves the original edge graph with retweeters and all of their followers in an RData file. Also saves all objects into an RData file at the end. Writes one CSV file with the edges of the graph and one CSV file with the nodes and their attributes. The plot showing the connections between the author of a tweet and the retweeters is saved as a PNG file. The file names begin with the tweet ID, so it is possible to collect data for several tweets without overwriting anything. ## Example An example that shows the input and the output produced by this script is presented in [this article](https://velaco.github.io/rtgraph-example/).
{ "content_hash": "3badb09735f1526f8d91952864db8334", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 212, "avg_line_length": 39.16279069767442, "alnum_prop": 0.7719714964370546, "repo_name": "velaco/rtgraph", "id": "9153b7adee92035ce8021fedb6839d385871b60f", "size": "1695", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "R", "bytes": "4518" } ], "symlink_target": "" }
require 'dfp_api' require 'dfp_api_statement' API_VERSION = :v201505 def set_line_item_custom_field_value() # Get DfpApi instance and load configuration from ~/dfp_api.yml. dfp = DfpApi::Api.new # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in # the configuration file or provide your own logger: # dfp.logger = Logger.new('dfp_xml.log') # Get the CustomFieldService. custom_field_service = dfp.service(:CustomFieldService, API_VERSION) # Get the LineItemService. line_item_service = dfp.service(:LineItemService, API_VERSION) # Set the ID of the custom fields, custom field option, and line item. custom_field_id = 'INSERT_CUSTOM_FIELD_ID_HERE'.to_i drop_down_custom_field_id = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE'.to_i custom_field_option_id = 'INSERT_CUSTOM_FIELD_OPTION_ID_HERE'.to_i line_item_id = 'INSERT_LINE_ITEM_ID_HERE'.to_i # Create a statement to only select a single custom field. custom_field_statement = DfpApiStatement::FilterStatement.new( 'WHERE id = :id ORDER BY id ASC', [ {:key => 'id', :value => {:value => custom_field_id, :xsi_type => 'NumberValue'}} ], 1 ) # Create a statement to only select a single drop down custom field. drop_down_custom_field_statement = DfpApiStatement::FilterStatement.new( 'WHERE id = :id ORDER BY id ASC', [ {:key => 'id', :value => {:value => drop_down_custom_field_id, :xsi_type => 'NumberValue'}} ], 1 ) # Create a statement to only select a single line item. line_item_statement = DfpApiStatement::FilterStatement.new( 'WHERE id = :id ORDER BY id ASC', [ {:key => 'id', :value => {:value => line_item_id, :xsi_type => 'NumberValue'}} ], 1 ) # Get custom fields by statement. custom_fields_page = custom_field_service.get_custom_fields_by_statement( custom_field_statement.toStatement()) # Get drop down custom fields by statement. drop_down_custom_fields_page = ( custom_field_service.get_custom_fields_by_statement( drop_down_custom_field_statement.toStatement())) # Get line items by statement. line_items_page = line_item_service.get_line_items_by_statement( line_item_statement.toStatement()) # Get singular custom field. if custom_field_page[:results] custom_field = custom_fields_page[:results].first # Get singular drop down custom field. if drop_down_custom_field_page[:results] drop_down_custom_field = drop_down_custom_fields_page[:results].first # Get singular line item. if line_item_page[:results] line_item = line_items_page[:results].first if custom_field and drop_down_custom_field and line_item # Create custom field values. custom_field_value = { :custom_field_id => custom_field[:id], :type => 'CustomFieldValue', :value => {:type => 'TextValue', :value => 'Custom field value'} } drop_down_custom_field_value = { :custom_field_id => drop_down_custom_field[:id], :type => 'DropDownCustomFieldValue', :custom_field_option_id => custom_field_option_id } custom_field_values = [custom_field_value, drop_down_custom_field_value] old_custom_field_values = line_item.include?(:custom_field_values) ? line_item[:custom_field_values] : [] # Only add existing custom field values for different custom fields than the # ones you are setting. old_custom_field_values.each do |old_custom_field_value| unless custom_field_values.map {|value| value[:id]}.include?( old_custom_field_value[:custom_field_id]) custom_field_values << old_custom_field_value end end line_item[:custom_field_values] = custom_field_values # Update the line item on the server. return_line_items = line_item_service.update_line_items([line_item]) return_line_items.each do |return_line_item| custom_field_value_strings = [] if return_line_item.include?(:custom_field_values) return_line_item[:custom_field_values].each do |value| if value[:base_custom_field_value_type].eql?('CustomFieldValue') custom_field_value_strings << "{ID: %d, value: '%s'}" % [value[:custom_field_id], value[:value][:value]] end if value[:base_custom_field_value_type].eql?( 'DropDownCustomFieldValue') custom_field_value_strings << "{ID: %d, custom field option ID: %d}" % [value[:custom_field_id], value[:custom_field_option_id]] end end end puts "Line item ID %d set with custom field values: [%s]" % [return_line_item[:id], custom_field_value_strings.join(', ')] end end end if __FILE__ == $0 begin set_line_item_custom_field_value() # HTTP errors. rescue AdsCommon::Errors::HttpError => e puts "HTTP Error: %s" % e # API errors. rescue DfpApi::Errors::ApiException => e puts "Message: %s" % e.message puts 'Errors:' e.errors.each_with_index do |error, index| puts "\tError [%d]:" % (index + 1) error.each do |field, value| puts "\t\t%s: %s" % [field, value] end end end end
{ "content_hash": "331abfc04bc179e48feca61e2828cc5f", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 80, "avg_line_length": 34.12903225806452, "alnum_prop": 0.6372400756143667, "repo_name": "t9nf/google-api-ads-ruby", "id": "aca95f8d315860e36aeab41abc62ec74ab61f5be", "size": "6462", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "dfp_api/examples/v201505/custom_field_service/set_line_item_custom_field_value.rb", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1028" }, { "name": "HTML", "bytes": "7762" }, { "name": "JavaScript", "bytes": "757" }, { "name": "Ruby", "bytes": "7929353" } ], "symlink_target": "" }
'use strict'; import nodefn from 'when/node'; import { reach } from 'origami'; import rest from '../lib/rest-client'; function requestAccessToken (options, callback) { const settings = { method: 'POST', path: 'https://api.cronofy.com/oauth/token', entity: options }; const result = rest(settings).fold(reach, 'entity'); return nodefn.bindCallback(result, callback); } export default requestAccessToken;
{ "content_hash": "af85e31dbbff5e43cc4d5220fa48e9b9", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 54, "avg_line_length": 23.72222222222222, "alnum_prop": 0.6978922716627635, "repo_name": "nbdaaron/CalendarMerge", "id": "e2aeeb39c1b38c97b7eec9ed061cef6b79333d91", "size": "427", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/cronofy/src/methods/request-access-token.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "479" }, { "name": "HTML", "bytes": "15202" }, { "name": "JavaScript", "bytes": "27256" } ], "symlink_target": "" }
package org.jge.render; import org.jge.Disposable; public class TextureAtlas implements Disposable { private Texture texture; private int tileWidth; private int tileHeight; private int xSpacing; private int ySpacing; /** * [Column][Row] */ private TextureRegion[][] tiles; private int xNbr; private int yNbr; public TextureAtlas(Texture texture, int tileWidth, int tileHeight) { this(texture, tileWidth, tileHeight, 0, 0); } public TextureAtlas(Texture texture, int tileWidth, int tileHeight, int xSpacing, int ySpacing) { this.texture = texture; this.tileWidth = tileWidth; this.tileHeight = tileHeight; this.xSpacing = xSpacing; this.ySpacing = ySpacing; for(int i = 0; i < texture.getWidth(); i += tileWidth + xSpacing) { xNbr++ ; } for(int i = 0; i < texture.getHeight(); i += tileHeight + ySpacing) { yNbr++ ; } tiles = new TextureRegion[xNbr][yNbr]; for(int x = 0; x < xNbr; x++ ) { for(int y = 0; y < yNbr; y++ ) { double minU = (x * (tileWidth + xSpacing)) / (double)texture.getWidth(); double minV = (y * (tileHeight + ySpacing)) / (double)texture.getHeight(); double maxU = (x * (tileWidth + xSpacing) + (tileWidth + xSpacing)) / (double)texture.getWidth(); double maxV = (y * (tileHeight + ySpacing) + (tileHeight + ySpacing)) / (double)texture.getHeight(); tiles[x][y] = new TextureRegion(texture, minU, minV, maxU, maxV); } } } /** * [Column][Row] */ public TextureRegion[][] getTiles() { return tiles; } public void dispose() { texture.dispose(); } public Texture getTexture() { return texture; } public int getTileWidth() { return tileWidth; } public int getTileHeight() { return tileHeight; } public int getXSpacing() { return xSpacing; } public int getYSpacing() { return ySpacing; } public int getXNbr() { return xNbr; } public int getYNbr() { return yNbr; } }
{ "content_hash": "18d075304bd646b7f56dfc27bfe55840", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 104, "avg_line_length": 18.401869158878505, "alnum_prop": 0.6368715083798883, "repo_name": "jglrxavpok/jglrEngine", "id": "e8c4144fbbba38c79efd45988ddcecd186907110", "size": "1969", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/jge/render/TextureAtlas.java", "mode": "33188", "license": "mit", "language": [ { "name": "Apex", "bytes": "227" }, { "name": "F#", "bytes": "4753" }, { "name": "Groovy", "bytes": "1275" }, { "name": "Haskell", "bytes": "5005" }, { "name": "Java", "bytes": "415175" }, { "name": "Lua", "bytes": "1223" } ], "symlink_target": "" }
'use strict'; /** * @ngdoc function * @name testReporterApp.controller:ViewsCtrl * @description * # ViewsCtrl * Controller of the testReporterApp */ angular.module('testReporterApp') .controller('ViewCtrl', [ '$scope', 'jenkins', 'NgTableParams', 'FileSaver', 'Blob', '$rootScope', '$filter', '$stateParams', '$http','$q', 'SolrSearch', function ($scope, jenkins, NgTableParams, FileSaver, Blob, $rootScope, $filter, $stateParams, $http, $q, SolrSearch) { var percentageFilter = $filter('percentage'); $scope.view = { name: $stateParams.view }; $scope.search = { jobSearch: '', testSearch: '', errorSearch: '' }; $scope.testSearch = ""; $scope.solrIndexed = false; $scope.$on('jenkins-report', function (event, downloadProgress) { $scope.downloadProgress = downloadProgress; }); $scope.$on('error-report', function (event, downloadProgress) { $scope.errorProgress = downloadProgress; }); jenkins.view($scope.view.name) .then(function (view) { $scope.jobs = view.allJobs; $scope.view = view; var allBuilds = []; $scope.jobs.forEach(function (j) { j.builds.forEach(function (b) { b.job = j; allBuilds.push(b); }); }); var indexInSolr = function(testReport) { var solrReport = []; testReport.cases.forEach(function(tc) { //index only failures if(tc.status !== 'Passed') { tc.executions.forEach(function (te) { var document = { id: te.id, testReportId: testReport.testReportId, name: te.name, className: te.className, error: te.error, shortError: te.shortError, stderr: te.stderr, stdout: te.stdout, view: tc.job.view, url: te.url, jobDisplayName: te.build.job.displayName, jobName: te.build.job.name, errorStackTrace: te.errorStackTrace, time_to_live_s: '+1DAYS' }; solrReport.push(document); }); } }); SolrSearch.selectByTestReportId(testReport.getHash()) .then(function(response) { if(response.data.response.numFound === 0) { return SolrSearch.indexData(solrReport); } }) .finally(function() { $scope.solrIndexed = true; }); }; jenkins.testReport(allBuilds) .then(function(testReport) { indexInSolr(testReport); return testReport; }) .then(function (testReport) { $scope.testReport = testReport; var testReportSummary = ''; for(var i=0; i<$rootScope.numberOfRecentBuilds; i++) { testReportSummary += 'Passing at least ' + (i + 1) + ' times: ' + percentageFilter(testReport.passRatePassingTimes(i + 1)); testReportSummary += ' (' + testReport.numberPassingTimes(i + 1) + ')'; testReportSummary += "\n"; } $scope.testReportSummary = testReportSummary; $scope.$apply(); $scope.tableParameters.sorting('report.passRate', 'asc'); $scope.$apply(); }); $scope.range = function(n) { return new Array(n); }; $scope.tableParameters = new NgTableParams({ count: 25, sorting: { passRate: 'asc' } }, { dataset: view.allJobs }); $scope.$watch('search.jobSearch', function () { $scope.tableParameters.filter({displayName: $scope.search.jobSearch}); }); $scope.$watch('search.testSearch', function (term) { if(!term || !$scope.testReport) { return; } SolrSearch.search({ error: term, testReportId: $scope.testReport.testReportId }) .then(function(results) { $scope.search.testSearchResults = results.response.docs.map(function (doc) { return $scope.testReport.getExecution(doc.id); }); $scope.search.facet_fields = results.facet_counts.facet_fields; }); }); }); $scope.assignErrorReport = function() { $scope.errorReport = $scope.testReport; }; }]);
{ "content_hash": "6c39e895e3598bb27a80197f2738e3c8", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 139, "avg_line_length": 32.58783783783784, "alnum_prop": 0.4945054945054945, "repo_name": "sponte/jenkins-test-statistics", "id": "f2f0d03ae845983424806ea1190ff28f8c46c388", "size": "4823", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/scripts/controllers/view.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "157966" }, { "name": "HTML", "bytes": "18038" }, { "name": "JavaScript", "bytes": "41612" } ], "symlink_target": "" }
package org.ektorp.http; import org.apache.http.params.HttpParams; import org.junit.Test; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class StdHttpClientBuilderTest { /** * This test documents that the configureHttpParams() should be protected * so that it can be overridden by applications who need to configure the HttpParams instance * before it is given to the DefaultHttpClient constructor. */ @Test public void shouldOverrideConfigureHttpParams() { final AtomicBoolean invoked = new AtomicBoolean(false); StdHttpClient.Builder builder = new StdHttpClient.Builder() { @Override protected HttpParams configureHttpParams() { HttpParams result = super.configureHttpParams(); // application can set additional configuration like the following // HttpConnectionParams.setStaleCheckingEnabled(result, false); invoked.set(true); return result; } }; HttpClient httpClient = builder.build(); assertNotNull(httpClient); assertTrue(invoked.get()); } }
{ "content_hash": "829b2d13e12d79c6eb03596003104e4d", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 94, "avg_line_length": 25.906976744186046, "alnum_prop": 0.7630161579892281, "repo_name": "maoueh/Ektorp", "id": "34fce24bbba1c0973f8dcea086a6aa52740d3012", "size": "1114", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "org.ektorp/src/test/java/org/ektorp/http/StdHttpClientBuilderTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "644" }, { "name": "Java", "bytes": "735363" }, { "name": "JavaScript", "bytes": "817" }, { "name": "XSLT", "bytes": "274" } ], "symlink_target": "" }
! { dg-do compile } ! This tests that the fix for PR25391 also fixes PR20244. If ! the USE mod1 in subroutine foo were deleted, the code would ! compile fine. With the USE statement, the compiler would ! make new TYPEs for T1 and T2 and bomb out in fold-convert. ! This is a slightly more elaborate test than ! used_dummy_types_1.f90 and came from the PR. ! ! Contributed by Jakub Jelinek <jakubcc.gnu.org> module mod1 type t1 real :: f1 end type t1 type t2 type(t1), pointer :: f2(:) real, pointer :: f3(:,:) end type t2 end module mod1 module mod2 use mod1 type(t1), pointer, save :: v(:) contains subroutine foo (x) use mod1 implicit none type(t2) :: x integer :: d d = size (x%f3, 2) v = x%f2(:) end subroutine foo end module mod2 ! { dg-final { cleanup-modules "mod1 mod2" } }
{ "content_hash": "01e5ec0e8e4e6a5b616c217bf98e3149", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 61, "avg_line_length": 24.647058823529413, "alnum_prop": 0.6610978520286396, "repo_name": "shaotuanchen/sunflower_exp", "id": "a47cabc430c439378940ae2a5336ee5e4f84e653", "size": "838", "binary": false, "copies": "52", "ref": "refs/heads/master", "path": "tools/source/gcc-4.2.4/gcc/testsuite/gfortran.dg/used_dummy_types_2.f90", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "459993" }, { "name": "Awk", "bytes": "6562" }, { "name": "Batchfile", "bytes": "9028" }, { "name": "C", "bytes": "50326113" }, { "name": "C++", "bytes": "2040239" }, { "name": "CSS", "bytes": "2355" }, { "name": "Clarion", "bytes": "2484" }, { "name": "Coq", "bytes": "61440" }, { "name": "DIGITAL Command Language", "bytes": "69150" }, { "name": "Emacs Lisp", "bytes": "186910" }, { "name": "Fortran", "bytes": "5364" }, { "name": "HTML", "bytes": "2171356" }, { "name": "JavaScript", "bytes": "27164" }, { "name": "Logos", "bytes": "159114" }, { "name": "M", "bytes": "109006" }, { "name": "M4", "bytes": "100614" }, { "name": "Makefile", "bytes": "5409865" }, { "name": "Mercury", "bytes": "702" }, { "name": "Module Management System", "bytes": "56956" }, { "name": "OCaml", "bytes": "253115" }, { "name": "Objective-C", "bytes": "57800" }, { "name": "Papyrus", "bytes": "3298" }, { "name": "Perl", "bytes": "70992" }, { "name": "Perl 6", "bytes": "693" }, { "name": "PostScript", "bytes": "3440120" }, { "name": "Python", "bytes": "40729" }, { "name": "Redcode", "bytes": "1140" }, { "name": "Roff", "bytes": "3794721" }, { "name": "SAS", "bytes": "56770" }, { "name": "SRecode Template", "bytes": "540157" }, { "name": "Shell", "bytes": "1560436" }, { "name": "Smalltalk", "bytes": "10124" }, { "name": "Standard ML", "bytes": "1212" }, { "name": "TeX", "bytes": "385584" }, { "name": "WebAssembly", "bytes": "52904" }, { "name": "Yacc", "bytes": "510934" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_22) on Fri Feb 11 22:06:27 PST 2011 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class com.fasterxml.aalto.util.EmptyIterator (aalto-xml 0.9.7 API) </TITLE> <META NAME="date" CONTENT="2011-02-11"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.fasterxml.aalto.util.EmptyIterator (aalto-xml 0.9.7 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../com/fasterxml/aalto/util/EmptyIterator.html" title="class in com.fasterxml.aalto.util"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><script type="text/javascript"><!-- google_ad_client = "ca-pub-1467773697956887"; /* Aalto-ad-small */ google_ad_slot = "3886247450"; google_ad_width = 234; google_ad_height = 60; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/fasterxml/aalto/util//class-useEmptyIterator.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="EmptyIterator.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>com.fasterxml.aalto.util.EmptyIterator</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../com/fasterxml/aalto/util/EmptyIterator.html" title="class in com.fasterxml.aalto.util">EmptyIterator</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#com.fasterxml.aalto.util"><B>com.fasterxml.aalto.util</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="com.fasterxml.aalto.util"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../com/fasterxml/aalto/util/EmptyIterator.html" title="class in com.fasterxml.aalto.util">EmptyIterator</A> in <A HREF="../../../../../com/fasterxml/aalto/util/package-summary.html">com.fasterxml.aalto.util</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../com/fasterxml/aalto/util/package-summary.html">com.fasterxml.aalto.util</A> that return <A HREF="../../../../../com/fasterxml/aalto/util/EmptyIterator.html" title="class in com.fasterxml.aalto.util">EmptyIterator</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0" SUMMARY=""> <TR ALIGN="right" VALIGN=""> <TD NOWRAP><FONT SIZE="-1"> <CODE>&lt;T&gt; <A HREF="../../../../../com/fasterxml/aalto/util/EmptyIterator.html" title="class in com.fasterxml.aalto.util">EmptyIterator</A>&lt;T&gt;</CODE></FONT></TD> </TR> </TABLE> </CODE></FONT></TD> <TD><CODE><B>EmptyIterator.</B><B><A HREF="../../../../../com/fasterxml/aalto/util/EmptyIterator.html#getInstance()">getInstance</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Since the actual type has no effect (as this iterator never returns any value objects), we can just cast away here: bit unclean, but safe.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR><td rowspan='3'><script type="text/javascript"><!-- google_ad_client = "ca-pub-1467773697956887"; /* Aalto-ad-small */ google_ad_slot = "3886247450"; google_ad_width = 234; google_ad_height = 60; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> <!-- GA --> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-140287-6"); pageTracker._trackPageview(); } catch(err) {} </script> </td> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../com/fasterxml/aalto/util/EmptyIterator.html" title="class in com.fasterxml.aalto.util"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/fasterxml/aalto/util//class-useEmptyIterator.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="EmptyIterator.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2011 <a href="http://fasterxml.com">Fasterxml.com</a>. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "5a29416493f6a34aaa6b4f378f6a88b4", "timestamp": "", "source": "github", "line_count": 222, "max_line_length": 292, "avg_line_length": 42.067567567567565, "alnum_prop": 0.6357211692900738, "repo_name": "FasterXML/aalto-xml", "id": "e62ea9471ce1f5c461f16ca883f7ef18ad7a4ec3", "size": "9339", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/javadoc/0.9.7/com/fasterxml/aalto/util/class-use/EmptyIterator.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1911443" } ], "symlink_target": "" }
"""Tasks related to format""" import os import subprocess from artman.tasks import task_base from artman.tasks.requirements import go_requirements from artman.tasks.requirements import php_requirements from artman.utils import task_utils from artman.utils.logger import logger # TODO: Store both intermediate and final output in all format tasks. class JavaFormatTask(task_base.TaskBase): def execute(self, gapic_code_dir, toolkit_path): logger.info('Formatting files in %s.' % os.path.abspath(gapic_code_dir)) # TODO(shinfan): Move gradle task into requirement path = task_utils.get_gradle_task_output( 'showJavaFormatterPath', toolkit_path) targetFiles = [] for root, dirs, files in os.walk(gapic_code_dir): for filename in files: if filename.endswith('.java'): targetFile = os.path.abspath(os.path.join(root, filename)) targetFiles.append(targetFile) self.exec_command( ['java', '-jar', path, '--replace'] + targetFiles) def validate(self): return [] class PythonFormatTask(task_base.TaskBase): def execute(self, gapic_code_dir): logger.info('Formatting files in %s.' % os.path.abspath(gapic_code_dir)) targetFiles = [] for root, dirs, files in os.walk(gapic_code_dir): for filename in files: if filename.endswith('.py'): targetFile = os.path.abspath(os.path.join(root, filename)) targetFiles.append(targetFile) # yapf returns code 2 when it formats, so we can't use `check_call`. exit_code = subprocess.call(['yapf', '-i'] + targetFiles) if exit_code not in [0, 2]: raise subprocess.CalledProcessError(exit_code, 'yapf') # yapf is installed by tox for the entire pipeline project's virtualenv, # so we shouldn't need a separate validation task. def validate(self): return [] class GoFormatTask(task_base.TaskBase): def execute(self, gapic_code_dir): logger.info('Formatting files in %s.' % os.path.abspath(gapic_code_dir)) self.exec_command(['gofmt', '-w', gapic_code_dir]) def validate(self): return [go_requirements.GoFormatRequirements] class PhpFormatTask(task_base.TaskBase): def execute(self, gapic_code_dir): abs_code_dir = os.path.abspath(gapic_code_dir) logger.info('Formatting file using php-cs-fixer in %s.' % abs_code_dir) subprocess.call(['php-cs-fixer', 'fix', gapic_code_dir]) # We require a second call to php-cs-fixer because instances of @type # have been converted to @var. We cannot disable this conversion in # the first call without affecting other aspects of the formatting. subprocess.call(['php-cs-fixer', 'fix', gapic_code_dir, '--fixers=phpdoc_var_to_type']) logger.info('Formatting file using phpcbf in %s.' % abs_code_dir) subprocess.call(['phpcbf', '--standard=PSR2', '--no-patch', gapic_code_dir]) def validate(self): return [php_requirements.PhpFormatRequirements] _FORMAT_TASK_DICT = { 'java': JavaFormatTask, 'python': PythonFormatTask, 'go': GoFormatTask, 'php': PhpFormatTask, } def get_format_task(language): return _FORMAT_TASK_DICT.get(language, task_base.EmptyTask)
{ "content_hash": "236ce617b436ac1b0059fb70415948d1", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 79, "avg_line_length": 37.53763440860215, "alnum_prop": 0.6299054712116872, "repo_name": "shinfan/artman", "id": "a4c6e5f765c7851cfba24137e51bf824ee928a2d", "size": "4084", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "artman/tasks/format_tasks.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Protocol Buffer", "bytes": "40829" }, { "name": "Python", "bytes": "316278" } ], "symlink_target": "" }
using NUnit.Framework; using RefactoringEssentials.CSharp.Diagnostics; namespace RefactoringEssentials.Tests.CSharp.Diagnostics { [TestFixture] [Ignore("TODO: Issue not ported yet")] public class CS0126ReturnMustBeFollowedByAnyExpressionTests : CSharpDiagnosticTestBase { static void Test(string type, string defaultValue) { Test<CS0126ReturnMustBeFollowedByAnyExpression>(@"class Foo { " + type + @" Bar (string str) { return; } }", @"class Foo { " + type + @" Bar (string str) { return " + defaultValue + @"; } }"); } [Test] public void TestSimpleCase() { Test("int", "0"); Test("string", "\"\""); Test("char", "' '"); Test("bool", "false"); Test("object", "null"); Test("System.DateTime", "default(System.DateTime)"); } [Test] public void TestReturnTypeFix() { Test<CS0126ReturnMustBeFollowedByAnyExpression>(@"class Foo { int Bar (string str) { return; } }", @"class Foo { void Bar (string str) { return; } }", 1); } [Test] public void TestProperty() { TestIssue<CS0126ReturnMustBeFollowedByAnyExpression>(@"class Foo { string Bar { get { return; } } }"); } [Test] public void TestPropertySetter() { Analyze<CS0126ReturnMustBeFollowedByAnyExpression>(@"class Foo { string Bar { set { return; } } }"); } [Test] public void TestIndexer() { TestIssue<CS0126ReturnMustBeFollowedByAnyExpression>(@"class Foo { string this [int idx] { get { return; } } }"); } [Test] public void TestAnonymousMethod() { TestIssue<CS0126ReturnMustBeFollowedByAnyExpression>(@" using System; class Foo { void Bar (string str) { System.Func<string> func = delegate { return; }; } }"); } [Test] public void TestAnonymousMethodReturnTypeFix() { Test<CS0126ReturnMustBeFollowedByAnyExpression>(@" using System; class Foo { int Bar (string str) { System.Func<string> func = delegate { return; }; } }", @" using System; class Foo { int Bar (string str) { System.Func<string> func = delegate { return """"; }; } }"); } [Test] public void TestAnonymousMethodReturningVoid() { Analyze<CS0126ReturnMustBeFollowedByAnyExpression>(@"using System; class Foo { void Bar (string str) { Action func = delegate { return; }; } }"); } [Test] public void TestLambdaMethod() { TestIssue<CS0126ReturnMustBeFollowedByAnyExpression>(@"class Foo { void Bar (string str) { System.Func<string> func = () => { return; }; } }"); } [Test] public void TestOperatorFalsePositives() { TestIssue<CS0126ReturnMustBeFollowedByAnyExpression>(@"class Foo { public static bool operator == (Foo left, Foo right) { return; } }"); } [Test] public void TestConstructor() { Analyze<CS0126ReturnMustBeFollowedByAnyExpression>(@"class Foo { Foo () { return; } }"); } [Test] public void TestDestructor() { Analyze<CS0126ReturnMustBeFollowedByAnyExpression>(@"class Foo { ~Foo () { return; } }"); } [Test] public void TestDontShowUpOnUndecidableCase() { Analyze<CS0126ReturnMustBeFollowedByAnyExpression>(@" using System; class Test { void Foo (Func<int, int> func) {} void Foo (Action<int> func) {} void Bar (string str) { Foo(delegate { return; }); } }"); } [Test] public void TestParallelForBug() { Analyze<CS0126ReturnMustBeFollowedByAnyExpression>(@" using System; using System.Threading.Tasks; using System.Collections.Generic; class Test { void FooBar(IEnumerable<string> str) { Parallel.ForEach(str, p => { return; }); } }"); } [Test] public void TestConstructorInitializer() { Analyze<CS0126ReturnMustBeFollowedByAnyExpression>(@" using System; class Test { Test (Func<int, int> func) {} Test (Action<int> func) {} Test () : this (delegate { return; }) { } }"); } [Test] public void TestAsyncMethod_Void() { Analyze<CS0126ReturnMustBeFollowedByAnyExpression>(@"using System; using System.Threading.Tasks; class Test { public async void M() { return; } }"); } [Test] public void TestAsyncMethod_Task() { Analyze<CS0126ReturnMustBeFollowedByAnyExpression>(@"using System; using System.Threading.Tasks; class Test { public async Task M() { return; } }"); } [Test] public void TestAsyncMethod_TaskOfInt() { TestIssue<CS0126ReturnMustBeFollowedByAnyExpression>(@"using System; using System.Threading.Tasks; class Test { public async Task<int> M() { return; } }"); } } }
{ "content_hash": "336f57376773da01f71f05f8fe243dd2", "timestamp": "", "source": "github", "line_count": 311, "max_line_length": 90, "avg_line_length": 16.7491961414791, "alnum_prop": 0.5703589940487618, "repo_name": "olathunberg/RefactoringEssentials", "id": "7bcba77ae2efea1a5783821ca8c33c39d2b2fb47", "size": "5209", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "Tests/CSharp/Diagnostics/CS0126ReturnMustBeFollowedByAnyExpressionTestes.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "102" }, { "name": "Batchfile", "bytes": "754" }, { "name": "C#", "bytes": "4807900" }, { "name": "CSS", "bytes": "1267" }, { "name": "HTML", "bytes": "28485" }, { "name": "PowerShell", "bytes": "995" }, { "name": "Visual Basic", "bytes": "8195" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Adding Mapzen Search geocoding to a basic Leaflet map.</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1"> <!-- Load Leaflet from CDN --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.5/leaflet.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.5/leaflet.js"></script> <!-- Load Pelias geocoding plugin after Leaflet --> <link rel="stylesheet" href="../src/leaflet-geocoder-mapzen.css"> <script src="../src/leaflet-geocoder-mapzen.js"></script> <link rel="stylesheet" href="assets/examples.css"> </head> <body> <div id="map"></div> <script> // Create a basic Leaflet map var map = L.map('map').setView([40.7259, -73.9805], 12); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap contributors</a>' }).addTo(map); // Add geocoding plugin var geocoder = L.control.geocoder('search-MKZrG6M').addTo(map); </script> </body> </html>
{ "content_hash": "df3af41a34633e35e9ed462f6af214eb", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 105, "avg_line_length": 36.935483870967744, "alnum_prop": 0.6655021834061136, "repo_name": "okstate-maps/okmaps-search", "id": "6dccc27cd03ebfe8b83998e33ddad1ef7a0c067d", "size": "1145", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/leaflet-geocoder-mapzen/examples/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "178419" }, { "name": "HTML", "bytes": "44049" }, { "name": "JavaScript", "bytes": "1063019" }, { "name": "Makefile", "bytes": "58" }, { "name": "Shell", "bytes": "539" } ], "symlink_target": "" }
update sqlview set type='VIEW' where type is null; update sqlview set cachestrategy='RESPECT_SYSTEM_SETTING' where cachestrategy is null; alter table sqlview alter column type set not null; alter table sqlview alter column cachestrategy set not null;
{ "content_hash": "26f40b59ac94c6288bf4d034af4caf07", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 86, "avg_line_length": 50.2, "alnum_prop": 0.8167330677290837, "repo_name": "msf-oca-his/dhis2-core", "id": "e3b97691e4b110da70a14b7068fb2e34d94be0a1", "size": "251", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "dhis-2/dhis-support/dhis-support-db-migration/src/main/resources/org/hisp/dhis/db/migration/2.38/V2_38_17__Add_notnull_constraint_for_sqlview_type_and_cachestrategy.sql", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "186517" }, { "name": "Dockerfile", "bytes": "2280" }, { "name": "HTML", "bytes": "69119" }, { "name": "Java", "bytes": "30867122" }, { "name": "JavaScript", "bytes": "958564" }, { "name": "PLpgSQL", "bytes": "60867" }, { "name": "Ruby", "bytes": "1011" }, { "name": "SCSS", "bytes": "4229" }, { "name": "Shell", "bytes": "21208" }, { "name": "XSLT", "bytes": "8451" } ], "symlink_target": "" }
// // ALPHAScreenItem.h // Alpha // // Created by Dal Rupnik on 20/05/15. // Copyright © 2015 Unified Sense. All rights reserved. // @import UIKit; #import "ALPHASerializableItem.h" #import "ALPHARequest.h" typedef NSInteger ALPHAScreenItemPriority; @interface ALPHAScreenItem : NSObject <ALPHASerializableItem> #pragma mark - Model /*! * Back-Reference for model if created from a model */ @property (nonatomic, strong) id object; #pragma mark - Screen /*! * NSString with Emoji or UIImage */ @property (nonatomic, strong) id icon; @property (nonatomic, assign) UIViewContentMode imageContentMode; - (NSString *)title; - (void)setTitle:(id)title; @property (nonatomic, copy) NSString *titleText; @property (nonatomic, copy) NSAttributedString *attributedTitleText; - (NSString *)detail; - (void)setDetail:(id)detail; @property (nonatomic, copy) NSString* detailText; @property (nonatomic, copy) NSAttributedString* attributedDetailText; @property (nonatomic, assign) UITableViewCellStyle style; @property (nonatomic, assign) UITableViewCellAccessoryType accessory; /*! * Set this property to YES to render the screen item half transparent */ @property (nonatomic, assign) BOOL transparent; /*! * If any Alpha implemented cell class should be used instead of default. */ @property (nonatomic, copy) NSString *cellClass; /*! * If cell class is used, additional parameters can be set on cell class. The keys in dictionary * correspond to properties in cell class. */ @property (nonatomic, copy) NSDictionary *cellParameters; /*! * Specified priority of the action item so the item is placed correctly in menus or table or collection */ @property (nonatomic, assign) ALPHAScreenItemPriority priority; @end
{ "content_hash": "05030f7c87990145ad6ae159183a548a", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 105, "avg_line_length": 24.942857142857143, "alnum_prop": 0.7485681557846506, "repo_name": "Legoless/Alpha", "id": "84a3f2b6bbc83826b35bcba40485ceda28fe3696", "size": "1747", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Alpha/Model/Screen/ALPHAScreenItem.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6098" }, { "name": "Objective-C", "bytes": "1347891" }, { "name": "Ruby", "bytes": "7464" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.loadtestservice.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.resourcemanager.loadtestservice.models.EncryptionProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** Load Test resource properties. */ @Fluent public final class LoadTestResourcePatchRequestBodyProperties { /* * Description of the resource. */ @JsonProperty(value = "description") private String description; /* * CMK Encryption property. */ @JsonProperty(value = "encryption") private EncryptionProperties encryption; /** Creates an instance of LoadTestResourcePatchRequestBodyProperties class. */ public LoadTestResourcePatchRequestBodyProperties() { } /** * Get the description property: Description of the resource. * * @return the description value. */ public String description() { return this.description; } /** * Set the description property: Description of the resource. * * @param description the description value to set. * @return the LoadTestResourcePatchRequestBodyProperties object itself. */ public LoadTestResourcePatchRequestBodyProperties withDescription(String description) { this.description = description; return this; } /** * Get the encryption property: CMK Encryption property. * * @return the encryption value. */ public EncryptionProperties encryption() { return this.encryption; } /** * Set the encryption property: CMK Encryption property. * * @param encryption the encryption value to set. * @return the LoadTestResourcePatchRequestBodyProperties object itself. */ public LoadTestResourcePatchRequestBodyProperties withEncryption(EncryptionProperties encryption) { this.encryption = encryption; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (encryption() != null) { encryption().validate(); } } }
{ "content_hash": "5933a6279f88e120f55d5f494dbaffb1", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 103, "avg_line_length": 29.25, "alnum_prop": 0.6863247863247863, "repo_name": "Azure/azure-sdk-for-java", "id": "cfc0f5f17ad298f54672c9700d2b1fa25f26cace", "size": "2340", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/loadtestservice/azure-resourcemanager-loadtestservice/src/main/java/com/azure/resourcemanager/loadtestservice/fluent/models/LoadTestResourcePatchRequestBodyProperties.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "8762" }, { "name": "Bicep", "bytes": "15055" }, { "name": "CSS", "bytes": "7676" }, { "name": "Dockerfile", "bytes": "2028" }, { "name": "Groovy", "bytes": "3237482" }, { "name": "HTML", "bytes": "42090" }, { "name": "Java", "bytes": "432409546" }, { "name": "JavaScript", "bytes": "36557" }, { "name": "Jupyter Notebook", "bytes": "95868" }, { "name": "PowerShell", "bytes": "737517" }, { "name": "Python", "bytes": "240542" }, { "name": "Scala", "bytes": "1143898" }, { "name": "Shell", "bytes": "18488" }, { "name": "XSLT", "bytes": "755" } ], "symlink_target": "" }
/* This file was generated by Dashcode and is covered by the license.txt included in the project. You may edit this file, however it is recommended to first turn off the Dashcode code generator otherwise the changes will be lost. */ var dashcodePartSpecs = { 'helloText': { view: 'DC.Text', text: "Hello, World!" }, 'info': { creationFunction: 'CreateInfoButton', frontID: 'front', foregroundStyle: 'white', backgroundStyle: 'black', onclick: 'showBack' }, 'done': { creationFunction: 'CreateGlassButton', text: "Done", onclick: 'showFront' } };
{ "content_hash": "77fbbcc0227f554c5b679ac450d49049", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 145, "avg_line_length": 51.90909090909091, "alnum_prop": 0.702276707530648, "repo_name": "daluu/textbelt-clients", "id": "d9ca82b21dd8af0dbf16bf82fd63c5c981fa7a04", "size": "571", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "macosx/textbelter.dcproj/project/widget.wdgt/Parts/setup.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "296" }, { "name": "HTML", "bytes": "22089" }, { "name": "JavaScript", "bytes": "1071242" } ], "symlink_target": "" }
from language import pluralize import termcolor def colored(msg, color): if color == 'term': return msg return termcolor.colored(msg, color) class OutputWriter(object): def __init__(self, stream, language, should_be_colored=True): self._stream = stream self._language = language self._should_be_colored = should_be_colored def _colored(self, msg, color): if self._should_be_colored: return colored(msg, color) return msg def _output_problems_info(self, problems, problem_type, color='red'): if not problems: return self._stream.write(self._colored('\n %ss:\n' % self._language[problem_type], color)) for problem in problems: self._stream.write(self._colored('%s\n' % problem, color)) def _output_step_line(self, step_name, message, status, color): self._stream.write(self._colored(' %s %s ... %s\n' % ( self._language[step_name].capitalize(), message, self._language[status].upper()), color)) def output_ok_step_line(self, step_name, message, color='green'): self._output_step_line(step_name, message, 'ok', color) def output_pending_step_line(self, step_name, message, color='blue'): self._output_step_line(step_name, message, 'pending', color) def output_fail_step_line(self, step_name, message, color='red'): self._output_step_line(step_name, message, 'fail', color) def output_error_step_line(self, step_name, message, color='red'): self._output_step_line(step_name, message, 'error', color) def output_failures_info(self, problems, color='red'): self._output_problems_info(problems, 'failure', color) def output_errors_info(self, problems, color='red'): self._output_problems_info(problems, 'error', color) def output_statistics(self, number_of_scenarios, number_of_failures, number_of_errors, number_of_pendings, color='white'): scenario_word = pluralize(self._language['scenario'], number_of_scenarios).lower() failure_word = pluralize(self._language['failure'], number_of_failures).lower() error_word = pluralize(self._language['error'], number_of_errors).lower() step_word = pluralize(self._language['step'], number_of_pendings).lower() pending_word = self._language['pending'].lower() steps_pending = pending_word + ' ' + step_word if self._language['pending'].lower() == 'pendente': pending_word = pluralize('pendente', number_of_pendings).lower() steps_pending = step_word + ' ' + pending_word ran = self._language['ran'].capitalize() with_word = self._language['with'].lower() and_word = self._language['and'].lower() self._stream.write(self._colored('\n %s\n' % ' '.join(map(str, [ran, number_of_scenarios, scenario_word, with_word, number_of_failures, failure_word+',', number_of_errors, error_word, and_word, number_of_pendings, steps_pending,])), color))
{ "content_hash": "5e29ed33650358c2149a39486266752b", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 77, "avg_line_length": 45.795698924731184, "alnum_prop": 0.45550598732096736, "repo_name": "hltbra/pyhistorian", "id": "30d38202b693e1b5d7d55618e83583c450389368", "size": "4259", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pyhistorian/output.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "79586" } ], "symlink_target": "" }
package org.apache.ibatis.submitted.constructor_automapping; import static org.junit.jupiter.api.Assertions.*; import java.io.Reader; import java.util.List; import org.apache.ibatis.BaseDataTest; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class ConstructorAutomappingTest { private static SqlSessionFactory sqlSessionFactory; @BeforeAll static void setUp() throws Exception { // create an SqlSessionFactory try (Reader reader = Resources .getResourceAsReader("org/apache/ibatis/submitted/constructor_automapping/mybatis-config.xml")) { sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } // populate in-memory database BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), "org/apache/ibatis/submitted/constructor_automapping/CreateDB.sql"); } @Test void shouldHandleColumnPrefixCorrectly() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { Mapper mapper = sqlSession.getMapper(Mapper.class); List<Article> articles = mapper.nestedConstructorAutomapping(); assertEquals(2, articles.size()); Article article1 = articles.get(0); assertEquals("Article1", article1.getTitle()); Author author1 = article1.getAuthor(); assertEquals(Integer.valueOf(100), author1.getId()); assertEquals("Author1", author1.getName()); } } }
{ "content_hash": "d536a86390a3cdff900838ac2448d8fd", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 105, "avg_line_length": 34.104166666666664, "alnum_prop": 0.7532070861331704, "repo_name": "langlan/mybatis-3", "id": "5c9ae96da045da9396eb93eb6a1020d2e995335d", "size": "2285", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/org/apache/ibatis/submitted/constructor_automapping/ConstructorAutomappingTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8370" }, { "name": "Java", "bytes": "3261506" }, { "name": "PLpgSQL", "bytes": "5675" }, { "name": "TSQL", "bytes": "5683" } ], "symlink_target": "" }
bool AssertFunction( bool test, char* desc, int line, char* file ) { static char outputbuffer[2048]; if (!test) { sprintf(outputbuffer, "%s line:[%d] file: %s", desc, line, file); OutputDebugStringA(outputbuffer); } return !test; }
{ "content_hash": "100c3ee94c5ac10b5379cb85684d598b", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 73, "avg_line_length": 24.363636363636363, "alnum_prop": 0.6082089552238806, "repo_name": "Nuclearfossil/IntroToCPPGraphics", "id": "e705a970b2ab1aa2c3d2154c9318a38e9c8e5287", "size": "309", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "code/tutorial01/src/utils/assert.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3720" }, { "name": "C++", "bytes": "106102" }, { "name": "HLSL", "bytes": "4246" }, { "name": "Lua", "bytes": "49857" }, { "name": "Objective-C", "bytes": "401" }, { "name": "PostScript", "bytes": "167" }, { "name": "ShaderLab", "bytes": "345" } ], "symlink_target": "" }
package org.apache.hadoop.hbase.client; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Arrays; import java.util.ConcurrentModificationException; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellScanner; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.testclassification.ClientTests; import org.apache.hadoop.hbase.testclassification.SmallTests; import org.apache.hadoop.hbase.util.Bytes; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Test that I can Iterate Client Actions that hold Cells (Get does not have Cells). */ @Category({SmallTests.class, ClientTests.class}) public class TestPutDeleteEtcCellIteration { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestPutDeleteEtcCellIteration.class); private static final byte [] ROW = new byte [] {'r'}; private static final long TIMESTAMP = System.currentTimeMillis(); private static final int COUNT = 10; @Test public void testPutIteration() throws IOException { Put p = new Put(ROW); for (int i = 0; i < COUNT; i++) { byte [] bytes = Bytes.toBytes(i); p.addColumn(bytes, bytes, TIMESTAMP, bytes); } int index = 0; for (CellScanner cellScanner = p.cellScanner(); cellScanner.advance();) { Cell cell = cellScanner.current(); byte [] bytes = Bytes.toBytes(index++); cell.equals(new KeyValue(ROW, bytes, bytes, TIMESTAMP, bytes)); } assertEquals(COUNT, index); } @Test (expected = ConcurrentModificationException.class) public void testPutConcurrentModificationOnIteration() throws IOException { Put p = new Put(ROW); for (int i = 0; i < COUNT; i++) { byte [] bytes = Bytes.toBytes(i); p.addColumn(bytes, bytes, TIMESTAMP, bytes); } int index = 0; int trigger = 3; for (CellScanner cellScanner = p.cellScanner(); cellScanner.advance();) { Cell cell = cellScanner.current(); byte [] bytes = Bytes.toBytes(index++); // When we hit the trigger, try inserting a new KV; should trigger exception if (trigger == 3) p.addColumn(bytes, bytes, TIMESTAMP, bytes); cell.equals(new KeyValue(ROW, bytes, bytes, TIMESTAMP, bytes)); } assertEquals(COUNT, index); } @Test public void testDeleteIteration() throws IOException { Delete d = new Delete(ROW); for (int i = 0; i < COUNT; i++) { byte [] bytes = Bytes.toBytes(i); d.addColumn(bytes, bytes, TIMESTAMP); } int index = 0; for (CellScanner cellScanner = d.cellScanner(); cellScanner.advance();) { Cell cell = cellScanner.current(); byte [] bytes = Bytes.toBytes(index++); cell.equals(new KeyValue(ROW, bytes, bytes, TIMESTAMP, KeyValue.Type.DeleteColumn)); } assertEquals(COUNT, index); } @Test public void testAppendIteration() throws IOException { Append a = new Append(ROW); for (int i = 0; i < COUNT; i++) { byte [] bytes = Bytes.toBytes(i); a.addColumn(bytes, bytes, bytes); } int index = 0; for (CellScanner cellScanner = a.cellScanner(); cellScanner.advance();) { Cell cell = cellScanner.current(); byte [] bytes = Bytes.toBytes(index++); KeyValue kv = (KeyValue)cell; assertTrue(Bytes.equals(CellUtil.cloneFamily(kv), bytes)); assertTrue(Bytes.equals(CellUtil.cloneValue(kv), bytes)); } assertEquals(COUNT, index); } @Test public void testIncrementIteration() throws IOException { Increment increment = new Increment(ROW); for (int i = 0; i < COUNT; i++) { byte [] bytes = Bytes.toBytes(i); increment.addColumn(bytes, bytes, i); } int index = 0; for (CellScanner cellScanner = increment.cellScanner(); cellScanner.advance();) { Cell cell = cellScanner.current(); int value = index; byte [] bytes = Bytes.toBytes(index++); KeyValue kv = (KeyValue)cell; assertTrue(Bytes.equals(CellUtil.cloneFamily(kv), bytes)); long a = Bytes.toLong(CellUtil.cloneValue(kv)); assertEquals(value, a); } assertEquals(COUNT, index); } @Test public void testResultIteration() throws IOException { Cell [] cells = new Cell[COUNT]; for(int i = 0; i < COUNT; i++) { byte [] bytes = Bytes.toBytes(i); cells[i] = new KeyValue(ROW, bytes, bytes, TIMESTAMP, bytes); } Result r = Result.create(Arrays.asList(cells)); int index = 0; for (CellScanner cellScanner = r.cellScanner(); cellScanner.advance();) { Cell cell = cellScanner.current(); byte [] bytes = Bytes.toBytes(index++); cell.equals(new KeyValue(ROW, bytes, bytes, TIMESTAMP, bytes)); } assertEquals(COUNT, index); } }
{ "content_hash": "2c729e3883762743062b000b7292f155", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 90, "avg_line_length": 35.0709219858156, "alnum_prop": 0.6717896865520728, "repo_name": "Eshcar/hbase", "id": "b55835875ced5d965b6a12719b05e074d2225add", "size": "5751", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestPutDeleteEtcCellIteration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "25330" }, { "name": "C", "bytes": "28534" }, { "name": "C++", "bytes": "56085" }, { "name": "CMake", "bytes": "13186" }, { "name": "CSS", "bytes": "37063" }, { "name": "Dockerfile", "bytes": "4842" }, { "name": "Groovy", "bytes": "37699" }, { "name": "HTML", "bytes": "17275" }, { "name": "Java", "bytes": "35340173" }, { "name": "JavaScript", "bytes": "2694" }, { "name": "Makefile", "bytes": "1359" }, { "name": "PHP", "bytes": "8385" }, { "name": "Perl", "bytes": "383739" }, { "name": "Python", "bytes": "90226" }, { "name": "Ruby", "bytes": "664567" }, { "name": "Shell", "bytes": "254787" }, { "name": "Thrift", "bytes": "52354" }, { "name": "XSLT", "bytes": "6764" } ], "symlink_target": "" }
require_relative 'rexml_test_utils' require "rexml/document" require "rexml/xpath" # Harness to test REXML's capabilities against the test suite from Jaxen # [email protected] module REXMLTests class JaxenTester < Test::Unit::TestCase include REXMLTestUtils include REXML def test_axis ; test("axis") ; end def test_basic ; test("basic") ; end def test_basicupdate ; test("basicupdate") ; end def test_contents ; test("contents") ; end def test_defaultNamespace ; test("defaultNamespace") ; end def test_fibo ; test("fibo") ; end def test_id ; test("id") ; end def test_jaxen24 ; test("jaxen24") ; end def test_lang ; test("lang") ; end def test_message ; test("message") ; end def test_moreover ; test("moreover") ; end def test_much_ado ; test("much_ado") ; end def test_namespaces ; test("namespaces") ; end def test_nitf ; test("nitf") ; end def test_numbers ; test("numbers") ; end def test_pi ; test("pi") ; end def test_pi2 ; test("pi2") ; end def test_simple ; test("simple") ; end def test_testNamespaces ; test("testNamespaces") ; end def test_text ; test("text") ; end def test_underscore ; test("underscore") ; end def test_web ; test("web") ; end def test_web2 ; test("web2") ; end private def test( fname ) # Dir.entries( xml_dir ).each { |fname| # if fname =~ /\.xml$/ doc = File.open(fixture_path(fname+".xml")) do |file| Document.new(file) end XPath.each( doc, "/tests/document" ) {|e| handleDocument(e)} # end # } end # processes a tests/document/context node def handleContext( testDoc, ctxElement) testCtx = XPath.match( testDoc, ctxElement.attributes["select"] )[0] namespaces = {} if testCtx.class == Element testCtx.prefixes.each { |pre| handleNamespace( testCtx, pre, namespaces ) } end variables = {} XPath.each( ctxElement, "@*[namespace-uri() = 'http://jaxen.org/test-harness/var']") { |attrib| handleVariable(testCtx, variables, attrib) } XPath.each( ctxElement, "valueOf") { |e| handleValueOf(testCtx, variables, namespaces, e) } XPath.each( ctxElement, "test[not(@exception) or (@exception != 'true') ]") { |e| handleNominalTest(testCtx,variables, namespaces, e) } XPath.each( ctxElement, "test[@exception = 'true']") { |e| handleExceptionalTest(testCtx,variables, namespaces, e) } end # processes a tests/document/context/valueOf or tests/document/context/test/valueOf node def handleValueOf(ctx,variables, namespaces, valueOfElement) expected = valueOfElement.text got = XPath.match( ctx, valueOfElement.attributes["select"], namespaces, variables )[0] assert_true( (got.nil? && expected.nil?) || !got.nil? ) case got.class when Element assert_equal( got.class, Element ) when Attribute, Text, Comment, TrueClass, FalseClass assert_equal( expected, got.to_s ) when Instruction assert_equal( expected, got.content ) when Fixnum assert_equal( exected.to_f, got ) when String # normalize values for comparison got = "" if got == nil or got == "" expected = "" if expected == nil or expected == "" assert_equal( expected, got ) else assert_fail( "Wassup?" ) end end # processes a tests/document/context/test node ( where @exception is false or doesn't exist ) def handleNominalTest(ctx, variables, namespaces, testElement) expected = testElement.attributes["count"] got = XPath.match( ctx, testElement.attributes["select"], namespaces, variables ) # might be a test with no count attribute, but nested valueOf elements assert( expected == got.size.to_s ) if !expected.nil? XPath.each( testElement, "valueOf") { |e| handleValueOf(got, variables, namespaces, e) } end # processes a tests/document/context/test node ( where @exception is true ) def handleExceptionalTest(ctx, variables, namespaces, testElement) assert_raise( Exception ) { XPath.match( ctx, testElement.attributes["select"], namespaces, variables ) } end # processes a tests/document node def handleDocument(docElement) puts "- Processing document: #{docElement.attributes['url']}" testFile = File.new( docElement.attributes["url"] ) testDoc = Document.new testFile XPath.each( docElement, "context") { |e| handleContext(testDoc, e) } end # processes a variable definition in a namespace like <test var:foo="bar"> def handleVariable( ctx, variables, attrib ) puts "--- Found attribute: #{attrib.name}" variables[attrib.name] = attrib.value end # processes a namespace definition like <test xmlns:foo="fiz:bang:bam"> def handleNamespace( ctx, prefix, namespaces ) puts "--- Found namespace: #{prefix}" namespaces[prefix] = ctx.namespaces[prefix] end end end
{ "content_hash": "9766fb76a1c8212e4511560dce23bd85", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 146, "avg_line_length": 39.10852713178294, "alnum_prop": 0.6442021803766105, "repo_name": "rokn/Count_Words_2015", "id": "aa9e2998abdc25aec0c3b131ec776289a0c4559f", "size": "5076", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "fetched_code/ruby/test_jaxen.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "61802" }, { "name": "Ruby", "bytes": "18888605" } ], "symlink_target": "" }
export default (nodelist, callback) => { let i = -1 const l = nodelist.length while (++i < l) callback({ el: nodelist.item(i), index: i }) }
{ "content_hash": "f00efec60cb40a8acd7caaec9fe753be", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 52, "avg_line_length": 21, "alnum_prop": 0.5357142857142857, "repo_name": "mikehwagz/jennifer-heintz", "id": "48ff650ac8663d7bc0cfa5df3bf274da4ae855a3", "size": "168", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "assets/js/utils/dom/each.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "168" }, { "name": "CSS", "bytes": "26875" }, { "name": "HTML", "bytes": "280775" }, { "name": "JavaScript", "bytes": "1449353" } ], "symlink_target": "" }
#ifndef FREERDP_SERVER_WIN_WASAPI_H #define FREERDP_SERVER_WIN_WASAPI_H #include <freerdp/server/rdpsnd.h> #include "wf_interface.h" int wf_rdpsnd_set_latest_peer(wfPeerContext* peer); int wf_wasapi_activate(RdpsndServerContext* context); int wf_wasapi_get_device_string(LPWSTR pattern, LPWSTR * deviceStr); DWORD WINAPI wf_rdpsnd_wasapi_thread(LPVOID lpParam); #endif /* FREERDP_SERVER_WIN_WASAPI_H */
{ "content_hash": "443430a420be76d9e1ccf451ec4a18cc", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 68, "avg_line_length": 27.266666666666666, "alnum_prop": 0.7726161369193154, "repo_name": "ilammy/FreeRDP", "id": "303b4f9b22b1568ac48b3f590b710e4a533f228b", "size": "409", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "server/Windows/wf_wasapi.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "11829910" }, { "name": "C#", "bytes": "9809" }, { "name": "C++", "bytes": "170799" }, { "name": "CMake", "bytes": "721831" }, { "name": "CSS", "bytes": "5696" }, { "name": "HTML", "bytes": "99139" }, { "name": "Java", "bytes": "419607" }, { "name": "Makefile", "bytes": "1585" }, { "name": "Objective-C", "bytes": "1132746" }, { "name": "Perl", "bytes": "8044" }, { "name": "Python", "bytes": "1430" }, { "name": "Roff", "bytes": "3708" }, { "name": "Shell", "bytes": "26343" } ], "symlink_target": "" }
import * as ma from 'azure-pipelines-task-lib/mock-answer'; import * as tmrm from 'azure-pipelines-task-lib/mock-run'; import path = require('path'); let taskPath = path.join(__dirname, '..', 'gradletask.js'); let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath); tr.setInput('wrapperScript', 'gradlew'); tr.setInput('cwd', '/home/repo/src'); tr.setInput('options', ''); tr.setInput('tasks', 'build'); tr.setInput('javaHomeSelection', 'JDKVersion'); tr.setInput('jdkVersion', 'default'); tr.setInput('testResultsFiles', '**/build/test-results/TEST-*.xml'); tr.setInput('publishJUnitResults', 'garbage'); // provide answers for task mock let a: ma.TaskLibAnswers = <ma.TaskLibAnswers>{ 'checkPath': { 'gradlew': true, 'gradlew.bat': true, '/home/repo/src': true }, 'exec': { 'gradlew build': { 'code': 0, 'stdout': 'Sample gradle output' }, 'gradlew.bat build': { 'code': 0, 'stdout': 'Sample gradle output' } } }; tr.setAnswers(a); tr.run();
{ "content_hash": "ed5f0811a77eaf5be2ad555536e58cc2", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 68, "avg_line_length": 28.36842105263158, "alnum_prop": 0.6094619666048238, "repo_name": "Microsoft/vsts-tasks", "id": "62443f3bf7cdeb4af92958fec67aff8b60d52da1", "size": "1078", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Tasks/GradleV3/Tests/L0GarbagePublishJUnitResults.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1636" }, { "name": "CSS", "bytes": "3780" }, { "name": "HTML", "bytes": "47002" }, { "name": "Java", "bytes": "1575" }, { "name": "JavaScript", "bytes": "118206" }, { "name": "PowerShell", "bytes": "1940315" }, { "name": "SQLPL", "bytes": "7822" }, { "name": "Shell", "bytes": "29352" }, { "name": "TypeScript", "bytes": "5363305" } ], "symlink_target": "" }
import React, {ChangeEvent, FC, useEffect, useRef} from "react" import ReactMarkdown from 'react-markdown' type EntityProps = { name: string, value: string, label: string, isEditMode: boolean, onChangeFunc: (event: ChangeEvent<HTMLTextAreaElement>) => void, } const EditableEntryV2: FC<EntityProps> = (props) => { const {isEditMode, onChangeFunc, name, label, value} = props; const ref = useRef<HTMLTextAreaElement>(null); const padding = 10; useEffect(() => { if (null !== ref.current) { ref.current.style.height = '1px'; let scrollHeight = ref.current.scrollHeight; ref.current.style.height = `${scrollHeight - padding * 2}px`; } }, [value, isEditMode] ) return <div className='quest-prop'> <label className='prop-title' htmlFor={name}>{label}</label> <div className='prop-content'> {isEditMode ? <textarea disabled={!isEditMode} ref={ref} id={name} name={name} onChange={onChangeFunc} value={value} style={{padding: padding}} /> : <ReactMarkdown>{value}</ReactMarkdown>} </div> </div> } export default EditableEntryV2;
{ "content_hash": "e78b6eaad75bfb702dbbe9333009db05", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 77, "avg_line_length": 30.02173913043478, "alnum_prop": 0.5372918175235337, "repo_name": "serzhshakur/quest-application-reactjs", "id": "750ccc421a28675a7e7a5993b30c671e526f72eb", "size": "1381", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/admin_components/EditableEntryV2.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13361" }, { "name": "HTML", "bytes": "252" }, { "name": "JavaScript", "bytes": "37789" }, { "name": "TypeScript", "bytes": "40129" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive.gcs; import com.facebook.presto.hive.DynamicConfigurationProvider; import com.google.cloud.hadoop.gcsio.GoogleCloudStorageFileSystem; import org.apache.hadoop.conf.Configuration; import java.net.URI; import static com.facebook.presto.hive.HdfsEnvironment.HdfsContext; import static com.facebook.presto.hive.gcs.GcsAccessTokenProvider.GCS_ACCESS_TOKEN_CONF; public class GcsConfigurationProvider implements DynamicConfigurationProvider { private static final String GCS_OAUTH_KEY = "hive.gcs.oauth"; @Override public void updateConfiguration(Configuration configuration, HdfsContext context, URI uri) { if (!uri.getScheme().equals(GoogleCloudStorageFileSystem.SCHEME)) { return; } String accessToken = context.getIdentity().getExtraCredentials().get(GCS_OAUTH_KEY); if (accessToken != null) { configuration.set(GCS_ACCESS_TOKEN_CONF, accessToken); } } }
{ "content_hash": "f0614167686e65dea109768619365074", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 94, "avg_line_length": 36.80952380952381, "alnum_prop": 0.7419146183699871, "repo_name": "ptkool/presto", "id": "1468dd4df6e7ffda4dec0b3b8480c83aa456413e", "size": "1546", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "presto-hive/src/main/java/com/facebook/presto/hive/gcs/GcsConfigurationProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "28777" }, { "name": "CSS", "bytes": "13127" }, { "name": "HTML", "bytes": "28660" }, { "name": "Java", "bytes": "37430827" }, { "name": "JavaScript", "bytes": "216033" }, { "name": "Makefile", "bytes": "6830" }, { "name": "PLSQL", "bytes": "2797" }, { "name": "Python", "bytes": "8714" }, { "name": "SQLPL", "bytes": "926" }, { "name": "Shell", "bytes": "29909" }, { "name": "TSQL", "bytes": "161695" }, { "name": "Thrift", "bytes": "12631" } ], "symlink_target": "" }
 /* * * * * * A simple JSON Parser / builder * ------------------------------ * * It mainly has been written as a simple JSON parser. It can build a JSON string * from the node-tree, or generate a node tree from any valid JSON string. * * If you want to use compression when saving to file / stream / B64 you have to include * SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and * define "USE_SharpZipLib" at the top of the file * * Written by Bunny83 * 2012-06-09 * * Modified by oPless, 2014-09-21 to round-trip properly * * Features / attributes: * - provides strongly typed node classes and lists / dictionaries * - provides easy access to class members / array items / data values * - the parser ignores data types. Each value is a string. * - only double quotes (") are used for quoting strings. * - values and names are not restricted to quoted strings. They simply add up and are trimmed. * - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData) * - provides "casting" properties to easily convert to / from those types: * int / float / double / bool * - provides a common interface for each node so no explicit casting is required. * - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined * * * 2012-12-17 Update: * - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree * Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator * The class determines the required type by it's further use, creates the type and removes itself. * - Added binary serialization / deserialization. * - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) * The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top * - The serializer uses different types when it comes to store the values. Since my data values * are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string. * It's not the most efficient way but for a moderate amount of data it should work on all platforms. * * * * * */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace VRGIN.Helpers { public enum JSONBinaryTag { Array = 1, Class = 2, Value = 3, IntValue = 4, DoubleValue = 5, BoolValue = 6, FloatValue = 7, } public abstract class JSONNode { #region common interface public virtual void Add(string aKey, JSONNode aItem) { } public virtual JSONNode this[int aIndex] { get { return null; } set { } } public virtual JSONNode this[string aKey] { get { return null; } set { } } public virtual string Value { get { return ""; } set { } } public virtual int Count { get { return 0; } } public virtual void Add(JSONNode aItem) { Add("", aItem); } public virtual JSONNode Remove(string aKey) { return null; } public virtual JSONNode Remove(int aIndex) { return null; } public virtual JSONNode Remove(JSONNode aNode) { return aNode; } public virtual IEnumerable<JSONNode> Children { get { yield break; } } public IEnumerable<JSONNode> DeepChildren { get { foreach (var C in Children) foreach (var D in C.DeepChildren) yield return D; } } public override string ToString() { return "JSONNode"; } public virtual string ToString(string aPrefix) { return "JSONNode"; } public abstract string ToJSON(int prefix); #endregion common interface #region typecasting properties public virtual JSONBinaryTag Tag { get; set; } public virtual int AsInt { get { int v = 0; if (int.TryParse(Value, out v)) return v; return 0; } set { Value = value.ToString(); Tag = JSONBinaryTag.IntValue; } } public virtual float AsFloat { get { float v = 0.0f; if (float.TryParse(Value, out v)) return v; return 0.0f; } set { Value = value.ToString(); Tag = JSONBinaryTag.FloatValue; } } public virtual double AsDouble { get { double v = 0.0; if (double.TryParse(Value, out v)) return v; return 0.0; } set { Value = value.ToString(); Tag = JSONBinaryTag.DoubleValue; } } public virtual bool AsBool { get { bool v = false; if (bool.TryParse(Value, out v)) return v; return !string.IsNullOrEmpty(Value); } set { Value = (value) ? "true" : "false"; Tag = JSONBinaryTag.BoolValue; } } public virtual JSONArray AsArray { get { return this as JSONArray; } } public virtual JSONClass AsObject { get { return this as JSONClass; } } #endregion typecasting properties #region operators public static implicit operator JSONNode(string s) { return new JSONData(s); } public static implicit operator string(JSONNode d) { return (d == null) ? null : d.Value; } public static bool operator ==(JSONNode a, object b) { if (b == null && a is JSONLazyCreator) return true; return System.Object.ReferenceEquals(a, b); } public static bool operator !=(JSONNode a, object b) { return !(a == b); } public override bool Equals(object obj) { return System.Object.ReferenceEquals(this, obj); } public override int GetHashCode() { return base.GetHashCode(); } #endregion operators internal static string Escape(string aText) { string result = ""; foreach (char c in aText) { switch (c) { case '\\': result += "\\\\"; break; case '\"': result += "\\\""; break; case '\n': result += "\\n"; break; case '\r': result += "\\r"; break; case '\t': result += "\\t"; break; case '\b': result += "\\b"; break; case '\f': result += "\\f"; break; default: result += c; break; } } return result; } static JSONData Numberize(string token) { bool flag = false; int integer = 0; double real = 0; if (int.TryParse(token, out integer)) { return new JSONData(integer); } if (double.TryParse(token, out real)) { return new JSONData(real); } if (bool.TryParse(token, out flag)) { return new JSONData(flag); } throw new NotImplementedException(token); } static void AddElement(JSONNode ctx, string token, string tokenName, bool tokenIsString) { if (tokenIsString) { if (ctx is JSONArray) ctx.Add(token); else ctx.Add(tokenName, token); // assume dictionary/object } else { JSONData number = Numberize(token); if (ctx is JSONArray) ctx.Add(number); else ctx.Add(tokenName, number); } } public static JSONNode Parse(string aJSON) { Stack<JSONNode> stack = new Stack<JSONNode>(); JSONNode ctx = null; int i = 0; string Token = ""; string TokenName = ""; bool QuoteMode = false; bool TokenIsString = false; while (i < aJSON.Length) { switch (aJSON[i]) { case '{': if (QuoteMode) { Token += aJSON[i]; break; } stack.Push(new JSONClass()); if (ctx != null) { TokenName = TokenName.Trim(); if (ctx is JSONArray) ctx.Add(stack.Peek()); else if (TokenName != "") ctx.Add(TokenName, stack.Peek()); } TokenName = ""; Token = ""; ctx = stack.Peek(); break; case '[': if (QuoteMode) { Token += aJSON[i]; break; } stack.Push(new JSONArray()); if (ctx != null) { TokenName = TokenName.Trim(); if (ctx is JSONArray) ctx.Add(stack.Peek()); else if (TokenName != "") ctx.Add(TokenName, stack.Peek()); } TokenName = ""; Token = ""; ctx = stack.Peek(); break; case '}': case ']': if (QuoteMode) { Token += aJSON[i]; break; } if (stack.Count == 0) throw new Exception("JSON Parse: Too many closing brackets"); stack.Pop(); if (Token != "") { TokenName = TokenName.Trim(); /* if (ctx is JSONArray) ctx.Add (Token); else if (TokenName != "") ctx.Add (TokenName, Token); */ AddElement(ctx, Token, TokenName, TokenIsString); TokenIsString = false; } TokenName = ""; Token = ""; if (stack.Count > 0) ctx = stack.Peek(); break; case ':': if (QuoteMode) { Token += aJSON[i]; break; } TokenName = Token; Token = ""; TokenIsString = false; break; case '"': QuoteMode ^= true; TokenIsString = QuoteMode == true ? true : TokenIsString; break; case ',': if (QuoteMode) { Token += aJSON[i]; break; } if (Token != "") { /* if (ctx is JSONArray) { ctx.Add (Token); } else if (TokenName != "") { ctx.Add (TokenName, Token); } */ AddElement(ctx, Token, TokenName, TokenIsString); TokenIsString = false; } TokenName = ""; Token = ""; TokenIsString = false; break; case '\r': case '\n': break; case ' ': case '\t': if (QuoteMode) Token += aJSON[i]; break; case '\\': ++i; if (QuoteMode) { char C = aJSON[i]; switch (C) { case 't': Token += '\t'; break; case 'r': Token += '\r'; break; case 'n': Token += '\n'; break; case 'b': Token += '\b'; break; case 'f': Token += '\f'; break; case 'u': { string s = aJSON.Substring(i + 1, 4); Token += (char)int.Parse( s, System.Globalization.NumberStyles.AllowHexSpecifier); i += 4; break; } default: Token += C; break; } } break; default: Token += aJSON[i]; break; } ++i; } if (QuoteMode) { throw new Exception("JSON Parse: Quotation marks seems to be messed up."); } return ctx; } public virtual void Serialize(System.IO.BinaryWriter aWriter) { } public void SaveToStream(System.IO.Stream aData) { var W = new System.IO.BinaryWriter(aData); Serialize(W); } #if USE_SharpZipLib public void SaveToCompressedStream(System.IO.Stream aData) { using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData)) { gzipOut.IsStreamOwner = false; SaveToStream(gzipOut); gzipOut.Close(); } } public void SaveToCompressedFile(string aFileName) { #if USE_FileIO System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName); using(var F = System.IO.File.OpenWrite(aFileName)) { SaveToCompressedStream(F); } #else throw new Exception("Can't use File IO stuff in webplayer"); #endif } public string SaveToCompressedBase64() { using (var stream = new System.IO.MemoryStream()) { SaveToCompressedStream(stream); stream.Position = 0; return System.Convert.ToBase64String(stream.ToArray()); } } #else public void SaveToCompressedStream(System.IO.Stream aData) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } public void SaveToCompressedFile(string aFileName) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } public string SaveToCompressedBase64() { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } #endif public void SaveToFile(string aFileName) { #if USE_FileIO System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName); using (var F = System.IO.File.OpenWrite(aFileName)) { SaveToStream(F); } #else throw new Exception ("Can't use File IO stuff in webplayer"); #endif } public string SaveToBase64() { using (var stream = new System.IO.MemoryStream()) { SaveToStream(stream); stream.Position = 0; return System.Convert.ToBase64String(stream.ToArray()); } } public static JSONNode Deserialize(System.IO.BinaryReader aReader) { JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte(); switch (type) { case JSONBinaryTag.Array: { int count = aReader.ReadInt32(); JSONArray tmp = new JSONArray(); for (int i = 0; i < count; i++) tmp.Add(Deserialize(aReader)); return tmp; } case JSONBinaryTag.Class: { int count = aReader.ReadInt32(); JSONClass tmp = new JSONClass(); for (int i = 0; i < count; i++) { string key = aReader.ReadString(); var val = Deserialize(aReader); tmp.Add(key, val); } return tmp; } case JSONBinaryTag.Value: { return new JSONData(aReader.ReadString()); } case JSONBinaryTag.IntValue: { return new JSONData(aReader.ReadInt32()); } case JSONBinaryTag.DoubleValue: { return new JSONData(aReader.ReadDouble()); } case JSONBinaryTag.BoolValue: { return new JSONData(aReader.ReadBoolean()); } case JSONBinaryTag.FloatValue: { return new JSONData(aReader.ReadSingle()); } default: { throw new Exception("Error deserializing JSON. Unknown tag: " + type); } } } #if USE_SharpZipLib public static JSONNode LoadFromCompressedStream(System.IO.Stream aData) { var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData); return LoadFromStream(zin); } public static JSONNode LoadFromCompressedFile(string aFileName) { #if USE_FileIO using(var F = System.IO.File.OpenRead(aFileName)) { return LoadFromCompressedStream(F); } #else throw new Exception("Can't use File IO stuff in webplayer"); #endif } public static JSONNode LoadFromCompressedBase64(string aBase64) { var tmp = System.Convert.FromBase64String(aBase64); var stream = new System.IO.MemoryStream(tmp); stream.Position = 0; return LoadFromCompressedStream(stream); } #else public static JSONNode LoadFromCompressedFile(string aFileName) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } public static JSONNode LoadFromCompressedStream(System.IO.Stream aData) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } public static JSONNode LoadFromCompressedBase64(string aBase64) { throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON"); } #endif public static JSONNode LoadFromStream(System.IO.Stream aData) { using (var R = new System.IO.BinaryReader(aData)) { return Deserialize(R); } } public static JSONNode LoadFromFile(string aFileName) { #if USE_FileIO using (var F = System.IO.File.OpenRead(aFileName)) { return LoadFromStream(F); } #else throw new Exception ("Can't use File IO stuff in webplayer"); #endif } public static JSONNode LoadFromBase64(string aBase64) { var tmp = System.Convert.FromBase64String(aBase64); var stream = new System.IO.MemoryStream(tmp); stream.Position = 0; return LoadFromStream(stream); } } // End of JSONNode public class JSONArray : JSONNode, IEnumerable { private List<JSONNode> m_List = new List<JSONNode>(); public override JSONNode this[int aIndex] { get { if (aIndex < 0 || aIndex >= m_List.Count) return new JSONLazyCreator(this); return m_List[aIndex]; } set { if (aIndex < 0 || aIndex >= m_List.Count) m_List.Add(value); else m_List[aIndex] = value; } } public override JSONNode this[string aKey] { get { return new JSONLazyCreator(this); } set { m_List.Add(value); } } public override int Count { get { return m_List.Count; } } public override void Add(string aKey, JSONNode aItem) { m_List.Add(aItem); } public override JSONNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_List.Count) return null; JSONNode tmp = m_List[aIndex]; m_List.RemoveAt(aIndex); return tmp; } public override JSONNode Remove(JSONNode aNode) { m_List.Remove(aNode); return aNode; } public override IEnumerable<JSONNode> Children { get { foreach (JSONNode N in m_List) yield return N; } } public IEnumerator GetEnumerator() { foreach (JSONNode N in m_List) yield return N; } public override string ToString() { string result = "[ "; foreach (JSONNode N in m_List) { if (result.Length > 2) result += ", "; result += N.ToString(); } result += " ]"; return result; } public override string ToString(string aPrefix) { string result = "[ "; foreach (JSONNode N in m_List) { if (result.Length > 3) result += ", "; result += "\n" + aPrefix + " "; result += N.ToString(aPrefix + " "); } result += "\n" + aPrefix + "]"; return result; } public override string ToJSON(int prefix) { string s = new string(' ', (prefix + 1) * 2); string ret = "[ "; foreach (JSONNode n in m_List) { if (ret.Length > 3) ret += ", "; ret += "\n" + s; ret += n.ToJSON(prefix + 1); } ret += "\n" + s + "]"; return ret; } public override void Serialize(System.IO.BinaryWriter aWriter) { aWriter.Write((byte)JSONBinaryTag.Array); aWriter.Write(m_List.Count); for (int i = 0; i < m_List.Count; i++) { m_List[i].Serialize(aWriter); } } } // End of JSONArray public class JSONClass : JSONNode, IEnumerable { private Dictionary<string, JSONNode> m_Dict = new Dictionary<string, JSONNode>(); public override JSONNode this[string aKey] { get { if (m_Dict.ContainsKey(aKey)) return m_Dict[aKey]; else return new JSONLazyCreator(this, aKey); } set { if (m_Dict.ContainsKey(aKey)) m_Dict[aKey] = value; else m_Dict.Add(aKey, value); } } public override JSONNode this[int aIndex] { get { if (aIndex < 0 || aIndex >= m_Dict.Count) return null; return m_Dict.ElementAt(aIndex).Value; } set { if (aIndex < 0 || aIndex >= m_Dict.Count) return; string key = m_Dict.ElementAt(aIndex).Key; m_Dict[key] = value; } } public override int Count { get { return m_Dict.Count; } } public override void Add(string aKey, JSONNode aItem) { if (!string.IsNullOrEmpty(aKey)) { if (m_Dict.ContainsKey(aKey)) m_Dict[aKey] = aItem; else m_Dict.Add(aKey, aItem); } else m_Dict.Add(Guid.NewGuid().ToString(), aItem); } public override JSONNode Remove(string aKey) { if (!m_Dict.ContainsKey(aKey)) return null; JSONNode tmp = m_Dict[aKey]; m_Dict.Remove(aKey); return tmp; } public override JSONNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_Dict.Count) return null; var item = m_Dict.ElementAt(aIndex); m_Dict.Remove(item.Key); return item.Value; } public override JSONNode Remove(JSONNode aNode) { try { var item = m_Dict.Where(k => k.Value == aNode).First(); m_Dict.Remove(item.Key); return aNode; } catch { return null; } } public override IEnumerable<JSONNode> Children { get { foreach (KeyValuePair<string, JSONNode> N in m_Dict) yield return N.Value; } } public IEnumerator GetEnumerator() { foreach (KeyValuePair<string, JSONNode> N in m_Dict) yield return N; } public override string ToString() { string result = "{"; foreach (KeyValuePair<string, JSONNode> N in m_Dict) { if (result.Length > 2) result += ", "; result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString(); } result += "}"; return result; } public override string ToString(string aPrefix) { string result = "{ "; foreach (KeyValuePair<string, JSONNode> N in m_Dict) { if (result.Length > 3) result += ", "; result += "\n" + aPrefix + " "; result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix + " "); } result += "\n" + aPrefix + "}"; return result; } public override string ToJSON(int prefix) { string s = new string(' ', (prefix + 1) * 2); string ret = "{ "; foreach (KeyValuePair<string, JSONNode> n in m_Dict) { if (ret.Length > 3) ret += ", "; ret += "\n" + s; ret += string.Format("\"{0}\": {1}", n.Key, n.Value.ToJSON(prefix + 1)); } ret += "\n" + s + "}"; return ret; } public override void Serialize(System.IO.BinaryWriter aWriter) { aWriter.Write((byte)JSONBinaryTag.Class); aWriter.Write(m_Dict.Count); foreach (string K in m_Dict.Keys) { aWriter.Write(K); m_Dict[K].Serialize(aWriter); } } } // End of JSONClass public class JSONData : JSONNode { private string m_Data; public override string Value { get { return m_Data; } set { m_Data = value; Tag = JSONBinaryTag.Value; } } public JSONData(string aData) { m_Data = aData; Tag = JSONBinaryTag.Value; } public JSONData(float aData) { AsFloat = aData; } public JSONData(double aData) { AsDouble = aData; } public JSONData(bool aData) { AsBool = aData; } public JSONData(int aData) { AsInt = aData; } public override string ToString() { return "\"" + Escape(m_Data) + "\""; } public override string ToString(string aPrefix) { return "\"" + Escape(m_Data) + "\""; } public override string ToJSON(int prefix) { switch (Tag) { case JSONBinaryTag.DoubleValue: case JSONBinaryTag.FloatValue: case JSONBinaryTag.IntValue: return m_Data; case JSONBinaryTag.Value: return string.Format("\"{0}\"", Escape(m_Data)); default: throw new NotSupportedException("This shouldn't be here: " + Tag.ToString()); } } public override void Serialize(System.IO.BinaryWriter aWriter) { var tmp = new JSONData(""); tmp.AsInt = AsInt; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.IntValue); aWriter.Write(AsInt); return; } tmp.AsFloat = AsFloat; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.FloatValue); aWriter.Write(AsFloat); return; } tmp.AsDouble = AsDouble; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.DoubleValue); aWriter.Write(AsDouble); return; } tmp.AsBool = AsBool; if (tmp.m_Data == this.m_Data) { aWriter.Write((byte)JSONBinaryTag.BoolValue); aWriter.Write(AsBool); return; } aWriter.Write((byte)JSONBinaryTag.Value); aWriter.Write(m_Data); } } // End of JSONData internal class JSONLazyCreator : JSONNode { private JSONNode m_Node = null; private string m_Key = null; public JSONLazyCreator(JSONNode aNode) { m_Node = aNode; m_Key = null; } public JSONLazyCreator(JSONNode aNode, string aKey) { m_Node = aNode; m_Key = aKey; } private void Set(JSONNode aVal) { if (m_Key == null) { m_Node.Add(aVal); } else { m_Node.Add(m_Key, aVal); } m_Node = null; // Be GC friendly. } public override JSONNode this[int aIndex] { get { return new JSONLazyCreator(this); } set { var tmp = new JSONArray(); tmp.Add(value); Set(tmp); } } public override JSONNode this[string aKey] { get { return new JSONLazyCreator(this, aKey); } set { var tmp = new JSONClass(); tmp.Add(aKey, value); Set(tmp); } } public override void Add(JSONNode aItem) { var tmp = new JSONArray(); tmp.Add(aItem); Set(tmp); } public override void Add(string aKey, JSONNode aItem) { var tmp = new JSONClass(); tmp.Add(aKey, aItem); Set(tmp); } public static bool operator ==(JSONLazyCreator a, object b) { if (b == null) return true; return System.Object.ReferenceEquals(a, b); } public static bool operator !=(JSONLazyCreator a, object b) { return !(a == b); } public override bool Equals(object obj) { if (obj == null) return true; return System.Object.ReferenceEquals(this, obj); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return ""; } public override string ToString(string aPrefix) { return ""; } public override string ToJSON(int prefix) { return ""; } public override int AsInt { get { JSONData tmp = new JSONData(0); Set(tmp); return 0; } set { JSONData tmp = new JSONData(value); Set(tmp); } } public override float AsFloat { get { JSONData tmp = new JSONData(0.0f); Set(tmp); return 0.0f; } set { JSONData tmp = new JSONData(value); Set(tmp); } } public override double AsDouble { get { JSONData tmp = new JSONData(0.0); Set(tmp); return 0.0; } set { JSONData tmp = new JSONData(value); Set(tmp); } } public override bool AsBool { get { JSONData tmp = new JSONData(false); Set(tmp); return false; } set { JSONData tmp = new JSONData(value); Set(tmp); } } public override JSONArray AsArray { get { JSONArray tmp = new JSONArray(); Set(tmp); return tmp; } } public override JSONClass AsObject { get { JSONClass tmp = new JSONClass(); Set(tmp); return tmp; } } } // End of JSONLazyCreator public static class JSON { public static JSONNode Parse(string aJSON) { return JSONNode.Parse(aJSON); } } }
{ "content_hash": "4470cd7d849b804e0c6ef862f815a04a", "timestamp": "", "source": "github", "line_count": 1317, "max_line_length": 150, "avg_line_length": 28.63401670463174, "alnum_prop": 0.4261090928376336, "repo_name": "akoaybobo/PlayHomeTrialVR", "id": "12541c2ae9e9cba00d9c1764930c0737a73a9a62", "size": "37713", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "VRGIN/VRGIN/Helpers/SimpleJSON.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1389167" }, { "name": "ShaderLab", "bytes": "11562" } ], "symlink_target": "" }
var db = require('../lib/jsonfs.js'); db.connect('db', ['articles']); var article = { title : 'jsonfs works', published : 'today', rating : '5 stars' } var savedArticle = db.articles.save(article); var query = { title : 'jsonfs works' }; var dataToBeUpdate = { title : 'jsonfs works again!', }; var options = { multi: false, upsert: false }; var updated = db.articles.update(query, dataToBeUpdate, options); console.log(updated); // { updated: 1, inserted: 0 } // run : node update.js
{ "content_hash": "81b8d0a015874b5cbf7a8192c574d257", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 65, "avg_line_length": 18.814814814814813, "alnum_prop": 0.6377952755905512, "repo_name": "mcmartins/jsonfs", "id": "e43ec5c18ee8f4e8d2c0e3dc93b6a5c63d358b8a", "size": "508", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "demos/update.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "26467" } ], "symlink_target": "" }
/* * AbstractDescribableScriptPlugin.java * * User: Greg Schueler <a href="mailto:[email protected]">[email protected]</a> * Created: 8/10/11 2:55 PM * */ package com.dtolabs.rundeck.core.plugins; import com.dtolabs.rundeck.core.common.Framework; import com.dtolabs.rundeck.core.common.INodeEntry; import com.dtolabs.rundeck.core.data.DataContext; import com.dtolabs.rundeck.core.dispatcher.DataContextUtils; import com.dtolabs.rundeck.core.execution.ExecutionContext; import com.dtolabs.rundeck.core.plugins.configuration.*; import com.dtolabs.rundeck.core.storage.ResourceMeta; import com.dtolabs.rundeck.core.storage.StorageTree; import com.dtolabs.rundeck.plugins.util.DescriptionBuilder; import com.dtolabs.rundeck.plugins.util.PropertyBuilder; import org.rundeck.storage.api.PathUtil; import org.rundeck.storage.api.Resource; import org.rundeck.storage.api.StorageException; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.*; /** * AbstractDescribableScriptPlugin is a base ScriptPlugin provider implementation that can be used to provide a * describable interface for a script plugin. The description provided by the base implementation is configured by the * {@link ScriptPluginProvider}'s metadata: * <pre> * title = Title of the Plugin * description = Description of the plugin * </pre> * <pre> * config.X.PROPERTY_TYPE = Type name of the property, from {@link com.dtolabs.rundeck.core.plugins.configuration.Property.Type} * config.X.name = Name of the property (key string) * config.X.title = Title of the property * config.X.description = description of the property * config.X.required = true/false, if the property is required. * config.X.default = default string of the property * config.X.values = comma-separated values list for Select or FreeSelect properties * config.X.scope = scope of the property, from {@link PropertyScope} * </pre> * * @author Greg Schueler <a href="mailto:[email protected]">[email protected]</a> */ public abstract class AbstractDescribableScriptPlugin implements Describable { public static final String TITLE_PROP = "title"; public static final String DESCRIPTION_PROP = "description"; public static final String CONFIG_PROP_PREFIX = "config"; public static final String CONFIG_TITLE = "title"; public static final String CONFIG_DESCRIPTION = "description"; public static final String CONFIG_NAME = "name"; public static final String CONFIG_TYPE = "type"; public static final String CONFIG_REQUIRED = "required"; public static final String CONFIG_DEFAULT = "default"; public static final String CONFIG_VALUES = "values"; public static final String CONFIG_LABELS = "labels"; public static final String CONFIG_SCOPE = "scope"; public static final String CONFIG_RENDERING_OPTIONS = "renderingOptions"; public static final String SETTING_MERGE_ENVIRONMENT = "mergeEnvironment"; private final ScriptPluginProvider provider; private final Framework framework; Description description; public AbstractDescribableScriptPlugin(final ScriptPluginProvider provider, final Framework framework) { this.provider = provider; this.framework = framework; } /** * @return data with exported plugin details */ public Map<String,String> createPluginData() { final Map<String,String> pluginDataContext = new HashMap<String, String>(); pluginDataContext.put("file", provider.getArchiveFile().getAbsolutePath()); pluginDataContext.put("scriptfile", provider.getScriptFile().getAbsolutePath()); pluginDataContext.put("base", provider.getContentsBasedir().getAbsolutePath()); return pluginDataContext; } /** * Return true if the "mergeEnvironment" is true for the plugin * @return */ boolean isMergeEnvVars(){ return metaBooleanProp(SETTING_MERGE_ENVIRONMENT, provider.getDefaultMergeEnvVars()); } private boolean metaBooleanProp(final String prop, boolean defVal) { Object o = provider.getMetadata().get(prop); if (o == null) { return defVal; } if (o == Boolean.TRUE) { return true; } return "true".equals(o); } static private void createProperties( final ScriptPluginProvider provider, final boolean useConventionalPropertiesMapping, final DescriptionBuilder dbuilder) throws ConfigurationException { final Map<String, Object> metadata = provider.getMetadata(); final Object config = metadata.get("config"); if (config instanceof List) { final List configs = (List) config; for (final Object citem : configs) { if (citem instanceof Map) { final PropertyBuilder pbuild = PropertyBuilder.builder(); final Map<String, Object> itemmeta = (Map<String, Object>) citem; final String typestr = metaStringProp(itemmeta, CONFIG_TYPE); try { pbuild.type(Property.Type.valueOf(typestr)); } catch (IllegalArgumentException e) { throw new ConfigurationException("Invalid property type: " + typestr); } String propName = metaStringProp(itemmeta, CONFIG_NAME); pbuild .name(propName) .title(metaStringProp(itemmeta, CONFIG_TITLE)) .description(metaStringProp(itemmeta, CONFIG_DESCRIPTION)); final Object reqValue = itemmeta.get(CONFIG_REQUIRED); final boolean required; if (reqValue instanceof Boolean) { required = (Boolean) reqValue; } else { required = reqValue instanceof String && Boolean.parseBoolean((String) reqValue); } pbuild.required(required); final Object defObj = itemmeta.get(CONFIG_DEFAULT); pbuild.defaultValue(null != defObj ? defObj.toString() : null); final List<String> valueList; final String valuesstr = metaStringProp(itemmeta, CONFIG_VALUES); if (null != valuesstr) { final String[] split = null != valuesstr ? valuesstr.split(",") : null; valueList = Arrays.asList(split); } else { Object vlist = itemmeta.get(CONFIG_VALUES); if (vlist instanceof List) { valueList = (List<String>) vlist; } else { valueList = null; } } final List<String> values; if (null != valueList) { final ArrayList<String> valuesA = new ArrayList<String>(); for (final String s : valueList) { valuesA.add(s.trim()); } values = valuesA; } else { values = null; } pbuild.values(values); Object labelmap = itemmeta.get(CONFIG_LABELS); if(labelmap instanceof Map){ pbuild.labels((Map) labelmap); } final String scopeString = metaStringProp(itemmeta, CONFIG_SCOPE); if(null!=scopeString) { try { pbuild.scope(PropertyScope.valueOf(scopeString.trim())); } catch (IllegalArgumentException e) { throw new ConfigurationException("Invalid property scope: " + scopeString); } } if(useConventionalPropertiesMapping) { final String projectPropertyPrefix = PropertyResolverFactory.projectPropertyPrefix ( PropertyResolverFactory .pluginPropertyPrefix( provider.getService(), provider.getName() ) ) ; dbuilder.mapping(propName, projectPropertyPrefix + propName); final String frameworkPropertyPrefix = PropertyResolverFactory.frameworkPropertyPrefix ( PropertyResolverFactory .pluginPropertyPrefix( provider.getService(), provider.getName() ) ); dbuilder.frameworkMapping(propName, frameworkPropertyPrefix + propName); } //rendering options final Object renderingOpts = itemmeta.get(CONFIG_RENDERING_OPTIONS); if(null != renderingOpts && renderingOpts instanceof Map){ Map<String,Object> renderingOptsMap=(Map<String,Object>) renderingOpts; pbuild.renderingOptions(renderingOptsMap); } try { dbuilder.property(pbuild.build()); } catch (IllegalStateException e) { throw new ConfigurationException(e.getMessage()); } } } } } private static String metaStringProp(final Map<String, Object> metadata, final String prop) { return metaStringProp(metadata, prop, null); } private static String metaStringProp(final Map<String, Object> metadata, final String prop, final String defString){ final Object titleobj = metadata.get(prop); return null != titleobj && titleobj instanceof String ? (String) titleobj : defString; } protected static void createDescription(final ScriptPluginProvider provider, final boolean allowCustomProperties, final DescriptionBuilder builder) throws ConfigurationException { createDescription(provider, allowCustomProperties, false, builder); } protected static void createDescription(final ScriptPluginProvider provider, final boolean allowCustomProperties, final boolean useConventionalPropertiesMapping, final DescriptionBuilder builder) throws ConfigurationException { builder .name(provider.getName()) .title(metaStringProp(provider.getMetadata(), TITLE_PROP, provider.getName() + " Script Plugin")) .description(metaStringProp(provider.getMetadata(), DESCRIPTION_PROP, "")); if(allowCustomProperties) { createProperties(provider, useConventionalPropertiesMapping, builder); } } /** * Map node attributes as instance configuration values based on property descriptions. * If a property has a rendering option key of * {@link StringRenderingConstants#INSTANCE_SCOPE_NODE_ATTRIBUTE_KEY} * then use the value of that option as the node attribute name to use. * * @param node node * @param description plugin description * * @return instance config data */ protected Map<String, Object> loadInstanceDataFromNodeAttributes( final INodeEntry node, final Description description ) { HashMap<String, Object> config = new HashMap<String, Object>(); for (Property property : description.getProperties()) { Map<String, Object> renderingOptions = property.getRenderingOptions(); if (null == renderingOptions) { continue; } Object o = renderingOptions.get( StringRenderingConstants.INSTANCE_SCOPE_NODE_ATTRIBUTE_KEY ); if (null == o || !(o instanceof String)) { continue; } String attribute = (String) o; String s = node.getAttributes().get(attribute); if (s == null) { continue; } config.put(property.getName(), s); } return config; } /** * Loads the plugin configuration values stored in project or framework properties, also * * @param context execution context * @param localDataContext current context data * @param description plugin description * @param instanceData instance data * * @param serviceName service name * @return context data with a new "config" entry containing the loaded plugin config * properties. * @throws ConfigurationException configuration error */ protected Map<String, Map<String, String>> loadConfigData( final ExecutionContext context, final Map<String, Object> instanceData, final Map<String, Map<String, String>> localDataContext, final Description description, final String serviceName ) throws ConfigurationException { final PropertyResolver resolver = PropertyResolverFactory.createPluginRuntimeResolver( context, instanceData, serviceName, getProvider().getName() ); final Map<String, Object> config = PluginAdapterUtility.mapDescribedProperties( resolver, description, PropertyScope.Instance ); //expand properties Map<String, Object> expanded = DataContextUtils.replaceDataReferences( config, localDataContext ); Map<String, String> data = toStringStringMap(expanded); loadContentConversionPropertyValues( data, context, description.getProperties() ); return DataContextUtils.addContext("config", data, localDataContext); } /** * Looks for properties with content conversion, and converts the values * * @param data map of values for config properties * @param context execution context * @param pluginProperties definition of plugin properties */ protected void loadContentConversionPropertyValues( final Map<String, String> data, final ExecutionContext context, final List<Property> pluginProperties ) throws ConfigurationException { //look for "valueConversion" properties for (Property property : pluginProperties) { String name = property.getName(); String propValue = data.get(name); if (null == propValue) { continue; } Map<String, Object> renderingOptions = property.getRenderingOptions(); if (renderingOptions != null) { Object conversion = renderingOptions.get(StringRenderingConstants.VALUE_CONVERSION_KEY); if (StringRenderingConstants.ValueConversion.STORAGE_PATH_AUTOMATIC_READ.equalsOrString(conversion)) { convertStoragePathValue(data, context.getStorageTree(), name, propValue, renderingOptions); } else if (StringRenderingConstants.ValueConversion.PRIVATE_DATA_CONTEXT.equalsOrString(conversion)) { convertPrivateDataValue(data, context.getPrivateDataContextObject(), name, propValue, renderingOptions); } } } } /** * Converts storage path properties by loading the values into the config data. * @param data config data * @param storageTree storage * @param name property name * @param propValue value to convert * @param renderingOptions options * @throws ConfigurationException */ private void convertStoragePathValue( final Map<String, String> data, final StorageTree storageTree, final String name, final String propValue, final Map<String, Object> renderingOptions ) throws ConfigurationException { //a storage path property String root = null; if (null != renderingOptions.get( StringRenderingConstants.STORAGE_PATH_ROOT_KEY)) { root = renderingOptions.get(StringRenderingConstants.STORAGE_PATH_ROOT_KEY).toString(); } String filter = null; if (null != renderingOptions.get(StringRenderingConstants.STORAGE_FILE_META_FILTER_KEY)) { filter = renderingOptions.get(StringRenderingConstants.STORAGE_FILE_META_FILTER_KEY).toString(); } boolean clearValue = isValueConversionFailureRemove(renderingOptions); if (null != root && !PathUtil.hasRoot(propValue, root)) { if(clearValue) { data.remove(name); } return; } try { Resource<ResourceMeta> resource = storageTree.getResource(propValue); ResourceMeta contents = resource.getContents(); //test filter if (filter != null) { String[] filterComponents = filter.split("=", 2); if (filterComponents.length == 2) { String key = filterComponents[0]; String test = filterComponents[1]; Map<String, String> meta = contents.getMeta(); if (meta == null || !test.equals(meta.get(key))) { if(clearValue) { data.remove(name); } return; } } } //finally load storage contents into a string ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); contents.writeContent(byteArrayOutputStream); data.put(name, new String(byteArrayOutputStream.toByteArray())); } catch (StorageException | IOException e) { if(clearValue) { data.remove(name); return; } throw new ConfigurationException("Unable to load configuration key '" + name + "' value from storage path: " + propValue, e); } } /** * Converts properties that refer to a private data context value * @param data config data * @param privateDataContext private data * @param name property name * @param propValue value to convert */ private void convertPrivateDataValue( final Map<String, String> data, final DataContext privateDataContext, final String name, final String propValue, final Map<String, Object> renderingOptions ) throws ConfigurationException { boolean clearValue = isValueConversionFailureRemove(renderingOptions); String[] prop = propValue.split("\\.", 2); if (prop.length < 2 || prop[0].length() < 1 || prop[1].length() < 1) { throw new ConfigurationException( "Unable to load '" + name + "' configuration value: Expected 'option.name' format, but saw: " + propValue ); } String newvalue = privateDataContext.resolve(prop[0], prop[1]); if (null == newvalue) { if(clearValue) { data.remove(name); } return; } data.put(name, newvalue); } private boolean isValueConversionFailureRemove(final Map<String, Object> renderingOptions) { return StringRenderingConstants.VALUE_CONVERSION_FAILURE_REMOVE.equals( renderingOptions.get( StringRenderingConstants.VALUE_CONVERSION_FAILURE_KEY ) ); } protected static Map<String, String> toStringStringMap(Map input) { Map<String, String> map = new HashMap<String, String>(); for (Object o : input.keySet()) { map.put(o.toString(), input.get(o) != null ? input.get(o).toString() : ""); } return map; } @Override public Description getDescription() { if(null==description){ final DescriptionBuilder builder = DescriptionBuilder.builder(); try { createDescription(provider, isAllowCustomProperties(), isUseConventionalPropertiesMapping(), builder); } catch (ConfigurationException e) { e.printStackTrace(); } description = builder.build(); } return description; } /** * @return true if the script-plugin allows custom configuration properties defined in plugin metadata. */ public abstract boolean isAllowCustomProperties(); /** * @return true to provide conventional mapping from config properties to framework/project properties. */ public boolean isUseConventionalPropertiesMapping(){ return false; } public ScriptPluginProvider getProvider() { return provider; } public Framework getFramework() { return framework; } }
{ "content_hash": "1c6b26298fb15eaf92ad36a686708a16", "timestamp": "", "source": "github", "line_count": 543, "max_line_length": 132, "avg_line_length": 41.125230202578265, "alnum_prop": 0.5738211454928127, "repo_name": "rophy/rundeck", "id": "bfa78d20569c2fca74e1f90f6538b632a2a152e4", "size": "22956", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/main/java/com/dtolabs/rundeck/core/plugins/AbstractDescribableScriptPlugin.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1659" }, { "name": "CSS", "bytes": "135872" }, { "name": "Groovy", "bytes": "6472447" }, { "name": "Java", "bytes": "4226140" }, { "name": "JavaScript", "bytes": "978813" }, { "name": "Makefile", "bytes": "6756" }, { "name": "Ruby", "bytes": "6463" }, { "name": "Shell", "bytes": "524868" } ], "symlink_target": "" }
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.meyersj.mobilesurveyor.app.MainControllor" > <item android:id="@+id/action_settings" android:title="@string/action_settings" android:orderInCategory="100" app:showAsAction="never" /> </menu>
{ "content_hash": "d4c8116c81b80755e64f1c21ea81e027", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 67, "avg_line_length": 46, "alnum_prop": 0.6956521739130435, "repo_name": "TransitSurveyor/MobileSurveyor", "id": "d1368abb7662fe2ad45b82880da431e095ef5992", "size": "414", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/menu/settings_action.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "240740" } ], "symlink_target": "" }
/// <reference path="lib.core.d.ts" /> ///////////////////////////// /// IE10 ECMAScript Extensions ///////////////////////////// /** * Represents a raw buffer of binary data, which is used to store data for the * different typed arrays. ArrayBuffers cannot be read from or written to directly, * but can be passed to a typed array or DataView Object to interpret the raw * buffer as needed. */ interface ArrayBuffer { /** * Read-only. The length of the ArrayBuffer (in bytes). */ byteLength: number; /** * Returns a section of an ArrayBuffer. */ slice(begin:number, end?:number): ArrayBuffer; } declare var ArrayBuffer: { prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; } interface ArrayBufferView { buffer: ArrayBuffer; byteOffset: number; byteLength: number; } /** * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. */ interface Int8Array extends ArrayBufferView { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The length of the array. */ length: number; [index: number]: number; /** * Gets the element at the specified index. * @param index The index at which to get the element of the array. */ get(index: number): number; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Int8Array, offset?: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: number[], offset?: number): void; /** * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Int8Array; } declare var Int8Array: { prototype: Int8Array; new (length: number): Int8Array; new (array: Int8Array): Int8Array; new (array: number[]): Int8Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; BYTES_PER_ELEMENT: number; } /** * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. */ interface Uint8Array extends ArrayBufferView { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The length of the array. */ length: number; [index: number]: number; /** * Gets the element at the specified index. * @param index The index at which to get the element of the array. */ get(index: number): number; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Uint8Array, offset?: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: number[], offset?: number): void; /** * Gets a new Uint8Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Uint8Array; } declare var Uint8Array: { prototype: Uint8Array; new (length: number): Uint8Array; new (array: Uint8Array): Uint8Array; new (array: number[]): Uint8Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; BYTES_PER_ELEMENT: number; } /** * A typed array of 16-bit integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. */ interface Int16Array extends ArrayBufferView { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The length of the array. */ length: number; [index: number]: number; /** * Gets the element at the specified index. * @param index The index at which to get the element of the array. */ get(index: number): number; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Int16Array, offset?: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: number[], offset?: number): void; /** * Gets a new Int16Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Int16Array; } declare var Int16Array: { prototype: Int16Array; new (length: number): Int16Array; new (array: Int16Array): Int16Array; new (array: number[]): Int16Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; BYTES_PER_ELEMENT: number; } /** * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. */ interface Uint16Array extends ArrayBufferView { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The length of the array. */ length: number; [index: number]: number; /** * Gets the element at the specified index. * @param index The index at which to get the element of the array. */ get(index: number): number; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Uint16Array, offset?: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: number[], offset?: number): void; /** * Gets a new Uint16Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Uint16Array; } declare var Uint16Array: { prototype: Uint16Array; new (length: number): Uint16Array; new (array: Uint16Array): Uint16Array; new (array: number[]): Uint16Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; BYTES_PER_ELEMENT: number; } /** * A typed array of 32-bit integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. */ interface Int32Array extends ArrayBufferView { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The length of the array. */ length: number; [index: number]: number; /** * Gets the element at the specified index. * @param index The index at which to get the element of the array. */ get(index: number): number; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Int32Array, offset?: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: number[], offset?: number): void; /** * Gets a new Int32Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Int32Array; } declare var Int32Array: { prototype: Int32Array; new (length: number): Int32Array; new (array: Int32Array): Int32Array; new (array: number[]): Int32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; BYTES_PER_ELEMENT: number; } /** * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. */ interface Uint32Array extends ArrayBufferView { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The length of the array. */ length: number; [index: number]: number; /** * Gets the element at the specified index. * @param index The index at which to get the element of the array. */ get(index: number): number; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Uint32Array, offset?: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: number[], offset?: number): void; /** * Gets a new Int8Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Uint32Array; } declare var Uint32Array: { prototype: Uint32Array; new (length: number): Uint32Array; new (array: Uint32Array): Uint32Array; new (array: number[]): Uint32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; BYTES_PER_ELEMENT: number; } /** * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. */ interface Float32Array extends ArrayBufferView { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The length of the array. */ length: number; [index: number]: number; /** * Gets the element at the specified index. * @param index The index at which to get the element of the array. */ get(index: number): number; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Float32Array, offset?: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: number[], offset?: number): void; /** * Gets a new Float32Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Float32Array; } declare var Float32Array: { prototype: Float32Array; new (length: number): Float32Array; new (array: Float32Array): Float32Array; new (array: number[]): Float32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; BYTES_PER_ELEMENT: number; } /** * A typed array of 64-bit float values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised. */ interface Float64Array extends ArrayBufferView { /** * The size in bytes of each element in the array. */ BYTES_PER_ELEMENT: number; /** * The length of the array. */ length: number; [index: number]: number; /** * Gets the element at the specified index. * @param index The index at which to get the element of the array. */ get(index: number): number; /** * Sets a value or an array of values. * @param index The index of the location to set. * @param value The value to set. */ set(index: number, value: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: Float64Array, offset?: number): void; /** * Sets a value or an array of values. * @param A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: number[], offset?: number): void; /** * Gets a new Float64Array view of the ArrayBuffer Object store for this array, specifying the first and last members of the subarray. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin: number, end?: number): Float64Array; } declare var Float64Array: { prototype: Float64Array; new (length: number): Float64Array; new (array: Float64Array): Float64Array; new (array: number[]): Float64Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; BYTES_PER_ELEMENT: number; } /** * You can use a DataView object to read and write the different kinds of binary data to any location in the ArrayBuffer. */ interface DataView extends ArrayBufferView { /** * Gets the Int8 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getInt8(byteOffset: number): number; /** * Gets the Uint8 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getUint8(byteOffset: number): number; /** * Gets the Int16 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getInt16(byteOffset: number, littleEndian?: boolean): number; /** * Gets the Uint16 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getUint16(byteOffset: number, littleEndian?: boolean): number; /** * Gets the Int32 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getInt32(byteOffset: number, littleEndian?: boolean): number; /** * Gets the Uint32 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getUint32(byteOffset: number, littleEndian?: boolean): number; /** * Gets the Float32 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getFloat32(byteOffset: number, littleEndian?: boolean): number; /** * Gets the Float64 value at the specified byte offset from the start of the view. There is no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getFloat64(byteOffset: number, littleEndian?: boolean): number; /** * Stores an Int8 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. */ setInt8(byteOffset: number, value: number): void; /** * Stores an Uint8 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. */ setUint8(byteOffset: number, value: number): void; /** * Stores an Int16 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. */ setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; /** * Stores an Uint16 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. */ setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; /** * Stores an Int32 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. */ setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; /** * Stores an Uint32 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. */ setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; /** * Stores an Float32 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. */ setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; /** * Stores an Float64 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, otherwise a little-endian value should be written. */ setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; } declare var DataView: { prototype: DataView; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): DataView; } ///////////////////////////// /// IE11 ECMAScript Extensions ///////////////////////////// interface Map<K, V> { clear(): void; delete(key: K): boolean; forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void; get(key: K): V; has(key: K): boolean; set(key: K, value: V): Map<K, V>; size: number; } declare var Map: { new <K, V>(): Map<K, V>; } interface WeakMap<K, V> { clear(): void; delete(key: K): boolean; get(key: K): V; has(key: K): boolean; set(key: K, value: V): WeakMap<K, V>; } declare var WeakMap: { new <K, V>(): WeakMap<K, V>; } interface Set<T> { add(value: T): Set<T>; clear(): void; delete(value: T): boolean; forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void; has(value: T): boolean; size: number; } declare var Set: { new <T>(): Set<T>; } declare module Intl { interface CollatorOptions { usage?: string; localeMatcher?: string; numeric?: boolean; caseFirst?: string; sensitivity?: string; ignorePunctuation?: boolean; } interface ResolvedCollatorOptions { locale: string; usage: string; sensitivity: string; ignorePunctuation: boolean; collation: string; caseFirst: string; numeric: boolean; } interface Collator { compare(x: string, y: string): number; resolvedOptions(): ResolvedCollatorOptions; } var Collator: { new (locales?: string[], options?: CollatorOptions): Collator; new (locale?: string, options?: CollatorOptions): Collator; (locales?: string[], options?: CollatorOptions): Collator; (locale?: string, options?: CollatorOptions): Collator; supportedLocalesOf(locales: string[], options?: CollatorOptions): string[]; supportedLocalesOf(locale: string, options?: CollatorOptions): string[]; } interface NumberFormatOptions { localeMatcher?: string; style?: string; currency?: string; currencyDisplay?: string; useGrouping?: boolean; } interface ResolvedNumberFormatOptions { locale: string; numberingSystem: string; style: string; currency?: string; currencyDisplay?: string; minimumintegerDigits: number; minimumFractionDigits: number; maximumFractionDigits: number; minimumSignificantDigits?: number; maximumSignificantDigits?: number; useGrouping: boolean; } interface NumberFormat { format(value: number): string; resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { new (locales?: string[], options?: NumberFormatOptions): Collator; new (locale?: string, options?: NumberFormatOptions): Collator; (locales?: string[], options?: NumberFormatOptions): Collator; (locale?: string, options?: NumberFormatOptions): Collator; supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[]; supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[]; } interface DateTimeFormatOptions { localeMatcher?: string; weekday?: string; era?: string; year?: string; month?: string; day?: string; hour?: string; minute?: string; second?: string; timeZoneName?: string; formatMatcher?: string; hour12: boolean; } interface ResolvedDateTimeFormatOptions { locale: string; calendar: string; numberingSystem: string; timeZone: string; hour12?: boolean; weekday?: string; era?: string; year?: string; month?: string; day?: string; hour?: string; minute?: string; second?: string; timeZoneName?: string; } interface DateTimeFormat { format(date: number): string; resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { new (locales?: string[], options?: DateTimeFormatOptions): Collator; new (locale?: string, options?: DateTimeFormatOptions): Collator; (locales?: string[], options?: DateTimeFormatOptions): Collator; (locale?: string, options?: DateTimeFormatOptions): Collator; supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[]; supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[]; } } interface String { /** * Determines whether two strings are equivalent in the current locale. * @param that String to compare to target string * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. */ localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number; /** * Determines whether two strings are equivalent in the current locale. * @param that String to compare to target string * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. */ localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number; } interface Number { /** * Converts a number to a string by using the current or specified locale. * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string; /** * Converts a number to a string by using the current or specified locale. * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string; } interface Date { /** * Converts a date to a string by using the current or specified locale. * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string; /** * Converts a date to a string by using the current or specified locale. * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. * @param options An object that contains one or more properties that specify comparison options. */ toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string; } ///////////////////////////// /// IE Worker APIs ///////////////////////////// interface Console { info(message?: any, ...optionalParams: any[]): void; warn(message?: any, ...optionalParams: any[]): void; error(message?: any, ...optionalParams: any[]): void; log(message?: any, ...optionalParams: any[]): void; profile(reportName?: string): void; assert(test?: boolean, message?: string, ...optionalParams: any[]): void; msIsIndependentlyComposed(element: any): boolean; clear(): void; dir(value?: any, ...optionalParams: any[]): void; profileEnd(): void; count(countTitle?: string): void; groupEnd(): void; time(timerName?: string): void; timeEnd(timerName?: string): void; trace(): void; group(groupTitle?: string): void; dirxml(value: any): void; debug(message?: string, ...optionalParams: any[]): void; groupCollapsed(groupTitle?: string): void; select(element: any): void; } declare var Console: { prototype: Console; new(): Console; } interface NavigatorID { appVersion: string; appName: string; userAgent: string; platform: string; product: string; vendor: string; } interface EventTarget { removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; dispatchEvent(evt: Event): boolean; } interface MessageEvent extends Event { source: any; origin: string; data: any; ports: any; initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: any): void; } declare var MessageEvent: { prototype: MessageEvent; new(): MessageEvent; } interface XMLHttpRequest extends EventTarget { responseBody: any; status: number; readyState: number; responseText: string; responseXML: any; ontimeout: (ev: Event) => any; statusText: string; onreadystatechange: (ev: Event) => any; timeout: number; onload: (ev: Event) => any; response: any; withCredentials: boolean; onprogress: (ev: ProgressEvent) => any; onabort: (ev: any) => any; responseType: string; onloadend: (ev: ProgressEvent) => any; upload: XMLHttpRequestEventTarget; onerror: (ev: ErrorEvent) => any; onloadstart: (ev: Event) => any; msCaching: string; open(method: string, url: string, async?: boolean, user?: string, password?: string): void; send(data?: any): void; abort(): void; getAllResponseHeaders(): string; setRequestHeader(header: string, value: string): void; getResponseHeader(header: string): string; msCachingEnabled(): boolean; overrideMimeType(mime: string): void; LOADING: number; DONE: number; UNSENT: number; OPENED: number; HEADERS_RECEIVED: number; addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "readystatechange", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var XMLHttpRequest: { prototype: XMLHttpRequest; new(): XMLHttpRequest; LOADING: number; DONE: number; UNSENT: number; OPENED: number; HEADERS_RECEIVED: number; create(): XMLHttpRequest; } interface EventListener { (evt: Event): void; } interface EventException { code: number; message: string; name: string; toString(): string; DISPATCH_REQUEST_ERR: number; UNSPECIFIED_EVENT_TYPE_ERR: number; } declare var EventException: { prototype: EventException; new(): EventException; DISPATCH_REQUEST_ERR: number; UNSPECIFIED_EVENT_TYPE_ERR: number; } interface NavigatorOnLine { onLine: boolean; } interface Event { timeStamp: number; defaultPrevented: boolean; isTrusted: boolean; currentTarget: EventTarget; cancelBubble: boolean; target: EventTarget; eventPhase: number; cancelable: boolean; type: string; srcElement: any; bubbles: boolean; initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; stopPropagation(): void; stopImmediatePropagation(): void; preventDefault(): void; CAPTURING_PHASE: number; AT_TARGET: number; BUBBLING_PHASE: number; } declare var Event: { prototype: Event; new(): Event; CAPTURING_PHASE: number; AT_TARGET: number; BUBBLING_PHASE: number; } interface ImageData { width: number; data: number[]; height: number; } declare var ImageData: { prototype: ImageData; new(): ImageData; } interface DOMException { code: number; message: string; name: string; toString(): string; HIERARCHY_REQUEST_ERR: number; NO_MODIFICATION_ALLOWED_ERR: number; INVALID_MODIFICATION_ERR: number; NAMESPACE_ERR: number; INVALID_CHARACTER_ERR: number; TYPE_MISMATCH_ERR: number; ABORT_ERR: number; INVALID_STATE_ERR: number; SECURITY_ERR: number; NETWORK_ERR: number; WRONG_DOCUMENT_ERR: number; QUOTA_EXCEEDED_ERR: number; INDEX_SIZE_ERR: number; DOMSTRING_SIZE_ERR: number; SYNTAX_ERR: number; SERIALIZE_ERR: number; VALIDATION_ERR: number; NOT_FOUND_ERR: number; URL_MISMATCH_ERR: number; PARSE_ERR: number; NO_DATA_ALLOWED_ERR: number; NOT_SUPPORTED_ERR: number; INVALID_ACCESS_ERR: number; INUSE_ATTRIBUTE_ERR: number; INVALID_NODE_TYPE_ERR: number; DATA_CLONE_ERR: number; TIMEOUT_ERR: number; } declare var DOMException: { prototype: DOMException; new(): DOMException; HIERARCHY_REQUEST_ERR: number; NO_MODIFICATION_ALLOWED_ERR: number; INVALID_MODIFICATION_ERR: number; NAMESPACE_ERR: number; INVALID_CHARACTER_ERR: number; TYPE_MISMATCH_ERR: number; ABORT_ERR: number; INVALID_STATE_ERR: number; SECURITY_ERR: number; NETWORK_ERR: number; WRONG_DOCUMENT_ERR: number; QUOTA_EXCEEDED_ERR: number; INDEX_SIZE_ERR: number; DOMSTRING_SIZE_ERR: number; SYNTAX_ERR: number; SERIALIZE_ERR: number; VALIDATION_ERR: number; NOT_FOUND_ERR: number; URL_MISMATCH_ERR: number; PARSE_ERR: number; NO_DATA_ALLOWED_ERR: number; NOT_SUPPORTED_ERR: number; INVALID_ACCESS_ERR: number; INUSE_ATTRIBUTE_ERR: number; INVALID_NODE_TYPE_ERR: number; DATA_CLONE_ERR: number; TIMEOUT_ERR: number; } interface ErrorEvent extends Event { colno: number; filename: string; error: any; lineno: number; message: string; initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; } declare var ErrorEvent: { prototype: ErrorEvent; new(): ErrorEvent; } interface MSStreamReader extends MSBaseReader { error: DOMError; readAsArrayBuffer(stream: MSStream, size?: number): void; readAsBlob(stream: MSStream, size?: number): void; readAsDataURL(stream: MSStream, size?: number): void; readAsText(stream: MSStream, encoding?: string, size?: number): void; } declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; } interface MessageChannel { port2: MessagePort; port1: MessagePort; } declare var MessageChannel: { prototype: MessageChannel; new(): MessageChannel; } interface DOMError { name: string; toString(): string; } declare var DOMError: { prototype: DOMError; new(): DOMError; } interface CloseEvent extends Event { wasClean: boolean; reason: string; code: number; initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; } declare var CloseEvent: { prototype: CloseEvent; new(): CloseEvent; } interface WebSocket extends EventTarget { protocol: string; readyState: number; bufferedAmount: number; onopen: (ev: Event) => any; extensions: string; onmessage: (ev: MessageEvent) => any; onclose: (ev: CloseEvent) => any; onerror: (ev: ErrorEvent) => any; binaryType: string; url: string; close(code?: number, reason?: string): void; send(data: any): void; OPEN: number; CLOSING: number; CONNECTING: number; CLOSED: number; addEventListener(type: "open", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var WebSocket: { prototype: WebSocket; new(url: string, protocols?: string): WebSocket; new(url: string, protocols?: string[]): WebSocket; OPEN: number; CLOSING: number; CONNECTING: number; CLOSED: number; } interface ProgressEvent extends Event { loaded: number; lengthComputable: boolean; total: number; initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; } declare var ProgressEvent: { prototype: ProgressEvent; new(): ProgressEvent; } interface IDBObjectStore { indexNames: DOMStringList; name: string; transaction: IDBTransaction; keyPath: string; count(key?: any): IDBRequest; add(value: any, key?: any): IDBRequest; clear(): IDBRequest; createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex; put(value: any, key?: any): IDBRequest; openCursor(range?: any, direction?: string): IDBRequest; deleteIndex(indexName: string): void; index(name: string): IDBIndex; get(key: any): IDBRequest; delete(key: any): IDBRequest; } declare var IDBObjectStore: { prototype: IDBObjectStore; new(): IDBObjectStore; } interface IDBVersionChangeEvent extends Event { newVersion: number; oldVersion: number; } declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; } interface IDBIndex { unique: boolean; name: string; keyPath: string; objectStore: IDBObjectStore; count(key?: any): IDBRequest; getKey(key: any): IDBRequest; openKeyCursor(range?: IDBKeyRange, direction?: string): IDBRequest; get(key: any): IDBRequest; openCursor(range?: IDBKeyRange, direction?: string): IDBRequest; } declare var IDBIndex: { prototype: IDBIndex; new(): IDBIndex; } interface FileList { length: number; item(index: number): File; [index: number]: File; } declare var FileList: { prototype: FileList; new(): FileList; } interface IDBCursor { source: any; direction: string; key: any; primaryKey: any; advance(count: number): void; delete(): IDBRequest; continue(key?: any): void; update(value: any): IDBRequest; PREV: string; PREV_NO_DUPLICATE: string; NEXT: string; NEXT_NO_DUPLICATE: string; } declare var IDBCursor: { prototype: IDBCursor; new(): IDBCursor; PREV: string; PREV_NO_DUPLICATE: string; NEXT: string; NEXT_NO_DUPLICATE: string; } interface File extends Blob { lastModifiedDate: any; name: string; } declare var File: { prototype: File; new(): File; } interface IDBCursorWithValue extends IDBCursor { value: any; } declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; } interface XMLHttpRequestEventTarget extends EventTarget { onprogress: (ev: ProgressEvent) => any; onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; ontimeout: (ev: Event) => any; onabort: (ev: any) => any; onloadstart: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeout", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var XMLHttpRequestEventTarget: { prototype: XMLHttpRequestEventTarget; new(): XMLHttpRequestEventTarget; } interface MSBaseReader extends EventTarget { onprogress: (ev: ProgressEvent) => any; readyState: number; onabort: (ev: any) => any; onloadend: (ev: ProgressEvent) => any; onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadstart: (ev: Event) => any; result: any; abort(): void; LOADING: number; EMPTY: number; DONE: number; addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface IDBKeyRange { upper: any; upperOpen: boolean; lower: any; lowerOpen: boolean; } declare var IDBKeyRange: { prototype: IDBKeyRange; new(): IDBKeyRange; bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; only(value: any): IDBKeyRange; lowerBound(bound: any, open?: boolean): IDBKeyRange; upperBound(bound: any, open?: boolean): IDBKeyRange; } interface WindowConsole { console: Console; } interface IDBTransaction extends EventTarget { oncomplete: (ev: Event) => any; db: IDBDatabase; mode: string; error: DOMError; onerror: (ev: ErrorEvent) => any; onabort: (ev: any) => any; abort(): void; objectStore(name: string): IDBObjectStore; READ_ONLY: string; VERSION_CHANGE: string; READ_WRITE: string; addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var IDBTransaction: { prototype: IDBTransaction; new(): IDBTransaction; READ_ONLY: string; VERSION_CHANGE: string; READ_WRITE: string; } interface WindowBase64 { btoa(rawString: string): string; atob(encodedString: string): string; } interface IDBDatabase extends EventTarget { version: string; name: string; objectStoreNames: DOMStringList; onerror: (ev: ErrorEvent) => any; onabort: (ev: any) => any; createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; close(): void; transaction(storeNames: any, mode?: string): IDBTransaction; deleteObjectStore(name: string): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "abort", listener: (ev: any) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; } interface DOMStringList { length: number; contains(str: string): boolean; item(index: number): string; [index: number]: string; } declare var DOMStringList: { prototype: DOMStringList; new(): DOMStringList; } interface IDBOpenDBRequest extends IDBRequest { onupgradeneeded: (ev: IDBVersionChangeEvent) => any; onblocked: (ev: Event) => any; addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "upgradeneeded", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; addEventListener(type: "blocked", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; } interface MSUnsafeFunctionCallback { (): any; } interface IDBRequest extends EventTarget { source: any; onsuccess: (ev: Event) => any; error: DOMError; transaction: IDBTransaction; onerror: (ev: ErrorEvent) => any; readyState: string; result: any; addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; } interface MessagePort extends EventTarget { onmessage: (ev: MessageEvent) => any; close(): void; postMessage(message?: any, ports?: any): void; start(): void; addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var MessagePort: { prototype: MessagePort; new(): MessagePort; } interface FileReader extends MSBaseReader { error: DOMError; readAsArrayBuffer(blob: Blob): void; readAsDataURL(blob: Blob): void; readAsText(blob: Blob, encoding?: string): void; } declare var FileReader: { prototype: FileReader; new(): FileReader; } interface BlobPropertyBag { type?: string; endings?: string; } interface Blob { type: string; size: number; msDetachStream(): any; slice(start?: number, end?: number, contentType?: string): Blob; msClose(): void; } declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; } interface MSStream { type: string; msDetachStream(): any; msClose(): void; } declare var MSStream: { prototype: MSStream; new(): MSStream; } interface MSBlobBuilder { append(data: any, endings?: string): void; getBlob(contentType?: string): Blob; } declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; } interface IDBFactory { open(name: string, version?: number): IDBOpenDBRequest; cmp(first: any, second: any): number; deleteDatabase(name: string): IDBOpenDBRequest; } declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; } interface AbstractWorker extends EventTarget { onerror: (ev: ErrorEvent) => any; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } interface MSApp { createFileFromStorageFile(storageFile: any): File; createBlobFromRandomAccessStream(type: string, seeker: any): Blob; createStreamFromInputStream(type: string, inputStream: any): MSStream; terminateApp(exceptionObject: any): void; createDataPackage(object: any): any; execUnsafeLocalFunction(unsafeFunction: MSUnsafeFunctionCallback): any; getHtmlPrintDocumentSource(htmlDoc: any): any; addPublicLocalApplicationUri(uri: string): void; createDataPackageFromSelection(): any; getViewOpener(): MSAppView; suppressSubdownloadCredentialPrompts(suppress: boolean): void; execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; isTaskScheduledAtPriorityOrHigher(priority: string): boolean; execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; createNewView(uri: string): MSAppView; getCurrentPriority(): string; NORMAL: string; HIGH: string; IDLE: string; CURRENT: string; } declare var MSApp: MSApp; interface Worker extends AbstractWorker { onmessage: (ev: MessageEvent) => any; postMessage(message: any, ports?: any): void; terminate(): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; } declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; } interface MSExecAtPriorityFunctionCallback { (...args: any[]): any; } interface MSAppView { viewId: number; close(): void; postMessage(message: any, targetOrigin: string, ports?: any): void; } declare var MSAppView: { prototype: MSAppView; new(): MSAppView; } interface WorkerLocation { hash: string; protocol: string; search: string; href: string; hostname: string; port: string; pathname: string; host: string; toString(): string; } declare var WorkerLocation: { prototype: WorkerLocation; new(): WorkerLocation; } interface FileReaderSync { readAsArrayBuffer(blob: Blob): any; readAsDataURL(blob: Blob): string; readAsText(blob: Blob, encoding?: string): string; } declare var FileReaderSync: { prototype: FileReaderSync; new(): FileReaderSync; } interface WorkerGlobalScope extends EventTarget, DedicatedWorkerGlobalScope, WindowConsole, WorkerUtils { location: WorkerLocation; self: WorkerGlobalScope; onerror: (ev: ErrorEvent) => any; msWriteProfilerMark(profilerMarkName: string): void; close(): void; toString(): string; } declare var WorkerGlobalScope: { prototype: WorkerGlobalScope; new(): WorkerGlobalScope; } interface DedicatedWorkerGlobalScope { onmessage: (ev: MessageEvent) => any; postMessage(data: any): void; } interface WorkerNavigator extends NavigatorID, NavigatorOnLine { } declare var WorkerNavigator: { prototype: WorkerNavigator; new(): WorkerNavigator; } interface WorkerUtils extends WindowBase64 { navigator: WorkerNavigator; msIndexedDB: IDBFactory; indexedDB: IDBFactory; clearImmediate(handle: number): void; importScripts(...urls: string[]): void; clearTimeout(handle: number): void; setImmediate(handler: any, ...args: any[]): number; setTimeout(handler: any, timeout?: any, ...args: any[]): number; clearInterval(handle: number): void; setInterval(handler: any, timeout?: any, ...args: any[]): number; } declare var location: WorkerLocation; declare var self: WorkerGlobalScope; declare var onerror: (ev: ErrorEvent) => any; declare function msWriteProfilerMark(profilerMarkName: string): void; declare function close(): void; declare function toString(): string; declare function removeEventListener(type: string, listener: EventListener, useCapture?: boolean): void; declare function addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; declare function dispatchEvent(evt: Event): boolean; declare var onmessage: (ev: MessageEvent) => any; declare function postMessage(data: any): void; declare var console: Console; declare var navigator: WorkerNavigator; declare var msIndexedDB: IDBFactory; declare var indexedDB: IDBFactory; declare function clearImmediate(handle: number): void; declare function importScripts(...urls: string[]): void; declare function clearTimeout(handle: number): void; declare function setImmediate(handler: any, ...args: any[]): number; declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; declare function clearInterval(handle: number): void; declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; declare function btoa(rawString: string): string; declare function atob(encodedString: string): string;
{ "content_hash": "ef6f9f0605b04897ec73191c1f079f06", "timestamp": "", "source": "github", "line_count": 1634, "max_line_length": 407, "avg_line_length": 35.48837209302326, "alnum_prop": 0.651755535628061, "repo_name": "RReverser/TSX", "id": "02485d2602afe5ec0985dfccf2045d94c05e235b", "size": "58818", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bin/lib.webworker.d.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "7544870" }, { "name": "Shell", "bytes": "232" }, { "name": "TypeScript", "bytes": "6994266" } ], "symlink_target": "" }
"""PT: PyTorch frontend.""" import itertools import logging import sys import numpy as np import tvm from tvm.topi.util import get_const_tuple from .. import analysis as _analysis from .. import expr as _expr from .. import op as _op from ..ty import TupleType, TensorType, Any from ..loops import while_loop from .. import transform from .common import AttrCvt, get_relay_op from .common import infer_shape as _infer_shape from .common import infer_value as _infer_value from .common import try_infer_value from .common import infer_value_simulated as _infer_value_simulated from .common import infer_type as _infer_type from ..prelude import Prelude, StaticTensorArrayOps from . import qnn_torch __all__ = ["from_pytorch"] def _is_version_greater_than(ver): import torch from packaging import version # Torch version > 1.4 changed upsampling API return version.parse(torch.__version__) > version.parse(ver) # List ADT utilities def _infer_type_with_prelude(val, prelude): body = _infer_type(val, prelude.mod) return body.checked_type def _convert_to_list_adt(py_lst, prelude): elem_tys = [_infer_type_with_prelude(elem, prelude) for elem in py_lst] msg = "List elements should have identical types" assert all(map(lambda ty: ty == elem_tys[0], elem_tys)), msg # get_type returns type_name, ctor1, ..., ctorN # 1 is nil _, cons, nil = prelude.mod.get_type("List") adt_lst = nil() for elem in reversed(py_lst): adt_lst = cons(elem, adt_lst) return adt_lst def _map_tensor_array_constructor(adt_lst, prelude, shape): static_tensor_array_ops = StaticTensorArrayOps(prelude, "float32", shape) static_tensor_array_ops.register() tensor_create = prelude.get_tensor_ctor_static("tensor_constructor", "float32", shape) return prelude.map(tensor_create, adt_lst) def _convert_to_tensor_array(adt_lst, prelude): _, cons, nil = prelude.mod.get_type("List") if prelude.length(adt_lst) == 0: return nil() checked_type = _infer_type_with_prelude(prelude.hd(adt_lst), prelude) shape = checked_type.shape tensor_array = _map_tensor_array_constructor(adt_lst, prelude, shape) return tensor_array, tuple(shape) def _should_construct_dynamic_list(list_construct_node): # if this list is element-accessed or modified at runtime, generate List ADT def inplace_add_to_add(op_name): if op_name == "aten::add_": return "aten::add" else: return op_name uses = _get_uses(list_construct_node) for loop_use in filter(lambda use: use.user.kind() == "prim::Loop", uses): block_input_index = loop_use.offset - 1 block = list(loop_use.user.blocks())[0] list_loop_var = list(block.inputs())[block_input_index] uses += _get_uses(list_loop_var.node()) op_names = map(inplace_add_to_add, set(use.user.kind() for use in uses)) list_ops = set(["aten::add", "aten::__getitem__"]) intersect = list_ops.intersection(op_names) if len(intersect) > 0 and intersect != set(["aten::add"]): return True # if add op outputs list, it is dynamic so we need to construct List ADT for use in filter(lambda use: use.user.kind() in ["aten::add", "aten::add_"], uses): output_type = _get_node_type(use.user) if output_type == "ListType": return True return False def _is_int_seq(seq): # TODO (t-vi): handle non-int constants? (like numpy.intXX) return len(seq) > 0 and all([isinstance(i, int) for i in seq]) def _is_quantized_tensor(data, prelude): # If a quantized Torch module is saved and loaded back, dtype will be dropped # Since dtypes from Torch tensors are not reliable in such cases, we use # Relay's type inference result to decide if an input tensor is quantized ty = _infer_type_with_prelude(data, prelude) return ty.dtype == "uint8" # operator implementation def _elemwise(name): def _impl(inputs, input_types): data0, data1 = _pytorch_promote_types(inputs[:2], input_types[:2]) return get_relay_op(name)(data0, data1) return _impl def _min_max_common(name_elemwise, name_reduce): def _impl(inputs, input_types): if len(inputs) == 1: data = _pytorch_promote_types(inputs[:1], input_types[:1]) return get_relay_op(name_reduce)(data[0]) elif len(inputs) >= 2 and isinstance(inputs[1], int): data = _pytorch_promote_types(inputs[:1], input_types[:1]) dim = inputs[1] keepdims = inputs[2] if len(inputs) > 2 else False # also return dummy indices return get_relay_op(name_reduce)(data[0], axis=dim, keepdims=keepdims), None else: data0, data1 = _pytorch_promote_types(inputs[:2], input_types[:2]) return get_relay_op(name_elemwise)(data0, data1) return _impl def _max(): return _min_max_common("maximum", "max") def _min(): return _min_max_common("minimum", "min") def _unary(name): def _impl(inputs, input_types): input_type = input_types[0] # this is just to ensure tensor input (data,) = _pytorch_promote_types(inputs[:1], input_types[:1]) return get_relay_op(name)(data) return _impl def _log1p(): def _impl(inputs, input_types): # 1_plus_log x = log(x + 1) (dtype,) = input_types one = _expr.const(1, dtype=dtype) return _op.log(inputs[0] + one) return _impl def _arange(): def _impl(inputs, input_types): def _get_value(val, dtype): # dtype is a tvm dtype if isinstance(val, _expr.Expr): inp = _op.cast(val, dtype) ret, _ = try_infer_value(inp, lambda ret: _expr.const(ret, dtype)) else: ret = _create_typed_const(val, dtype) return ret def _get_type(val, inp_type): if isinstance(val, _expr.Expr): dtype = str(_infer_type(val).checked_type) return dtype return inp_type # PyTorch arange uses the following type semantics: # - if a dtype is given, start, stop, step are converted to that dtype # - if no dtype is given and all args are integral, dtype is int64 # - if no dtype is given and there is a float arg, dtype is float32 if len(inputs) == 5: dtype0 = _get_type(inputs[0], input_types[0]) if inputs[1] is not None: dtype = _convert_dtype_value(inputs[1]) elif dtype0.startswith("float"): dtype = "float32" else: dtype = "int64" start = _expr.const(0, dtype) stop = _get_value(inputs[0], dtype) step = _expr.const(1, dtype) elif len(inputs) == 7: types = [_get_type(inputs[i], input_types[i]) for i in range(3)] if inputs[3] is not None: dtype = _convert_dtype_value(inputs[3]) elif any([t.startswith("float") for t in types]): dtype = "float32" else: dtype = "int64" start = _get_value(inputs[0], dtype) stop = _get_value(inputs[1], dtype) step = _get_value(inputs[2], dtype) else: msg = "Unknown number of arguments (%d) to parse." % (len(inputs)) raise AssertionError(msg) return _op.transform.arange(start=start, stop=stop, step=step, dtype=dtype) return _impl def _squeeze(): def _impl(inputs, input_types): data = inputs[0] if len(inputs) == 1: axis = None else: # TODO (t-vi): why is the cast to int needed? similarly elsewhere axis = [int(inputs[1])] return _op.transform.squeeze(data, axis) return _impl def _unsqueeze(): def _impl(inputs, input_types): data = inputs[0] axis = inputs[1] return _op.transform.expand_dims(data, int(axis), 1) return _impl def _concatenate(prelude): def tensor_array_concat(lst, axis): assert axis == 0, "Tensor array concat supported only for axis 0" tensor_array, shape = _convert_to_tensor_array(lst, prelude) concat_shape = (Any(),) + shape[1:] concat = prelude.get_global_var_static("tensor_array_concat", "float32", shape) concatenated = concat(tensor_array) static_tensor_array_ops = StaticTensorArrayOps(prelude, "float32", concat_shape) static_tensor_array_ops.register() get_tensor = prelude.get_global_var_static("tensor_get_data", "float32", concat_shape) return get_tensor(concatenated) def _impl(inputs, input_types): data = inputs[0] axis = inputs[1] if not isinstance(data, list): return tensor_array_concat(data, axis) if isinstance(data, _expr.Expr): data = [data] return _op.tensor.concatenate(data, int(axis)) return _impl def _slice(): def _impl(inputs, input_types): axis_dtype = "int64" index_size_limit = 2 ** 63 - 1 data = inputs[0] dshape = _infer_shape(data) ndim = len(dshape) end = [] for dim in dshape: if isinstance(dim, tvm.tir.Any): end = _op.shape_of(data) break end.append(int(dim)) begin = [0] * ndim dim = int(inputs[1]) stride = int(inputs[4]) if isinstance(inputs[2], _expr.Call): begin[dim], _ = try_infer_value(inputs[2], lambda ret: np.asscalar(ret.astype(np.int))) else: begin[dim] = int(inputs[2]) # Process begin if not isinstance(begin[dim], int): tmp = [] for b in begin: if isinstance(b, int): tmp.append(_op.expand_dims(_expr.const(b, axis_dtype), axis=0)) else: tmp.append(_op.cast(_op.expand_dims(b, axis=0), axis_dtype)) begin = _op.concatenate(tmp, axis=0) btype = _infer_type(begin).checked_type.dtype if str(btype) != axis_dtype: begin = _op.cast(begin, axis_dtype) if isinstance(inputs[3], str) and inputs[3].isdigit(): target_end = int(inputs[3]) else: if isinstance(inputs[3], _expr.Expr): target_end, _ = try_infer_value( inputs[3], lambda ret: np.asscalar(ret.astype(np.int)) ) else: target_end = inputs[3] if isinstance(target_end, int) and target_end >= index_size_limit: # Quick path for original data. if ( isinstance(begin, _expr.Constant) and begin.data.asnumpy().tolist()[dim] == 0 and stride == 1 ): return data target_end = dshape[dim] # Process end if isinstance(target_end, int): if isinstance(end, list): end[dim] = target_end else: all_static = True for i, shape_dim in enumerate(dshape): if i != dim and isinstance(shape_dim, tvm.tir.Any): all_static = False if all_static: end = list(get_const_tuple(dshape)) end[dim] = target_end else: target_end = _expr.const(target_end) end = _op.scatter( end, _op.expand_dims(_expr.const(dim), axis=0), _op.expand_dims(target_end, axis=0), axis=0, ) else: end = _op.cast(_op.shape_of(data), axis_dtype) if not isinstance(target_end, tvm.tir.Any): ttype = _infer_type(target_end).checked_type.dtype if str(ttype) != axis_dtype: target_end = _op.cast(target_end, axis_dtype) end = _op.scatter( end, _op.expand_dims(_expr.const(dim), axis=0), _op.expand_dims(target_end, axis=0), axis=0, ) if not isinstance(end, list): etype = _infer_type(end).checked_type.dtype if str(etype) != axis_dtype: end = _op.cast(end, axis_dtype) strides = [1] * ndim strides[dim] = int(inputs[4]) return _op.transform.strided_slice( data, begin=begin, end=end, strides=strides, slice_mode="end" ) return _impl def _split(): def _impl(inputs, input_types): data = inputs[0] split_size = int(inputs[1]) dim = int(inputs[2]) split_index = split_size indices = [] while split_index < _infer_shape(data)[dim]: indices.append(split_index) split_index += split_size return _op.split(data, indices, dim) return _impl def _split_with_sizes(): def _impl(inputs, input_types): data = inputs[0] sections = inputs[1] dim = int(inputs[2]) if len(sections) == 1: # a special case used in torchvision detection models return _expr.TupleWrapper(_expr.Tuple([data]), 1) split_index = 0 indices = [] for i in range(len(sections) - 1): index, _ = try_infer_value(sections[i], lambda ret: int(ret)) split_index += index indices.append(split_index) return _op.split(data, indices, dim) return _impl def _select(): def _impl(inputs, input_types): data = inputs[0] dim = int(inputs[1]) index = _wrap_const(inputs[2]) return _op.transform.take(data, index, axis=dim) return _impl def _take(): def _impl(inputs, input_types): data = inputs[0] indices = _op.cast(inputs[1], "int32") return _op.transform.take(data, indices=indices) return _impl def _topk(): def _impl(inputs, input_types): data = inputs[0] axis = int(inputs[2]) is_ascend = not bool(inputs[3]) sort = bool(inputs[4]) if isinstance(inputs[1], _expr.Expr): k, _ = try_infer_value(inputs[1], lambda ret: ret.tolist()) else: k = inputs[1] if not sort: msg = "Currently supports only sorted output for topk operator." raise AssertionError(msg) outs = _op.topk(data, k=k, axis=axis, is_ascend=is_ascend, ret_type="both", dtype="int64") return outs[0], outs[1] return _impl def _reciprocal(): def _impl(inputs, input_types): data = inputs[0] return _expr.const(1.0, dtype=input_types[0]) / data return _impl def _repeat(): def _impl(inputs, input_types): data = inputs[0] reps = inputs[1] return _op.transform.tile(data, reps=reps) return _impl def _repeat_interleave(): def _impl(inputs, input_types): data = inputs[0] if isinstance(inputs[1], int): repeats = inputs[1] axis = inputs[2] else: msg = "Only repeat with one value as repeat is currently supported." raise AssertionError(msg) if axis is None: # Flatten the data if no axis is given from torch data = _op.transform.reshape(data, [-1]) axis = 0 return _op.transform.repeat(data, repeats=repeats, axis=axis) return _impl def _addcdiv(): def _impl(inputs, input_types): data, t1, t2, c = _pytorch_promote_types(inputs[:4], input_types[:4]) return data + (c * (t1 / t2)) return _impl def _addcmul(): def _impl(inputs, input_types): data, t1, t2, c = _pytorch_promote_types(inputs[:4], input_types[:4]) return data + (c * (t1 * t2)) return _impl def _where(): def _impl(inputs, input_types): if len(inputs) == 1: return _nonzero(False)([inputs[0], True], input_types) cond = inputs[0] x, y = _pytorch_promote_types(inputs[1:3], input_types[1:3]) return _op.where(cond, x, y) return _impl def _full_impl(data, fill_value, dtype): size = [] need_reshape = False new_shape = [] for dim in data: if isinstance(dim, _expr.Expr): if isinstance(dim, _expr.Constant): dim = int(dim.data.asnumpy()) if isinstance(size, list): size.append(dim) new_shape.append(dim) else: dim, success = try_infer_value(dim, lambda ret: int(ret), lambda: 0) new_shape.append(dim) if success: if isinstance(size, list): size.append(dim) else: size = None need_reshape = True else: if isinstance(size, list): size.append(dim) new_shape.append(dim) if size is None: tmp = [] for dim in data: tmp.append(_op.cast(_op.expand_dims(dim, axis=0), "int64")) size = _op.concatenate(tmp, axis=0) out = _op.full(_expr.const(fill_value), size, dtype=dtype) if need_reshape: out = _op.reshape(out, new_shape) return out def _ones(default_dtype): def _impl(inputs, input_types): data = inputs[0] import torch if not isinstance(data, (_expr.Expr, list, torch.Tensor, np.ndarray)): msg = "Data type %s could not be parsed in ones op" % (type(data)) raise AssertionError(msg) if inputs[1] is not None: dtype = _convert_dtype_value(inputs[1]) else: dtype = default_dtype return _full_impl(data, 1, dtype) return _impl def _ones_like(default_dtype): def _impl(inputs, input_types): data = inputs[0] out = _op.ones_like(data) # If the input and the output datatype is different, do a cast if inputs[1] is not None: dtype = _convert_dtype_value(inputs[1]) else: dtype = default_dtype if input_types[0] != dtype: out = _op.cast(out, dtype) return out return _impl def _zeros(default_dtype): def _impl(inputs, input_types): data = inputs[0] import torch if not isinstance(data, (_expr.Expr, list, torch.Tensor, np.ndarray)): msg = "Data type %s could not be parsed in zeros op" % (type(data)) raise AssertionError(msg) if inputs[1] is not None: dtype = _convert_dtype_value(inputs[1]) else: dtype = default_dtype return _full_impl(data, 0, dtype) return _impl def _zeros_like(default_dtype): def _impl(inputs, input_types): data = inputs[0] out = _op.zeros_like(data) # If the input and the output datatype is different, do a cast if inputs[1] is not None: dtype = _convert_dtype_value(inputs[1]) else: dtype = default_dtype if input_types[0] not in dtype: out = _op.cast(out, dtype) return out return _impl def _full(default_dtype): def _impl(inputs, input_types): data = inputs[0] fill_value = inputs[1] import torch if not isinstance(data, (_expr.Expr, list, torch.Tensor, np.ndarray)): msg = "Data type %s could not be parsed in full op" % (type(data)) raise AssertionError(msg) if inputs[2] is not None: # dtype given dtype = _convert_dtype_value(inputs[2]) else: # if dtype is None, torch uses a global default set by torch.set_default_tensor_type() dtype = default_dtype return _full_impl(data, fill_value, dtype) return _impl def _full_like(default_dtype): def _impl(inputs, input_types): data = inputs[0] fill_value = inputs[1] out = _op.full_like(data, _expr.const(fill_value)) # If the input and the output datatype is different, do a cast if inputs[2] is not None: # dtype given dtype = _convert_dtype_value(inputs[2]) else: # if dtype is None, torch uses a global default set by torch.set_default_tensor_type() dtype = default_dtype if input_types[0] not in dtype: out = _op.cast(out, dtype) return out return _impl def _linspace(): def _impl(inputs, input_types): start = inputs[0] stop = inputs[1] step = inputs[2] # Find the spacing between values as step if step != 1: step = (stop - start) / (step - 1) stop = stop + step else: stop = start + step dtype = "float32" if inputs[3] is not None else _convert_dtype_value(inputs[3]) start = _create_typed_const(start, dtype) stop = _create_typed_const(stop, dtype) step = _create_typed_const(step, dtype) return _op.transform.arange(start=start, stop=stop, step=step, dtype=dtype) return _impl def _relu(prelude): def _impl(inputs, input_types): data = inputs[0] if _is_quantized_tensor(data, prelude): assert len(inputs) == 3, "Input quant param not found in op inputs" input_zero_point = _expr.const(inputs[2], dtype="int32") return qnn_torch.quantized_relu(data, input_zero_point) return _op.nn.relu(data) return _impl def _prelu(): def _impl(inputs, input_types): data = inputs[0] alpha = inputs[1] return _op.nn.prelu(data, alpha) return _impl def _leaky_relu(): def _impl(inputs, input_types): data = inputs[0] alpha = float(inputs[1]) return _op.nn.leaky_relu(data, alpha) return _impl def _elu(): def _impl(inputs, input_types): data = inputs[0] dtype = input_types[0] alpha = _expr.const(float(inputs[1]), dtype=dtype) return alpha * _op.nn.relu(_expr.const(1, dtype=dtype) - _op.exp(data)) + _op.nn.relu(data) return _impl def _celu(): def _impl(inputs, input_types): data = inputs[0] dtype = input_types[0] alpha = _expr.const(float(inputs[1]), dtype=dtype) return alpha * _op.nn.relu( _expr.const(1, dtype=dtype) - _op.exp(data / alpha) ) + _op.nn.relu(data) return _impl def _gelu(): def _impl(inputs, input_types): data = inputs[0] dtype = input_types[0] # gelu is data * normcdf(data) # normcdf expressed as erf because we don't currently have that intrinsic # note that there is also a fastgelu variant approximating normcdf # with tanh and third order polynomials, but this is "true" gelu return data * ( _expr.const(0.5, dtype=dtype) + _op.erf(data * _expr.const(0.5 ** 0.5, dtype=dtype)) * _expr.const(0.5, dtype=dtype) ) return _impl def _selu(): def _impl(inputs, input_types): data = inputs[0] # https://pytorch.org/docs/stable/nn.html#selu dtype = input_types[0] alpha = _expr.const(-1.6732632423543772848170429916717, dtype=dtype) gamma = _expr.const(1.0507009873554804934193349852946, dtype=dtype) return gamma * ( alpha * _op.nn.relu(_expr.const(1.0, dtype=dtype) - _op.exp(data)) + _op.nn.relu(data) ) return _impl def _log_sigmoid(): def _impl(inputs, input_types): data = inputs[0] return _op.log(_op.tensor.sigmoid(data)) return _impl def _adaptive_avg_pool_2d(prelude): def _impl(inputs, input_types): data = inputs[0] output_size = inputs[1] def func(x): return _op.nn.adaptive_avg_pool2d(x, output_size=output_size) if _is_quantized_tensor(data, prelude): return qnn_torch.apply_with_upcast(data, func) return func(data) return _impl def _adaptive_max_pool_2d(): def _impl(inputs, input_types): data = inputs[0] output_size = inputs[1] # returns dummy indices too return _op.nn.adaptive_max_pool2d(data, output_size=output_size), None return _impl def _adaptive_max_pool_3d(): def _impl(inputs, input_types): data = inputs[0] output_size = inputs[1] # returns dummy indices too return _op.nn.adaptive_max_pool3d(data, output_size=output_size), None return _impl def _adaptive_avg_pool_3d(): def _impl(inputs, input_types): data = inputs[0] output_size = inputs[1] return _op.nn.adaptive_avg_pool3d(data, output_size=output_size) return _impl def _maxpool_2d(): def _impl(inputs, input_types): data = inputs[0] pool_size = inputs[1] strides = inputs[2] if inputs[2] else pool_size padding = inputs[3] dilation = inputs[4] ceil_mode = int(inputs[5]) if dilation != [1, 1]: msg = "MaxPool2d with dilation %s is not implemented" % (str(dilation)) raise NotImplementedError(msg) return _op.nn.max_pool2d(data, pool_size, strides, padding, "NCHW", ceil_mode) return _impl def _maxpool_2d_with_indices(): def _impl(inputs, input_types): # returns dummy indices too return _maxpool_2d()(inputs, input_types), None return _impl def _maxpool_1d(): def _impl(inputs, input_types): data = inputs[0] pool_size = inputs[1] strides = inputs[2] if inputs[2] else pool_size padding = inputs[3] dilation = inputs[4] ceil_mode = int(inputs[5]) if dilation != [1]: msg = "MaxPool1d with dilation %s is not implemented" % (str(dilation)) raise NotImplementedError(msg) return _op.nn.max_pool1d(data, pool_size, strides, padding, "NCW", ceil_mode) return _impl def _maxpool_3d(): def _impl(inputs, input_types): data = inputs[0] pool_size = inputs[1] strides = inputs[2] if inputs[2] else pool_size padding = inputs[3] dilation = inputs[4] ceil_mode = int(inputs[5]) if dilation != [1, 1, 1]: msg = "MaxPool3d with dilation %s is not implemented" % (str(dilation)) raise NotImplementedError(msg) return _op.nn.max_pool3d( data, pool_size=pool_size, strides=strides, padding=padding, ceil_mode=ceil_mode ) return _impl def _hardtanh(): def _impl(inputs, input_types): a = inputs[0] tanh_min = float(inputs[1]) tanh_max = float(inputs[2]) return _op.tensor.clip(a, tanh_min, tanh_max) return _impl def _convolution(): def _impl(inputs, input_types): # Use transpose or normal use_transpose = True if inputs[6] == 1 else False data = inputs[0] weight = inputs[1] bias = inputs[2] strides = tuple(inputs[3]) padding = tuple(inputs[4]) dilation = tuple(inputs[5]) if isinstance(weight, _expr.Expr): inferred_shape = _infer_shape(weight) weight_shape = [] for infer in inferred_shape: weight_shape.append(infer) else: msg = "Data type %s could not be parsed in conv op" % (type(weight)) raise AssertionError(msg) # Transposed convolutions have IOHW layout. if use_transpose: weight_shape[0], weight_shape[1] = weight_shape[1], weight_shape[0] channels = weight_shape[0] groups = int(inputs[8]) # Check if this is depth wise convolution # We need to reshape weight so that Relay could recognize this is depth wise # weight_shape[1] is always in_channels // groups # For depthwise, in_channels == groups, so weight_shape[1] == 1 # If groups > 1 but weight_shape[1] != 1, this is group convolution if groups > 1 and weight_shape[1] == 1: channel_multiplier = channels // groups new_weight_shape = (groups, channel_multiplier) + tuple(weight_shape[2:]) weight = _op.transform.reshape(weight, new_weight_shape) kernel_size = weight_shape[2:] use_bias = isinstance(bias, _expr.Expr) if len(kernel_size) == 1: strides = (1,) + strides padding = (0,) + padding dilation = (1,) + dilation if use_transpose: if len(kernel_size) == 3: conv_op = _op.nn.conv3d_transpose else: conv_op = _op.nn.conv2d_transpose else: if len(kernel_size) == 3: conv_op = _op.nn.conv3d else: conv_op = _op.nn.conv2d if len(kernel_size) == 3: data_layout = "NCDHW" kernel_layout = "OIDHW" else: data_layout = "NCHW" kernel_layout = "OIHW" if len(kernel_size) == 1: data = _op.expand_dims(data, axis=2) weight = _op.expand_dims(weight, axis=2) conv_out = conv_op( data, weight, strides=strides, padding=padding, dilation=dilation, groups=groups, channels=channels, kernel_size=[1] + kernel_size if len(kernel_size) == 1 else kernel_size, data_layout=data_layout, kernel_layout=kernel_layout, out_layout="", out_dtype="", ) if use_bias: res = _op.nn.bias_add(conv_out, bias) else: res = conv_out if len(kernel_size) == 1: res = _op.squeeze(res, axis=[2]) return res return _impl def _softmax(): def _impl(inputs, input_types): data = inputs[0] axis = inputs[1] if isinstance(axis, str): axis = int(axis) return _op.nn.softmax(data, axis=axis) return _impl def _threshold(): def _impl(inputs, input_types): data = inputs[0] return _op.nn.relu(data) return _impl def _contiguous(): def _impl(inputs, input_types): data = inputs[0] return _op.tensor.copy(data) return _impl def _batch_norm(): def _impl(inputs, input_types): data = inputs[0] data_type = input_types[0] channels = _infer_shape(data) if isinstance(inputs[1], _expr.Expr) and isinstance(inputs[2], _expr.Expr): scale = center = True weight = inputs[1] beta = inputs[2] gamma = weight else: scale = center = False if not scale: gamma = _create_typed_const(np.ones([int(channels[1])]), data_type) if not center: beta = _create_typed_const(np.zeros([int(channels[1])]), data_type) moving_mean = inputs[3] moving_var = inputs[4] epsilon = float(inputs[7]) return _op.nn.batch_norm( data, gamma, beta, moving_mean, moving_var, axis=1, epsilon=epsilon, center=center, scale=scale, )[0] return _impl def _instance_norm(): def _impl(inputs, input_types): data = inputs[0] data_type = input_types[0] channels = _infer_shape(data) if isinstance(inputs[1], _expr.Expr) and isinstance(inputs[2], _expr.Expr): scale = center = True weight = inputs[1] beta = inputs[2] gamma = weight else: scale = center = False if not scale: gamma = _create_typed_const(np.ones([int(channels[1])]), data_type) if not center: beta = _create_typed_const(np.zeros([int(channels[1])]), data_type) epsilon = float(inputs[7]) return _op.nn.instance_norm( data, gamma, beta, axis=1, epsilon=epsilon, center=center, scale=scale ) return _impl def _get_dims(data): import torch if isinstance(data, _expr.Expr): dims = _infer_shape(data) elif isinstance(data, list): dims = data elif isinstance(data, (torch.Tensor, np.ndarray)): dims = data.shape else: msg = "Data type %s could not be parsed" % type(data) raise AssertionError(msg) return dims def _layer_norm(): def _impl(inputs, input_types): data = inputs[0] ndims = len(_get_dims(inputs[1])) assert ndims == 1, "Support only normalization over last one dimension." return _op.nn.layer_norm( data, gamma=inputs[2], beta=inputs[3], axis=-1, epsilon=float(inputs[4]), center=True, scale=True, ) return _impl def _group_norm(): def _impl(inputs, input_types): data = inputs[0] gamma = inputs[2] beta = inputs[3] num_groups = inputs[1] epsilon = float(inputs[4]) return _op.nn.group_norm( data, gamma=gamma, beta=beta, num_groups=num_groups, axis=1, epsilon=epsilon, center=True, scale=True, ) return _impl def _transpose(prelude): def _impl(inputs, input_types): data = inputs[0] import torch if isinstance(data, _expr.Expr): ndims = len(_infer_shape(data, prelude.mod)) elif isinstance(data, list): ndims = data elif isinstance(data, (torch.Tensor, np.ndarray)): ndims = data.shape else: msg = "Data type %s could not be parsed in transpose op" % (type(data)) raise AssertionError(msg) if isinstance(data, tvm.runtime.NDArray): ndims = len(data.shape) axes = list(range(ndims)) num_inputs = len(inputs) if num_inputs == 1: if ndims >= 2: axes[-1] = ndims - 2 axes[-2] = ndims - 1 if not isinstance(data, _expr.Expr): data = _expr.const(data) elif num_inputs == 3: parse = lambda i: ndims * (i < 0) + i src, dst = [parse(int(inputs[i])) for i in [1, 2]] axes[src] = dst axes[dst] = src else: axes = inputs[1] return _op.transform.transpose(data, axes) return _impl def _flatten(): def _impl(inputs, input_types): data = inputs[0] start = int(inputs[1]) end = int(inputs[2]) dshape = get_const_tuple(_infer_shape(data)) ndim = len(dshape) if end < 0: end += ndim new_shape = [0] * start new_shape.append(-1) squeeze_axes = [] for i in range(start + 1, end + 1): new_shape.append(1) squeeze_axes.append(i) for _ in range(end + 1, ndim): new_shape.append(0) out = _op.reshape(data, new_shape) if squeeze_axes: out = _op.squeeze(out, axis=squeeze_axes) return out return _impl def _addmm(): def _impl(inputs, input_types): input_mat = inputs[0] mat1 = inputs[1] data_type = input_types[1] mat2 = inputs[2] beta = inputs[3] alpha = inputs[4] if not isinstance(alpha, _expr.Expr) and alpha != 1: alpha = _create_typed_const(alpha, data_type) mat1 *= alpha if not isinstance(beta, _expr.Expr) and beta != 1: beta = _create_typed_const(beta, data_type) mat2 *= beta transposed_mat2 = _op.transform.transpose(mat2, axes=[1, 0]) units = _infer_shape(transposed_mat2)[0] dense_out = _op.nn.dense(mat1, transposed_mat2, units=units) return dense_out + input_mat return _impl def _size(prelude): def _impl_dynamic(inp, axis): shape_dynamic = _op.shape_of(inp, dtype="int32") if axis is not None: return _op.take(shape_dynamic, _expr.const(axis), 0) return shape_dynamic def _impl(inputs, input_types): shape = _infer_shape(inputs[0], prelude.mod) axis = None if len(inputs) > 1: axis = int(inputs[1]) if any(map(lambda s: isinstance(s, tvm.tir.expr.Any), shape)): if axis is None or isinstance(shape[axis], tvm.tir.expr.Any): return _impl_dynamic(inputs[0], axis) if axis is not None: return _expr.const(shape[axis]) return _expr.const(shape) return _impl def _numtotensor(): def _impl(inputs, input_types): val = inputs[0] dtype = input_types[0] if isinstance(val, _expr.Expr): return val if isinstance(val, tvm.tir.IntImm): val = val.__int__() dtype = int arr = val * np.ones([]).astype(dtype) return arr return _impl def _tensortonum(): def _impl(inputs, input_types): return inputs[0] return _impl def _view(): def _impl(inputs, input_types): data = inputs[0] if len(inputs) == 3: shape_inp = [inputs[1], _infer_shape(inputs[2])[0]] else: if isinstance(inputs[1], list): shape_inp = inputs[1] else: shape_inp = _infer_shape(inputs[1]) new_shape = shape_inp for i, shape in enumerate(shape_inp): if isinstance(shape, _expr.Expr): val = _infer_value_simulated(shape, {}) new_shape[i] = np.asscalar(val.asnumpy()) return _op.transform.reshape(data, new_shape) return _impl def _reshape(): def _impl(inputs, input_types): data = inputs[0] new_shape = inputs[1] tmp_shape = [] is_dyn = False for s in new_shape: if isinstance(s, _expr.Constant): tmp_shape.append(int(s.data.asnumpy())) elif isinstance(s, _expr.Expr): dim, success = try_infer_value(s, lambda ret: int(ret)) tmp_shape.append(dim) if not success: is_dyn = True else: tmp_shape.append(s) if is_dyn: new_shape = [] for i, s in enumerate(tmp_shape): if not isinstance(s, _expr.Expr): s = _expr.const(s, "int64") else: s = _op.cast(s, "int64") new_shape.append(_op.expand_dims(s, axis=0)) new_shape = _op.concatenate(new_shape, axis=0) else: new_shape = tmp_shape return _op.transform.reshape(data, new_shape) return _impl def _pixel_shuffle(prelude): def _impl(inputs, input_types): data = inputs[0] upscale_factor = inputs[1] upscale_squared = upscale_factor * upscale_factor b, c, h, w = _infer_shape(data) assert ( c % upscale_squared == 0 ), "input channel should be divisible by square of upscale_factor" ndims = len(_infer_shape(data, prelude.mod)) axes = list(range(ndims)) num_inputs = len(inputs) oc = c // upscale_squared oh = h * upscale_factor ow = w * upscale_factor new_shape = [b, oc, upscale_factor, upscale_factor, h, w] out_shape = [b, oc, oh, ow] data = _op.transform.reshape(data, new_shape) # The data will be transposed to # [b, oc, h, upscale_factor, w, upscale_factor] # for further reshape axes = [0, 1, 4, 2, 5, 3] data = _op.transform.transpose(data, axes) return _op.transform.reshape(data, out_shape) return _impl def _clone(): def _impl(inputs, input_types): data = inputs[0] return _op.tensor.copy(data) return _impl def _log_softmax(): def _impl(inputs, input_types): data = inputs[0] axis = int(inputs[1]) return _op.nn.log_softmax(data, axis) return _impl def _sigmoid(): def _impl(inputs, input_types): data = inputs[0] return _op.tensor.sigmoid(data) return _impl def _softplus(): def _impl(inputs, input_types): data = inputs[0] dtype = input_types[0] beta = _expr.const(float(inputs[1]), dtype=dtype) return _op.log(_op.exp(inputs[0] * beta) + _expr.const(1.0, dtype=dtype)) / beta return _impl def _avg_pool2d(prelude): def _impl(inputs, input_types): data = inputs[0] pool_size = inputs[1] strides = inputs[2] if inputs[2] else pool_size padding = inputs[3] ceil_mode = int(inputs[4]) count_include_pad = int(inputs[5]) def func(x): return _op.nn.avg_pool2d( x, pool_size=pool_size, strides=strides, padding=padding, ceil_mode=ceil_mode, count_include_pad=count_include_pad, ) if _is_quantized_tensor(data, prelude): return qnn_torch.apply_with_upcast(data, func) return func(data) return _impl def _avg_pool3d(): def _impl(inputs, input_types): data = inputs[0] pool_size = inputs[1] strides = inputs[2] if inputs[2] else pool_size padding = inputs[3] ceil_mode = int(inputs[4]) count_include_pad = int(inputs[5]) return _op.nn.avg_pool3d( data, pool_size=pool_size, strides=strides, padding=padding, ceil_mode=ceil_mode, count_include_pad=count_include_pad, ) return _impl def _dropout(): def _impl(inputs, input_types): data = inputs[0] rate = float(inputs[1]) return _op.nn.dropout(data, rate) return _impl def _reduce(name): def _impl(inputs, input_types): data = inputs[0] axis = None keepdims = False if len(inputs) > 2: # default, torch have only data, axis=None, keepdims=False if isinstance(inputs[1], int): axis = int(inputs[1]) elif _is_int_seq(inputs[1]): axis = inputs[1] else: axis = list(_infer_shape(inputs[1])) keepdims = bool(inputs[2]) return get_relay_op(name)(data, axis=axis, keepdims=keepdims) return _impl def _norm(): def _impl(inputs, input_types): data = inputs[0] dtype = input_types[0] axis = None keepdims = False if len(inputs) > 3: axis = inputs[2] keepdims = bool(inputs[3]) order = inputs[1] if order == np.inf: return _op.reduce.max(_op.abs(data), axis=axis, keepdims=keepdims) elif order == np.NINF: return _op.reduce.min(_op.abs(data), axis=axis, keepdims=keepdims) else: reci_order = _expr.const(1.0 / order, dtype=dtype) order = _expr.const(order) return _op.power( _op.reduce.sum(_op.power(_op.abs(data), order), axis=axis, keepdims=keepdims), reci_order, ) return _impl def _frobenius_norm(): def _impl(inputs, input_types): data = inputs[0] axis = None keepdims = False if len(inputs) > 2: axis = inputs[1] keepdims = bool(inputs[2]) return _op.sqrt(_op.reduce.sum((data * data), axis=axis, keepdims=keepdims)) return _impl def _std(): def _impl(inputs, input_types): data = inputs[0] if len(inputs) == 2: axis = None keepdims = False unbiased = bool(inputs[1]) else: axis = inputs[1] keepdims = bool(inputs[3]) unbiased = bool(inputs[2]) return _op.reduce.std(data, axis=axis, keepdims=keepdims, unbiased=unbiased) return _impl def _variance(): def _impl(inputs, input_types): data = inputs[0] if len(inputs) == 2: axis = None keepdims = False unbiased = bool(inputs[1]) else: axis = inputs[1] keepdims = bool(inputs[3]) unbiased = bool(inputs[2]) return _op.reduce.variance(data, axis=axis, keepdims=keepdims, unbiased=unbiased) return _impl def _mean(prelude): def _impl(inputs, input_types): data = inputs[0] if inputs[1]: axis = inputs[1] else: axis = None if len(inputs) > 2 and inputs[2]: keepdims = int(inputs[2]) else: keepdims = False if len(inputs) > 3 and inputs[3]: exclude = int(inputs[3]) else: exclude = False def func(x): return _op.mean(x, axis, keepdims, exclude) if _is_quantized_tensor(data, prelude): assert len(inputs) == 6, "Input quant param not found in op inputs" input_scale = _expr.const(inputs[4]) input_zero_point = _expr.const(inputs[5]) return qnn_torch.quantized_mean(data, input_scale, input_zero_point, func) return func(data) return _impl def _chunk(prelude): def _impl(inputs, input_types): data = inputs[0] num_chunks = int(inputs[1]) axis = int(inputs[2]) if isinstance(data, _expr.Expr): inferred_shape = _infer_shape(data, prelude.mod) shape = [] for infer in inferred_shape: shape.append(infer) dim = int(shape[axis]) if dim % num_chunks: unif_size = int(dim / (num_chunks - 1)) else: unif_size = int(dim / num_chunks) chunks = [] for i in range(0, dim, unif_size): begin = [0] * len(shape) end = shape[:] begin[axis] = i end[axis] = i + unif_size stride = [1] * len(shape) chunk_out = _op.transform.strided_slice(data, begin=begin, end=end, strides=stride) chunks.append(chunk_out) if dim % num_chunks: begin = [0] * len(shape) end = shape[:] begin[axis] = unif_size * (num_chunks - 1) end[axis] = dim stride = [1] * len(shape) chunk_out = _op.transform.strided_slice(data, begin=begin, end=end, strides=stride) chunks.append(chunk_out) return chunks return _impl def _matmul(prelude): def _impl(inputs, input_types): inputs_0 = inputs[0] inputs_1 = inputs[1] # Need to check input shape as batch matmul must be supported. a_shape = _infer_shape(inputs_0, prelude.mod) b_shape = _infer_shape(inputs_1, prelude.mod) # When performing a batch matmul, we need to properly handle N-dim shapes. if len(a_shape) > 2 or len(b_shape) > 2: # Convert a and b into 3 dimensional tensors. a = _op.reshape(inputs_0, [-1, a_shape[-2], a_shape[-1]]) b = _op.reshape(inputs_1, [-1, b_shape[-2], b_shape[-1]]) # Broadcast b to match batch size of a new_b_shape = list(_infer_shape(b, prelude.mod)) new_a_shape = _infer_shape(a, prelude.mod) if new_a_shape[0] > new_b_shape[0]: new_b_shape[0] = new_a_shape[0] b = _op.broadcast_to(b, new_b_shape) # Transpose matrix dimensions of b. b = _op.transpose(b, [0, 2, 1]) # Perform a batch matmul. output = _op.nn.batch_matmul(a, b) # Reshape output to original dimensions. return _op.reshape(output, [*a_shape[:-2], a_shape[-2], b_shape[-1]]) # Otherwise a simple dense op will get the job done. if len(b_shape) == 1: input_1 = _op.expand_dims(inputs_1, 0, 1) else: input_1 = _op.transpose(inputs_1, axes=(1, 0)) out = _op.nn.dense(inputs_0, input_1) if len(b_shape) == 1: out = _op.squeeze(out, axis=[-1]) return out return _impl def _expand(): def _impl(inputs, input_types): data_in = inputs[0] shape = list(_infer_shape(data_in)) ndims = len(shape) sizes = inputs[1] out = data_in out_dims = len(sizes) if ndims < out_dims: num_newaxis = out_dims - ndims out = _op.expand_dims(out, axis=0, num_newaxis=num_newaxis) shape = [1] * num_newaxis + shape for i in range(out_dims): if sizes[i] != -1 and shape[i] == 1: if not isinstance(sizes[i], int): sizes[i] = int(_infer_value(sizes[i], {}).asnumpy()) out = _op.repeat(out, sizes[i], axis=i) return out return _impl def _int(): def _impl(inputs, input_types): if isinstance(inputs[0], _expr.Expr): return inputs[0] return int(inputs[0]) return _impl def _identity(): def _impl(inputs, input_types): return inputs[0] return _impl def _none(): def _impl(inputs, input_types): return None return _impl def _pad(mode): def _impl(inputs, input_types): data = inputs[0] if isinstance(inputs[1], list): pad_list = inputs[1] else: pad_list = list(_infer_shape(inputs[1])) # initialize paddings based on input len pad_len = len(_infer_shape(data)) * 2 paddings = [0] * pad_len if len(pad_list) >= 2: paddings[-1] = pad_list[1] paddings[-2] = pad_list[0] if len(pad_list) >= 4: paddings[-3] = pad_list[3] paddings[-4] = pad_list[2] if len(pad_list) >= 6: paddings[-5] = pad_list[5] paddings[-6] = pad_list[4] # group into tuple of 2 ints paddings = [paddings[i : i + 2] for i in range(0, len(paddings), 2)] const_paddings = [] for pad in paddings: const_paddings.append([]) for p in pad: if not isinstance(p, int): p = int(_infer_value(p, {}).asnumpy()) const_paddings[-1].append(p) if mode == "constant": return _op.nn.pad(data, const_paddings, pad_value=inputs[2], pad_mode=mode) else: return _op.nn.pad(data, const_paddings, pad_mode=mode) return _impl def _clamp(): def _impl(inputs, input_types): data = inputs[0] amin = inputs[1] if inputs[1] else np.finfo(np.float32).min amax = inputs[2] if inputs[2] else np.finfo(np.float32).max return _op.clip(data, amin, amax) return _impl def _to(): def _impl(inputs, input_types): data = inputs[0] dtype = inputs[1] if inputs[1] is not None and not isinstance(inputs[1], str) else inputs[2] # special handling for aten::to(data, 6, _, _, _) case # 6 means dtype = float # this happens when converting upsampling with scale factor cast_map = { 5: "float16", 6: "float32", 7: "float64", 3: "int32", 4: "int64", } cast_func = {5: float, 6: float, 7: float, 3: int, 4: int} ret = data if isinstance(data, _expr.Expr): actual_dtype = str(_infer_type(data).checked_type.dtype) if dtype in cast_map and cast_map[dtype] != actual_dtype: ret = _op.cast(data, cast_map[dtype]) elif dtype in cast_map: ret = cast_func[dtype](data) return ret return _impl def _upsample(method, prelude): def _impl(inputs, input_types): out_size = [] for size in inputs[1]: if not isinstance(size, int): out_size.append(int(_infer_value(size, {}).asnumpy())) else: out_size.append(size) data = inputs[0] if len(inputs) > 2: align_corners = inputs[2] else: align_corners = False if method == "nearest_neighbor": coord_trans = "asymmetric" elif align_corners: coord_trans = "align_corners" else: coord_trans = "half_pixel" def func(x): return _op.image.resize(x, out_size, "NCHW", method, coord_trans) if _is_quantized_tensor(data, prelude): # Torch version > 1.4 changed upsampling API if _is_version_greater_than("1.4.0"): num_inputs = 7 else: num_inputs = 5 assert len(inputs) == num_inputs, "Input quant param not found in op inputs" input_scale = _expr.const(inputs[-2]) input_zero_point = _expr.const(inputs[-1]) return qnn_torch.quantized_upsample(data, input_scale, input_zero_point, func) return func(data) return _impl def _upsample3d(method): def _impl(inputs, input_types): if isinstance(inputs[1], _expr.Var): out_size = _infer_shape(inputs[1]) elif _is_int_seq(inputs[1]): out_size = inputs[1] elif isinstance(inputs[1], list): infer_res = [_infer_value(size, {}) for size in inputs[1]] out_size = [np.asscalar(res.asnumpy().astype(np.int)) for res in infer_res] data = inputs[0] if len(inputs) > 2: align_corners = inputs[2] else: align_corners = False if method == "nearest_neighbor": coord_trans = "asymmetric" elif align_corners: coord_trans = "align_corners" else: coord_trans = "half_pixel" return _op.image.resize3d(data, out_size, "NCDHW", method, coord_trans) return _impl def _expand_as(): def _impl(inputs, input_types): target = inputs[1] t0 = _infer_type(inputs[0]).checked_type.dtype t1 = _infer_type(inputs[1]).checked_type.dtype if str(t0) != str(t1): target = _op.cast(target, t0) return _op.broadcast_to_like(inputs[0], target) return _impl def _Bool(): def _impl(inputs, input_types): assert len(inputs) == 1 return inputs[0] return _impl def _Float(): def _impl(inputs, input_types): assert len(inputs) == 1 return _op.cast(inputs[0], "float32") return _impl def _mm(): def _impl(inputs, input_types): return _op.nn.dense(inputs[0], inputs[1]) return _impl def _bitwise_not(): def _impl(inputs, input_types): data = inputs[0] # The input tensor must be of integral or Boolean types. # For bool tensors, it computes the logical NOT if input_types[0] == "bool": out = _op.logical_not(_op.cast(data, "bool")) else: out = _op.bitwise_not(_op.cast(data, "int")) return out return _impl def _bitwise_xor(): def _impl(inputs, input_types): lhs = inputs[0] rhs = inputs[1] lhs = _op.cast(lhs, "bool") if input_types[0] == "bool" else _op.cast(lhs, "int") rhs = _op.cast(rhs, "bool") if input_types[1] == "bool" else _op.cast(rhs, "int") return _op.bitwise_xor(lhs, rhs) return _impl def _logical_not(): def _impl(inputs, input_types): data = inputs[0] return _op.logical_not(_op.cast(data, "bool")) return _impl def _logical_xor(): def _impl(inputs, input_types): lhs = _op.cast(inputs[0], "bool") rhs = _op.cast(inputs[1], "bool") return _op.logical_xor(lhs, rhs) return _impl def _list_getitem(prelude): def _impl(inputs, input_types): return prelude.nth(inputs[0], _wrap_const(inputs[1])) return _impl def _list_len(prelude): def _impl(inputs, input_types): return prelude.length(inputs[0]) return _impl def _type_as(): def _impl(inputs, input_types): assert len(inputs) == 2 assert len(input_types) == 2 return _op.cast(inputs[0], input_types[1]) return _impl def _gather(): def _impl(inputs, input_types): data = inputs[0] axis = inputs[1] indices = inputs[2] return _op.gather(data, axis, indices) return _impl def _add(prelude): # add_ is overloaded for tensor add and list concat def _impl(inputs, input_types): if input_types[0] == "ListType": return prelude.concat(inputs[0], inputs[1]) return _elemwise("add")(inputs, input_types) return _impl def _tensor_array_stack(prelude): def _impl(inputs, input_types): dim = inputs[1] assert dim == 0, "stacking on a dynamic tensor list only supported on a first axis" tensor_array, shape = _convert_to_tensor_array(inputs[0], prelude) stacked_shape = (Any(),) + shape stack = prelude.get_global_var_static("tensor_array_stack", "float32", shape) stacked = stack(tensor_array) static_tensor_array_ops = StaticTensorArrayOps(prelude, "float32", stacked_shape) static_tensor_array_ops.register() get_tensor = prelude.get_global_var_static("tensor_get_data", "float32", stacked_shape) return get_tensor(stacked) return _impl def _stack(prelude): def _impl(inputs, input_types): if isinstance(inputs[0], list): # a static python list of tensors dim = inputs[1] return _op.stack(inputs[0], dim) else: # List ADT case assert isinstance(inputs[0], _expr.Expr) ty = _infer_type_with_prelude(inputs[0], prelude) list_ty = prelude.mod.get_global_type_var("List") msg = "The input list is expected to be List ADT" assert isinstance(ty, tvm.ir.TypeCall) and ty.func == list_ty, msg return _tensor_array_stack(prelude)(inputs, input_types) return _impl def _rsub(): def _impl(inputs, input_types): data0, data1 = _pytorch_promote_types(inputs[:2], input_types[:2]) # TODO (t-vi): should this also be part of the type promotion? alpha = _expr.const(float(inputs[2])) # note: rsub means data0 and data1 swap places return get_relay_op("subtract")(data1, alpha * data0) return _impl def _embedding(): def _impl(inputs, input_types): weight = inputs[0] indices = inputs[1] return _op.take(weight, indices.astype("int32"), axis=0) return _impl def _one_hot(): def _impl(inputs, input_types): indices = inputs[0].astype("int32") num_classes = inputs[1] if num_classes == -1: msg = "Inferring the number of classes is not yet supported." raise NotImplementedError(msg) dtype = "int32" on_value = tvm.relay.const(1.0, dtype) off_value = tvm.relay.const(0.0, dtype) return _op.one_hot(indices, on_value, off_value, num_classes, -1, dtype) return _impl def _index(): def _impl(inputs, input_types): data = inputs[0] indices = inputs[1] return _op.adv_index([data] + indices) return _impl def _meshgrid(): def _impl(inputs, input_types): data = inputs[0] return _op.meshgrid(data, indexing="ij") return _impl def _nms(prelude): def _impl(inputs, input_types): boxes = inputs[0] scores = inputs[1] iou_threshold = inputs[2] # Generate data with shape (1, num_anchors, 5) scores = AttrCvt(op_name="expand_dims", extras={"axis": -1, "num_newaxis": 1})([scores], {}) # Prepare input data for get_valid_counts data = _op.concatenate([scores, boxes], -1) data = _op.expand_dims(data, 0, 1) # Leverage get_valid_counts to sort the data and clear invalid boxes ct, data, indices = get_relay_op("get_valid_counts")( data, score_threshold=-1.0, id_index=-1, score_index=0 ) # Perform Non-Maximum Suppression, # PyTorch NMS doesn't have parameter top_k and max_output_size score_index = 0 top_k = max_out_size = -1 nms_ret = get_relay_op("non_max_suppression")( data=data, valid_count=ct, indices=indices, max_output_size=max_out_size, iou_threshold=iou_threshold, force_suppress=True, top_k=top_k, coord_start=1, score_index=score_index, id_index=-1, return_indices=True, invalid_to_bottom=False, ) # squeeze the two outputs of nms for strided_slice size = get_relay_op("squeeze")(nms_ret[1], axis=[1]) data_slice = get_relay_op("squeeze")(nms_ret[0], axis=[0]) # strided slice to get the dynamic result ret = get_relay_op("strided_slice")( data_slice, begin=_expr.const([0]), end=size, slice_mode="size" ) # in torchvision, indices from nms are int64 return _op.cast(ret, "int64") return _impl def _logsumexp(): def _impl(inputs, input_types): data = _pytorch_promote_types(inputs[:1], input_types[:1]) dim_list = inputs[1] keepdim = inputs[2] if len(inputs) > 2 else False # dim is output of prim::ListConstruct, even if it is int in python code assert isinstance(dim_list, list), "dim is expected to be a list" return _op.logsumexp(data[0], axis=dim_list, keepdims=keepdim) return _impl def _roi_align(prelude): def _impl(inputs, input_types): data = inputs[0] boxes = inputs[1] output_size = (inputs[3], inputs[4]) spatial_scale = inputs[2] sample_ratio = inputs[5] aligned = False if len(inputs) < 7 else inputs[6] if aligned: boxes -= _expr.const(0.5 / spatial_scale) return _op.vision.roi_align(data, boxes, output_size, spatial_scale, sample_ratio) return _impl def _unbind(): def _impl(inputs, input_types): data = inputs[0] dim = int(inputs[1]) ishapes = _infer_shape(data) if dim >= len(ishapes): msg = "Please check input dim, it shouldn't" "be greater than or equal to rank." raise AttributeError(msg) selections = ishapes[dim] res_split = _op.split(data, selections, dim) # squeeze each split piece to get same shape as aten::unbind # TODO (yongwww): add new op to avoid the squeeze overhead ret = [] for i in range(selections): ret.append(_op.transform.squeeze(res_split[i], axis=[dim])) ret = _expr.TupleWrapper(_expr.Tuple(ret), selections) return ret return _impl def _shape_as_tensor(prelude): def _impl(inputs, input_types): is_symbolic_shape = False input_shape = _infer_shape(inputs[0], prelude.mod) for axis in input_shape: if not isinstance(axis, (int, tvm.tir.IntImm)): is_symbolic_shape = True break if is_symbolic_shape: ret = _op.shape_of(inputs[0], dtype="int64") else: ret = _expr.const(np.array(input_shape), dtype="int64") return ret return _impl def _logical_and(): def _impl(inputs, input_types): lhs = _op.cast(inputs[0], "bool") rhs = _op.cast(inputs[1], "bool") return _op.logical_and(lhs, rhs) return _impl def _nonzero(is_numpy_style): def _impl(inputs, input_types): data = inputs[0] ret = _op.transform.argwhere(data) if is_numpy_style or (len(inputs) > 1 and inputs[1]): return _unbind()([ret, 1], None) return ret return _impl def _scatter(): def _impl(inputs, input_types): data = inputs[0] axis = int(inputs[1]) index = inputs[2] src = inputs[3] return _op.transform.scatter(data, index, src, axis) return _impl def _scalar_tensor(): def _impl(inputs, input_types): data = inputs[0] cast_map = { 6: "float32", 7: "float64", 3: "int32", 4: "int64", } type_key = inputs[1] if isinstance(data, _expr.Constant): data = data.data.asnumpy().tolist() return _expr.const(data, cast_map[type_key]) return _impl def _interpolate(): def _impl(inputs, input_types): if isinstance(inputs[1], _expr.Expr): out_size = inputs[1] elif isinstance(inputs[1], list): out_size = [] for i in [0, 1]: size, _ = try_infer_value( inputs[1][i], lambda ret: ret.astype(np.int), lambda: _op.expand_dims(inputs[1][i], axis=0), ) out_size.append(size) out_size = _op.concatenate(out_size, axis=0) data = inputs[0] align_corners = inputs[4] method = inputs[3] if method.startswith("nearest"): method = "nearest_neighbor" if method == "nearest_neighbor": coord_trans = "asymmetric" elif align_corners: coord_trans = "align_corners" else: coord_trans = "half_pixel" return _op.image.resize(data, out_size, "NCHW", method, coord_trans) return _impl def _numel(): def _impl(inputs, input_types): return _op.ndarray_size(inputs[0]) return _impl def _empty(): def _impl(inputs, input_types): shape = inputs[0] return _op.zeros(shape, _convert_dtype_value(inputs[1])) return _impl def _pytorch_result_type(dtypes, non_tensor_inputs): """This promotes TVM dtypes like PyTorch would""" import torch dtype_map = { "float64": torch.float64, "float32": torch.float32, "float16": torch.float16, "bfloat16": torch.bfloat16, "int64": torch.int64, "int32": torch.int32, "int16": torch.int16, "int8": torch.int8, "uint8": torch.uint8, "bool": torch.bool, } if len(dtypes) > 0: result_type = dtypes[0] for dt in dtypes[1:]: if dt != result_type: # we don't want to work with same types as we # don't do quantized here (which cannot be promoted?) result_type = _convert_data_type( str( torch.result_type( torch.zeros((), dtype=dtype_map[result_type]), torch.zeros((), dtype=dtype_map[dt]), ) ) ) else: result_type = "bool" # this is the smallest type... for inp in non_tensor_inputs: result_type = _convert_data_type( str(torch.result_type(torch.zeros((), dtype=dtype_map[result_type]), inp)) ) return result_type def _pytorch_promote_types(inputs, dtypes): """This promotes TVM inputs with TVM dtypes passed like PyTorch would""" actual_dtypes = [] for i, inp in enumerate(inputs): if isinstance(inp, _expr.Expr): idt = _infer_type(inp).checked_type.dtype actual_dtypes.append(idt) else: actual_dtypes.append(dtypes[i]) dtypes = actual_dtypes tensor_dtypes = [dt for inp, dt in zip(inputs, dtypes) if not np.isscalar(inp)] non_tensor_inputs = [inp for inp in inputs if np.isscalar(inp)] result_type = _pytorch_result_type(tensor_dtypes, non_tensor_inputs) results = [] for inp, dt in zip(inputs, dtypes): if np.isscalar(inp): results.append(_expr.const(inp, dtype=result_type)) elif dt == result_type: results.append(inp) else: results.append(_op.cast(inp, result_type)) return results # Helper functions for operator implementation def _convert_dtype_value(val): """converts a PyTorch the PyTorch numeric type id to a torch scalar type.""" convert_torch_dtype_map = { 7: "torch.float64", 6: "torch.float32", 5: "torch.float16", 4: "torch.int64", 3: "torch.int32", 2: "torch.int16", 1: "torch.int8", 0: "torch.unit8", None: "torch.int64", } # Default is torch.int64 if val in convert_torch_dtype_map: return _convert_data_type(convert_torch_dtype_map[val]) else: msg = "Torch data type value %d is not handled yet." % (val) raise NotImplementedError(msg) def _convert_data_type(input_type, default_dtype=None): """converts the PyTorch scalar type input_type to a TVM dtype. optionally, default_dtype can be a TVM dtype that is used if input_type is None (but not when it is unknown)""" if input_type is None and default_dtype is not None: return default_dtype input_type = input_type.lower() if input_type in ["double", "float64", "torch.float64"]: return "float64" elif input_type in ["float", "float32", "torch.float32"]: return "float32" elif input_type in ["half", "float16", "torch.float16"]: return "float16" elif input_type in ["long", "int64", "torch.int64"]: return "int64" elif input_type in ["int", "int32", "torch.int32"]: return "int32" elif input_type in ["short", "int16", "torch.int16"]: return "int16" elif input_type in ["char", "int8", "torch.int8"]: return "int8" elif input_type in ["byte", "uint8", "torch.uint8"]: return "uint8" elif input_type in ["quint8", "torch.quint8"]: return "quint8" elif input_type in ["qint8", "torch.qint8"]: return "qint8" elif input_type in ["qint32", "torch.qint32"]: return "qint32" elif input_type in ["bool", "torch.bool"]: return "bool" elif input_type in ["str"]: return "str" else: raise NotImplementedError("input_type {} is not handled yet".format(input_type)) return "float32" # Never reached def _create_typed_const(data, dtype): """create a (scalar) constant of given value and dtype. dtype should be a TVM dtype""" if dtype == "float64": typed_data = _expr.const(np.float64(data), dtype=dtype) elif dtype == "float32": typed_data = _expr.const(np.float32(data), dtype=dtype) elif dtype == "float16": typed_data = _expr.const(np.float16(data), dtype=dtype) elif dtype == "int64": typed_data = _expr.const(np.int64(data), dtype=dtype) elif dtype == "int32": typed_data = _expr.const(np.int32(data), dtype=dtype) elif dtype == "int16": typed_data = _expr.const(np.int16(data), dtype=dtype) elif dtype == "int8": typed_data = _expr.const(np.int8(data), dtype=dtype) elif dtype == "uint8": typed_data = _expr.const(np.uint8(data), dtype=dtype) else: raise NotImplementedError("input_type {} is not handled yet".format(dtype)) return typed_data def _wrap_const(c): if not isinstance(c, (_expr.Expr, list, tvm.tir.expr.Any)): return _expr.const(c) return c # Operator mappings def _get_convert_map(prelude, default_dtype): convert_map = { "aten::pixel_shuffle": _pixel_shuffle(prelude), "aten::device": _none(), "prim::device": _none(), "aten::sub": _elemwise("subtract"), "aten::sub_": _elemwise("subtract"), "aten::max": _max(), "aten::min": _min(), "aten::mul": _elemwise("multiply"), "aten::mul_": _elemwise("multiply"), "aten::pow": _elemwise("power"), "aten::arange": _arange(), "aten::meshgrid": _meshgrid(), "aten::div": _elemwise("divide"), "aten::div_": _elemwise("divide"), "aten::floor_divide": _elemwise("floor_divide"), "aten::true_divide": _elemwise("divide"), "aten::addcdiv": _addcdiv(), "aten::addcmul": _addcmul(), "aten::ones": _ones(default_dtype), "aten::ones_like": _ones_like(default_dtype), "aten::zeros": _zeros(default_dtype), "aten::zeros_like": _zeros_like(default_dtype), "aten::full": _full(default_dtype), "aten::full_like": _full_like(default_dtype), "aten::linspace": _linspace(), "aten::reciprocal": _reciprocal(), "aten::repeat": _repeat(), "aten::repeat_interleave": _repeat_interleave(), "aten::to": _to(), "aten::squeeze": _squeeze(), "aten::unsqueeze": _unsqueeze(), "aten::cat": _concatenate(prelude), "aten::slice": _slice(), "aten::split": _split(), "aten::split_with_sizes": _split_with_sizes(), "aten::select": _select(), "aten::take": _take(), "aten::where": _where(), "aten::topk": _topk(), "aten::relu": _relu(prelude), "aten::relu_": _relu(prelude), "aten::prelu": _prelu(), "aten::leaky_relu": _leaky_relu(), "aten::leaky_relu_": _leaky_relu(), "aten::elu": _elu(), "aten::elu_": _elu(), "aten::celu": _celu(), "aten::gelu": _gelu(), "aten::selu": _selu(), "aten::log_sigmoid": _log_sigmoid(), "aten::adaptive_avg_pool2d": _adaptive_avg_pool_2d(prelude), "aten::adaptive_max_pool2d": _adaptive_max_pool_2d(), "aten::max_pool2d": _maxpool_2d(), "aten::max_pool2d_with_indices": _maxpool_2d_with_indices(), "aten::max_pool1d": _maxpool_1d(), "aten::max_pool3d": _maxpool_3d(), "aten::hardtanh": _hardtanh(), "aten::hardtanh_": _hardtanh(), "aten::_convolution": _convolution(), "aten::softmax": _softmax(), "aten::threshold": _threshold(), "aten::threshold_": _threshold(), "aten::contiguous": _contiguous(), "aten::batch_norm": _batch_norm(), "aten::instance_norm": _instance_norm(), "aten::layer_norm": _layer_norm(), "aten::group_norm": _group_norm(), "aten::transpose": _transpose(prelude), "aten::transpose_": _transpose(prelude), "aten::t": _transpose(prelude), "aten::flatten": _flatten(), "aten::addmm": _addmm(), "aten::size": _size(prelude), "aten::view": _view(), "aten::reshape": _reshape(), "aten::clone": _clone(), "aten::log_softmax": _log_softmax(), "aten::sigmoid": _sigmoid(), "aten::softplus": _softplus(), "aten::avg_pool2d": _avg_pool2d(prelude), "aten::avg_pool3d": _avg_pool3d(), "aten::dropout": _dropout(), "aten::dropout_": _dropout(), "aten::feature_dropout": _dropout(), "aten::alpha_dropout": _dropout(), "aten::mean": _mean(prelude), "aten::chunk": _chunk(prelude), "aten::matmul": _matmul(prelude), "aten::bmm": _matmul(prelude), "aten::expand": _expand(), "aten::Int": _int(), "prim::NumToTensor": _numtotensor(), "prim::ImplicitTensorToNum": _tensortonum(), "aten::ScalarImplicit": _tensortonum(), "aten::constant_pad_nd": _pad("constant"), "aten::reflection_pad1d": _pad("reflect"), "aten::reflection_pad2d": _pad("reflect"), "aten::replication_pad1d": _pad("edge"), "aten::replication_pad2d": _pad("edge"), "aten::replication_pad3d": _pad("edge"), "aten::permute": _transpose(prelude), "aten::sum": _reduce("sum"), "aten::prod": _reduce("prod"), "aten::argmin": _reduce("argmin"), "aten::argmax": _reduce("argmax"), "aten::norm": _norm(), "aten::frobenius_norm": _frobenius_norm(), "aten::std": _std(), "aten::var": _variance(), "aten::abs": _unary("abs"), "aten::neg": _unary("negative"), "aten::cos": _unary("cos"), "aten::cosh": _unary("cosh"), "aten::sin": _unary("sin"), "aten::sinh": _unary("sinh"), "aten::tan": _unary("tan"), "aten::tanh": _unary("tanh"), "aten::acos": _unary("acos"), "aten::asin": _unary("asin"), "aten::atan": _unary("atan"), "aten::log": _unary("log"), "aten::log2": _unary("log2"), "aten::log10": _unary("log10"), "aten::log1p": _log1p(), "aten::exp": _unary("exp"), "aten::erf": _unary("erf"), "aten::trunc": _unary("trunc"), "aten::sign": _unary("sign"), "aten::sqrt": _unary("sqrt"), "aten::rsqrt": _unary("rsqrt"), "aten::ceil": _unary("ceil"), "aten::floor": _unary("floor"), "aten::round": _unary("round"), "aten::isfinite": _unary("isfinite"), "aten::isinf": _unary("isinf"), "aten::isnan": _unary("isnan"), "aten::clamp": _clamp(), "aten::clamp_": _clamp(), "aten::detach": _identity(), "aten::upsample_bilinear2d": _upsample("bilinear", prelude), "aten::upsample_nearest2d": _upsample("nearest_neighbor", prelude), "aten::upsample_trilinear3d": _upsample3d("trilinear"), "aten::upsample_nearest3d": _upsample3d("nearest_neighbor"), "aten::expand_as": _expand_as(), "aten::lt": _elemwise("less"), "aten::gt": _elemwise("greater"), "aten::le": _elemwise("less_equal"), "aten::ge": _elemwise("greater_equal"), "aten::ne": _elemwise("not_equal"), "aten::eq": _elemwise("equal"), "aten::logical_not": _logical_not(), "aten::logical_xor": _logical_xor(), "aten::bitwise_not": _bitwise_not(), "aten::bitwise_xor": _bitwise_xor(), "aten::Bool": _Bool(), "aten::Float": _Float(), "aten::adaptive_avg_pool3d": _adaptive_avg_pool_3d(), "aten::adaptive_max_pool3d": _adaptive_max_pool_3d(), "aten::rsub": _rsub(), "aten::embedding": _embedding(), "aten::one_hot": _one_hot(), "aten::mm": _matmul(prelude), "aten::add": _add(prelude), "aten::add_": _add(prelude), "aten::stack": _stack(prelude), "aten::__getitem__": _list_getitem(prelude), "aten::len": _list_len(prelude), "aten::type_as": _type_as(), "aten::gather": _gather(), "aten::index_select": _select(), "aten::index": _index(), "torchvision::nms": _nms(prelude), "aten::logsumexp": _logsumexp(), "torchvision::roi_align": _roi_align(prelude), "aten::unbind": _unbind(), "aten::__and__": _logical_and(), "aten::_shape_as_tensor": _shape_as_tensor(prelude), "aten::nonzero": _nonzero(False), "aten::nonzero_numpy": _nonzero(True), "aten::scatter": _scatter(), "aten::scalar_tensor": _scalar_tensor(), "aten::__interpolate": _interpolate(), "aten::IntImplicit": _identity(), "aten::tensor": _identity(), # used for example in tensor(1.0) "aten::numel": _numel(), "aten::empty": _empty(), } return convert_map def _run_jit_passes(graph): """ The inline pass is necessary to unwrap prim::CallMethod """ import torch if _is_version_greater_than("1.5.0"): # This is required for torchvision detection models from 1.6 above # It is the same as _jit_pass_inline, except that it has some special # case behaviors for some ops such as aten::__interpolate() torch._C._jit_pass_onnx_function_substitution(graph) else: torch._C._jit_pass_inline(graph) def _get_tensor_and_var(torch_tensor, name): tensor = tvm.nd.array(torch_tensor.cpu().numpy()) var = _expr.var(name, shape=tensor.shape, dtype=tensor.dtype) return tensor, var def _get_output_name(node): assert node.outputsSize() == 1 return node.output().debugName() def _get_output_names(node): return [output.debugName() for output in node.outputs()] def _get_input_names(node_or_graph): return [inp.debugName() for inp in node_or_graph.inputs()] def _get_op_inputs(op_node, outputs): return [outputs[name] for name in _get_input_names(op_node)] def _get_node_type(node): assert node.outputsSize() == 1 return node.output().type().kind() def _get_uses(node): uses = [] for output in node.outputs(): uses += output.uses() return uses def _get_users(node): return [use.user for use in _get_uses(node)] def _report_missing_conversion(op_names, convert_map): """ Check if all ops in an input graph are supported by TVM """ known_ops = [ "prim::Constant", "prim::GetAttr", "prim::ListConstruct", "prim::ListUnpack", "prim::TupleConstruct", "prim::TupleUnpack", "prim::If", "prim::Loop", ] known_ops += list(convert_map.keys()) known_ops += list(qnn_torch.convert_map.keys()) missing = [op_name for op_name in op_names if op_name not in known_ops] if missing: msg = "The following operators are not implemented: {}".format(missing) raise NotImplementedError(msg) def _getattr_attr_name(node): attribute_names = node.attributeNames() assert len(attribute_names) == 1 attr_name = node.s(attribute_names[0]) return attr_name def _getattr_full_name(getattrs): return ".".join([_getattr_attr_name(node) for node in getattrs]) def _get_pytorch_value_type(typ, default_dtype="float32"): kind = typ.kind() if kind == "TensorType": if typ.scalarType() is None: # Tensor's type can be unknown if we use torch.jit.script(...) # Defaults can be passed in, if not it is float32 logging.warning("Untyped Tensor found, assume it is %s", default_dtype) return default_dtype else: return _convert_data_type(typ.scalarType()) elif kind == "ListType": return "ListType" elif kind in ["IntType", "FloatType", "BoolType", "StringType", "OptionalType"]: pt_dtype = str(typ).lower() dtype = pt_dtype if pt_dtype == "OptionalType" else _convert_data_type(pt_dtype) return dtype else: return "UnsupportedType" def _get_input_types(op_node, outputs, default_dtype="float32"): """Returns a TVM dtype for each input nodes derived from the torch type""" in_types = [] for inp in op_node.inputs(): if inp.node().kind() == "prim::GetAttr": # GetAttr nodes always return None when we call scalarType() on it name = inp.debugName() assert name in outputs if isinstance(outputs[name], _expr.Var): in_types.append(outputs[name].type_annotation.dtype) else: # For quantized modules with parameters, here we would get # "prim::GetAttr[name="_packed_params"]". Since the dtype corresponding to # _packed_params is not needed by quantized ops, we return an arbitrary type. in_types.append(default_dtype) else: in_types.append(_get_pytorch_value_type(inp.type(), default_dtype=default_dtype)) return in_types def _get_constant(node): """ Retrieve a constant associated with this prim::Constant node """ attribute_names = node.attributeNames() num_attributes = len(attribute_names) if num_attributes == 1: attr_name = attribute_names[0] ty = node.output().type().kind() if ty == "IntType": return node.i(attr_name) elif ty == "BoolType": return bool(node.i(attr_name)) elif ty in ["FloatType", "LongType"]: return node.f(attr_name) elif ty in ["TensorType", "CompleteTensorType"]: tensor = node.t(attr_name) if tensor.is_cuda: tensor = tensor.cpu() if len(tensor.shape) == 0: # tensor(0.1) # TODO(t-vi): When is this needed? return tensor.item() return _wrap_const(tensor.numpy()) elif ty in ["DeviceObjType", "StringType"]: return node.s(attr_name) elif ty == "FunctionType": return None else: raise NotImplementedError("Unsupported type: %s" % ty) else: assert num_attributes == 0 return None def _get_operator_nodes(nodes): """ Returns torch IR nodes that need conversion to Relay """ ops = [] # Traverse nodes and add to graph for node in nodes: if node.outputsSize() > 1: node_name = "_".join(_get_output_names(node)) else: node_name = _get_output_name(node) if node.kind() != "prim::GetAttr": ops.append((node_name, node)) return ops def _get_relay_input_vars(graph, input_infos, prelude, is_module=True, default_dtype="float32"): """ Return Relay vars from input shapes and create entries based on expected graph inputs - to allow translation """ graph_inputs = list(graph.inputs()) if is_module: # a module has "self" as first input, which we do not need/want graph_inputs = graph_inputs[1:] if not isinstance(input_infos, list): msg = "Graph inputs input_infos should be a list" raise RuntimeError(msg) if len(graph_inputs) != len(input_infos): msg = "PyTorch has {} inputs and input_infos lists {}.".format( len(graph_inputs), len(input_infos) ) raise RuntimeError(msg) def get_relay_ty(ishape, itype, pt_type): if pt_type.kind() == "TensorType": if not (_is_int_seq(ishape) or len(ishape) == 0): msg = "Shape for Tensors must be lists of ints" raise RuntimeError(msg) if (pt_type.dim() is not None and pt_type.dim() != len(ishape)) or ( pt_type.sizes() is not None and any([s1 != s2 for s1, s2 in zip(pt_type.sizes(), ishape)]) ): msg = "Shapes of input list and information in the graph do not match" raise RuntimeError(msg) pt_dtype = pt_type.scalarType() if not pt_dtype and itype: pt_dtype = itype dtype = _convert_data_type(pt_dtype, default_dtype=default_dtype) return TensorType(ishape, dtype) elif pt_type.kind() == "TupleType": if not isinstance(ishape, tuple): msg = "Shapes for tuples must be tuples" raise RuntimeError(msg) return TupleType( [get_relay_ty(elem, itype, pt_t) for elem, pt_t in zip(ishape, pt_type.elements())] ) elif pt_type.kind() == "ListType": if not isinstance(ishape, list): msg = "Shapes for lists must be lists" raise RuntimeError(msg) pt_elemtype = pt_type.getElementType() elem_tys = [get_relay_ty(s, itype, pt_elemtype) for s in ishape] if len(elem_tys) > 0 and not all(map(lambda ty: ty == elem_tys[0], elem_tys)): msg = "List elements need have identical types" raise RuntimeError(msg) rlist, _, _ = prelude.mod.get_type("List") return rlist(elem_tys[0]) elif pt_type.kind() == "OptionalType": # we do not support None yet, so we fill in the type return get_relay_ty(ishape, itype, pt_type.getElementType()) # TODO: scalar inputs raise NotImplementedError("unsupported input type") input_vars = {} new_input_infos = [] for num, inp in enumerate(input_infos): if not isinstance(inp, tuple): msg = "Graph input {} is not a tuple".format(num) raise RuntimeError(msg) if len(inp) != 2 or not isinstance(inp[0], str): msg = ( "Graph input {} is not valid," " expected ('name', shape) or ('name', (shape, dtype))".format(inp) ) raise RuntimeError(msg) if not isinstance(inp[1], tuple) or len(inp[1]) == 0 or not isinstance(inp[1][-1], str): new_input_infos.append((inp[0], (inp[1], default_dtype))) else: new_input_infos.append(inp) input_types = [ (name, get_relay_ty(info[0], info[1], gi.type())) for (name, info), gi in zip(new_input_infos, graph_inputs) ] ir_inputs = [i.debugName() for i in graph_inputs] for ir_input, (name, itype) in zip(ir_inputs, input_types): inp = _expr.var(name, type_annotation=itype) # Translate from graph input to user input name input_vars[ir_input] = inp return input_vars def _unpack_tuple(tup): def unpack(tup, num_fields): return [_expr.TupleGetItem(tup, i) for i in range(num_fields)] if isinstance(tup, _expr.Tuple): return unpack(tup, len(tup.fields)) elif isinstance(tup.type_annotation, TupleType): return unpack(tup, len(tup.type_annotation.fields)) # shouldn't happen assert False def _get_free_vars_from_block(block): block_inp_names = _get_input_names(block) bound_names = block_inp_names free_vars = set() for node in block.nodes(): inp_names = _get_input_names(node) list_diff = [name for name in inp_names if name not in bound_names] free_vars.update(list_diff) bound_names += _get_output_names(node) return free_vars def get_use_chains(root_node, terminate=lambda _: False): """ Track a chain of users of this node forward, returning a list of chains See get_attr_chains below for its usage """ def concat_lists(lists): return itertools.chain.from_iterable(lists) def inner(current, accum): users = _get_users(current) if not users or terminate(users): return [accum] return concat_lists([inner(nxt, accum + [nxt]) for nxt in users]) return inner(root_node, [root_node]) def get_attr_chains(root_getattr_node): """Returns chains of attribute access starting from root_getattr_node For example, given attribute "block", as in "self.block" when "self" points to the top level torch.nn.Module, it returns lists of attribute "chains", e.g. ['block', '2'], ['block', '1'], ['block', '0', '_packed_params'] These sets of attributes form full attribute accessors. For example, "self.block.1", "self.block.2" will return the second and third submodule, and "self.block.0._packed_params" will return the parameters of the first submodule. """ def terminate(users): next_attrs = [user for user in users if user.kind() == "prim::GetAttr"] return len(next_attrs) == 0 return get_use_chains(root_getattr_node, terminate) def convert_params(graph, state_dict): """ Return Relay vars and TVM NDArrays for input parameters A chain of prim::GetAttr nodes is processed one at a time """ getattr_nodes = graph.findAllNodes("prim::GetAttr", recurse=True) params = {} param_tensors = {} packed_param_map = {} vars_by_name = {} seen = set() for node in getattr_nodes: if _get_output_name(node) in seen: continue for getattrs in get_attr_chains(node): seen.update(map(_get_output_name, getattrs)) full_attr = _getattr_full_name(getattrs) full_attr_node_name = _get_output_name(getattrs[-1]) if full_attr.endswith("_packed_params"): # for quantized models err_msg = "parameter %s not found in state dict" % full_attr assert full_attr in state_dict, err_msg packed_param_map[full_attr_node_name] = full_attr elif full_attr in state_dict: if full_attr in vars_by_name: var = vars_by_name[full_attr] else: torch_tensor = state_dict[full_attr] tensor, var = _get_tensor_and_var(torch_tensor, full_attr) param_tensors[full_attr] = tensor vars_by_name[full_attr] = var params[full_attr_node_name] = var return params, param_tensors, packed_param_map def convert_block(block, outputs, convert_map, prelude, default_dtype="float32"): """ Translate Torch "Block", used for prim::If and prim::Loop """ ops = _get_operator_nodes(block.nodes()) ret_names = _get_input_names(block.returnNode()) return convert_operators( ops, outputs, ret_names, convert_map, prelude, default_dtype=default_dtype ) def convert_if(if_node, outputs, convert_map, prelude, default_dtype="float32"): """ Translate Torch prim::If to Relay If """ cond = outputs[if_node.inputsAt(0).debugName()] blocks = list(if_node.blocks()) true_branch = convert_block( blocks[0], outputs, convert_map, prelude, default_dtype=default_dtype ) false_branch = convert_block( blocks[1], outputs, convert_map, prelude, default_dtype=default_dtype ) assert len(true_branch) == 1 and len(false_branch) == 1 return _expr.If(cond, true_branch[0], false_branch[0]) def convert_loop(loop_node, outputs, convert_map, prelude): """ Translate Torch prim::Loop to Relay while_loop """ def get_input(index): ivalue = loop_node.inputsAt(index) inode = ivalue.node() if inode.kind() == "prim::Constant": return _expr.const(_get_constant(inode)) var_name = ivalue.debugName() assert var_name in outputs return _wrap_const(outputs[var_name]) # Refer to the spec for prim::Loop below # https://github.com/pytorch/pytorch/blob/master/torch/csrc/jit/OVERVIEW.md#loops # The first input: %max_trip_count # The second input: %initial_condition # The rest of input: loop variables max_loop_count = get_input(0) init_cond = get_input(1) num_loop_var = len(list(loop_node.inputs())) - 2 init_vals = [get_input(i + 2) for i in range(num_loop_var)] # while loop has always max_loop_count being int64 max # max_loop_count.data (tvm.runtime.NDArray) is -1, so _get_constant again is_while_loop = ( isinstance(max_loop_count, _expr.Constant) and _get_constant(loop_node.inputsAt(0).node()) == sys.maxsize ) if is_while_loop: loop_iter_dtype = "bool" # while loop with non input dependent condition such as while i < 10: # init_cond is int, need to cast to bool to type check if isinstance(init_cond, _expr.Constant): init_cond = _op.cast(init_cond, "bool") init_loop_iter_val = init_cond else: loop_iter_dtype = "int32" # always count from 0 init_loop_iter_val = _expr.const(0, dtype="int32") body_block = list(loop_node.blocks())[0] block_input_names = _get_input_names(body_block) num_block_inputs = len(block_input_names) name_val_pairs = list(zip(block_input_names, [init_loop_iter_val] + init_vals)) outputs.update(name_val_pairs) def get_var(name, val): if val: checked_type = _infer_type_with_prelude(val, prelude) if hasattr(checked_type, "shape"): shape = get_const_tuple(checked_type.shape) actual_shape = [] for dim in shape: if isinstance(dim, int) and dim == 0: actual_shape.append(Any()) else: actual_shape.append(dim) return _expr.var(name, shape=actual_shape, dtype=checked_type.dtype) else: return _expr.var(name, type_annotation=checked_type) return _expr.var(name) loop_iter_var = _expr.var(block_input_names[0], shape=(), dtype=loop_iter_dtype) loop_vars = [get_var(name, val) for name, val in name_val_pairs[1:]] # Add non constant free variables to loop variables to prevent code blow up # Without this, if there are two for loops in a row, which often happens # if the outer loop is unrolled, the computation corresponding to the first for loop # is inlined inside loop body, turning O(N) + O(N) computation into O(N^2). # This issue was found when converting from Stacked LSTM test. Torch does not add the output # of the eariler loop into loop variables of the next loop. # So the variable corresponding to the first loop output appears free in the second loop body. free_vars = [ var for var in _get_free_vars_from_block(body_block) if var in outputs and not isinstance(outputs[var], (_expr.Constant, int, float, str)) and outputs[var] ] prev_outputs = {} for name in free_vars: prev_output = outputs[name] new_loop_var = get_var(name, prev_output) prev_outputs[name] = prev_output outputs[name] = new_loop_var loop_vars.append(new_loop_var) init_vals.append(prev_output) def cond(*current_vals): i = current_vals[0] if is_while_loop: return _op.equal(i, _expr.const(True, "bool")) return _op.less(i, max_loop_count) def body(*current_vals): # Update loop variables using the prev iteration outputs assert len(current_vals) == num_block_inputs + len(free_vars) for (i, val) in enumerate(current_vals): if i < num_block_inputs: outputs[block_input_names[i]] = val else: outputs[free_vars[i - num_block_inputs]] = val block_outputs = convert_block(body_block, outputs, convert_map, prelude) block_outputs += [outputs[name] for name in free_vars] if not is_while_loop: # iter var increment implicit in torch, so do it manually # for while loop, block_outputs[0] is already a boolean, # the result of termination check incr = _expr.const(1, dtype="int32") block_outputs[0] = current_vals[0] + incr return block_outputs loop = while_loop(cond, [loop_iter_var] + loop_vars, body) loop_val = loop(init_loop_iter_val, *init_vals) # restore original output values for free vars outputs.update(prev_outputs) # The first element is a loop counter or boolean condition, ignore it return [_expr.TupleGetItem(loop_val, i + 1) for i in range(num_loop_var)] def convert_operators(operators, outputs, ret_names, convert_map, prelude, default_dtype="float32"): """ Convert each Torch IR operators to Relay equivalent """ for node_name, op_node in operators: operator = op_node.kind() inputs = _get_op_inputs(op_node, outputs) if operator == "prim::Constant": outputs[node_name] = _get_constant(op_node) elif operator == "prim::ListConstruct" and _should_construct_dynamic_list(op_node): outputs[node_name] = _convert_to_list_adt(inputs, prelude) elif operator == "prim::ListConstruct": # This assumes that no more elements will be appended to this list # In this case, we keep the Python list outputs[node_name] = inputs elif operator == "prim::TupleConstruct": outputs[node_name] = _expr.Tuple(inputs) elif operator in ["prim::ListUnpack", "prim::TupleUnpack"]: assert len(inputs) == 1 if isinstance(inputs[0], (list, _expr.TupleWrapper)): unpacked = inputs[0] else: unpacked = _unpack_tuple(inputs[0]) outputs.update(zip(_get_output_names(op_node), unpacked)) elif operator == "prim::If": if_out = convert_if(op_node, outputs, convert_map, prelude, default_dtype=default_dtype) outputs[node_name] = if_out elif operator == "prim::Loop": loop_out = convert_loop(op_node, outputs, convert_map, prelude) unpacked_names = _get_output_names(op_node) assert len(loop_out) == len(unpacked_names) outputs.update(zip(unpacked_names, loop_out)) else: relay_op = convert_map[operator] relay_out = relay_op( inputs, _get_input_types(op_node, outputs, default_dtype=default_dtype) ) if isinstance(relay_out, tuple): # This is for torch operators that return multiple outputs # See _adaptive_max_2d above for example out_names = _get_output_names(op_node) outputs.update(zip(out_names, relay_out)) else: assert op_node.outputsSize() == 1 outputs[node_name] = relay_out return [_wrap_const(outputs[ret_name]) for ret_name in ret_names] def get_all_op_names(graph): """ Return all operator names in the input graph """ nodes = list(graph.nodes()) prim_with_blocks = ["prim::If", "prim::Loop"] for prim in prim_with_blocks: prim_nodes = graph.findAllNodes(prim, recurse=True) for prim_node in prim_nodes: for block in prim_node.blocks(): nodes += block.nodes() return set(node.kind() for node in nodes) def from_pytorch(script_module, input_infos, custom_convert_map=None, default_dtype="float32"): """Load PyTorch model in the form of a scripted PyTorch model and convert into relay. The companion parameters will be handled automatically. Parameters ---------- script_module : TopLevelTracedModule object TorchScripted PyTorch graph Note: We currently only support traces (ie: torch.jit.trace(model, input)) input_infos: List of tuples of (input name, input shape) or (input name, (input shape, input types)) Graph level input shape and type list The same input names need to be used for deployment, so choose easy to remember names (such as: input0, input1) e.g. [('input0', (1, 2)), ('input1', (3, 4))] or [('input0', ((1, 2), 'int')), ('input1', ((3, 4), 'float'))] custom_convert_map: Dictionary of str to Relay op A custom op conversion map in the same format as _convert_map above Returns ------- mod : tvm.relay.Module The module that optimizations will be performed on. params : dict of str to tvm.runtime.NDArray Dict of converted parameters stored in tvm.runtime.ndarray format """ import torch mod = tvm.IRModule() prelude = Prelude(mod) convert_map = _get_convert_map(prelude, default_dtype) graph = script_module.graph.copy() _run_jit_passes(graph) if custom_convert_map: convert_map.update(custom_convert_map) op_names = get_all_op_names(graph) _report_missing_conversion(op_names, convert_map) is_module = isinstance(script_module, torch.jit.ScriptModule) params = script_module.state_dict() if is_module else {} outputs = _get_relay_input_vars( graph, input_infos, prelude, default_dtype=default_dtype, is_module=is_module ) param_vars, tensors, packed_param_map = convert_params(graph, params) tvm_params = {k: tvm.nd.array(v) for k, v in tensors.items()} outputs.update(param_vars) ret_name = _get_input_names(graph.return_node()) # For quantized models if "aten::quantize_per_tensor" in op_names: weight_quant_params = qnn_torch.get_weight_quant_params(script_module) qnn_torch.add_input_quant_params_to_op_inputs(graph) qnn_torch.add_quant_params_to_outputs(outputs, packed_param_map, weight_quant_params) qnn_torch.add_quant_params(tvm_params, weight_quant_params) convert_map.update(qnn_torch.convert_map) ret = convert_operators( _get_operator_nodes(graph.nodes()), outputs, ret_name, convert_map, prelude, default_dtype=default_dtype, ) mod["main"] = tvm.relay.Function(_analysis.free_vars(ret[0]), ret[0]) return transform.RemoveUnusedFunctions()(mod), tvm_params
{ "content_hash": "9950fb45c27ab5c3ceefe271cac16072", "timestamp": "", "source": "github", "line_count": 3360, "max_line_length": 100, "avg_line_length": 31.205952380952382, "alnum_prop": 0.5607522984778545, "repo_name": "sxjscience/tvm", "id": "8e626f52d528202550b08d5209f9461bc65c3421", "size": "105978", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/tvm/relay/frontend/pytorch.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "6056" }, { "name": "C", "bytes": "95567" }, { "name": "C++", "bytes": "5565032" }, { "name": "CMake", "bytes": "67305" }, { "name": "Go", "bytes": "112376" }, { "name": "HTML", "bytes": "8625" }, { "name": "Java", "bytes": "173219" }, { "name": "JavaScript", "bytes": "49801" }, { "name": "Makefile", "bytes": "50818" }, { "name": "Objective-C", "bytes": "15264" }, { "name": "Objective-C++", "bytes": "46673" }, { "name": "Python", "bytes": "6763729" }, { "name": "Rust", "bytes": "182027" }, { "name": "Scala", "bytes": "184105" }, { "name": "Shell", "bytes": "96967" }, { "name": "Tcl", "bytes": "53645" }, { "name": "Verilog", "bytes": "30605" } ], "symlink_target": "" }
using System; using System.ComponentModel; namespace Azure.Search.Documents.Indexes.Models { /// <summary> A string indicating what entity categories to return. </summary> public readonly partial struct EntityCategory : IEquatable<EntityCategory> { private readonly string _value; /// <summary> Initializes a new instance of <see cref="EntityCategory"/>. </summary> /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception> public EntityCategory(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } private const string LocationValue = "location"; private const string OrganizationValue = "organization"; private const string PersonValue = "person"; private const string QuantityValue = "quantity"; private const string DatetimeValue = "datetime"; private const string UrlValue = "url"; private const string EmailValue = "email"; /// <summary> Entities describing a physical location. </summary> public static EntityCategory Location { get; } = new EntityCategory(LocationValue); /// <summary> Entities describing an organization. </summary> public static EntityCategory Organization { get; } = new EntityCategory(OrganizationValue); /// <summary> Entities describing a person. </summary> public static EntityCategory Person { get; } = new EntityCategory(PersonValue); /// <summary> Entities describing a quantity. </summary> public static EntityCategory Quantity { get; } = new EntityCategory(QuantityValue); /// <summary> Entities describing a date and time. </summary> public static EntityCategory Datetime { get; } = new EntityCategory(DatetimeValue); /// <summary> Entities describing a URL. </summary> public static EntityCategory Url { get; } = new EntityCategory(UrlValue); /// <summary> Entities describing an email address. </summary> public static EntityCategory Email { get; } = new EntityCategory(EmailValue); /// <summary> Determines if two <see cref="EntityCategory"/> values are the same. </summary> public static bool operator ==(EntityCategory left, EntityCategory right) => left.Equals(right); /// <summary> Determines if two <see cref="EntityCategory"/> values are not the same. </summary> public static bool operator !=(EntityCategory left, EntityCategory right) => !left.Equals(right); /// <summary> Converts a string to a <see cref="EntityCategory"/>. </summary> public static implicit operator EntityCategory(string value) => new EntityCategory(value); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is EntityCategory other && Equals(other); /// <inheritdoc /> public bool Equals(EntityCategory other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; /// <inheritdoc /> public override string ToString() => _value; } }
{ "content_hash": "df6b7bab6064e9c32b02445a27d9f83f", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 133, "avg_line_length": 56.220338983050844, "alnum_prop": 0.6750075369309617, "repo_name": "Azure/azure-sdk-for-net", "id": "88684f5b52f37274a7fb044fa39ca8e718228713", "size": "3455", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "sdk/search/Azure.Search.Documents/src/Generated/Models/EntityCategory.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>Laser Scanner infoscreen: src/measure_biometrics.cpp File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Laser Scanner infoscreen &#160;<span id="projectnumber">1.0</span> </div> <div id="projectbrief">SICK 561 -controlled infoscreen, source code for Summer 2017 Protopaja project at Aalto University</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> &#124; <a href="#define-members">Macros</a> &#124; <a href="#func-members">Functions</a> &#124; <a href="#var-members">Variables</a> </div> <div class="headertitle"> <div class="title">measure_biometrics.cpp File Reference</div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><code>#include &quot;ros/ros.h&quot;</code><br /> <code>#include &quot;ros/topic.h&quot;</code><br /> <code>#include &quot;sensor_msgs/LaserScan.h&quot;</code><br /> <code>#include &quot;laser_scanner_infoscreen/biometrics.h&quot;</code><br /> <code>#include &quot;laser_scanner_infoscreen/biometrics_results.h&quot;</code><br /> <code>#include &quot;laser_scanner_infoscreen/servo_control.h&quot;</code><br /> <code>#include &quot;laser_scanner_infoscreen/servo_feedback.h&quot;</code><br /> <code>#include &lt;cstdlib&gt;</code><br /> <code>#include &lt;visualization_msgs/Marker.h&gt;</code><br /> <code>#include &lt;math.h&gt;</code><br /> <code>#include &lt;chrono&gt;</code><br /> <code>#include &lt;thread&gt;</code><br /> </div><div class="textblock"><div class="dynheader"> Include dependency graph for measure_biometrics.cpp:</div> <div class="dyncontent"> <div class="center"><img src="measure__biometrics_8cpp__incl.png" border="0" usemap="#src_2measure__biometrics_8cpp" alt=""/></div> </div> </div><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structservo__angle__t.html">servo_angle_t</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="define-members"></a> Macros</h2></td></tr> <tr class="memitem:a652fa32c4482bb0d3805c3c5f5900af5"><td class="memItemLeft" align="right" valign="top">#define&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="measure__biometrics_8cpp.html#a652fa32c4482bb0d3805c3c5f5900af5">servo_speed_const</a>&#160;&#160;&#160;5235</td></tr> <tr class="separator:a652fa32c4482bb0d3805c3c5f5900af5"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:a4097f5bdd8d9b874738cfeb7fd72828c"><td class="memItemLeft" align="right" valign="top">float&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="measure__biometrics_8cpp.html#a4097f5bdd8d9b874738cfeb7fd72828c">calculate_range</a> (float angle_h, float low_range)</td></tr> <tr class="separator:a4097f5bdd8d9b874738cfeb7fd72828c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a4ad0813f9401699c8840005f44ac4891"><td class="memItemLeft" align="right" valign="top">float&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="measure__biometrics_8cpp.html#a4ad0813f9401699c8840005f44ac4891">set_tilt_uppper_scanner</a> (float rad)</td></tr> <tr class="separator:a4ad0813f9401699c8840005f44ac4891"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a5b62649fd6ccd78f4595bd3e1329e2c3"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="measure__biometrics_8cpp.html#a5b62649fd6ccd78f4595bd3e1329e2c3">biometrics_callback</a> (const laser_scanner_infoscreen::biometrics::ConstPtr &amp;<a class="el" href="gesture__control_8cpp.html#a1aa23b898528eadf4c747440d5e8a396">poi</a>)</td></tr> <tr class="separator:a5b62649fd6ccd78f4595bd3e1329e2c3"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a272dea7f151f9bf75131542422903056"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="measure__biometrics_8cpp.html#a272dea7f151f9bf75131542422903056">servo_feedback_callback</a> (const laser_scanner_infoscreen::servo_feedback &amp;msg)</td></tr> <tr class="separator:a272dea7f151f9bf75131542422903056"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a3c04138a5bfe5d72780bb7e82a18e627"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="measure__biometrics_8cpp.html#a3c04138a5bfe5d72780bb7e82a18e627">main</a> (int argc, char **argv)</td></tr> <tr class="separator:a3c04138a5bfe5d72780bb7e82a18e627"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="var-members"></a> Variables</h2></td></tr> <tr class="memitem:a63b0cea48d2da7a328302aee063e57b9"><td class="memItemLeft" align="right" valign="top">ros::Publisher *&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="measure__biometrics_8cpp.html#a63b0cea48d2da7a328302aee063e57b9">marker_pub_pointer</a></td></tr> <tr class="separator:a63b0cea48d2da7a328302aee063e57b9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad7c4130fa2a9b5b52c9cc9762accfe31"><td class="memItemLeft" align="right" valign="top">ros::Publisher *&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="measure__biometrics_8cpp.html#ad7c4130fa2a9b5b52c9cc9762accfe31">servo_control_pointer</a></td></tr> <tr class="separator:ad7c4130fa2a9b5b52c9cc9762accfe31"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a859597d1d3be30a6f99cb8051a03d0c8"><td class="memItemLeft" align="right" valign="top">ros::Publisher *&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="measure__biometrics_8cpp.html#a859597d1d3be30a6f99cb8051a03d0c8">biometrics_results_pointer</a></td></tr> <tr class="separator:a859597d1d3be30a6f99cb8051a03d0c8"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad1749a3f174e5a1ea7406541575cc99d"><td class="memItemLeft" align="right" valign="top">struct <a class="el" href="structservo__angle__t.html">servo_angle_t</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="measure__biometrics_8cpp.html#ad1749a3f174e5a1ea7406541575cc99d">servo_angle</a></td></tr> <tr class="separator:ad1749a3f174e5a1ea7406541575cc99d"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Macro Definition Documentation</h2> <a class="anchor" id="a652fa32c4482bb0d3805c3c5f5900af5"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define servo_speed_const&#160;&#160;&#160;5235</td> </tr> </table> </div><div class="memdoc"> </div> </div> <h2 class="groupheader">Function Documentation</h2> <a class="anchor" id="a5b62649fd6ccd78f4595bd3e1329e2c3"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void biometrics_callback </td> <td>(</td> <td class="paramtype">const laser_scanner_infoscreen::biometrics::ConstPtr &amp;&#160;</td> <td class="paramname"><em>poi</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="a4097f5bdd8d9b874738cfeb7fd72828c"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">float calculate_range </td> <td>(</td> <td class="paramtype">float&#160;</td> <td class="paramname"><em>angle_h</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">float&#160;</td> <td class="paramname"><em>low_range</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="a3c04138a5bfe5d72780bb7e82a18e627"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int main </td> <td>(</td> <td class="paramtype">int&#160;</td> <td class="paramname"><em>argc</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">char **&#160;</td> <td class="paramname"><em>argv</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="a272dea7f151f9bf75131542422903056"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void servo_feedback_callback </td> <td>(</td> <td class="paramtype">const laser_scanner_infoscreen::servo_feedback &amp;&#160;</td> <td class="paramname"><em>msg</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="a4ad0813f9401699c8840005f44ac4891"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">float set_tilt_uppper_scanner </td> <td>(</td> <td class="paramtype">float&#160;</td> <td class="paramname"><em>rad</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> </div> </div> <h2 class="groupheader">Variable Documentation</h2> <a class="anchor" id="a859597d1d3be30a6f99cb8051a03d0c8"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">ros::Publisher* biometrics_results_pointer</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="a63b0cea48d2da7a328302aee063e57b9"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">ros::Publisher* marker_pub_pointer</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="ad1749a3f174e5a1ea7406541575cc99d"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">struct <a class="el" href="structservo__angle__t.html">servo_angle_t</a> servo_angle</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="ad7c4130fa2a9b5b52c9cc9762accfe31"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">ros::Publisher* servo_control_pointer</td> </tr> </table> </div><div class="memdoc"> </div> </div> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
{ "content_hash": "2bddb04b6f65bdb89ed12860d7c834e9", "timestamp": "", "source": "github", "line_count": 321, "max_line_length": 429, "avg_line_length": 46.47040498442367, "alnum_prop": 0.6564322584970168, "repo_name": "GeodesicCarbon/protopaja-sick", "id": "5eb6504314b30ac18b45a657885ebac220ef9577", "size": "14917", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/laser_scanner_infoscreen/docs/html/measure__biometrics_8cpp.html", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "6831" }, { "name": "C", "bytes": "60197" }, { "name": "C++", "bytes": "1843703" }, { "name": "CMake", "bytes": "231633" }, { "name": "CSS", "bytes": "31495" }, { "name": "Common Lisp", "bytes": "244154" }, { "name": "EmberScript", "bytes": "565" }, { "name": "HTML", "bytes": "415598" }, { "name": "JavaScript", "bytes": "140932" }, { "name": "Makefile", "bytes": "7868" }, { "name": "Processing", "bytes": "20189" }, { "name": "Python", "bytes": "200490" }, { "name": "Shell", "bytes": "7127" }, { "name": "TeX", "bytes": "92431" }, { "name": "XSLT", "bytes": "645" } ], "symlink_target": "" }
cask "sequel-ace" do version "3.4.1,3041" sha256 "99c337ff24561b7161c056604b8ee1c91bd85d0dc371e2a26690e8d0b7069382" url "https://github.com/Sequel-Ace/Sequel-Ace/releases/download/production/#{version.before_comma}-#{version.after_comma}/Sequel-Ace-#{version.before_comma}.zip" name "Sequel Ace" desc "MySQL/MariaDB database management" homepage "https://github.com/Sequel-Ace/Sequel-Ace" livecheck do url :url strategy :git do |tags| tags.map do |tag| match = tag.match(%r{^production/(\d+(?:\.\d+)*)-(\d+)$}i) "#{match[1]},#{match[2]}" if match end.compact end end app "Sequel Ace.app" zap trash: [ "~/Library/Application Support/Sequel Ace", "~/Library/Caches/com.sequelace.SequelAce", "~/Library/Preferences/com.sequelace.SequelAce.plist", "~/Library/Saved Application State/com.sequelace.SequelAce.savedState", ] end
{ "content_hash": "1ad2584bd0bf11282d1dde24943115d5", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 163, "avg_line_length": 32.285714285714285, "alnum_prop": 0.6836283185840708, "repo_name": "caskroom/homebrew-cask", "id": "ccb028c2f3490b4eb626bb004ce7f4dc8bfb5ad4", "size": "904", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Casks/sequel-ace.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "2309113" }, { "name": "Shell", "bytes": "39520" } ], "symlink_target": "" }
[See all contributors on GitHub](https://github.com/maliceio/malice/graphs/contributors). Please update the [CHANGELOG.md](https://github.com/maliceio/malice/blob/master/CHANGELOG.md) and submit a [Pull Request on GitHub](https://help.github.com/articles/using-pull-requests/).
{ "content_hash": "8a07f0a45847154eb38ad82ae6b75ac7", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 187, "avg_line_length": 93, "alnum_prop": 0.7849462365591398, "repo_name": "blacktop/go-malice", "id": "f5468f6c7a27ee966bb1acb9eca8e673fd3d9028", "size": "295", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CONTRIBUTING.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "104768" }, { "name": "HTML", "bytes": "225" }, { "name": "JavaScript", "bytes": "1395" }, { "name": "Makefile", "bytes": "1732" }, { "name": "Shell", "bytes": "5276" } ], "symlink_target": "" }
<?php namespace PDepend\Source\AST; /** * This class represents a compound expression node. * * <code> * // ----- * Foo::${BAR}(); * // ----- * * // ----- * Foo::$${BAR}(); * // ----- * * // ----- * $foo->{BAR}(); * // ----- * </code> * * @copyright 2008-2013 Manuel Pichler. All rights reserved. * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @since 0.9.6 */ class ASTCompoundExpression extends \PDepend\Source\AST\ASTNode { /** * Accept method of the visitor design pattern. This method will be called * by a visitor during tree traversal. * * @param \PDepend\Source\ASTVisitor\ASTVisitor $visitor The calling visitor instance. * @param mixed $data * * @return mixed * @since 0.9.12 */ public function accept(\PDepend\Source\ASTVisitor\ASTVisitor $visitor, $data = null) { return $visitor->visitCompoundExpression($this, $data); } }
{ "content_hash": "15d10e76996c568f6d6286f5e6a20701", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 90, "avg_line_length": 23.6046511627907, "alnum_prop": 0.5605911330049261, "repo_name": "sustmi/pdepend", "id": "980bc6352318e16a5fa6b563e3be648fe3e4bec5", "size": "2857", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "src/main/php/PDepend/Source/AST/ASTCompoundExpression.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1924" }, { "name": "C++", "bytes": "444" }, { "name": "CSS", "bytes": "9861" }, { "name": "PHP", "bytes": "3722756" }, { "name": "Shell", "bytes": "498" }, { "name": "XSLT", "bytes": "1544" } ], "symlink_target": "" }
package cache import ( "io/ioutil" "os" "path" ) // FSCache is an implementation of Cache that stores information in the // filesystem type FSCache struct { Root string } // NewFSCache returns a FileSystemcache with defaults set, and makes // sure that the FSCache has a directory to store info in. func NewFSCache(root string) (Cache, error) { fs := &FSCache{root} err := fs.Setup() return fs, err } // Setup creates the directory for storage, if it doesn't exist func (fs *FSCache) Setup() error { err := os.MkdirAll(fs.Root, os.ModeDir|0777) return err } // Get returns the content under key or ErrNoSuchKey func (fs *FSCache) Get(key string) ([]byte, error) { content, err := ioutil.ReadFile(path.Join(fs.Root, key)) if os.IsNotExist(err) { return content, ErrNoSuchKey } return content, err } // Set writes the content under the given key func (fs *FSCache) Set(key string, content []byte) error { return ioutil.WriteFile( path.Join(fs.Root, key), content, 0600, ) } // Keys returns the keys managed by this cache func (fs *FSCache) Keys() ([]string, error) { keys := []string{} files, err := ioutil.ReadDir(fs.Root) if err != nil { return keys, err } for _, entry := range files { if entry.IsDir() { continue } keys = append(keys, entry.Name()) } return keys, nil } // Delete removes a key or returns ErrNoSuchKey func (fs *FSCache) Delete(key string) error { err := os.Remove(path.Join(fs.Root, key)) if os.IsNotExist(err) { return ErrNoSuchKey } return err }
{ "content_hash": "916c1a8bc505020286b38b414d562ce2", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 71, "avg_line_length": 20.36, "alnum_prop": 0.6856581532416502, "repo_name": "asteris-llc/hammer", "id": "55bf90a3cd96b107ba63a2111c9f924d3218d0bd", "size": "1527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hammer/cache/fs.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "43997" }, { "name": "Makefile", "bytes": "897" } ], "symlink_target": "" }
import datetime import dateutil.tz from dateutil.parser import parse as parse_date class AssetState: """AssetState is used instead of primitive state values (like ``2``, ``"a"`` or ``True``) when publishing data with a custom timestamp, i.e. not the current timestamp at the time of publishing.""" def __init__(self, value, at=None): """Initializes the asset state. :param value: Any JSON-serializable value applicable to the given :class:`~allthingstalk.Asset`. :param datetime.datetime at: Optional timestamp """ self.value = value if at is None: self.at = datetime.datetime.utcnow() elif isinstance(at, str): self.at = parse_date(at) elif isinstance(at, datetime.datetime): self.at = at else: raise ValueError('Invalid timestamp in at: %s' % at) if self.at.tzinfo is None: self.at = self.at.replace(tzinfo=dateutil.tz.tzutc()) def __repr__(self): return 'AssetState(value=%s, at=%s)' % (self.value, self.at) def __str__(self): return str(self.value)
{ "content_hash": "e22e2d5f886298557e5f11af379b90cc", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 104, "avg_line_length": 32.6, "alnum_prop": 0.6108676599474145, "repo_name": "allthingstalk/python-sdk", "id": "5f686e143a32bae57f369806ca8d5856ee7c8707", "size": "2040", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "allthingstalk/asset_state.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "790" }, { "name": "Makefile", "bytes": "619" }, { "name": "Python", "bytes": "32083" }, { "name": "Shell", "bytes": "50" } ], "symlink_target": "" }
'use strict'; /** * Post link tag * * Syntax: * {% post_link slug [title] %} */ module.exports = function(ctx){ var Post = ctx.model('Post'); return function postLinkTag(args){ var slug = args.shift(); if (!slug) return; var post = Post.findOne({slug: slug}); if (!post) return; var title = args.length ? args.join(' ') : post.title; return '<a href="' + ctx.config.root + post.path + '" title="' + title + '">' + title + '</a>'; }; };
{ "content_hash": "45dfba8e4ba0fa6d2272774a883b40ea", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 99, "avg_line_length": 21.695652173913043, "alnum_prop": 0.5290581162324649, "repo_name": "hejiheji001/HexoBlog", "id": "1cde2cb17ef5682c036195b83cca56d15b7352fa", "size": "499", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/hexo/lib/plugins/tag/post_link.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "118210" }, { "name": "HTML", "bytes": "999055" }, { "name": "JavaScript", "bytes": "83623" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_37) on Mon Mar 25 00:16:18 EDT 2013 --> <TITLE> OpacityPropertyTest </TITLE> <META NAME="date" CONTENT="2013-03-25"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="OpacityPropertyTest"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/OpacityPropertyTest.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../../edu/american/student/stonewall/display/css/property/OpacityProperty.html" title="class in edu.american.student.stonewall.display.css.property"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../edu/american/student/stonewall/display/css/property/OutlineProperty.html" title="class in edu.american.student.stonewall.display.css.property"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?edu/american/student/stonewall/display/css/property/OpacityPropertyTest.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="OpacityPropertyTest.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> edu.american.student.stonewall.display.css.property</FONT> <BR> Class OpacityPropertyTest</H2> <PRE> java.lang.Object <IMG SRC="../../../../../../../resources/inherit.gif" ALT="extended by "><B>edu.american.student.stonewall.display.css.property.OpacityPropertyTest</B> </PRE> <HR> <DL> <DT><PRE>public class <B>OpacityPropertyTest</B><DT>extends java.lang.Object</DL> </PRE> <P> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../../../edu/american/student/stonewall/display/css/property/OpacityPropertyTest.html#OpacityPropertyTest()">OpacityPropertyTest</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../../edu/american/student/stonewall/display/css/property/OpacityPropertyTest.html#test()">test</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="OpacityPropertyTest()"><!-- --></A><H3> OpacityPropertyTest</H3> <PRE> public <B>OpacityPropertyTest</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="test()"><!-- --></A><H3> test</H3> <PRE> public void <B>test</B>()</PRE> <DL> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/OpacityPropertyTest.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../../edu/american/student/stonewall/display/css/property/OpacityProperty.html" title="class in edu.american.student.stonewall.display.css.property"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../edu/american/student/stonewall/display/css/property/OutlineProperty.html" title="class in edu.american.student.stonewall.display.css.property"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?edu/american/student/stonewall/display/css/property/OpacityPropertyTest.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="OpacityPropertyTest.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
{ "content_hash": "be2d43f87d68fb3698b4881392c4eced", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 212, "avg_line_length": 41.34920634920635, "alnum_prop": 0.6212092130518234, "repo_name": "Ccook/Stonewall", "id": "784db5765afb186884957a5b2a8163281e02f865", "size": "10420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javadoc/edu/american/student/stonewall/display/css/property/OpacityPropertyTest.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "853867" }, { "name": "JavaScript", "bytes": "217" } ], "symlink_target": "" }
<?php namespace Symfony\Component\Validator\Mapping; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\GroupSequence; use Symfony\Component\Validator\Constraints\Traverse; use Symfony\Component\Validator\Constraints\Valid; use Symfony\Component\Validator\Exception\ConstraintDefinitionException; use Symfony\Component\Validator\Exception\GroupDefinitionException; /** * Default implementation of {@link ClassMetadataInterface}. * * This class supports serialization and cloning. * * @author Bernhard Schussek <[email protected]> * @author Fabien Potencier <[email protected]> */ class ClassMetadata extends GenericMetadata implements ClassMetadataInterface { /** * @var string * * @internal This property is public in order to reduce the size of the * class' serialized representation. Do not access it. Use * {@link getClassName()} instead. */ public $name; /** * @var string * * @internal This property is public in order to reduce the size of the * class' serialized representation. Do not access it. Use * {@link getDefaultGroup()} instead. */ public $defaultGroup; /** * @var MemberMetadata[][] * * @internal This property is public in order to reduce the size of the * class' serialized representation. Do not access it. Use * {@link getPropertyMetadata()} instead. */ public $members = array(); /** * @var PropertyMetadata[] * * @internal This property is public in order to reduce the size of the * class' serialized representation. Do not access it. Use * {@link getPropertyMetadata()} instead. */ public $properties = array(); /** * @var GetterMetadata[] * * @internal This property is public in order to reduce the size of the * class' serialized representation. Do not access it. Use * {@link getPropertyMetadata()} instead. */ public $getters = array(); /** * @var array * * @internal This property is public in order to reduce the size of the * class' serialized representation. Do not access it. Use * {@link getGroupSequence()} instead. */ public $groupSequence = array(); /** * @var bool * * @internal This property is public in order to reduce the size of the * class' serialized representation. Do not access it. Use * {@link isGroupSequenceProvider()} instead. */ public $groupSequenceProvider = false; /** * The strategy for traversing traversable objects. * * By default, only instances of {@link \Traversable} are traversed. * * @var int * * @internal This property is public in order to reduce the size of the * class' serialized representation. Do not access it. Use * {@link getTraversalStrategy()} instead. */ public $traversalStrategy = TraversalStrategy::IMPLICIT; /** * @var \ReflectionClass */ private $reflClass; public function __construct(string $class) { $this->name = $class; // class name without namespace if (false !== $nsSep = strrpos($class, '\\')) { $this->defaultGroup = substr($class, $nsSep + 1); } else { $this->defaultGroup = $class; } } /** * {@inheritdoc} */ public function __sleep() { $parentProperties = parent::__sleep(); // Don't store the cascading strategy. Classes never cascade. unset($parentProperties[array_search('cascadingStrategy', $parentProperties)]); return array_merge($parentProperties, array( 'getters', 'groupSequence', 'groupSequenceProvider', 'members', 'name', 'properties', 'defaultGroup', )); } /** * {@inheritdoc} */ public function getClassName() { return $this->name; } /** * Returns the name of the default group for this class. * * For each class, the group "Default" is an alias for the group * "<ClassName>", where <ClassName> is the non-namespaced name of the * class. All constraints implicitly or explicitly assigned to group * "Default" belong to both of these groups, unless the class defines * a group sequence. * * If a class defines a group sequence, validating the class in "Default" * will validate the group sequence. The constraints assigned to "Default" * can still be validated by validating the class in "<ClassName>". * * @return string The name of the default group */ public function getDefaultGroup() { return $this->defaultGroup; } /** * {@inheritdoc} */ public function addConstraint(Constraint $constraint) { if (!in_array(Constraint::CLASS_CONSTRAINT, (array) $constraint->getTargets())) { throw new ConstraintDefinitionException(sprintf( 'The constraint "%s" cannot be put on classes.', get_class($constraint) )); } if ($constraint instanceof Valid) { throw new ConstraintDefinitionException(sprintf( 'The constraint "%s" cannot be put on classes.', get_class($constraint) )); } if ($constraint instanceof Traverse) { if ($constraint->traverse) { // If traverse is true, traversal should be explicitly enabled $this->traversalStrategy = TraversalStrategy::TRAVERSE; } else { // If traverse is false, traversal should be explicitly disabled $this->traversalStrategy = TraversalStrategy::NONE; } // The constraint is not added return $this; } $constraint->addImplicitGroupName($this->getDefaultGroup()); parent::addConstraint($constraint); return $this; } /** * Adds a constraint to the given property. * * @param string $property The name of the property * @param Constraint $constraint The constraint * * @return $this */ public function addPropertyConstraint($property, Constraint $constraint) { if (!isset($this->properties[$property])) { $this->properties[$property] = new PropertyMetadata($this->getClassName(), $property); $this->addPropertyMetadata($this->properties[$property]); } $constraint->addImplicitGroupName($this->getDefaultGroup()); $this->properties[$property]->addConstraint($constraint); return $this; } /** * @param string $property * @param Constraint[] $constraints * * @return $this */ public function addPropertyConstraints($property, array $constraints) { foreach ($constraints as $constraint) { $this->addPropertyConstraint($property, $constraint); } return $this; } /** * Adds a constraint to the getter of the given property. * * The name of the getter is assumed to be the name of the property with an * uppercased first letter and either the prefix "get" or "is". * * @param string $property The name of the property * @param Constraint $constraint The constraint * * @return $this */ public function addGetterConstraint($property, Constraint $constraint) { if (!isset($this->getters[$property])) { $this->getters[$property] = new GetterMetadata($this->getClassName(), $property); $this->addPropertyMetadata($this->getters[$property]); } $constraint->addImplicitGroupName($this->getDefaultGroup()); $this->getters[$property]->addConstraint($constraint); return $this; } /** * Adds a constraint to the getter of the given property. * * @param string $property The name of the property * @param string $method The name of the getter method * @param Constraint $constraint The constraint * * @return $this */ public function addGetterMethodConstraint($property, $method, Constraint $constraint) { if (!isset($this->getters[$property])) { $this->getters[$property] = new GetterMetadata($this->getClassName(), $property, $method); $this->addPropertyMetadata($this->getters[$property]); } $constraint->addImplicitGroupName($this->getDefaultGroup()); $this->getters[$property]->addConstraint($constraint); return $this; } /** * @param string $property * @param Constraint[] $constraints * * @return $this */ public function addGetterConstraints($property, array $constraints) { foreach ($constraints as $constraint) { $this->addGetterConstraint($property, $constraint); } return $this; } /** * @param string $property * @param string $method * @param Constraint[] $constraints * * @return $this */ public function addGetterMethodConstraints($property, $method, array $constraints) { foreach ($constraints as $constraint) { $this->addGetterMethodConstraint($property, $method, $constraint); } return $this; } /** * Merges the constraints of the given metadata into this object. */ public function mergeConstraints(self $source) { if ($source->isGroupSequenceProvider()) { $this->setGroupSequenceProvider(true); } foreach ($source->getConstraints() as $constraint) { $this->addConstraint(clone $constraint); } foreach ($source->getConstrainedProperties() as $property) { foreach ($source->getPropertyMetadata($property) as $member) { $member = clone $member; foreach ($member->getConstraints() as $constraint) { if (in_array($constraint::DEFAULT_GROUP, $constraint->groups, true)) { $member->constraintsByGroup[$this->getDefaultGroup()][] = $constraint; } $constraint->addImplicitGroupName($this->getDefaultGroup()); } $this->addPropertyMetadata($member); if ($member instanceof MemberMetadata && !$member->isPrivate($this->name)) { $property = $member->getPropertyName(); if ($member instanceof PropertyMetadata && !isset($this->properties[$property])) { $this->properties[$property] = $member; } elseif ($member instanceof GetterMetadata && !isset($this->getters[$property])) { $this->getters[$property] = $member; } } } } } /** * {@inheritdoc} */ public function hasPropertyMetadata($property) { return array_key_exists($property, $this->members); } /** * {@inheritdoc} */ public function getPropertyMetadata($property) { if (!isset($this->members[$property])) { return array(); } return $this->members[$property]; } /** * {@inheritdoc} */ public function getConstrainedProperties() { return array_keys($this->members); } /** * Sets the default group sequence for this class. * * @param array $groupSequence An array of group names * * @return $this * * @throws GroupDefinitionException */ public function setGroupSequence($groupSequence) { if ($this->isGroupSequenceProvider()) { throw new GroupDefinitionException('Defining a static group sequence is not allowed with a group sequence provider'); } if (is_array($groupSequence)) { $groupSequence = new GroupSequence($groupSequence); } if (in_array(Constraint::DEFAULT_GROUP, $groupSequence->groups, true)) { throw new GroupDefinitionException(sprintf('The group "%s" is not allowed in group sequences', Constraint::DEFAULT_GROUP)); } if (!in_array($this->getDefaultGroup(), $groupSequence->groups, true)) { throw new GroupDefinitionException(sprintf('The group "%s" is missing in the group sequence', $this->getDefaultGroup())); } $this->groupSequence = $groupSequence; return $this; } /** * {@inheritdoc} */ public function hasGroupSequence() { return $this->groupSequence && count($this->groupSequence->groups) > 0; } /** * {@inheritdoc} */ public function getGroupSequence() { return $this->groupSequence; } /** * Returns a ReflectionClass instance for this class. * * @return \ReflectionClass */ public function getReflectionClass() { if (!$this->reflClass) { $this->reflClass = new \ReflectionClass($this->getClassName()); } return $this->reflClass; } /** * Sets whether a group sequence provider should be used. * * @param bool $active * * @throws GroupDefinitionException */ public function setGroupSequenceProvider($active) { if ($this->hasGroupSequence()) { throw new GroupDefinitionException('Defining a group sequence provider is not allowed with a static group sequence'); } if (!$this->getReflectionClass()->implementsInterface('Symfony\Component\Validator\GroupSequenceProviderInterface')) { throw new GroupDefinitionException(sprintf('Class "%s" must implement GroupSequenceProviderInterface', $this->name)); } $this->groupSequenceProvider = $active; } /** * {@inheritdoc} */ public function isGroupSequenceProvider() { return $this->groupSequenceProvider; } /** * Class nodes are never cascaded. * * {@inheritdoc} */ public function getCascadingStrategy() { return CascadingStrategy::NONE; } private function addPropertyMetadata(PropertyMetadataInterface $metadata) { $property = $metadata->getPropertyName(); $this->members[$property][] = $metadata; } }
{ "content_hash": "518c52bc96e7d5e835f265a1687a54fb", "timestamp": "", "source": "github", "line_count": 497, "max_line_length": 135, "avg_line_length": 29.613682092555333, "alnum_prop": 0.5898219866829733, "repo_name": "iltar/symfony", "id": "d7773861445fb5d9b253f1f11e3d52cb6aa74ad4", "size": "14947", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Symfony/Component/Validator/Mapping/ClassMetadata.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2961" }, { "name": "HTML", "bytes": "355256" }, { "name": "JavaScript", "bytes": "354" }, { "name": "PHP", "bytes": "15028955" }, { "name": "Shell", "bytes": "375" } ], "symlink_target": "" }
package org.gradoop.storage.config; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.hbase.TableName; import org.gradoop.common.model.impl.pojo.EdgeFactory; import org.gradoop.common.model.impl.pojo.GraphHeadFactory; import org.gradoop.common.model.impl.pojo.VertexFactory; import org.gradoop.storage.common.config.GradoopStoreConfig; import org.gradoop.storage.impl.hbase.api.EdgeHandler; import org.gradoop.storage.impl.hbase.api.GraphHeadHandler; import org.gradoop.storage.impl.hbase.api.VertexHandler; import org.gradoop.storage.impl.hbase.constants.HBaseConstants; import org.gradoop.storage.impl.hbase.handler.HBaseEdgeHandler; import org.gradoop.storage.impl.hbase.handler.HBaseGraphHeadHandler; import org.gradoop.storage.impl.hbase.handler.HBaseVertexHandler; import org.gradoop.storage.utils.RegionSplitter; import org.gradoop.storage.utils.RowKeyDistributor; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * Configuration class for using HBase with Gradoop. */ public class GradoopHBaseConfig implements GradoopStoreConfig { /** * Definition for serialize version control */ private static final int serialVersionUID = 23; /** * Graph table name. */ private final String graphTableName; /** * EPGMVertex table name. */ private final String vertexTableName; /** * EPGMEdge table name. */ private final String edgeTableName; /** * Graph head handler. */ private final GraphHeadHandler graphHeadHandler; /** * EPGMVertex handler. */ private final VertexHandler vertexHandler; /** * EPGMEdge handler. */ private final EdgeHandler edgeHandler; /** * Creates a new Configuration. * * @param graphHeadHandler graph head handler * @param vertexHandler vertex handler * @param edgeHandler edge handler * @param graphTableName graph table name * @param vertexTableName vertex table name * @param edgeTableName edge table name */ private GradoopHBaseConfig( GraphHeadHandler graphHeadHandler, VertexHandler vertexHandler, EdgeHandler edgeHandler, String graphTableName, String vertexTableName, String edgeTableName ) { checkArgument(!StringUtils.isEmpty(graphTableName), "Graph table name was null or empty"); checkArgument(!StringUtils.isEmpty(vertexTableName), "EPGMVertex table name was null or empty"); checkArgument(!StringUtils.isEmpty(edgeTableName), "EPGMEdge table name was null or empty"); this.graphTableName = graphTableName; this.vertexTableName = vertexTableName; this.edgeTableName = edgeTableName; this.graphHeadHandler = checkNotNull(graphHeadHandler, "GraphHeadHandler was null"); this.vertexHandler = checkNotNull(vertexHandler, "VertexHandler was null"); this.edgeHandler = checkNotNull(edgeHandler, "EdgeHandler was null"); } /** * Creates a new Configuration. * * @param config Gradoop configuration * @param graphTableName graph table name * @param vertexTableName vertex table name * @param edgeTableName edge table name */ private GradoopHBaseConfig( GradoopHBaseConfig config, String graphTableName, String vertexTableName, String edgeTableName ) { this(config.getGraphHeadHandler(), config.getVertexHandler(), config.getEdgeHandler(), graphTableName, vertexTableName, edgeTableName); } /** * Creates a default Configuration using POJO handlers for vertices, edges * and graph heads and default table names. * * @return Default Gradoop HBase configuration. */ public static GradoopHBaseConfig getDefaultConfig() { GraphHeadHandler graphHeadHandler = new HBaseGraphHeadHandler(new GraphHeadFactory()); VertexHandler vertexHandler = new HBaseVertexHandler(new VertexFactory()); EdgeHandler edgeHandler = new HBaseEdgeHandler(new EdgeFactory()); return new GradoopHBaseConfig( graphHeadHandler, vertexHandler, edgeHandler, HBaseConstants.DEFAULT_TABLE_GRAPHS, HBaseConstants.DEFAULT_TABLE_VERTICES, HBaseConstants.DEFAULT_TABLE_EDGES ); } /** * Creates a Gradoop HBase configuration based on the given arguments. * * @param gradoopConfig Gradoop configuration * @param graphTableName graph table name * @param vertexTableName vertex table name * @param edgeTableName edge table name * * @return Gradoop HBase configuration */ public static GradoopHBaseConfig createConfig( GradoopHBaseConfig gradoopConfig, String graphTableName, String vertexTableName, String edgeTableName ) { return new GradoopHBaseConfig(gradoopConfig, graphTableName, vertexTableName, edgeTableName); } /** * Get vertex table name * * @return vertex table name */ public TableName getVertexTableName() { return TableName.valueOf(vertexTableName); } /** * Get edge table name * * @return edge table name */ public TableName getEdgeTableName() { return TableName.valueOf(edgeTableName); } /** * Get graph table name * * @return graph table name */ public TableName getGraphTableName() { return TableName.valueOf(graphTableName); } /** * Get graph head handler * * @return graph head handler */ public GraphHeadHandler getGraphHeadHandler() { return graphHeadHandler; } /** * Get vertex handler * * @return vertex handler */ public VertexHandler getVertexHandler() { return vertexHandler; } /** * Get edge handler * * @return edge handler */ public EdgeHandler getEdgeHandler() { return edgeHandler; } /** * Enable/Disable the usage of pre-splitting regions at the moment of table creation. * If the HBase table size grows, it should be created with pre-split regions in order to avoid * region hotspots. If certain region servers are stressed by very intensive write/read * operations, HBase may drop that region server because the Zookeeper connection will timeout. * * Note that this flag has no effect if the tables already exist. * * @param numberOfRegions the number of regions used for splitting * @return this modified config */ public GradoopHBaseConfig enablePreSplitRegions(final int numberOfRegions) { RegionSplitter.getInstance().setNumberOfRegions(numberOfRegions); this.vertexHandler.setPreSplitRegions(true); this.edgeHandler.setPreSplitRegions(true); this.graphHeadHandler.setPreSplitRegions(true); return this; } /** * Enable/Disable the usage of a spreading byte as prefix of each HBase row key. This affects * reading and writing from/to HBase. * * Records in HBase are sorted lexicographically by the row key. This allows fast access to * an individual record by its key and fast fetching of a range of data given start and stop keys. * But writing records with such naive keys will cause hotspotting because of how HBase writes * data to its Regions. With this option you can disable this hotspotting. * * @param bucketCount the number of spreading bytes to use * @return this modified config */ public GradoopHBaseConfig useSpreadingByte(final int bucketCount) { RowKeyDistributor.getInstance().setBucketCount((byte) bucketCount); this.vertexHandler.setSpreadingByteUsage(true); this.edgeHandler.setSpreadingByteUsage(true); this.graphHeadHandler.setSpreadingByteUsage(true); return this; } }
{ "content_hash": "2f879087df56d1399641c474f629fa8d", "timestamp": "", "source": "github", "line_count": 251, "max_line_length": 100, "avg_line_length": 30.609561752988046, "alnum_prop": 0.7249772224391514, "repo_name": "rostam/gradoop", "id": "39834e16b6b04a67798826e204769b09682d4a1a", "size": "8320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gradoop-store/gradoop-hbase/src/main/java/org/gradoop/storage/config/GradoopHBaseConfig.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "4829342" }, { "name": "Shell", "bytes": "4071" } ], "symlink_target": "" }
cask 'freemind' do version '1.0.1' sha256 '0bd93317567f947e7fa3b3e8d2e0d908300642edc5e07f1929157469ffd14ea3' # downloads.sourceforge.net/freemind/ was verified as official when first introduced to the cask url "https://downloads.sourceforge.net/freemind/freemind/#{version}/FreeMind_#{version}.dmg" appcast 'https://sourceforge.net/projects/freemind/rss?path=/freemind' name 'FreeMind' homepage 'https://freemind.sourceforge.io/wiki/index.php/Main_Page' app 'FreeMind.app' end
{ "content_hash": "0ad7905b03b7c7928b734d75a55ccef4", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 98, "avg_line_length": 41.25, "alnum_prop": 0.7797979797979798, "repo_name": "morganestes/homebrew-cask", "id": "e88783d1c9e7cf8ebde63e41e4e18f869fa437ae", "size": "495", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Casks/freemind.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "2152638" }, { "name": "Shell", "bytes": "70817" } ], "symlink_target": "" }
package cmdex import ( "errors" "os" "os/exec" "strings" "syscall" ) // RunCommandInDir ... func RunCommandInDir(dir, name string, args ...string) error { cmd := exec.Command(name, args...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if dir != "" { cmd.Dir = dir } return cmd.Run() } // RunCommandInDirWithExitCode ... func RunCommandInDirWithExitCode(dir, name string, args ...string) (int, error) { cmd := exec.Command(name, args...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if dir != "" { cmd.Dir = dir } cmdExitCode := 0 if err := cmd.Run(); err != nil { if exitError, ok := err.(*exec.ExitError); ok { waitStatus, ok := exitError.Sys().(syscall.WaitStatus) if !ok { return 1, errors.New("Failed to cast exit status") } cmdExitCode = waitStatus.ExitStatus() } return cmdExitCode, err } return 0, nil } // RunCommand ... func RunCommand(name string, args ...string) error { return RunCommandInDir("", name, args...) } // RunCommandAndReturnStdout .. func RunCommandAndReturnStdout(name string, args ...string) (string, error) { cmd := exec.Command(name, args...) outBytes, err := cmd.Output() outStr := string(outBytes) return strings.TrimSpace(outStr), err } // RunCommandInDirAndReturnCombinedStdoutAndStderr ... func RunCommandInDirAndReturnCombinedStdoutAndStderr(dir, name string, args ...string) (string, error) { cmd := exec.Command(name, args...) if dir != "" { cmd.Dir = dir } outBytes, err := cmd.CombinedOutput() outStr := string(outBytes) return strings.TrimSpace(outStr), err } // RunCommandAndReturnCombinedStdoutAndStderr .. func RunCommandAndReturnCombinedStdoutAndStderr(name string, args ...string) (string, error) { return RunCommandInDirAndReturnCombinedStdoutAndStderr("", name, args...) } // RunBashCommand ... func RunBashCommand(cmdStr string) error { return RunCommand("bash", "-c", cmdStr) } // RunBashCommandLines ... func RunBashCommandLines(cmdLines []string) error { for _, aLine := range cmdLines { if err := RunCommand("bash", "-c", aLine); err != nil { return err } } return nil }
{ "content_hash": "c3e075d2fa30e2ce9d9df313c0cf3c10", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 104, "avg_line_length": 24.146067415730336, "alnum_prop": 0.6854350860865519, "repo_name": "mistydemeo/bitrise", "id": "437adc8f39d1605818c49fdc7b214c8395cdf651", "size": "2149", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Godeps/_workspace/src/github.com/bitrise-io/go-utils/cmdex/run.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "120150" }, { "name": "Shell", "bytes": "3656" } ], "symlink_target": "" }
fieldset { padding: 0; margin: 0; border: 0; min-width: 0; } legend { display: block; width: 100%; padding: 0; margin-bottom: 20px; font-size: 21px; line-height: inherit; color: #333333; border: 0; border-bottom: 1px solid #e5e5e5; } label { display: inline-block; max-width: 100%; margin-bottom: 5px; font-weight: bold; } input[type="search"] { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } input[type="radio"], input[type="checkbox"] { margin: 4px 0 0; margin-top: 1px \9; line-height: normal; } input[type="file"] { display: block; } input[type="range"] { display: block; width: 100%; } select[multiple], select[size] { height: auto; } input[type="file"]:focus, input[type="radio"]:focus, input[type="checkbox"]:focus { outline: thin dotted; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } output { display: block; padding-top: 7px; font-size: 14px; line-height: 1.42857143; color: #555555; } .form-control { display: block; width: 100%; height: 34px; padding: 6px 12px; font-size: 14px; line-height: 1.42857143; color: #555555; background-color: #fff; background-image: none; border: 1px solid #ccc; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; } .form-control:focus { border-color: #66afe9; outline: 0; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6); box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6); } .form-control::-moz-placeholder { color: #999; opacity: 1; } .form-control:-ms-input-placeholder { color: #999; } .form-control::-webkit-input-placeholder { color: #999; } .form-control[disabled], .form-control[readonly], fieldset[disabled] .form-control { background-color: #eeeeee; opacity: 1; } .form-control[disabled], fieldset[disabled] .form-control { cursor: not-allowed; } textarea.form-control { height: auto; } input[type="search"] { -webkit-appearance: none; } @media screen and (-webkit-min-device-pixel-ratio: 0) { input[type="date"].form-control, input[type="time"].form-control, input[type="datetime-local"].form-control, input[type="month"].form-control { line-height: 34px; } input[type="date"].input-sm, input[type="time"].input-sm, input[type="datetime-local"].input-sm, input[type="month"].input-sm, .input-group-sm input[type="date"], .input-group-sm input[type="time"], .input-group-sm input[type="datetime-local"], .input-group-sm input[type="month"] { line-height: 30px; } input[type="date"].input-lg, input[type="time"].input-lg, input[type="datetime-local"].input-lg, input[type="month"].input-lg, .input-group-lg input[type="date"], .input-group-lg input[type="time"], .input-group-lg input[type="datetime-local"], .input-group-lg input[type="month"] { line-height: 46px; } } .form-group { margin-bottom: 15px; } .radio, .checkbox { position: relative; display: block; margin-top: 10px; margin-bottom: 10px; } .radio label, .checkbox label { min-height: 20px; padding-left: 20px; margin-bottom: 0; font-weight: normal; cursor: pointer; } .radio input[type="radio"], .radio-inline input[type="radio"], .checkbox input[type="checkbox"], .checkbox-inline input[type="checkbox"] { position: absolute; margin-left: -20px; margin-top: 4px \9; } .radio + .radio, .checkbox + .checkbox { margin-top: -5px; } .radio-inline, .checkbox-inline { position: relative; display: inline-block; padding-left: 20px; margin-bottom: 0; vertical-align: middle; font-weight: normal; cursor: pointer; } .radio-inline + .radio-inline, .checkbox-inline + .checkbox-inline { margin-top: 0; margin-left: 10px; } input[type="radio"][disabled], input[type="checkbox"][disabled], input[type="radio"].disabled, input[type="checkbox"].disabled, fieldset[disabled] input[type="radio"], fieldset[disabled] input[type="checkbox"] { cursor: not-allowed; } .radio-inline.disabled, .checkbox-inline.disabled, fieldset[disabled] .radio-inline, fieldset[disabled] .checkbox-inline { cursor: not-allowed; } .radio.disabled label, .checkbox.disabled label, fieldset[disabled] .radio label, fieldset[disabled] .checkbox label { cursor: not-allowed; } .form-control-static { padding-top: 7px; padding-bottom: 7px; margin-bottom: 0; min-height: 34px; } .form-control-static.input-lg, .form-control-static.input-sm { padding-left: 0; padding-right: 0; } .input-sm { height: 30px; padding: 5px 10px; font-size: 12px; line-height: 1.5; border-radius: 3px; } select.input-sm { height: 30px; line-height: 30px; } textarea.input-sm, select[multiple].input-sm { height: auto; } .form-group-sm .form-control { height: 30px; padding: 5px 10px; font-size: 12px; line-height: 1.5; border-radius: 3px; } .form-group-sm select.form-control { height: 30px; line-height: 30px; } .form-group-sm textarea.form-control, .form-group-sm select[multiple].form-control { height: auto; } .form-group-sm .form-control-static { height: 30px; min-height: 32px; padding: 6px 10px; font-size: 12px; line-height: 1.5; } .input-lg { height: 46px; padding: 10px 16px; font-size: 18px; line-height: 1.3333333; border-radius: 6px; } select.input-lg { height: 46px; line-height: 46px; } textarea.input-lg, select[multiple].input-lg { height: auto; } .form-group-lg .form-control { height: 46px; padding: 10px 16px; font-size: 18px; line-height: 1.3333333; border-radius: 6px; } .form-group-lg select.form-control { height: 46px; line-height: 46px; } .form-group-lg textarea.form-control, .form-group-lg select[multiple].form-control { height: auto; } .form-group-lg .form-control-static { height: 46px; min-height: 38px; padding: 11px 16px; font-size: 18px; line-height: 1.3333333; } .has-feedback { position: relative; } .has-feedback .form-control { padding-right: 42.5px; } .form-control-feedback { position: absolute; top: 0; right: 0; z-index: 2; display: block; width: 34px; height: 34px; line-height: 34px; text-align: center; pointer-events: none; } .input-lg + .form-control-feedback, .input-group-lg + .form-control-feedback, .form-group-lg .form-control + .form-control-feedback { width: 46px; height: 46px; line-height: 46px; } .input-sm + .form-control-feedback, .input-group-sm + .form-control-feedback, .form-group-sm .form-control + .form-control-feedback { width: 30px; height: 30px; line-height: 30px; } .has-success .help-block, .has-success .control-label, .has-success .radio, .has-success .checkbox, .has-success .radio-inline, .has-success .checkbox-inline, .has-success.radio label, .has-success.checkbox label, .has-success.radio-inline label, .has-success.checkbox-inline label { color: #3c763d; } .has-success .form-control { border-color: #3c763d; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .has-success .form-control:focus { border-color: #2b542c; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #67b168; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #67b168; } .has-success .input-group-addon { color: #3c763d; border-color: #3c763d; background-color: #dff0d8; } .has-success .form-control-feedback { color: #3c763d; } .has-warning .help-block, .has-warning .control-label, .has-warning .radio, .has-warning .checkbox, .has-warning .radio-inline, .has-warning .checkbox-inline, .has-warning.radio label, .has-warning.checkbox label, .has-warning.radio-inline label, .has-warning.checkbox-inline label { color: #8a6d3b; } .has-warning .form-control { border-color: #8a6d3b; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .has-warning .form-control:focus { border-color: #66512c; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #c0a16b; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #c0a16b; } .has-warning .input-group-addon { color: #8a6d3b; border-color: #8a6d3b; background-color: #fcf8e3; } .has-warning .form-control-feedback { color: #8a6d3b; } .has-error .help-block, .has-error .control-label, .has-error .radio, .has-error .checkbox, .has-error .radio-inline, .has-error .checkbox-inline, .has-error.radio label, .has-error.checkbox label, .has-error.radio-inline label, .has-error.checkbox-inline label { color: #a94442; } .has-error .form-control { border-color: #a94442; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .has-error .form-control:focus { border-color: #843534; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #ce8483; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #ce8483; } .has-error .input-group-addon { color: #a94442; border-color: #a94442; background-color: #f2dede; } .has-error .form-control-feedback { color: #a94442; } .has-feedback label ~ .form-control-feedback { top: 25px; } .has-feedback label.sr-only ~ .form-control-feedback { top: 0; } .help-block { display: block; margin-top: 5px; margin-bottom: 10px; color: #737373; } @media (min-width: 768px) { .form-inline .form-group { display: inline-block; margin-bottom: 0; vertical-align: middle; } .form-inline .form-control { display: inline-block; width: auto; vertical-align: middle; } .form-inline .form-control-static { display: inline-block; } .form-inline .input-group { display: inline-table; vertical-align: middle; } .form-inline .input-group .input-group-addon, .form-inline .input-group .input-group-btn, .form-inline .input-group .form-control { width: auto; } .form-inline .input-group > .form-control { width: 100%; } .form-inline .control-label { margin-bottom: 0; vertical-align: middle; } .form-inline .radio, .form-inline .checkbox { display: inline-block; margin-top: 0; margin-bottom: 0; vertical-align: middle; } .form-inline .radio label, .form-inline .checkbox label { padding-left: 0; } .form-inline .radio input[type="radio"], .form-inline .checkbox input[type="checkbox"] { position: relative; margin-left: 0; } .form-inline .has-feedback .form-control-feedback { top: 0; } } .form-horizontal .radio, .form-horizontal .checkbox, .form-horizontal .radio-inline, .form-horizontal .checkbox-inline { margin-top: 0; margin-bottom: 0; padding-top: 7px; } .form-horizontal .radio, .form-horizontal .checkbox { min-height: 27px; } .form-horizontal .form-group { margin-left: -15px; margin-right: -15px; } @media (min-width: 768px) { .form-horizontal .control-label { text-align: right; margin-bottom: 0; padding-top: 7px; } } .form-horizontal .has-feedback .form-control-feedback { right: 15px; } @media (min-width: 768px) { .form-horizontal .form-group-lg .control-label { padding-top: 14.333333px; font-size: 18px; } } @media (min-width: 768px) { .form-horizontal .form-group-sm .control-label { padding-top: 6px; font-size: 12px; } } .input-group { position: relative; display: table; border-collapse: separate; } .input-group[class*="col-"] { float: none; padding-left: 0; padding-right: 0; } .input-group .form-control { position: relative; z-index: 2; float: left; width: 100%; margin-bottom: 0; } .input-group-lg > .form-control, .input-group-lg > .input-group-addon, .input-group-lg > .input-group-btn > .btn { height: 46px; padding: 10px 16px; font-size: 18px; line-height: 1.3333333; border-radius: 6px; } select.input-group-lg > .form-control, select.input-group-lg > .input-group-addon, select.input-group-lg > .input-group-btn > .btn { height: 46px; line-height: 46px; } textarea.input-group-lg > .form-control, textarea.input-group-lg > .input-group-addon, textarea.input-group-lg > .input-group-btn > .btn, select[multiple].input-group-lg > .form-control, select[multiple].input-group-lg > .input-group-addon, select[multiple].input-group-lg > .input-group-btn > .btn { height: auto; } .input-group-sm > .form-control, .input-group-sm > .input-group-addon, .input-group-sm > .input-group-btn > .btn { height: 30px; padding: 5px 10px; font-size: 12px; line-height: 1.5; border-radius: 3px; } select.input-group-sm > .form-control, select.input-group-sm > .input-group-addon, select.input-group-sm > .input-group-btn > .btn { height: 30px; line-height: 30px; } textarea.input-group-sm > .form-control, textarea.input-group-sm > .input-group-addon, textarea.input-group-sm > .input-group-btn > .btn, select[multiple].input-group-sm > .form-control, select[multiple].input-group-sm > .input-group-addon, select[multiple].input-group-sm > .input-group-btn > .btn { height: auto; } .input-group-addon, .input-group-btn, .input-group .form-control { display: table-cell; } .input-group-addon:not(:first-child):not(:last-child), .input-group-btn:not(:first-child):not(:last-child), .input-group .form-control:not(:first-child):not(:last-child) { border-radius: 0; } .input-group-addon, .input-group-btn { width: 1%; white-space: nowrap; vertical-align: middle; } .input-group-addon { padding: 6px 12px; font-size: 14px; font-weight: normal; line-height: 1; color: #555555; text-align: center; background-color: #eeeeee; border: 1px solid #ccc; border-radius: 4px; } .input-group-addon.input-sm { padding: 5px 10px; font-size: 12px; border-radius: 3px; } .input-group-addon.input-lg { padding: 10px 16px; font-size: 18px; border-radius: 6px; } .input-group-addon input[type="radio"], .input-group-addon input[type="checkbox"] { margin-top: 0; } .input-group .form-control:first-child, .input-group-addon:first-child, .input-group-btn:first-child > .btn, .input-group-btn:first-child > .btn-group > .btn, .input-group-btn:first-child > .dropdown-toggle, .input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle), .input-group-btn:last-child > .btn-group:not(:last-child) > .btn { border-bottom-right-radius: 0; border-top-right-radius: 0; } .input-group-addon:first-child { border-right: 0; } .input-group .form-control:last-child, .input-group-addon:last-child, .input-group-btn:last-child > .btn, .input-group-btn:last-child > .btn-group > .btn, .input-group-btn:last-child > .dropdown-toggle, .input-group-btn:first-child > .btn:not(:first-child), .input-group-btn:first-child > .btn-group:not(:first-child) > .btn { border-bottom-left-radius: 0; border-top-left-radius: 0; } .input-group-addon:last-child { border-left: 0; } .input-group-btn { position: relative; font-size: 0; white-space: nowrap; } .input-group-btn > .btn { position: relative; } .input-group-btn > .btn + .btn { margin-left: -1px; } .input-group-btn > .btn:hover, .input-group-btn > .btn:focus, .input-group-btn > .btn:active { z-index: 2; } .input-group-btn:first-child > .btn, .input-group-btn:first-child > .btn-group { margin-right: -1px; } .input-group-btn:last-child > .btn, .input-group-btn:last-child > .btn-group { z-index: 2; margin-left: -1px; } .btn { display: inline-block; margin-bottom: 0; font-weight: normal; text-align: center; vertical-align: middle; touch-action: manipulation; cursor: pointer; background-image: none; border: 1px solid transparent; white-space: nowrap; padding: 6px 12px; font-size: 14px; line-height: 1.42857143; border-radius: 4px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .btn:focus, .btn:active:focus, .btn.active:focus, .btn.focus, .btn:active.focus, .btn.active.focus { outline: thin dotted; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } .btn:hover, .btn:focus, .btn.focus { color: #333; text-decoration: none; } .btn:active, .btn.active { outline: 0; background-image: none; -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn.disabled, .btn[disabled], fieldset[disabled] .btn { cursor: not-allowed; filter: alpha(opacity=65); opacity: 0.65; -webkit-box-shadow: none; box-shadow: none; } a.btn.disabled, fieldset[disabled] a.btn { pointer-events: none; } .btn-default { color: #333; background-color: #fff; border-color: #ccc; } .btn-default:focus, .btn-default.focus { color: #333; background-color: #e6e6e6; border-color: #8c8c8c; } .btn-default:hover { color: #333; background-color: #e6e6e6; border-color: #adadad; } .btn-default:active, .btn-default.active, .open > .dropdown-toggle.btn-default { color: #333; background-color: #e6e6e6; border-color: #adadad; } .btn-default:active:hover, .btn-default.active:hover, .open > .dropdown-toggle.btn-default:hover, .btn-default:active:focus, .btn-default.active:focus, .open > .dropdown-toggle.btn-default:focus, .btn-default:active.focus, .btn-default.active.focus, .open > .dropdown-toggle.btn-default.focus { color: #333; background-color: #d4d4d4; border-color: #8c8c8c; } .btn-default:active, .btn-default.active, .open > .dropdown-toggle.btn-default { background-image: none; } .btn-default.disabled, .btn-default[disabled], fieldset[disabled] .btn-default, .btn-default.disabled:hover, .btn-default[disabled]:hover, fieldset[disabled] .btn-default:hover, .btn-default.disabled:focus, .btn-default[disabled]:focus, fieldset[disabled] .btn-default:focus, .btn-default.disabled.focus, .btn-default[disabled].focus, fieldset[disabled] .btn-default.focus, .btn-default.disabled:active, .btn-default[disabled]:active, fieldset[disabled] .btn-default:active, .btn-default.disabled.active, .btn-default[disabled].active, fieldset[disabled] .btn-default.active { background-color: #fff; border-color: #ccc; } .btn-default .badge { color: #fff; background-color: #333; } .btn-primary { color: #fff; background-color: #337ab7; border-color: #2e6da4; } .btn-primary:focus, .btn-primary.focus { color: #fff; background-color: #286090; border-color: #122b40; } .btn-primary:hover { color: #fff; background-color: #286090; border-color: #204d74; } .btn-primary:active, .btn-primary.active, .open > .dropdown-toggle.btn-primary { color: #fff; background-color: #286090; border-color: #204d74; } .btn-primary:active:hover, .btn-primary.active:hover, .open > .dropdown-toggle.btn-primary:hover, .btn-primary:active:focus, .btn-primary.active:focus, .open > .dropdown-toggle.btn-primary:focus, .btn-primary:active.focus, .btn-primary.active.focus, .open > .dropdown-toggle.btn-primary.focus { color: #fff; background-color: #204d74; border-color: #122b40; } .btn-primary:active, .btn-primary.active, .open > .dropdown-toggle.btn-primary { background-image: none; } .btn-primary.disabled, .btn-primary[disabled], fieldset[disabled] .btn-primary, .btn-primary.disabled:hover, .btn-primary[disabled]:hover, fieldset[disabled] .btn-primary:hover, .btn-primary.disabled:focus, .btn-primary[disabled]:focus, fieldset[disabled] .btn-primary:focus, .btn-primary.disabled.focus, .btn-primary[disabled].focus, fieldset[disabled] .btn-primary.focus, .btn-primary.disabled:active, .btn-primary[disabled]:active, fieldset[disabled] .btn-primary:active, .btn-primary.disabled.active, .btn-primary[disabled].active, fieldset[disabled] .btn-primary.active { background-color: #337ab7; border-color: #2e6da4; } .btn-primary .badge { color: #337ab7; background-color: #fff; } .btn-weird { color: #fff; background-color: #6f5499; border-color: #634b89; } .btn-weird:focus, .btn-weird.focus { color: #fff; background-color: #574278; border-color: #271e36; } .btn-weird:hover { color: #fff; background-color: #574278; border-color: #463561; } .btn-weird:active, .btn-weird.active, .open > .dropdown-toggle.btn-weird { color: #fff; background-color: #574278; border-color: #463561; } .btn-weird:active:hover, .btn-weird.active:hover, .open > .dropdown-toggle.btn-weird:hover, .btn-weird:active:focus, .btn-weird.active:focus, .open > .dropdown-toggle.btn-weird:focus, .btn-weird:active.focus, .btn-weird.active.focus, .open > .dropdown-toggle.btn-weird.focus { color: #fff; background-color: #463561; border-color: #271e36; } .btn-weird:active, .btn-weird.active, .open > .dropdown-toggle.btn-weird { background-image: none; } .btn-weird.disabled, .btn-weird[disabled], fieldset[disabled] .btn-weird, .btn-weird.disabled:hover, .btn-weird[disabled]:hover, fieldset[disabled] .btn-weird:hover, .btn-weird.disabled:focus, .btn-weird[disabled]:focus, fieldset[disabled] .btn-weird:focus, .btn-weird.disabled.focus, .btn-weird[disabled].focus, fieldset[disabled] .btn-weird.focus, .btn-weird.disabled:active, .btn-weird[disabled]:active, fieldset[disabled] .btn-weird:active, .btn-weird.disabled.active, .btn-weird[disabled].active, fieldset[disabled] .btn-weird.active { background-color: #6f5499; border-color: #634b89; } .btn-weird .badge { color: #6f5499; background-color: #fff; } .btn-success { color: #fff; background-color: #5cb85c; border-color: #4cae4c; } .btn-success:focus, .btn-success.focus { color: #fff; background-color: #449d44; border-color: #255625; } .btn-success:hover { color: #fff; background-color: #449d44; border-color: #398439; } .btn-success:active, .btn-success.active, .open > .dropdown-toggle.btn-success { color: #fff; background-color: #449d44; border-color: #398439; } .btn-success:active:hover, .btn-success.active:hover, .open > .dropdown-toggle.btn-success:hover, .btn-success:active:focus, .btn-success.active:focus, .open > .dropdown-toggle.btn-success:focus, .btn-success:active.focus, .btn-success.active.focus, .open > .dropdown-toggle.btn-success.focus { color: #fff; background-color: #398439; border-color: #255625; } .btn-success:active, .btn-success.active, .open > .dropdown-toggle.btn-success { background-image: none; } .btn-success.disabled, .btn-success[disabled], fieldset[disabled] .btn-success, .btn-success.disabled:hover, .btn-success[disabled]:hover, fieldset[disabled] .btn-success:hover, .btn-success.disabled:focus, .btn-success[disabled]:focus, fieldset[disabled] .btn-success:focus, .btn-success.disabled.focus, .btn-success[disabled].focus, fieldset[disabled] .btn-success.focus, .btn-success.disabled:active, .btn-success[disabled]:active, fieldset[disabled] .btn-success:active, .btn-success.disabled.active, .btn-success[disabled].active, fieldset[disabled] .btn-success.active { background-color: #5cb85c; border-color: #4cae4c; } .btn-success .badge { color: #5cb85c; background-color: #fff; } .btn-info { color: #fff; background-color: #5bc0de; border-color: #46b8da; } .btn-info:focus, .btn-info.focus { color: #fff; background-color: #31b0d5; border-color: #1b6d85; } .btn-info:hover { color: #fff; background-color: #31b0d5; border-color: #269abc; } .btn-info:active, .btn-info.active, .open > .dropdown-toggle.btn-info { color: #fff; background-color: #31b0d5; border-color: #269abc; } .btn-info:active:hover, .btn-info.active:hover, .open > .dropdown-toggle.btn-info:hover, .btn-info:active:focus, .btn-info.active:focus, .open > .dropdown-toggle.btn-info:focus, .btn-info:active.focus, .btn-info.active.focus, .open > .dropdown-toggle.btn-info.focus { color: #fff; background-color: #269abc; border-color: #1b6d85; } .btn-info:active, .btn-info.active, .open > .dropdown-toggle.btn-info { background-image: none; } .btn-info.disabled, .btn-info[disabled], fieldset[disabled] .btn-info, .btn-info.disabled:hover, .btn-info[disabled]:hover, fieldset[disabled] .btn-info:hover, .btn-info.disabled:focus, .btn-info[disabled]:focus, fieldset[disabled] .btn-info:focus, .btn-info.disabled.focus, .btn-info[disabled].focus, fieldset[disabled] .btn-info.focus, .btn-info.disabled:active, .btn-info[disabled]:active, fieldset[disabled] .btn-info:active, .btn-info.disabled.active, .btn-info[disabled].active, fieldset[disabled] .btn-info.active { background-color: #5bc0de; border-color: #46b8da; } .btn-info .badge { color: #5bc0de; background-color: #fff; } .btn-warning { color: #fff; background-color: #f0ad4e; border-color: #eea236; } .btn-warning:focus, .btn-warning.focus { color: #fff; background-color: #ec971f; border-color: #985f0d; } .btn-warning:hover { color: #fff; background-color: #ec971f; border-color: #d58512; } .btn-warning:active, .btn-warning.active, .open > .dropdown-toggle.btn-warning { color: #fff; background-color: #ec971f; border-color: #d58512; } .btn-warning:active:hover, .btn-warning.active:hover, .open > .dropdown-toggle.btn-warning:hover, .btn-warning:active:focus, .btn-warning.active:focus, .open > .dropdown-toggle.btn-warning:focus, .btn-warning:active.focus, .btn-warning.active.focus, .open > .dropdown-toggle.btn-warning.focus { color: #fff; background-color: #d58512; border-color: #985f0d; } .btn-warning:active, .btn-warning.active, .open > .dropdown-toggle.btn-warning { background-image: none; } .btn-warning.disabled, .btn-warning[disabled], fieldset[disabled] .btn-warning, .btn-warning.disabled:hover, .btn-warning[disabled]:hover, fieldset[disabled] .btn-warning:hover, .btn-warning.disabled:focus, .btn-warning[disabled]:focus, fieldset[disabled] .btn-warning:focus, .btn-warning.disabled.focus, .btn-warning[disabled].focus, fieldset[disabled] .btn-warning.focus, .btn-warning.disabled:active, .btn-warning[disabled]:active, fieldset[disabled] .btn-warning:active, .btn-warning.disabled.active, .btn-warning[disabled].active, fieldset[disabled] .btn-warning.active { background-color: #f0ad4e; border-color: #eea236; } .btn-warning .badge { color: #f0ad4e; background-color: #fff; } .btn-danger { color: #fff; background-color: #d9534f; border-color: #d43f3a; } .btn-danger:focus, .btn-danger.focus { color: #fff; background-color: #c9302c; border-color: #761c19; } .btn-danger:hover { color: #fff; background-color: #c9302c; border-color: #ac2925; } .btn-danger:active, .btn-danger.active, .open > .dropdown-toggle.btn-danger { color: #fff; background-color: #c9302c; border-color: #ac2925; } .btn-danger:active:hover, .btn-danger.active:hover, .open > .dropdown-toggle.btn-danger:hover, .btn-danger:active:focus, .btn-danger.active:focus, .open > .dropdown-toggle.btn-danger:focus, .btn-danger:active.focus, .btn-danger.active.focus, .open > .dropdown-toggle.btn-danger.focus { color: #fff; background-color: #ac2925; border-color: #761c19; } .btn-danger:active, .btn-danger.active, .open > .dropdown-toggle.btn-danger { background-image: none; } .btn-danger.disabled, .btn-danger[disabled], fieldset[disabled] .btn-danger, .btn-danger.disabled:hover, .btn-danger[disabled]:hover, fieldset[disabled] .btn-danger:hover, .btn-danger.disabled:focus, .btn-danger[disabled]:focus, fieldset[disabled] .btn-danger:focus, .btn-danger.disabled.focus, .btn-danger[disabled].focus, fieldset[disabled] .btn-danger.focus, .btn-danger.disabled:active, .btn-danger[disabled]:active, fieldset[disabled] .btn-danger:active, .btn-danger.disabled.active, .btn-danger[disabled].active, fieldset[disabled] .btn-danger.active { background-color: #d9534f; border-color: #d43f3a; } .btn-danger .badge { color: #d9534f; background-color: #fff; } .btn-link { color: #337ab7; font-weight: normal; border-radius: 0; } .btn-link, .btn-link:active, .btn-link.active, .btn-link[disabled], fieldset[disabled] .btn-link { background-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .btn-link, .btn-link:hover, .btn-link:focus, .btn-link:active { border-color: transparent; } .btn-link:hover, .btn-link:focus { color: #23527c; text-decoration: underline; background-color: transparent; } .btn-link[disabled]:hover, fieldset[disabled] .btn-link:hover, .btn-link[disabled]:focus, fieldset[disabled] .btn-link:focus { color: #777777; text-decoration: none; } .btn-lg, .btn-group-lg > .btn { padding: 10px 16px; font-size: 18px; line-height: 1.3333333; border-radius: 6px; } .btn-sm, .btn-group-sm > .btn { padding: 5px 10px; font-size: 12px; line-height: 1.5; border-radius: 3px; } .btn-xs, .btn-group-xs > .btn { padding: 1px 5px; font-size: 12px; line-height: 1.5; border-radius: 3px; } .btn-block { display: block; width: 100%; } .btn-block + .btn-block { margin-top: 5px; } input[type="submit"].btn-block, input[type="reset"].btn-block, input[type="button"].btn-block { width: 100%; } .btn-group, .btn-group-vertical { position: relative; display: inline-block; vertical-align: middle; } .btn-group > .btn, .btn-group-vertical > .btn { position: relative; float: left; } .btn-group > .btn:hover, .btn-group-vertical > .btn:hover, .btn-group > .btn:focus, .btn-group-vertical > .btn:focus, .btn-group > .btn:active, .btn-group-vertical > .btn:active, .btn-group > .btn.active, .btn-group-vertical > .btn.active { z-index: 2; } .btn-group .btn + .btn, .btn-group .btn + .btn-group, .btn-group .btn-group + .btn, .btn-group .btn-group + .btn-group { margin-left: -1px; } .btn-toolbar { margin-left: -5px; } .btn-toolbar .btn, .btn-toolbar .btn-group, .btn-toolbar .input-group { float: left; } .btn-toolbar > .btn, .btn-toolbar > .btn-group, .btn-toolbar > .input-group { margin-left: 5px; } .btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) { border-radius: 0; } .btn-group > .btn:first-child { margin-left: 0; } .btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) { border-bottom-right-radius: 0; border-top-right-radius: 0; } .btn-group > .btn:last-child:not(:first-child), .btn-group > .dropdown-toggle:not(:first-child) { border-bottom-left-radius: 0; border-top-left-radius: 0; } .btn-group > .btn-group { float: left; } .btn-group > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle { border-bottom-right-radius: 0; border-top-right-radius: 0; } .btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child { border-bottom-left-radius: 0; border-top-left-radius: 0; } .btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { outline: 0; } .btn-group > .btn + .dropdown-toggle { padding-left: 8px; padding-right: 8px; } .btn-group > .btn-lg + .dropdown-toggle { padding-left: 12px; padding-right: 12px; } .btn-group.open .dropdown-toggle { -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn-group.open .dropdown-toggle.btn-link { -webkit-box-shadow: none; box-shadow: none; } .btn .caret { margin-left: 0; } .btn-lg .caret { border-width: 5px 5px 0; border-bottom-width: 0; } .dropup .btn-lg .caret { border-width: 0 5px 5px; } .btn-group-vertical > .btn, .btn-group-vertical > .btn-group, .btn-group-vertical > .btn-group > .btn { display: block; float: none; width: 100%; max-width: 100%; } .btn-group-vertical > .btn-group > .btn { float: none; } .btn-group-vertical > .btn + .btn, .btn-group-vertical > .btn + .btn-group, .btn-group-vertical > .btn-group + .btn, .btn-group-vertical > .btn-group + .btn-group { margin-top: -1px; margin-left: 0; } .btn-group-vertical > .btn:not(:first-child):not(:last-child) { border-radius: 0; } .btn-group-vertical > .btn:first-child:not(:last-child) { border-top-right-radius: 4px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .btn-group-vertical > .btn:last-child:not(:first-child) { border-bottom-left-radius: 4px; border-top-right-radius: 0; border-top-left-radius: 0; } .btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle { border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child { border-top-right-radius: 0; border-top-left-radius: 0; } .btn-group-justified { display: table; width: 100%; table-layout: fixed; border-collapse: separate; } .btn-group-justified > .btn, .btn-group-justified > .btn-group { float: none; display: table-cell; width: 1%; } .btn-group-justified > .btn-group .btn { width: 100%; } .btn-group-justified > .btn-group .dropdown-menu { left: auto; } [data-toggle="buttons"] > .btn input[type="radio"], [data-toggle="buttons"] > .btn-group > .btn input[type="radio"], [data-toggle="buttons"] > .btn input[type="checkbox"], [data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] { position: absolute; clip: rect(0, 0, 0, 0); pointer-events: none; } .alert { padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-radius: 4px; } .alert h4 { margin-top: 0; color: inherit; } .alert .alert-link { font-weight: bold; } .alert > p, .alert > ul { margin-bottom: 0; } .alert > p + p { margin-top: 5px; } .alert-dismissable, .alert-dismissible { padding-right: 35px; } .alert-dismissable .close, .alert-dismissible .close { position: relative; top: -2px; right: -21px; color: inherit; } .alert-success { background-color: #dff0d8; border-color: #d6e9c6; color: #3c763d; } .alert-success hr { border-top-color: #c9e2b3; } .alert-success .alert-link { color: #2b542c; } .alert-info { background-color: #d9edf7; border-color: #bce8f1; color: #31708f; } .alert-info hr { border-top-color: #a6e1ec; } .alert-info .alert-link { color: #245269; } .alert-warning { background-color: #fcf8e3; border-color: #faebcc; color: #8a6d3b; } .alert-warning hr { border-top-color: #f7e1b5; } .alert-warning .alert-link { color: #66512c; } .alert-danger { background-color: #f2dede; border-color: #ebccd1; color: #a94442; } .alert-danger hr { border-top-color: #e4b9c0; } .alert-danger .alert-link { color: #843534; } @font-face { font-family: 'Glyphicons Halflings'; src: url('../res/fonts/glyphicons-halflings-regular.eot'); src: url('../res/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../res/fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../res/fonts/glyphicons-halflings-regular.woff') format('woff'), url('../res/fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../res/fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg'); } .glyphicon { position: relative; top: 1px; display: inline-block; font-family: 'Glyphicons Halflings'; font-style: normal; font-weight: normal; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .glyphicon-asterisk:before { content: "\2a"; } .glyphicon-plus:before { content: "\2b"; } .glyphicon-euro:before, .glyphicon-eur:before { content: "\20ac"; } .glyphicon-minus:before { content: "\2212"; } .glyphicon-cloud:before { content: "\2601"; } .glyphicon-envelope:before { content: "\2709"; } .glyphicon-pencil:before { content: "\270f"; } .glyphicon-glass:before { content: "\e001"; } .glyphicon-music:before { content: "\e002"; } .glyphicon-search:before { content: "\e003"; } .glyphicon-heart:before { content: "\e005"; } .glyphicon-star:before { content: "\e006"; } .glyphicon-star-empty:before { content: "\e007"; } .glyphicon-user:before { content: "\e008"; } .glyphicon-film:before { content: "\e009"; } .glyphicon-th-large:before { content: "\e010"; } .glyphicon-th:before { content: "\e011"; } .glyphicon-th-list:before { content: "\e012"; } .glyphicon-ok:before { content: "\e013"; } .glyphicon-remove:before { content: "\e014"; } .glyphicon-zoom-in:before { content: "\e015"; } .glyphicon-zoom-out:before { content: "\e016"; } .glyphicon-off:before { content: "\e017"; } .glyphicon-signal:before { content: "\e018"; } .glyphicon-cog:before { content: "\e019"; } .glyphicon-trash:before { content: "\e020"; } .glyphicon-home:before { content: "\e021"; } .glyphicon-file:before { content: "\e022"; } .glyphicon-time:before { content: "\e023"; } .glyphicon-road:before { content: "\e024"; } .glyphicon-download-alt:before { content: "\e025"; } .glyphicon-download:before { content: "\e026"; } .glyphicon-upload:before { content: "\e027"; } .glyphicon-inbox:before { content: "\e028"; } .glyphicon-play-circle:before { content: "\e029"; } .glyphicon-repeat:before { content: "\e030"; } .glyphicon-refresh:before { content: "\e031"; } .glyphicon-list-alt:before { content: "\e032"; } .glyphicon-lock:before { content: "\e033"; } .glyphicon-flag:before { content: "\e034"; } .glyphicon-headphones:before { content: "\e035"; } .glyphicon-volume-off:before { content: "\e036"; } .glyphicon-volume-down:before { content: "\e037"; } .glyphicon-volume-up:before { content: "\e038"; } .glyphicon-qrcode:before { content: "\e039"; } .glyphicon-barcode:before { content: "\e040"; } .glyphicon-tag:before { content: "\e041"; } .glyphicon-tags:before { content: "\e042"; } .glyphicon-book:before { content: "\e043"; } .glyphicon-bookmark:before { content: "\e044"; } .glyphicon-print:before { content: "\e045"; } .glyphicon-camera:before { content: "\e046"; } .glyphicon-font:before { content: "\e047"; } .glyphicon-bold:before { content: "\e048"; } .glyphicon-italic:before { content: "\e049"; } .glyphicon-text-height:before { content: "\e050"; } .glyphicon-text-width:before { content: "\e051"; } .glyphicon-align-left:before { content: "\e052"; } .glyphicon-align-center:before { content: "\e053"; } .glyphicon-align-right:before { content: "\e054"; } .glyphicon-align-justify:before { content: "\e055"; } .glyphicon-list:before { content: "\e056"; } .glyphicon-indent-left:before { content: "\e057"; } .glyphicon-indent-right:before { content: "\e058"; } .glyphicon-facetime-video:before { content: "\e059"; } .glyphicon-picture:before { content: "\e060"; } .glyphicon-map-marker:before { content: "\e062"; } .glyphicon-adjust:before { content: "\e063"; } .glyphicon-tint:before { content: "\e064"; } .glyphicon-edit:before { content: "\e065"; } .glyphicon-share:before { content: "\e066"; } .glyphicon-check:before { content: "\e067"; } .glyphicon-move:before { content: "\e068"; } .glyphicon-step-backward:before { content: "\e069"; } .glyphicon-fast-backward:before { content: "\e070"; } .glyphicon-backward:before { content: "\e071"; } .glyphicon-play:before { content: "\e072"; } .glyphicon-pause:before { content: "\e073"; } .glyphicon-stop:before { content: "\e074"; } .glyphicon-forward:before { content: "\e075"; } .glyphicon-fast-forward:before { content: "\e076"; } .glyphicon-step-forward:before { content: "\e077"; } .glyphicon-eject:before { content: "\e078"; } .glyphicon-chevron-left:before { content: "\e079"; } .glyphicon-chevron-right:before { content: "\e080"; } .glyphicon-plus-sign:before { content: "\e081"; } .glyphicon-minus-sign:before { content: "\e082"; } .glyphicon-remove-sign:before { content: "\e083"; } .glyphicon-ok-sign:before { content: "\e084"; } .glyphicon-question-sign:before { content: "\e085"; } .glyphicon-info-sign:before { content: "\e086"; } .glyphicon-screenshot:before { content: "\e087"; } .glyphicon-remove-circle:before { content: "\e088"; } .glyphicon-ok-circle:before { content: "\e089"; } .glyphicon-ban-circle:before { content: "\e090"; } .glyphicon-arrow-left:before { content: "\e091"; } .glyphicon-arrow-right:before { content: "\e092"; } .glyphicon-arrow-up:before { content: "\e093"; } .glyphicon-arrow-down:before { content: "\e094"; } .glyphicon-share-alt:before { content: "\e095"; } .glyphicon-resize-full:before { content: "\e096"; } .glyphicon-resize-small:before { content: "\e097"; } .glyphicon-exclamation-sign:before { content: "\e101"; } .glyphicon-gift:before { content: "\e102"; } .glyphicon-leaf:before { content: "\e103"; } .glyphicon-fire:before { content: "\e104"; } .glyphicon-eye-open:before { content: "\e105"; } .glyphicon-eye-close:before { content: "\e106"; } .glyphicon-warning-sign:before { content: "\e107"; } .glyphicon-plane:before { content: "\e108"; } .glyphicon-calendar:before { content: "\e109"; } .glyphicon-random:before { content: "\e110"; } .glyphicon-comment:before { content: "\e111"; } .glyphicon-magnet:before { content: "\e112"; } .glyphicon-chevron-up:before { content: "\e113"; } .glyphicon-chevron-down:before { content: "\e114"; } .glyphicon-retweet:before { content: "\e115"; } .glyphicon-shopping-cart:before { content: "\e116"; } .glyphicon-folder-close:before { content: "\e117"; } .glyphicon-folder-open:before { content: "\e118"; } .glyphicon-resize-vertical:before { content: "\e119"; } .glyphicon-resize-horizontal:before { content: "\e120"; } .glyphicon-hdd:before { content: "\e121"; } .glyphicon-bullhorn:before { content: "\e122"; } .glyphicon-bell:before { content: "\e123"; } .glyphicon-certificate:before { content: "\e124"; } .glyphicon-thumbs-up:before { content: "\e125"; } .glyphicon-thumbs-down:before { content: "\e126"; } .glyphicon-hand-right:before { content: "\e127"; } .glyphicon-hand-left:before { content: "\e128"; } .glyphicon-hand-up:before { content: "\e129"; } .glyphicon-hand-down:before { content: "\e130"; } .glyphicon-circle-arrow-right:before { content: "\e131"; } .glyphicon-circle-arrow-left:before { content: "\e132"; } .glyphicon-circle-arrow-up:before { content: "\e133"; } .glyphicon-circle-arrow-down:before { content: "\e134"; } .glyphicon-globe:before { content: "\e135"; } .glyphicon-wrench:before { content: "\e136"; } .glyphicon-tasks:before { content: "\e137"; } .glyphicon-filter:before { content: "\e138"; } .glyphicon-briefcase:before { content: "\e139"; } .glyphicon-fullscreen:before { content: "\e140"; } .glyphicon-dashboard:before { content: "\e141"; } .glyphicon-paperclip:before { content: "\e142"; } .glyphicon-heart-empty:before { content: "\e143"; } .glyphicon-link:before { content: "\e144"; } .glyphicon-phone:before { content: "\e145"; } .glyphicon-pushpin:before { content: "\e146"; } .glyphicon-usd:before { content: "\e148"; } .glyphicon-gbp:before { content: "\e149"; } .glyphicon-sort:before { content: "\e150"; } .glyphicon-sort-by-alphabet:before { content: "\e151"; } .glyphicon-sort-by-alphabet-alt:before { content: "\e152"; } .glyphicon-sort-by-order:before { content: "\e153"; } .glyphicon-sort-by-order-alt:before { content: "\e154"; } .glyphicon-sort-by-attributes:before { content: "\e155"; } .glyphicon-sort-by-attributes-alt:before { content: "\e156"; } .glyphicon-unchecked:before { content: "\e157"; } .glyphicon-expand:before { content: "\e158"; } .glyphicon-collapse-down:before { content: "\e159"; } .glyphicon-collapse-up:before { content: "\e160"; } .glyphicon-log-in:before { content: "\e161"; } .glyphicon-flash:before { content: "\e162"; } .glyphicon-log-out:before { content: "\e163"; } .glyphicon-new-window:before { content: "\e164"; } .glyphicon-record:before { content: "\e165"; } .glyphicon-save:before { content: "\e166"; } .glyphicon-open:before { content: "\e167"; } .glyphicon-saved:before { content: "\e168"; } .glyphicon-import:before { content: "\e169"; } .glyphicon-export:before { content: "\e170"; } .glyphicon-send:before { content: "\e171"; } .glyphicon-floppy-disk:before { content: "\e172"; } .glyphicon-floppy-saved:before { content: "\e173"; } .glyphicon-floppy-remove:before { content: "\e174"; } .glyphicon-floppy-save:before { content: "\e175"; } .glyphicon-floppy-open:before { content: "\e176"; } .glyphicon-credit-card:before { content: "\e177"; } .glyphicon-transfer:before { content: "\e178"; } .glyphicon-cutlery:before { content: "\e179"; } .glyphicon-header:before { content: "\e180"; } .glyphicon-compressed:before { content: "\e181"; } .glyphicon-earphone:before { content: "\e182"; } .glyphicon-phone-alt:before { content: "\e183"; } .glyphicon-tower:before { content: "\e184"; } .glyphicon-stats:before { content: "\e185"; } .glyphicon-sd-video:before { content: "\e186"; } .glyphicon-hd-video:before { content: "\e187"; } .glyphicon-subtitles:before { content: "\e188"; } .glyphicon-sound-stereo:before { content: "\e189"; } .glyphicon-sound-dolby:before { content: "\e190"; } .glyphicon-sound-5-1:before { content: "\e191"; } .glyphicon-sound-6-1:before { content: "\e192"; } .glyphicon-sound-7-1:before { content: "\e193"; } .glyphicon-copyright-mark:before { content: "\e194"; } .glyphicon-registration-mark:before { content: "\e195"; } .glyphicon-cloud-download:before { content: "\e197"; } .glyphicon-cloud-upload:before { content: "\e198"; } .glyphicon-tree-conifer:before { content: "\e199"; } .glyphicon-tree-deciduous:before { content: "\e200"; } .glyphicon-cd:before { content: "\e201"; } .glyphicon-save-file:before { content: "\e202"; } .glyphicon-open-file:before { content: "\e203"; } .glyphicon-level-up:before { content: "\e204"; } .glyphicon-copy:before { content: "\e205"; } .glyphicon-paste:before { content: "\e206"; } .glyphicon-alert:before { content: "\e209"; } .glyphicon-equalizer:before { content: "\e210"; } .glyphicon-king:before { content: "\e211"; } .glyphicon-queen:before { content: "\e212"; } .glyphicon-pawn:before { content: "\e213"; } .glyphicon-bishop:before { content: "\e214"; } .glyphicon-knight:before { content: "\e215"; } .glyphicon-baby-formula:before { content: "\e216"; } .glyphicon-tent:before { content: "\26fa"; } .glyphicon-blackboard:before { content: "\e218"; } .glyphicon-bed:before { content: "\e219"; } .glyphicon-apple:before { content: "\f8ff"; } .glyphicon-erase:before { content: "\e221"; } .glyphicon-hourglass:before { content: "\231b"; } .glyphicon-lamp:before { content: "\e223"; } .glyphicon-duplicate:before { content: "\e224"; } .glyphicon-piggy-bank:before { content: "\e225"; } .glyphicon-scissors:before { content: "\e226"; } .glyphicon-bitcoin:before { content: "\e227"; } .glyphicon-btc:before { content: "\e227"; } .glyphicon-xbt:before { content: "\e227"; } .glyphicon-yen:before { content: "\00a5"; } .glyphicon-jpy:before { content: "\00a5"; } .glyphicon-ruble:before { content: "\20bd"; } .glyphicon-rub:before { content: "\20bd"; } .glyphicon-scale:before { content: "\e230"; } .glyphicon-ice-lolly:before { content: "\e231"; } .glyphicon-ice-lolly-tasted:before { content: "\e232"; } .glyphicon-education:before { content: "\e233"; } .glyphicon-option-horizontal:before { content: "\e234"; } .glyphicon-option-vertical:before { content: "\e235"; } .glyphicon-menu-hamburger:before { content: "\e236"; } .glyphicon-modal-window:before { content: "\e237"; } .glyphicon-oil:before { content: "\e238"; } .glyphicon-grain:before { content: "\e239"; } .glyphicon-sunglasses:before { content: "\e240"; } .glyphicon-text-size:before { content: "\e241"; } .glyphicon-text-color:before { content: "\e242"; } .glyphicon-text-background:before { content: "\e243"; } .glyphicon-object-align-top:before { content: "\e244"; } .glyphicon-object-align-bottom:before { content: "\e245"; } .glyphicon-object-align-horizontal:before { content: "\e246"; } .glyphicon-object-align-left:before { content: "\e247"; } .glyphicon-object-align-vertical:before { content: "\e248"; } .glyphicon-object-align-right:before { content: "\e249"; } .glyphicon-triangle-right:before { content: "\e250"; } .glyphicon-triangle-left:before { content: "\e251"; } .glyphicon-triangle-bottom:before { content: "\e252"; } .glyphicon-triangle-top:before { content: "\e253"; } .glyphicon-console:before { content: "\e254"; } .glyphicon-superscript:before { content: "\e255"; } .glyphicon-subscript:before { content: "\e256"; } .glyphicon-menu-left:before { content: "\e257"; } .glyphicon-menu-right:before { content: "\e258"; } .glyphicon-menu-down:before { content: "\e259"; } .glyphicon-menu-up:before { content: "\e260"; } .caret { display: inline-block; width: 0; height: 0; margin-left: 2px; vertical-align: middle; border-top: 4px dashed; border-top: 4px solid \9; border-right: 4px solid transparent; border-left: 4px solid transparent; } .dropup, .dropdown { position: relative; } .dropdown-toggle:focus { outline: 0; } .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: 1000; display: none; float: left; min-width: 160px; padding: 5px 0; margin: 2px 0 0; list-style: none; font-size: 14px; text-align: left; background-color: #fff; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 4px; -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); background-clip: padding-box; } .dropdown-menu.pull-right { right: 0; left: auto; } .dropdown-menu .divider { height: 1px; margin: 9px 0; overflow: hidden; background-color: #e5e5e5; } .dropdown-menu > li > a { display: block; padding: 3px 20px; clear: both; font-weight: normal; line-height: 1.42857143; color: #333333; white-space: nowrap; } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { text-decoration: none; color: #262626; background-color: #f5f5f5; } .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { color: #fff; text-decoration: none; outline: 0; background-color: #337ab7; } .dropdown-menu > .disabled > a, .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { color: #777777; } .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { text-decoration: none; background-color: transparent; background-image: none; filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); cursor: not-allowed; } .open > .dropdown-menu { display: block; } .open > a { outline: 0; } .dropdown-menu-right { left: auto; right: 0; } .dropdown-menu-left { left: 0; right: auto; } .dropdown-header { display: block; padding: 3px 20px; font-size: 12px; line-height: 1.42857143; color: #777777; white-space: nowrap; } .dropdown-backdrop { position: fixed; left: 0; right: 0; bottom: 0; top: 0; z-index: 990; } .pull-right > .dropdown-menu { right: 0; left: auto; } .dropup .caret, .navbar-fixed-bottom .dropdown .caret { border-top: 0; border-bottom: 4px dashed; border-bottom: 4px solid \9; content: ""; } .dropup .dropdown-menu, .navbar-fixed-bottom .dropdown .dropdown-menu { top: auto; bottom: 100%; margin-bottom: 2px; } @media (min-width: 768px) { .navbar-right .dropdown-menu { left: auto; right: 0; } .navbar-right .dropdown-menu-left { left: 0; right: auto; } } @-webkit-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } @keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } .progress { overflow: hidden; height: 20px; margin-bottom: 20px; background-color: #f5f5f5; border-radius: 4px; -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); } .progress-bar { float: left; width: 0%; height: 100%; font-size: 12px; line-height: 20px; color: #fff; text-align: center; background-color: #337ab7; -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); -webkit-transition: width 0.6s ease; -o-transition: width 0.6s ease; transition: width 0.6s ease; } .progress-striped .progress-bar, .progress-bar-striped { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-size: 40px 40px; } .progress.active .progress-bar, .progress-bar.active { -o-animation: progress-bar-stripes 2s linear infinite; -webkit-animation: progress-bar-stripes 2s linear infinite; animation: progress-bar-stripes 2s linear infinite; } .progress-bar-success { background-color: #5cb85c; } .progress-striped .progress-bar-success { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-info { background-color: #5bc0de; } .progress-striped .progress-bar-info { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-warning { background-color: #f0ad4e; } .progress-striped .progress-bar-warning { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-danger { background-color: #d9534f; } .progress-striped .progress-bar-danger { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } table { background-color: transparent; } caption { padding-top: 8px; padding-bottom: 8px; color: #777777; text-align: left; } th { text-align: left; } .table { width: 100%; max-width: 100%; margin-bottom: 20px; } .table > thead > tr > th, .table > tbody > tr > th, .table > tfoot > tr > th, .table > thead > tr > td, .table > tbody > tr > td, .table > tfoot > tr > td { padding: 8px; line-height: 1.42857143; vertical-align: top; border-top: 1px solid #ddd; } .table > thead > tr > th { vertical-align: bottom; border-bottom: 2px solid #ddd; } .table > caption + thead > tr:first-child > th, .table > colgroup + thead > tr:first-child > th, .table > thead:first-child > tr:first-child > th, .table > caption + thead > tr:first-child > td, .table > colgroup + thead > tr:first-child > td, .table > thead:first-child > tr:first-child > td { border-top: 0; } .table > tbody + tbody { border-top: 2px solid #ddd; } .table .table { background-color: #fff; } .table-condensed > thead > tr > th, .table-condensed > tbody > tr > th, .table-condensed > tfoot > tr > th, .table-condensed > thead > tr > td, .table-condensed > tbody > tr > td, .table-condensed > tfoot > tr > td { padding: 5px; } .table-bordered { border: 1px solid #ddd; } .table-bordered > thead > tr > th, .table-bordered > tbody > tr > th, .table-bordered > tfoot > tr > th, .table-bordered > thead > tr > td, .table-bordered > tbody > tr > td, .table-bordered > tfoot > tr > td { border: 1px solid #ddd; } .table-bordered > thead > tr > th, .table-bordered > thead > tr > td { border-bottom-width: 2px; } .table-striped > tbody > tr:nth-of-type(odd) { background-color: #f9f9f9; } .table-hover > tbody > tr:hover { background-color: #f5f5f5; } table col[class*="col-"] { position: static; float: none; display: table-column; } table td[class*="col-"], table th[class*="col-"] { position: static; float: none; display: table-cell; } .table > thead > tr > td.active, .table > tbody > tr > td.active, .table > tfoot > tr > td.active, .table > thead > tr > th.active, .table > tbody > tr > th.active, .table > tfoot > tr > th.active, .table > thead > tr.active > td, .table > tbody > tr.active > td, .table > tfoot > tr.active > td, .table > thead > tr.active > th, .table > tbody > tr.active > th, .table > tfoot > tr.active > th { background-color: #f5f5f5; } .table-hover > tbody > tr > td.active:hover, .table-hover > tbody > tr > th.active:hover, .table-hover > tbody > tr.active:hover > td, .table-hover > tbody > tr:hover > .active, .table-hover > tbody > tr.active:hover > th { background-color: #e8e8e8; } .table > thead > tr > td.success, .table > tbody > tr > td.success, .table > tfoot > tr > td.success, .table > thead > tr > th.success, .table > tbody > tr > th.success, .table > tfoot > tr > th.success, .table > thead > tr.success > td, .table > tbody > tr.success > td, .table > tfoot > tr.success > td, .table > thead > tr.success > th, .table > tbody > tr.success > th, .table > tfoot > tr.success > th { background-color: #dff0d8; } .table-hover > tbody > tr > td.success:hover, .table-hover > tbody > tr > th.success:hover, .table-hover > tbody > tr.success:hover > td, .table-hover > tbody > tr:hover > .success, .table-hover > tbody > tr.success:hover > th { background-color: #d0e9c6; } .table > thead > tr > td.info, .table > tbody > tr > td.info, .table > tfoot > tr > td.info, .table > thead > tr > th.info, .table > tbody > tr > th.info, .table > tfoot > tr > th.info, .table > thead > tr.info > td, .table > tbody > tr.info > td, .table > tfoot > tr.info > td, .table > thead > tr.info > th, .table > tbody > tr.info > th, .table > tfoot > tr.info > th { background-color: #d9edf7; } .table-hover > tbody > tr > td.info:hover, .table-hover > tbody > tr > th.info:hover, .table-hover > tbody > tr.info:hover > td, .table-hover > tbody > tr:hover > .info, .table-hover > tbody > tr.info:hover > th { background-color: #c4e3f3; } .table > thead > tr > td.warning, .table > tbody > tr > td.warning, .table > tfoot > tr > td.warning, .table > thead > tr > th.warning, .table > tbody > tr > th.warning, .table > tfoot > tr > th.warning, .table > thead > tr.warning > td, .table > tbody > tr.warning > td, .table > tfoot > tr.warning > td, .table > thead > tr.warning > th, .table > tbody > tr.warning > th, .table > tfoot > tr.warning > th { background-color: #fcf8e3; } .table-hover > tbody > tr > td.warning:hover, .table-hover > tbody > tr > th.warning:hover, .table-hover > tbody > tr.warning:hover > td, .table-hover > tbody > tr:hover > .warning, .table-hover > tbody > tr.warning:hover > th { background-color: #faf2cc; } .table > thead > tr > td.danger, .table > tbody > tr > td.danger, .table > tfoot > tr > td.danger, .table > thead > tr > th.danger, .table > tbody > tr > th.danger, .table > tfoot > tr > th.danger, .table > thead > tr.danger > td, .table > tbody > tr.danger > td, .table > tfoot > tr.danger > td, .table > thead > tr.danger > th, .table > tbody > tr.danger > th, .table > tfoot > tr.danger > th { background-color: #f2dede; } .table-hover > tbody > tr > td.danger:hover, .table-hover > tbody > tr > th.danger:hover, .table-hover > tbody > tr.danger:hover > td, .table-hover > tbody > tr:hover > .danger, .table-hover > tbody > tr.danger:hover > th { background-color: #ebcccc; } .table-responsive { overflow-x: auto; min-height: 0.01%; } @media screen and (max-width: 767px) { .table-responsive { width: 100%; margin-bottom: 15px; overflow-y: hidden; -ms-overflow-style: -ms-autohiding-scrollbar; border: 1px solid #ddd; } .table-responsive > .table { margin-bottom: 0; } .table-responsive > .table > thead > tr > th, .table-responsive > .table > tbody > tr > th, .table-responsive > .table > tfoot > tr > th, .table-responsive > .table > thead > tr > td, .table-responsive > .table > tbody > tr > td, .table-responsive > .table > tfoot > tr > td { white-space: nowrap; } .table-responsive > .table-bordered { border: 0; } .table-responsive > .table-bordered > thead > tr > th:first-child, .table-responsive > .table-bordered > tbody > tr > th:first-child, .table-responsive > .table-bordered > tfoot > tr > th:first-child, .table-responsive > .table-bordered > thead > tr > td:first-child, .table-responsive > .table-bordered > tbody > tr > td:first-child, .table-responsive > .table-bordered > tfoot > tr > td:first-child { border-left: 0; } .table-responsive > .table-bordered > thead > tr > th:last-child, .table-responsive > .table-bordered > tbody > tr > th:last-child, .table-responsive > .table-bordered > tfoot > tr > th:last-child, .table-responsive > .table-bordered > thead > tr > td:last-child, .table-responsive > .table-bordered > tbody > tr > td:last-child, .table-responsive > .table-bordered > tfoot > tr > td:last-child { border-right: 0; } .table-responsive > .table-bordered > tbody > tr:last-child > th, .table-responsive > .table-bordered > tfoot > tr:last-child > th, .table-responsive > .table-bordered > tbody > tr:last-child > td, .table-responsive > .table-bordered > tfoot > tr:last-child > td { border-bottom: 0; } } .ym-button { display: inline-block; white-space: nowrap; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #eeeeee), color-stop(100%, #cccccc)); background: -webkit-linear-gradient(top, #eeeeee, #cccccc); background: -moz-linear-gradient(top, #eeeeee, #cccccc); background: -ms-linear-gradient(top, #eeeeee, #cccccc); background: linear-gradient("to bottom", #eeeeee, #cccccc); zoom: 1; border: 1px solid #777; border-radius: .2em; -webkit-box-shadow: 0 0 1px 1px rgba(255, 255, 255, 0.8) inset, 0 1px 0 rgba(0, 0, 0, 0.15); box-shadow: 0 0 1px 1px rgba(255, 255, 255, 0.8) inset, 0 1px 0 rgba(0, 0, 0, 0.15); color: #333 !important; font: normal 1em/2em Arial, Helvetica; padding: 0 1.5em; overflow: visible; text-decoration: none !important; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.8); outline: none; } .ym-button.ym-xlarge { font-size: 1.5em; } .ym-button.ym-large { font-size: 1.2857em; } .ym-button:not(.solid):hover { background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fafafa), color-stop(100%, #dddddd)); background: -webkit-linear-gradient(top, #fafafa, #dddddd); background: -moz-linear-gradient(top, #fafafa, #dddddd); background: -ms-linear-gradient(top, #fafafa, #dddddd); background: linear-gradient("to bottom", #fafafa, #dddddd); zoom: 1; } .ym-button:not(.solid):active { -webkit-box-shadow: inset 2px 2px 3px rgba(0, 0, 0, 0.2); box-shadow: inset 2px 2px 3px rgba(0, 0, 0, 0.2); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #cccccc), color-stop(100%, #bbbbbb)); background: -webkit-linear-gradient(top, #cccccc, #bbbbbb); background: -moz-linear-gradient(top, #cccccc, #bbbbbb); background: -ms-linear-gradient(top, #cccccc, #bbbbbb); background: linear-gradient("to bottom", #cccccc, #bbbbbb); zoom: 1; position: relative; } .ym-button.ym-primary { -webkit-box-shadow: 0 0 1px 1px rgba(255, 255, 255, 0.3) inset, 0 1px 0 rgba(0, 0, 0, 0.15); box-shadow: 0 0 1px 1px rgba(255, 255, 255, 0.3) inset, 0 1px 0 rgba(0, 0, 0, 0.15); background-color: #8888ee; background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #8888ee), color-stop(100% #6666cc)); background-image: -webkit-linear-gradient(top, #8888ee 0, #6666cc 100%); background-image: -moz-linear-gradient(top, #8888ee 0, #6666cc 100%); background-image: -ms-linear-gradient(top, #8888ee 0, #6666cc 100%); background-image: -o-linear-gradient(top, #8888ee 0, #6666cc 100%); background-image: linear-gradient(top, #8888ee 0, #6666cc 100%); zoom: 1; border: 1px solid #007; color: #fff !important; text-shadow: 0 1px 0 rgba(0, 0, 0, 0.8); } .ym-button.ym-primary:not(.solid):hover { background-color: #8888ff; background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #8888ff), color-stop(100% #6666dd)); background-image: -webkit-linear-gradient(top, #8888ff 0, #6666dd 100%); background-image: -moz-linear-gradient(top, #8888ff 0, #6666dd 100%); background-image: -ms-linear-gradient(top, #8888ff 0, #6666dd 100%); background-image: -o-linear-gradient(top, #8888ff 0, #6666dd 100%); background-image: linear-gradient(top, #8888ff 0, #6666dd 100%); zoom: 1; } .ym-button.ym-primary:not(.solid):active { -webkit-box-shadow: inset 2px 2px 3px rgba(0, 0, 0, 0.2); box-shadow: inset 2px 2px 3px rgba(0, 0, 0, 0.2); background-color: #8888cc; background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #8888cc), color-stop(100% #6666aa)); background-image: -webkit-linear-gradient(top, #8888cc 0, #6666aa 100%); background-image: -moz-linear-gradient(top, #8888cc 0, #6666aa 100%); background-image: -ms-linear-gradient(top, #8888cc 0, #6666aa 100%); background-image: -o-linear-gradient(top, #8888cc 0, #6666aa 100%); background-image: linear-gradient(top, #8888cc 0, #6666aa 100%); zoom: 1; } .ym-button.ym-black { -webkit-box-shadow: inset 0px 1px rgba(255, 255, 255, 0.24), 0px 1px 5px rgba(0, 0, 0, 0.6); box-shadow: inset 0px 1px rgba(255, 255, 255, 0.24), 0px 1px 5px rgba(0, 0, 0, 0.6); background-color: #5c5b5b; background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #5c5b5b), color-stop(100% #353535)); background-image: -webkit-linear-gradient(top, #5c5b5b 0, #353535 100%); background-image: -moz-linear-gradient(top, #5c5b5b 0, #353535 100%); background-image: -ms-linear-gradient(top, #5c5b5b 0, #353535 100%); background-image: -o-linear-gradient(top, #5c5b5b 0, #353535 100%); background-image: linear-gradient(top, #5c5b5b 0, #353535 100%); zoom: 1; border: 1px solid rgba(0, 0, 0, 0.5); color: #fff !important; text-shadow: 0 1px 0 rgba(0, 0, 0, 0.8); } .ym-button.ym-success { -webkit-box-shadow: 0 0 1px 1px rgba(255, 255, 255, 0.3) inset, 0 1px 0 rgba(0, 0, 0, 0.15); box-shadow: 0 0 1px 1px rgba(255, 255, 255, 0.3) inset, 0 1px 0 rgba(0, 0, 0, 0.15); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #66bb66), color-stop(100%, #449944)); background: -webkit-linear-gradient(top, #66bb66, #449944); background: -moz-linear-gradient(top, #66bb66, #449944); background: -ms-linear-gradient(top, #66bb66, #449944); background: linear-gradient("to bottom", #66bb66, #449944); zoom: 1; border: 1px solid #070; color: #fff !important; text-shadow: 0 1px 0 rgba(0, 0, 0, 0.8); } .ym-button.ym-success:not(.solid):hover { background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #66cc66), color-stop(100%, #55aa55)); background: -webkit-linear-gradient(top, #66cc66, #55aa55); background: -moz-linear-gradient(top, #66cc66, #55aa55); background: -ms-linear-gradient(top, #66cc66, #55aa55); background: linear-gradient("to bottom", #66cc66, #55aa55); zoom: 1; } .ym-button.ym-success:not(.solid):active { -webkit-box-shadow: inset 2px 2px 3px rgba(0, 0, 0, 0.2); box-shadow: inset 2px 2px 3px rgba(0, 0, 0, 0.2); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #66aa66), color-stop(100%, #448844)); background: -webkit-linear-gradient(top, #66aa66, #448844); background: -moz-linear-gradient(top, #66aa66, #448844); background: -ms-linear-gradient(top, #66aa66, #448844); background: linear-gradient("to bottom", #66aa66, #448844); zoom: 1; } .ym-button.ym-warning { -webkit-box-shadow: 0 0 1px 1px rgba(255, 255, 255, 0.3) inset, 0 1px 0 rgba(0, 0, 0, 0.15); box-shadow: 0 0 1px 1px rgba(255, 255, 255, 0.3) inset, 0 1px 0 rgba(0, 0, 0, 0.15); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ddaa44), color-stop(100%, #bb7722)); background: -webkit-linear-gradient(top, #ddaa44, #bb7722); background: -moz-linear-gradient(top, #ddaa44, #bb7722); background: -ms-linear-gradient(top, #ddaa44, #bb7722); background: linear-gradient("to bottom", #ddaa44, #bb7722); zoom: 1; border: 1px solid #970; color: #fff !important; text-shadow: 0 1px 0 rgba(0, 0, 0, 0.8); } .ym-button.ym-warning:not(.solid):hover { background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #eebb55), color-stop(100%, #cc8833)); background: -webkit-linear-gradient(top, #eebb55, #cc8833); background: -moz-linear-gradient(top, #eebb55, #cc8833); background: -ms-linear-gradient(top, #eebb55, #cc8833); background: linear-gradient("to bottom", #eebb55, #cc8833); zoom: 1; } .ym-button.ym-warning:not(.solid):active { -webkit-box-shadow: inset 2px 2px 3px rgba(0, 0, 0, 0.2); box-shadow: inset 2px 2px 3px rgba(0, 0, 0, 0.2); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #cc9944), color-stop(100%, #aa6622)); background: -webkit-linear-gradient(top, #cc9944, #aa6622); background: -moz-linear-gradient(top, #cc9944, #aa6622); background: -ms-linear-gradient(top, #cc9944, #aa6622); background: linear-gradient("to bottom", #cc9944, #aa6622); zoom: 1; } .ym-button.ym-danger { -webkit-box-shadow: 0 0 1px 1px rgba(255, 255, 255, 0.3) inset, 0 1px 0 rgba(0, 0, 0, 0.15); box-shadow: 0 0 1px 1px rgba(255, 255, 255, 0.3) inset, 0 1px 0 rgba(0, 0, 0, 0.15); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #bb6666), color-stop(100%, #994444)); background: -webkit-linear-gradient(top, #bb6666, #994444); background: -moz-linear-gradient(top, #bb6666, #994444); background: -ms-linear-gradient(top, #bb6666, #994444); background: linear-gradient("to bottom", #bb6666, #994444); zoom: 1; border: 1px solid #700; color: #fff !important; text-shadow: 0 1px 0 rgba(0, 0, 0, 0.8); } .ym-button.ym-danger:not(.solid):hover { background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #cc6666), color-stop(100%, #aa5555)); background: -webkit-linear-gradient(top, #cc6666, #aa5555); background: -moz-linear-gradient(top, #cc6666, #aa5555); background: -ms-linear-gradient(top, #cc6666, #aa5555); background: linear-gradient("to bottom", #cc6666, #aa5555); zoom: 1; } .ym-button.ym-danger:not(.solid):active { -webkit-box-shadow: inset 2px 2px 3px rgba(0, 0, 0, 0.2); box-shadow: inset 2px 2px 3px rgba(0, 0, 0, 0.2); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #aa5555), color-stop(100%, #884444)); background: -webkit-linear-gradient(top, #aa5555, #884444); background: -moz-linear-gradient(top, #aa5555, #884444); background: -ms-linear-gradient(top, #aa5555, #884444); background: linear-gradient("to bottom", #aa5555, #884444); zoom: 1; } .normal-pointer { cursor: url("../res/cursor/normal.cur"), auto !important; } .text-pointer { cursor: url("../res/cursor/text.cur"), auto !important; } .pointer-cursor { cursor: url("../res/cursor/link.cur"), pointer !important; } .clickable { cursor: url("../res/cursor/link.cur"), pointer !important; } .clickable > * { cursor: url("../res/cursor/link.cur"), pointer !important; } .clickable:active, .clickable:focus, .clickable:hover, .clickable:visited { cursor: url("../res/cursor/link.cur"), pointer !important; } .filter-gray { -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); -ms-filter: grayscale(100%); -o-filter: grayscale(100%); filter: grayscale(100%); filter: gray; } .unselectable { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } .clickable { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; -webkit-tap-highlight-color: transparent; } .clickable > * { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } img { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } .caret { display: inline-block; width: 0; height: 0; margin-left: 2px; border-top: 4px solid; border-right: 4px solid transparent; border-left: 4px solid transparent; vertical-align: middle; margin: 0px; } .fill { height: 100%; width: 100%; } .abs-fill { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; } .trans { -webkit-transition: -webkit-transform 400ms; -o-transition: -webkit-transform 400ms; transition: -webkit-transform 400ms; -webkit-transition: -moz-transform 400ms; -o-transition: -moz-transform 400ms; transition: -moz-transform 400ms; -webkit-transition: -ms-transform 400ms; -o-transition: -ms-transform 400ms; transition: -ms-transform 400ms; -webkit-transition: -o-transform 400ms; -o-transition: -o-transform 400ms; transition: -o-transform 400ms; -webkit-transition: transform 400ms; -o-transition: transform 400ms; transition: transform 400ms; } .hide { display: none !important; } *[data-show="0"] { display: none !important; } .round { border-radius: 10000px; overflow: hidden; } .transform-center { position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } .vertical-center { position: absolute; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); } .horizontal-center { position: absolute; left: 50%; -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%); } .blue-panel { background-color: rgba(70, 130, 180, 0.25); border-radius: 10px; border: #4682b4 1px solid; } .bold { font-weight: bold; } html, body { margin: 0; padding: 0; background-color: black; } body { box-sizing: border-box; font-family: Arial, Verdana, "微软雅黑", "黑体", serif; -webkit-font-smoothing: subpixel-antialiased; font-smoothing: subpixel-antialiased; cursor: url("../res/cursor/normal.cur"), auto !important; } button { font-family: Arial, Verdana, "微软雅黑", "黑体", serif; } #wrap { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; } * { box-sizing: border-box; outline: none; } h1, h2, h3, h4, h5, h6 { cursor: url("../res/cursor/text.cur"), auto !important; } button, a { cursor: url("../res/cursor/link.cur"), pointer !important; } button { cursor: url("../res/cursor/link.cur"), pointer !important; -webkit-tap-highlight-color: transparent; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } button > * { cursor: url("../res/cursor/link.cur"), pointer !important; } button:active, button:focus, button:hover, button:visited { cursor: url("../res/cursor/link.cur"), pointer !important; } button > * { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } input { height: 30px; border-radius: 3px; border: 1px solid #aaa; } .scene-wrap { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; width: 960px; height: 540px; overflow: visible; } .scene-wrap > .debug { position: absolute; left: 0; top: -40px; opacity: 0.03; } .scene-wrap > .debug-panel { position: absolute; z-index: 100; } .scene-wrap > .debug-panel .go-scene { display: block; } .scene { border-radius: 7px; z-index: 0; position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; overflow: hidden; opacity: 1; transition: 0s all linear; } .scene.ng-enter-active { opacity: 1; } .scene.ng-leave { opacity: 0; } .scene[data-scene="bigmap"] .big-bg { transition: 0.3s opacity linear; } .scene[data-scene="bigmap"] .big-bg.active { opacity: 0.7; } .scene[data-scene="character"] { background: url("../res/Background/make.png"); background-position: bottom; background-size: cover; } .scene[data-scene="character"] .center-area { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; color: wheat; text-align: center; } .scene[data-scene="character"] .center-area .btn-wrap { margin-bottom: 10px; } .scene[data-scene="character"] .center-area .btn-wrap .tip { margin-top: -5px; } .scene[data-scene="character"] .center-area .points-remain { margin-bottom: 10px; } .scene[data-scene="character"] .settings-wrap { display: inline-block; } .scene[data-scene="character"] .settings-wrap .title { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; color: white; margin-left: 5px; margin-bottom: 2px; color: wheat; position: relative; bottom: -17px; left: 12px; } .scene[data-scene="character"] .settings-wrap .settings-content-wrap { height: 230px; width: 402px; position: relative; padding: 17px; z-index: 1; } .scene[data-scene="character"] .settings-wrap .settings-content-wrap .item { margin-left: 2px; margin-top: 2px; } .scene[data-scene="character"] .settings-wrap .settings-content-wrap .item .cost { font-size: 10px; line-height: 10px; height: 10px; position: absolute; bottom: 6px; right: 8px; } .scene[data-scene="character"] .settings-wrap .settings-content-wrap .item .cost img { width: 9px; } .scene[data-scene="character"] .settings-wrap.goodness { position: absolute; left: 15px; top: 5px; } .scene[data-scene="character"] .settings-wrap.goodness-selecting { position: absolute; right: 15px; top: 5px; } .scene[data-scene="character"] .settings-wrap.weakness { position: absolute; left: 15px; bottom: 5px; } .scene[data-scene="character"] .settings-wrap.weakness-selecting { position: absolute; right: 15px; bottom: 5px; } .scene[data-scene="chat"] .chat-wrap { position: absolute; height: 100%; width: 100%; } .scene[data-scene="chat"] .chat-wrap > .emphasize .big-half { position: absolute; right: 1100px; left: auto; bottom: -154px; width: auto; height: 660px; transition: right 1000ms cubic-bezier(0.26, 0.815, 0.59, 0.995); } .scene[data-scene="chat"] .chat-wrap > .emphasize .big-half.active { right: 57px; } .scene[data-scene="chat"] .chat-wrap > .emphasize .big-half.leave { right: -557px; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr { position: absolute; width: 70%; bottom: 10%; height: 70px; right: -716px; transition: right 1000ms cubic-bezier(0.26, 0.815, 0.59, 0.995); } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr.active { right: -40px; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr.leave { right: 1540px; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr .panel-wrap { height: 60px; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr .panel-mask { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; -webkit-transform: skewX(44.7deg); -ms-transform: skewX(44.7deg); transform: skewX(44.7deg); overflow: hidden; bottom: 6px; top: 2px; left: 32px; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr .panel-mask .mask { position: absolute; top: 0; border: 0; width: 253px; transform: skewX(-84deg); background-color: rgba(255, 255, 255, 0.5); bottom: 0; left: -530px; transition: left 500ms; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr .panel-mask .mask.active { left: 121px; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr .panel-mask .mask.leave { left: -521px; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr .panel { height: 100%; border-style: solid; border-width: 68.4px 0px 0px 70.8px; -webkit-border-image: url("../res/UI/chat_emphasize.png") 114 1 0 118 fill repeat round; -moz-border-image: url("../res/UI/chat_emphasize.png") 114 1 0 118 fill repeat round; -ms-border-image: url("../res/UI/chat_emphasize.png") 114 1 0 118 fill repeat round; -o-border-image: url("../res/UI/chat_emphasize.png") 114 1 0 118 fill repeat round; border-image: url("../res/UI/chat_emphasize.png") 114 1 0 118 fill repeat round; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr .title { position: absolute; left: 40px; top: -24px; font-size: 20px; font-weight: bold; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr .title .title-bg { background-color: black; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr .title text { stroke: #444; stroke-width: 1; stroke-linejoin: round; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr .content { position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); left: 64%; top: 134%; font-size: 40px; font-family: "chinese"; margin: auto; } .scene[data-scene="chat"] .chat-wrap > .emphasize .descr .content text { stroke: black; stroke-width: 1; stroke-linejoin: round; } .scene[data-scene="chat"] .layer { position: absolute; height: 100%; border: none; width: 100%; } .scene[data-scene="chat"] .btn-wrap { display: flex; flex-direction: column; justify-content: center; } .scene[data-scene="chat"] .btn-wrap.chatting { padding-bottom: 180px; } .scene[data-scene="chat"] .btn-wrap .chat-btn-group .single-btn-wrap { text-align: center; } .scene[data-scene="chat"] .btn-wrap .chat-btn-group .single-btn-wrap button.menu_btn, .scene[data-scene="chat"] .btn-wrap .chat-btn-group .single-btn-wrap input.menu_btn, .scene[data-scene="chat"] .btn-wrap .chat-btn-group .single-btn-wrap .input-group { font-size: 20px; min-width: 300px; display: inline-block; margin-bottom: 10px; text-align: center; } .scene[data-scene="chat"] .text-wrap .chat-text { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; background-image: url("../res/UI/messageBack.png"); position: relative; top: 350px; width: 960px; height: 180px; padding-top: 30px; padding-left: 50px; padding-right: 50px; } .scene[data-scene="chat"] .text-wrap .chat-text .chat-content { text-align: left; font-size: 25px; color: #ffffff; text-indent: 2em; margin: 0px; } .scene[data-scene="chat"] .text-wrap .name-wrap { position: absolute; top: 315px; left: 0px; width: 398px; height: 53px; } .scene[data-scene="chat"] .text-wrap .name-wrap .name-content { font-size: 23px; margin-top: 18px; text-align: center; width: 250px; } .scene[data-scene="chat"] .half-wrap .pp { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%); position: absolute; height: 450px; bottom: 0; } .scene[data-scene="chat"] .mood-wrap { position: absolute; height: 100%; width: 100%; text-align: center; } .scene[data-scene="chat"] .mood-wrap .mood { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; } .scene[data-scene="chat"] .bg { width: 100%; background-size: cover; } .scene[data-scene="chat"] .bg.ease { transition: all 1000ms cubic-bezier(0.26, 0.815, 0.59, 0.995); } .scene[data-scene="cover"] { background: url("../res/Background/cover.jpg"); text-align: center; background-position: bottom; background-size: cover; } .scene[data-scene="cover"] .logo-title { font-size: 43px; color: white; margin-top: 100px; margin-bottom: 80px; text-shadow: 1px 1px 3px black; } .scene[data-scene="cover"] .btns { display: inline-block; } .scene[data-scene="cover"] .btn { margin-bottom: 40px; display: block; text-align: center; position: relative; } .scene[data-scene="cover"] .btn:before { content: ""; width: 23px; height: 56px; position: absolute; top: 0; bottom: 0; left: -40px; background-size: contain; opacity: 0; -webkit-transition: 0.2s ease-out all; -o-transition: 0.2s ease-out all; transition: 0.2s ease-out all; } .scene[data-scene="cover"] .btn:hover:before { -webkit-transform: translateX(10px); -ms-transform: translateX(10px); transform: translateX(10px); opacity: 1; } .scene[data-scene="cover"] .btn:nth-child(1):hover:before { background: url("../res/pixel/me.gif") no-repeat; } .scene[data-scene="cover"] .btn:nth-child(2):hover:before { background: url("../res/pixel/chenjiong.gif") no-repeat; } .scene[data-scene="cover"] .btn:nth-child(3):hover:before { background: url("../res/pixel/zhangfuai.gif") no-repeat; } .scene[data-scene="home"] { background-image: url("../res/Background/home.jpg"); background-repeat: no-repeat; background-size: contain; background-size: cover; } .scene[data-scene="home"] .shop-panel { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; z-index: 101; border-radius: 10px; text-align: center; width: 770px; height: 500px; -webkit-transition: 0.3s transform ease-out; -o-transition: 0.3s transform ease-out; transition: 0.3s transform ease-out; -webkit-transform: translateY(-30px); -ms-transform: translateY(-30px); transform: translateY(-30px); } .scene[data-scene="home"] .shop-panel.active { -webkit-transform: translateY(0px); -ms-transform: translateY(0px); transform: translateY(0px); } .scene[data-scene="home"] .shop-panel .items-money-sum, .scene[data-scene="home"] .shop-panel .have-money { position: absolute; color: wheat; } .scene[data-scene="home"] .shop-panel .items-money-sum { bottom: 37px; left: 230px; } .scene[data-scene="home"] .shop-panel .have-money { bottom: 37px; left: 53px; } .scene[data-scene="home"] .shop-panel .close { display: inline-block; background-size: contain; position: absolute; right: -15px; top: -15px; z-index: 1; width: 60px; height: 60px; } .scene[data-scene="home"] .shop-panel .dark-scroll::-webkit-scrollbar { width: 5px; } .scene[data-scene="home"] .shop-panel .dark-scroll::-webkit-scrollbar-thumb { border-radius: 5px; background: #4d4444; border: 0px solid #fff; } .scene[data-scene="home"] .shop-panel .checkout { position: absolute; right: 39px; bottom: 30px; } .scene[data-scene="home"] .shop-panel .checkout.poor { opacity: 0.5; } .scene[data-scene="home"] .shop-panel .page-select { z-index: 1; position: relative; } .scene[data-scene="home"] .shop-panel .page-select > button { position: absolute; top: 18px; padding: 0 10px; word-break: break-all; white-space: pre-wrap; outline: none; color: #f5deb3; opacity: 0.4; -webkit-transform: translateY(-100%); -ms-transform: translateY(-100%); transform: translateY(-100%); } .scene[data-scene="home"] .shop-panel .page-select > button.active { z-index: 1; color: wheat; opacity: 1; } .scene[data-scene="home"] .shop-panel .page-select > button[data-page="器件"] { left: 30px; } .scene[data-scene="home"] .shop-panel .page-select > button[data-page="仪器"] { left: 90px; } .scene[data-scene="home"] .shop-panel .center-panel-wrap { position: absolute; left: 30px; right: 30px; top: 50px; bottom: 65px; color: wheat; } .scene[data-scene="home"] .shop-panel .center-panel-wrap > .bg { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; pointer-events: none; z-index: 1; } .scene[data-scene="home"] .shop-panel .center-panel { position: absolute; top: 20px; right: 20px; bottom: 20px; left: 20px; z-index: 2; border-radius: 10px; text-align: left; } .scene[data-scene="home"] .shop-panel .center-panel .list { position: relative; overflow: auto; width: 60%; height: 100%; } .scene[data-scene="home"] .shop-panel .center-panel .list table { width: 98%; } .scene[data-scene="home"] .shop-panel .center-panel .list .item-line:hover { background-color: rgba(0, 0, 0, 0.2); } .scene[data-scene="home"] .shop-panel .center-panel .list th.name { width: 120px; } .scene[data-scene="home"] .shop-panel .center-panel .list th.price { width: 70px; text-align: right; } .scene[data-scene="home"] .shop-panel .center-panel .list td.price { text-align: right; } .scene[data-scene="home"] .shop-panel .center-panel .list th.cnt { text-align: center; } .scene[data-scene="home"] .shop-panel .center-panel .list th.have { width: 35px; text-align: center; } .scene[data-scene="home"] .shop-panel .center-panel .list th.price { text-align: right; } .scene[data-scene="home"] .shop-panel .center-panel .list td.cnt { width: 130px; text-align: center; } .scene[data-scene="home"] .shop-panel .center-panel .list td.cnt button { width: 25px; height: 25px; text-align: center; padding: 0; padding-top: 3px; margin: 0; outline: none; } .scene[data-scene="home"] .shop-panel .center-panel .list td.cnt button span { line-height: 14px; width: 13px; height: 13px; text-align: center; } .scene[data-scene="home"] .shop-panel .center-panel .list td.cnt .value { display: inline-block; width: 40px; text-align: center; } .scene[data-scene="home"] .shop-panel .center-panel .list td.have { text-align: center; } .scene[data-scene="home"] .shop-panel .center-panel .items-desc-frame { position: relative; width: 40%; position: absolute; right: 0; top: 0; bottom: 0; padding: 10px; padding-top: 20px; font-size: 14px; overflow: auto; } .scene[data-scene="home"] .shop-panel .center-panel .items-desc-frame .tag { margin-bottom: 5px; } .scene[data-scene="home"] .shop-panel .center-panel .items-desc-frame .value { text-indent: 2em; margin-top: 0; margin-bottom: 10px; } .scene[data-scene="home"] .shop-panel .center-panel .items-desc-frame .icon-wrap { text-align: center; } .scene[data-scene="home"] .shop-panel .center-panel .items-desc-frame .icon-wrap .icon { width: 100px; } .scene[data-scene="home"] .shop-panel > .bg { height: 100%; width: 100%; } .scene[data-scene="home"] .basic { padding: 3px 7px 4px 7px; border-radius: 5px; display: inline-block; font-size: 0; color: white; background-color: #337ab7; } .scene[data-scene="home"] .basic .key { vertical-align: middle; display: inline-block; padding: 6px 10px 5px 5px; font-size: 18px; } .scene[data-scene="home"] .basic .value { height: 30px; vertical-align: middle; overflow: hidden; display: inline-block; text-align: center; border-radius: 4px; font-size: 18px; color: black; background-color: white; padding: 3px 0px; width: 100px; } .scene[data-scene="home"] .basic.name { position: absolute; top: 15px; left: 15px; } .scene[data-scene="home"] .basic.power { position: absolute; top: 70px; left: 15px; } .scene[data-scene="home"] .basic.power .value { width: 150px; background-color: white; color: black; position: relative; } .scene[data-scene="home"] .basic.power .value > span { border-radius: 4px; } .scene[data-scene="home"] .basic.power .value > .bg { background-color: white; } .scene[data-scene="home"] .basic.power .value > .fill { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; transition: 1s width linear; right: auto; background-color: #449d44; width: 100%; } .scene[data-scene="home"] .basic.power .value > .text { position: relative; color: white; text-shadow: 1px 1px 1px black, -1px 1px 1px black, 1px -1px 1px black, -1px -1px 1px black; } .scene[data-scene="home"] .basic.term { position: absolute; top: 125px; left: 15px; background-color: #6f5499; } .scene[data-scene="home"] .basic.month { position: absolute; top: 180px; left: 15px; background-color: #6f5499; } .scene[data-scene="home"] .basic.month .rotate { display: inline-block; line-height: 24px; } .scene[data-scene="home"] .basic.month .rotate.transition { transition: 0.5s transform ease-out; } .scene[data-scene="home"] .basic.month .rotate.upon { -webkit-transform: translateY(-24px); -ms-transform: translateY(-24px); transform: translateY(-24px); } .scene[data-scene="home"] .basic.month .rotate.upon.active { -webkit-transform: translateY(0px); -ms-transform: translateY(0px); transform: translateY(0px); } .scene[data-scene="home"] .basic.month .rotate.below { -webkit-transform: translateY(-24px); -ms-transform: translateY(-24px); transform: translateY(-24px); } .scene[data-scene="home"] .basic.month .rotate.below.active { -webkit-transform: translateY(0px); -ms-transform: translateY(0px); transform: translateY(0px); } .scene[data-scene="home"] .settings { background-image: url("../res/icon/cogwheel3.svg"); background-repeat: no-repeat; background-size: contain; width: 40px; height: 40px; border-radius: 10000px; overflow: hidden; position: absolute; left: 218px; top: 15px; transition: 0.2s transform ease-out; } .scene[data-scene="home"] .settings:hover { -webkit-transform: rotate(10deg); -ms-transform: rotate(10deg); transform: rotate(10deg); } .scene[data-scene="home"] .skill-wrap { display: inline-block; text-align: center; padding-bottom: 5px; height: 90px; width: 116px; vertical-align: middle; } .scene[data-scene="home"] .skill-wrap .skill { display: inline-block; position: relative; height: 52px; width: 48px; } .scene[data-scene="home"] .skill-wrap .skill .skill-icon { position: absolute; top: 3px; left: 3px; } .scene[data-scene="home"] .skill-wrap .skill .skill-bg { position: absolute; top: 0; left: 0; z-index: 1; } .scene[data-scene="home"] .skill-wrap .skill .level { color: white; position: absolute; left: 63%; z-index: 1; bottom: -3%; font-size: 13px; width: 26px; text-align: center; font-weight: normal; margin-bottom: 0; } .scene[data-scene="home"] .skill-wrap .name { position: relative; top: -3px; display: block; font-weight: normal; } .scene[data-scene="home"] .action-panel { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; top: auto; bottom: 15px; left: 15px; right: 15px; border-radius: 10px; height: 135px; background-color: rgba(255, 255, 255, 0.8); border: 6px solid #337ab7; box-sizing: content-box; overflow: hidden; } .scene[data-scene="home"] .action-panel > .corner { position: absolute; zoom: 0.4; } .scene[data-scene="home"] .action-panel > .corner.left-top { left: 0; top: 0; } .scene[data-scene="home"] .action-panel > .corner.left-bottom { left: 0; bottom: 0; -webkit-transform: rotate(-90deg); -ms-transform: rotate(-90deg); transform: rotate(-90deg); } .scene[data-scene="home"] .action-panel > .corner.right-top { right: 0; top: 0; -webkit-transform: scaleX(-1); -ms-transform: scaleX(-1); transform: scaleX(-1); } .scene[data-scene="home"] .action-panel > .corner.right-bottom { right: 0; bottom: 0; -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .scene[data-scene="home"] .action-panel > .border { position: absolute; zoom: 0.4; } .scene[data-scene="home"] .action-panel > .border.top { top: 0; width: 90%; height: 61px; margin-left: 224px; } .scene[data-scene="home"] .action-panel > .border.bottom { bottom: 0; width: 90%; height: 61px; margin-left: 224px; -webkit-transform: scaleY(-1); -ms-transform: scaleY(-1); transform: scaleY(-1); } .scene[data-scene="home"] .action-panel .panel-bg { position: absolute; left: 20px; top: 20px; bottom: 20px; right: 20px; background-color: #1f1916; } .scene[data-scene="home"] .action-panel .actions-frame { overflow: hidden; height: 135px; transition: 0.3s transform ease-out; position: relative; } .scene[data-scene="home"] .action-panel .actions-frame.active { -webkit-transform: translateY(100%); -ms-transform: translateY(100%); transform: translateY(100%); } .scene[data-scene="home"] .action-panel .actions-frame.action-top-frame { position: absolute; width: 100%; bottom: 135px; } .scene[data-scene="home"] .action-panel .actions-frame.class-detail .study-info { font-size: 18px; margin-top: 34px; margin-left: 500px; } .scene[data-scene="home"] .action-panel .actions-frame.class-detail .study-info div { margin-bottom: 15px; } .scene[data-scene="home"] .action-panel .actions-frame.class-detail .go-class { top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); position: absolute; left: 330px; } .scene[data-scene="home"] .action-panel .actions-frame.skill-select .skills-wrap { position: absolute; left: 116px; overflow: auto; top: 0; bottom: 0; padding: 10px 0; } .scene[data-scene="home"] .action-panel .actions-frame.skill-select .skills-wrap .skill-page { height: 100%; } .scene[data-scene="home"] .action-panel .action { display: inline-block; text-align: center; margin: 20px; width: 70px; } .scene[data-scene="home"] .action-panel .action.disabled { opacity: 0.7; } .scene[data-scene="home"] .action-panel .action:hover { transition: 0.1s transform linear; -webkit-transform: scale(1.1); -ms-transform: scale(1.1); transform: scale(1.1); } .scene[data-scene="home"] .action-panel .action img { height: 100%; width: 100%; } .scene[data-scene="home"] .action-panel .action[data-action="状态"] { float: right; } .scene[data-scene="home"] .action-panel .action.action-back { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; right: auto; left: 30px; height: 50px; } .scene[data-scene="home"] .action-show { background-color: white; width: 100px; height: 100px; border-radius: 10000px; overflow: hidden; position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; text-align: center; border: 5px solid #337ab7; transition: 0.1s opacity linear; } .scene[data-scene="home"] .action-show.ng-hide { opacity: 0; } .scene[data-scene="home"] .action-show img { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; display: inline-block; } .scene[data-scene="home"] .skill-detail { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; bottom: auto; top: auto; width: 300px; background-color: rgba(51, 122, 183, 0.8); padding: 15px; padding-bottom: 0; color: white; } .scene[data-scene="home"] .skill-detail .title { text-align: center; margin-top: 0; font-size: 16px; margin-bottom: 5px; line-height: 18px; } .scene[data-scene="home"] .skill-detail .key { margin-bottom: 0; } .scene[data-scene="home"] .skill-detail .value { margin-top: 0; margin-bottom: 20px; text-indent: 2em; } .scene[data-scene="home"] .shop-wrap { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; } .scene[data-scene="home"] .home-mask { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; z-index: 100; background-color: rgba(0, 0, 0, 0); transition: 0.3s background-color ease-out; } .scene[data-scene="home"] .home-mask.active { background-color: rgba(0, 0, 0, 0.3); } .scene[data-scene="home"] .mask { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; background-color: rgba(0, 0, 0, 0.5); } .scene[data-scene="home"] .settings-mask { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; } .scene[data-scene="home"] .settings-mask.active { background-color: rgba(0, 0, 0, 0.3); } .scene[data-scene="make"] { background: url("../res/Background/make.png"); background-position: bottom; background-size: cover; color: wheat; } .scene[data-scene="make"] .game-wrap { position: relative; box-sizing: content-box; } .scene[data-scene="make"] .game-wrap.active .row, .scene[data-scene="make"] .game-wrap.active .column { opacity: 1; } .scene[data-scene="make"] .game-wrap .grid { display: inline-block; } .scene[data-scene="make"] .game-wrap .row, .scene[data-scene="make"] .game-wrap .column { opacity: 0; transition: 0.5s opacity ease-out; } .scene[data-scene="make"] .game-wrap .row { border-bottom: 1px solid #0e0a02; position: absolute; left: 0; right: 0; bottom: auto; } .scene[data-scene="make"] .game-wrap .column { border-left: 1px solid #0e0a02; position: absolute; top: 0; bottom: 0; } .scene[data-scene="make"] .game-wrap .game-item { position: absolute; transition: 0.3s all; } .scene[data-scene="make"] .game-wrap .game-item.player { opacity: 0.5; } .scene[data-scene="make"] .game-wrap .game-item.player.active { opacity: 1; } .scene[data-scene="make"] > .center { left: 25%; width: 50%; top: 20px !important; } .scene[data-scene="make"] > .center .deep-header { width: 235px; transform: translateY(-15%); } .scene[data-scene="make"] > .center .deep-header > .deep-header-text { font-size: 18px; line-height: 59px; } .scene[data-scene="make"] > .center > main { position: absolute; top: 23px; right: 23px; bottom: 23px; left: 23px; top: 0px; padding-top: 10px; } .scene[data-scene="make"] > .center .main-content { transition: 0.3s all ease-out; } .scene[data-scene="make"] > .center .main-content.ng-hide.ng-hide-add { opacity: 0; } .scene[data-scene="make"] > .center .main-content[data-phase="ready-to-make"] { text-align: center; } .scene[data-scene="make"] > .center .main-content[data-phase="ready-to-make"] > header { margin-top: 20px; } .scene[data-scene="make"] > .center .main-content[data-phase="ready-to-make"] button.start-build { margin-bottom: 10px; } .scene[data-scene="make"] > .center .main-content[data-phase="ready-to-make"] .item { margin: 10px; margin-top: 0; } .scene[data-scene="make"] > .center .main-content[data-phase="ready-to-make"] section { margin-bottom: 15px; } .scene[data-scene="make"] > .center .main-content[data-phase="ready-to-make"] section.extension label { margin: 10px; } .scene[data-scene="make"] > .center .main-content[data-phase="making"] { width: 100%; height: 86%; display: flex; flex-direction: column; justify-content: center; align-items: center; margin-top: 35px; } .scene[data-scene="make"] > .center .main-content[data-phase="making"] .deep-item-star .star-icon { position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } .scene[data-scene="make"] > .center .main-content[data-phase="making"] .deep-item-star .round-num { position: absolute; top: 4px; left: 4px; font-size: 16px; display: inline-block; } .scene[data-scene="make"] > .center .main-content[data-phase="making"] .item-row { position: absolute; bottom: -4px; left: 0; right: 0; text-align: center; margin: auto; } .scene[data-scene="make"] > .center .main-content[data-phase="making"] .item-row .game-item-wrap { width: 40px; height: 40px; display: inline-block; overflow: visible; transition: all 0.5s; } .scene[data-scene="make"] > .center .main-content[data-phase="making"] .item-row .game-item-wrap.adding { transform: translateX(50px); width: 0; } .scene[data-scene="make"] > .center .main-content[data-phase="making"] .item-row .game-item-wrap .game-item { width: 40px; height: 40px; } .scene[data-scene="make"] > .top-block { position: absolute; top: 0; bottom: 0; display: inline-block; } .scene[data-scene="make"] > .left { left: 0%; width: 25%; padding-top: 40px; padding-left: 10px; padding-right: 10px; } .scene[data-scene="make"] > .left .go-back { position: absolute; left: 30px; bottom: 10px; } .scene[data-scene="make"] > .left .go-state { position: absolute; right: 30px; bottom: 10px; } .scene[data-scene="make"] > .left .deep-fill { transition: 0.3s width ease-out; } .scene[data-scene="make"] > .left .info-block { margin-bottom: 5px; } .scene[data-scene="make"] > .left .info-block header { margin-left: 10px; } .scene[data-scene="make"] > .left .info-block main { width: 100%; font-size: 15px; } .scene[data-scene="make"] > .left .btn-wrap { text-align: center; } .scene[data-scene="make"] > .left .btn-wrap button { margin: auto; margin-bottom: 10px; } .scene[data-scene="make"] > .right { left: 75%; width: 25%; top: 20px; padding: 17px 22px; } .scene[data-scene="make"] > .right > .section { padding-top: 10px; } .scene[data-scene="make"] > .right > .section > header { margin-bottom: 5px; } .scene[data-scene="make"] > .right .skill-wrap { width: 72px; height: auto; text-align: center; } .scene[data-scene="make"] > .right .skill-wrap .name { position: relative; top: -7px; font-size: 10px; } .scene[data-scene="make"] > .right .instrument, .scene[data-scene="make"] > .right .ext-instrument { margin-bottom: 10px; margin-left: 6px; position: relative; } .scene[data-scene="make"] > .right .instrument .name, .scene[data-scene="make"] > .right .ext-instrument .name { font-size: 12px; } .scene[data-scene="make"] > .right .left-header .item-icon { display: block; } .scene[data-scene="make-select"] { background-image: url("../res/Background/make.png"); background-repeat: no-repeat; background-size: contain; background-size: cover; } .scene[data-scene="make-select"] .select-target { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; height: 500px; width: 333px; } .scene[data-scene="make-select"] .select-target .go-back { position: absolute; right: -11px; bottom: -6px; -webkit-transform: translate(23%, 23%); -ms-transform: translate(23%, 23%); transform: translate(23%, 23%); } .scene[data-scene="make-select"] .select-target header { position: absolute; left: -100px; right: -100px; top: 10px; margin: auto; } .scene[data-scene="make-select"] .select-target header.little > span { font-size: 16px; } .scene[data-scene="make-select"] .select-target main { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; top: 69px; left: 40px; right: 40px; bottom: 35px; overflow: hidden; } .scene[data-scene="make-select"] .select-target main .page { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; transition: 0.3s transform ease-out; } .scene[data-scene="make-select"] .select-target main .page.left { -webkit-transform: translateX(-100%); -ms-transform: translateX(-100%); transform: translateX(-100%); } .scene[data-scene="make-select"] .select-target main .page.right { -webkit-transform: translateX(100%); -ms-transform: translateX(100%); transform: translateX(100%); } .scene[data-scene="make-select"] .select-target main .start-new-product { margin-bottom: 5px; } .scene[data-scene="make-select"] .select-target main .work { font-size: 14px; } .scene[data-scene="preload"] { text-align: center; } .scene[data-scene="preload"] .wrap { position: absolute; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); } .scene[data-scene="preload"] .wrap .loading-img { width: 20px; } .scene[data-scene="save"] { background: url("../res/Background/make.png"); background-position: bottom; background-size: cover; color: wheat; text-align: center; } .scene[data-scene="save"] > .go-back { position: absolute; left: 10px; bottom: 10px; } .scene[data-scene="save"] .btn-save { display: block; margin-bottom: 10px; min-width: 300px; height: 40px; } .scene[data-scene="save"] .select-save { width: 40%; height: 87%; margin: auto; margin-top: 45px; } .scene[data-scene="state"] > .wrap { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; } .scene[data-scene="state"] > .wrap > .back { background-image: url("../res/UI/blue_back_left.png"); background-repeat: no-repeat; background-size: contain; width: 50px; height: 50px; position: absolute; left: 10px; top: 10px; z-index: 1; transition: 0.05s transform linear; } .scene[data-scene="state"] > .wrap > .back:hover { -webkit-transform: scale(1.1); -ms-transform: scale(1.1); transform: scale(1.1); } .scene[data-scene="state"] .page-select-wrap { position: absolute; z-index: 1; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); top: 50%; left: 15px; height: 350px; display: flex; flex-direction: column; justify-content: space-between; } .scene[data-scene="state"] .page-select-wrap .page-select { width: 105px; height: 46px; opacity: 0.6; position: relative; outline: none; transition: all 0.1s linear; } .scene[data-scene="state"] .page-select-wrap .page-select > .bg { height: 100%; width: 100%; } .scene[data-scene="state"] .page-select-wrap .page-select > .cover { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; width: 100%; opacity: 0; } .scene[data-scene="state"] .page-select-wrap .page-select > .select { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; text-align: center; margin-top: 12px; color: #A1E0E7; } .scene[data-scene="state"] .page-select-wrap .page-select:hover { opacity: 1; } .scene[data-scene="state"] .page-select-wrap .page-select:active, .scene[data-scene="state"] .page-select-wrap .page-select.active { -webkit-transform: translateX(10%); -ms-transform: translateX(10%); transform: translateX(10%); opacity: 1; } .scene[data-scene="state"] .page { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; transition: 0.15s opacity linear; opacity: 1; background-size: cover; } .scene[data-scene="state"] .page.ng-hide { opacity: 0; } .scene[data-scene="state"] .page[data-page="status"] { background-image: url("../res/Background/state/state.jpg"); } .scene[data-scene="state"] .page[data-page="status"] .user-name, .scene[data-scene="state"] .page[data-page="status"] .job { background-color: #6f5499; color: white; position: absolute; right: 20px; top: 10px; padding: 5px 15px; font-size: 20px; display: inline-block; vertical-align: middle; } .scene[data-scene="state"] .page[data-page="status"] .job { right: 20px; top: 60px; } .scene[data-scene="state"] .page[data-page="status"] .money { position: absolute; left: 50%; -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%); bottom: 10px; font-size: 20px; color: white; background-image: linear-gradient(#5c5b5b, #353535); background-color: #5c5b5b; border: 1px solid rgba(0, 0, 0, 0.5); border-radius: 4px; box-shadow: inset 0px 1px rgba(255, 255, 255, 0.24), 0px 1px 5px rgba(0, 0, 0, 0.6); padding: 5px 15px; } .scene[data-scene="state"] .page[data-page="status"] .analog, .scene[data-scene="state"] .page[data-page="status"] .digital { position: absolute; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; font-size: 23px; color: white; transition: font-size 0.1s linear; text-align: center; text-shadow: 1px 1px 1px black; } .scene[data-scene="state"] .page[data-page="status"] .analog:hover, .scene[data-scene="state"] .page[data-page="status"] .digital:hover { text-shadow: 1px 1px 1px black, -1px -1px 1px black; } .scene[data-scene="state"] .page[data-page="status"] .analog img, .scene[data-scene="state"] .page[data-page="status"] .digital img { width: 60px; display: block; margin: 10px; } .scene[data-scene="state"] .page[data-page="status"] .analog { color: black; text-shadow: 1px 1px 1px white; left: 30%; top: 47%; } .scene[data-scene="state"] .page[data-page="status"] .analog:hover { text-shadow: 1px 1px 1px white, -1px -1px 1px white; } .scene[data-scene="state"] .page[data-page="status"] .digital { left: 61%; top: 55%; } .scene[data-scene="state"] .page[data-page="status"] .props-wrap { position: absolute; right: 100px; top: 220px; display: flex; flex-direction: column; } .scene[data-scene="state"] .page[data-page="status"] .props-wrap .prop { margin-bottom: 20px; } .scene[data-scene="state"] .page[data-page="status"] .prop { padding: 3px 7px 4px 7px; border-radius: 5px; display: inline-block; font-size: 0; color: white; background-color: steelblue; } .scene[data-scene="state"] .page[data-page="status"] .prop .key { display: inline-block; padding: 5px 10px 5px 5px; font-size: 18px; } .scene[data-scene="state"] .page[data-page="status"] .prop .value { display: inline-block; text-align: center; border-radius: 4px; font-size: 18px; color: black; background-color: white; padding: 3px 0px; width: 60px; } .scene[data-scene="state"] .page[data-page="status"] .basic-wrap { position: absolute; right: 60px; top: 30px; display: flex; flex-direction: column; } .scene[data-scene="state"] .page[data-page="status"] .basic-wrap .basic { margin-bottom: 15px; } .scene[data-scene="state"] .page[data-page="status"] .basic { padding: 3px 7px 4px 7px; border-radius: 5px; display: inline-block; font-size: 0; color: white; background-color: #6f5499; } .scene[data-scene="state"] .page[data-page="status"] .basic .key { display: inline-block; padding: 5px 10px 5px 5px; font-size: 18px; } .scene[data-scene="state"] .page[data-page="status"] .basic .value { display: inline-block; text-align: center; border-radius: 4px; font-size: 18px; color: black; background-color: white; padding: 3px 0px; width: 100px; } .scene[data-scene="state"] .page[data-page="skill"] { background-image: url("../res/Background/state/skill_bg.jpg"); } .scene[data-scene="state"] .page[data-page="skill"] .highlight { overflow: auto; padding: 9px 14px; margin-bottom: 14px; background-color: rgba(255, 255, 255, 0.3); border: 1px solid #e1e1e8; border-radius: 4px; position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; left: 200px; top: 20px; bottom: 20px; right: 30px; } .scene[data-scene="state"] .page[data-page="skill"] .highlight table { color: white; } .scene[data-scene="state"] .page[data-page="people"] { background-image: url("../res/Background/state/people_bg2.jpg"); } .scene[data-scene="state"] .page[data-page="people"] > .desc-wrap, .scene[data-scene="state"] .page[data-page="people"] > .select { position: absolute; background-color: rgba(70, 130, 180, 0.25); border-radius: 10px; border: #4682b4 1px solid; } .scene[data-scene="state"] .page[data-page="people"] > .desc-wrap { left: 200px; width: 550px; top: 50px; bottom: 50px; } .scene[data-scene="state"] .page[data-page="people"] > .desc-wrap .currentP { position: absolute; bottom: 0; left: 50px; height: 384px; } .scene[data-scene="state"] .page[data-page="people"] > .select { width: 160px; right: 30px; top: 50px; bottom: 50px; padding: 10px; overflow: auto; display: flex; flex-direction: row; flex-wrap: wrap; } .scene[data-scene="state"] .page[data-page="people"] > .select .pp-select { justify-content: space-around; width: 58px; height: 58px; display: inline-block; margin: 5px; border: 1px solid black; position: relative; overflow: hidden; padding-top: 5px; } .scene[data-scene="state"] .page[data-page="people"] > .select .pp-select img { width: 100%; pointer-events: none; } .scene[data-scene="state"] .page[data-page="item"] { background-image: url("../res/Background/state/item.jpg"); } .scene[data-scene="state"] .page[data-page="item"] .kind-wrap { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; left: 100px; bottom: auto; top: 10px; text-align: center; } .scene[data-scene="state"] .page[data-page="item"] .kind-wrap .item-kind-select { display: inline-block; margin: 0px 15px; opacity: 0.5; transition: opacity 0.1s linear; } .scene[data-scene="state"] .page[data-page="item"] .kind-wrap .item-kind-select:hover { opacity: 0.7; } .scene[data-scene="state"] .page[data-page="item"] .kind-wrap .item-kind-select.active { opacity: 1; } .scene[data-scene="state"] .page[data-page="item"] .kind-wrap .item-kind-select img { height: 65px; vertical-align: middle; } .scene[data-scene="state"] .page[data-page="item"] .kind-wrap .item-kind-select .name { vertical-align: middle; width: 17px; display: inline-block; } .scene[data-scene="state"] .page[data-page="item"] .items-wrap, .scene[data-scene="state"] .page[data-page="item"] .desc-wrap { top: 120px; bottom: 30px; } .scene[data-scene="state"] .page[data-page="item"] .items-frame { position: absolute; left: 180px; bottom: 20px; } .scene[data-scene="state"] .page[data-page="item"] .items-frame > .bg { width: 500px; } .scene[data-scene="state"] .page[data-page="item"] .items-wrap { position: absolute; left: 49px; width: 448px; top: 72px; padding: 13px; } .scene[data-scene="state"] .page[data-page="item"] .items-wrap .item-wrap { margin: 7px 15px; display: inline-block; position: relative; height: 95px; width: 64px; text-align: center; } .scene[data-scene="state"] .page[data-page="item"] .items-wrap .item-wrap .item-body-wrap { width: 64px; height: 64px; background-image: url("../res/UI/item_bg.svg"); background-repeat: no-repeat; background-size: contain; display: inline-block; position: relative; } .scene[data-scene="state"] .page[data-page="item"] .items-wrap .item-wrap .item-body-wrap img.item-icon { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; width: 55%; height: 55%; display: block; } .scene[data-scene="state"] .page[data-page="item"] .items-wrap .item-wrap label { color: #A1E0E7; font-weight: normal; position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; } .scene[data-scene="state"] .page[data-page="item"] .items-wrap .item-wrap label.name { bottom: auto; top: 70%; font-size: 14px; text-align: center; } .scene[data-scene="state"] .page[data-page="item"] .items-wrap .item-wrap label.cnt { font-size: 13px; left: auto; bottom: auto; right: 7%; top: 7%; } .scene[data-scene="state"] .page[data-page="item"] .items-desc-frame { position: absolute; right: 20px; width: 250px; padding: 0px; color: white; bottom: 22px; top: 105px; box-sizing: border-box; } .scene[data-scene="state"] .page[data-page="item"] .items-desc-frame > .bg { height: 100%; width: 100%; opacity: 0.7; } .scene[data-scene="state"] .page[data-page="item"] .items-desc-frame .desc-wrap { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; left: 15px; right: 15px; top: 15px; } .scene[data-scene="state"] .page[data-page="item"] .items-desc-frame .desc-wrap .icon-wrap { padding-top: 5px; text-align: center; } .scene[data-scene="state"] .page[data-page="item"] .items-desc-frame .desc-wrap .icon-wrap img { width: 80px; display: inline-block; } .scene[data-scene="state"] .page[data-page="item"] .items-desc-frame .desc-wrap .tag { font-weight: normal; } .scene[data-scene="state"] .page[data-page="item"] .items-desc-frame .desc-wrap p { text-indent: 2em; margin-top: 0; margin-bottom: 5px; } .hover-card-wrap { position: absolute; } .hover-card-wrap > .hover-card { z-index: 1000; color: wheat; background-color: rgba(0, 0, 0, 0.7); font-size: 12px; } .hover-card-wrap[hover-card="character"] > .hover-card { width: 200px; } .hover-card-wrap[hover-card="character"] > .hover-card .summary { margin-bottom: 10px; } .hover-card-wrap[hover-card="item"] > .hover-card { width: 250px; } .hover-card-wrap[hover-card="item"] > .hover-card .key { margin: 0; } .hover-card-wrap[hover-card="item"] > .hover-card .value { margin: 0; margin-bottom: 10px; } #editor-wrap { background-color: white; } #editor-wrap .table-wrap { width: 100%; overflow-x: auto; } @font-face { font-family: 'chinese'; src: url('../res/fonts/chinese.ttf'); }
{ "content_hash": "83987651b5bf732568d39e9b9b8f4e42", "timestamp": "", "source": "github", "line_count": 5000, "max_line_length": 406, "avg_line_length": 24.5706, "alnum_prop": 0.6695725786102089, "repo_name": "blackmiaool/kexie_game", "id": "3840b45aafe0e9476fe6eaa24d43b6b13626816e", "size": "122889", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "dist/css/style.css", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "38" }, { "name": "CSS", "bytes": "625645" }, { "name": "HTML", "bytes": "236043" }, { "name": "JavaScript", "bytes": "2111258" }, { "name": "Lua", "bytes": "30651" }, { "name": "Python", "bytes": "50202" }, { "name": "Shell", "bytes": "1749" } ], "symlink_target": "" }
* Added the [-g] option to output an animated gif ## [0.2.3] ### Changes * Removed the [-n] option * Bundle the and dependencies into **build/ffbetool.js** so the can be run without requiring `npm install` * Refactored for maintainability * Use ES6 ## [0.2.2] ### New Features * Added [-n] option to use the out filename format `$uid_$action` ### Changes * Default out filename format to `unit_$action_$uid` ## [0.2.1] ### New Features * Added [-e] option to include empty frames * Added [-v] option to print out more information to console * Added [-j] option to save the animation sheet information as json file ### Changes * Fixed blend mode * Some optimizations * Recursively create directories to output path if necessary * Print less to console by default * Made the logs to console more informative ## [0.2.0] ### Changes * Flip part image before applying rotation * Some optimizations * Removed the [-e] option to include empty frames * Removed the [-d] divider option * Promisification of callbacks ## [0.1.0] ### Notes * Initial Release
{ "content_hash": "c2cf20bc4433ef784294b29214d3c2ff", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 106, "avg_line_length": 20.5, "alnum_prop": 0.7082551594746717, "repo_name": "dsxragnarok/FFBE-sprite-sheet-assembler", "id": "c42e5540084b1a1b15853f40d69c50be4f644822", "size": "1096", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2757269" } ], "symlink_target": "" }
/** * @param {Object} $ - Global jQuery object * @param {Object} bolt - The Bolt module */ (function ($, bolt) { 'use strict'; /** * BUIC listing widget. * * @license http://opensource.org/licenses/mit-license.php MIT License * @author rarila * * @class buicListing * @memberOf jQuery.widget.bolt */ $.widget('bolt.buicListing', /** @lends jQuery.widget.bolt.buicListing.prototype */ { /** * The constructor of the listing widget. * * @private */ _create: function () { this.csrfToken = this.element.data('bolt_csrf_token'); this.contentType = this.element.data('contenttype'); this.element.find('table.listing tbody').buicListingPart(); }, /** * Execute commands on triggered button. * * @param {string} action - Triggered action (Allowed: 'delete'). * @param {array} ids - Array of ids to perform the action on. * @param {string} buttonText - Button text to be displayed on ok button. */ modifyRecords: function (action, ids, buttonText) { var self = this, modifications = {}, actions = { 'delete': { 'name': bolt.data('recordlisting.action.delete'), 'cmd': {'delete': null} }, 'publish': { 'name': bolt.data('recordlisting.action.publish'), 'cmd': {'modify': {'status': 'published'}} }, 'depublish': { 'name': bolt.data('recordlisting.action.depublish'), 'cmd': {'modify': {'status': 'held'}} }, 'draft': { 'name': bolt.data('recordlisting.action.draft'), 'cmd': {'modify': {'status': 'draft'}} } }, msg; // Build POST data. modifications[self.contentType] = {}; $(ids).each(function () { modifications[self.contentType][this] = actions[action].cmd; }); // Build message: if (ids.length === 1) { msg = bolt.data('recordlisting.confirm.one'); } else { msg = bolt.data('recordlisting.confirm.multi', {'%NUMBER%': '<b>' + ids.length + '</b>'}); } msg = msg + '<br><br><b>' + bolt.data('recordlisting.confirm.no-undo') + '</b>'; // Remove when done: msg = msg + '<hr><b style="color:red;">Anti CSRF token functionality still disabled ' + 'in Bolt\Controller\Async\Records::modify</b>'; bootbox.dialog({ message: msg, title: actions[action].name, buttons: { cancel: { label: bolt.data('recordlisting.action.cancel'), className: 'btn-default' }, ok: { label: buttonText, className: 'btn-primary', callback: function () { var url = bolt.conf('paths.async') + 'content/action' + window.location.search; $.ajax({ url: url, type: 'POST', data: { 'bolt_csrf_token': self.csrfToken, 'contenttype': self.contentType, 'actions': modifications }, success: function (data) { self.element.html(data); self.element.find('table.listing tbody').buicListingPart(); /* Commented out for now - it has to be decided if functionality is wanted // Restore selection state. $(table).find('td input:checkbox[name="checkRow"]').each(function () { var id = $(this).parents('tr').attr('id').substr(5); if (id && ids.indexOf(id) >= 0) { this.checked = true; self._rowSelection(this); } }); $(table).find('tbody').each(function () { self._handleSelectionState(this); }); */ }, error: function (jqXHR, textStatus, errorThrown) { console.log(jqXHR.status + ' (' + errorThrown + '):'); console.log(JSON.parse(jqXHR.responseText)); }, dataType: 'html' }); } } } }); } }); })(jQuery, Bolt);
{ "content_hash": "ddd8b2eb74d1c8ce66c8c57edd71dd4c", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 108, "avg_line_length": 41.666666666666664, "alnum_prop": 0.3850909090909091, "repo_name": "nantunes/bolt", "id": "acc0082caa1a6f77cb8d1305aa9a8979761446ae", "size": "5500", "binary": false, "copies": "3", "ref": "refs/heads/blimp", "path": "app/src/js/widgets/buic/buicListing.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1464" }, { "name": "CSS", "bytes": "315135" }, { "name": "HTML", "bytes": "390483" }, { "name": "JavaScript", "bytes": "1016204" }, { "name": "Nginx", "bytes": "2075" }, { "name": "PHP", "bytes": "2281465" }, { "name": "Shell", "bytes": "2461" } ], "symlink_target": "" }
"""Utilities for Backward differentiation formula (BDF) solver.""" import collections import numpy as np import tensorflow.compat.v1 as tf1 import tensorflow.compat.v2 as tf from tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.internal import prefer_static as ps from tensorflow_probability.python.internal import tensorshape_util MAX_ORDER = 5 ORDERS = np.arange(0, MAX_ORDER + 1) RECIPROCAL_SUMS = np.concatenate([[np.nan], np.cumsum(1. / ORDERS[1:])]) def error_ratio(backward_difference, error_coefficient, tol): """Computes the ratio of the error in the computed state to the tolerance.""" tol_cast = tf.cast(tol, backward_difference.dtype) error_ratio_ = tf.norm(error_coefficient * backward_difference / tol_cast) return tf.cast(error_ratio_, tf.abs(backward_difference).dtype) def first_step_size( atol, first_order_error_coefficient, initial_state_vec, initial_time, ode_fn_vec, rtol, safety_factor, epsilon=1e-12, max_step_size=1., min_step_size=1e-12, ): """Selects the first step size to use.""" next_time = initial_time + epsilon first_derivative = ode_fn_vec(initial_time, initial_state_vec) state_dtype = initial_state_vec.dtype next_state_vec = initial_state_vec + first_derivative * epsilon second_derivative = (ode_fn_vec(next_time, next_state_vec) - first_derivative) / epsilon tol = tf.cast(atol + rtol * tf.abs(initial_state_vec), state_dtype) # Local truncation error of an order one step is # `err(step_size) = first_order_error_coefficient * second_derivative * # * step_size**2`. # Choose the largest `step_size` such that `norm(err(step_size) / tol) <= 1`. norm = tf.norm(first_order_error_coefficient * second_derivative / tol) step_size = tf.cast(tf.math.rsqrt(norm), tf.abs(initial_state_vec).dtype) return tf.clip_by_value(safety_factor * step_size, min_step_size, max_step_size) def interpolate_backward_differences(backward_differences, order, step_size_ratio): """Updates backward differences when a change in the step size occurs.""" state_dtype = backward_differences.dtype interpolation_matrix_ = interpolation_matrix(state_dtype, order, step_size_ratio) interpolation_matrix_unit_step_size_ratio = interpolation_matrix( state_dtype, order, 1.) interpolated_backward_differences_orders_one_to_five = tf.matmul( interpolation_matrix_unit_step_size_ratio, tf.matmul(interpolation_matrix_, backward_differences[1:MAX_ORDER + 1])) interpolated_backward_differences = tf.concat([ tf.gather(backward_differences, [0]), interpolated_backward_differences_orders_one_to_five, ps.zeros( ps.stack([2, ps.shape(backward_differences)[1]]), dtype=state_dtype), ], 0) return interpolated_backward_differences def interpolation_matrix(dtype, order, step_size_ratio): """Creates the matrix used to interpolate backward differences.""" orders = tf.cast(tf.range(1, MAX_ORDER + 1), dtype=dtype) i = orders[:, tf.newaxis] j = orders[tf.newaxis, :] # Matrix whose (i, j)-th entry (`1 <= i, j <= order`) is # `1/j! (0 - i * step_size_ratio) * ... * ((j-1) - i * step_size_ratio)`. step_size_ratio_cast = tf.cast(step_size_ratio, dtype) full_interpolation_matrix = tf.math.cumprod( ((j - 1) - i * step_size_ratio_cast) / j, axis=1) zeros_matrix = tf.zeros_like(full_interpolation_matrix) interpolation_matrix_ = tf1.where( tf.range(1, MAX_ORDER + 1) <= order, tf.transpose( tf1.where( tf.range(1, MAX_ORDER + 1) <= order, tf.transpose(full_interpolation_matrix), zeros_matrix)), zeros_matrix) return interpolation_matrix_ def newton(backward_differences, max_num_iters, newton_coefficient, ode_fn_vec, order, step_size, time, tol, unitary, upper): """Runs Newton's method to solve the BDF equation.""" initial_guess = tf.reduce_sum( tf1.where( tf.range(MAX_ORDER + 1) <= order, backward_differences[:MAX_ORDER + 1], tf.zeros_like(backward_differences)[:MAX_ORDER + 1]), axis=0) np_dtype = np_dtype = dtype_util.as_numpy_dtype(backward_differences.dtype) rhs_constant_term = newton_coefficient * tf.reduce_sum( tf1.where( tf.range(1, MAX_ORDER + 1) <= order, RECIPROCAL_SUMS[1:, np.newaxis].astype(np_dtype) * backward_differences[1:MAX_ORDER + 1], tf.zeros_like(backward_differences)[1:MAX_ORDER + 1]), axis=0) next_time = time + step_size step_size_cast = tf.cast(step_size, backward_differences.dtype) real_dtype = tf.abs(backward_differences).dtype def newton_body(iterand): """Performs one iteration of Newton's method.""" next_backward_difference = iterand.next_backward_difference next_state_vec = iterand.next_state_vec rhs = newton_coefficient * step_size_cast * ode_fn_vec( next_time, next_state_vec) - rhs_constant_term - next_backward_difference delta = tf.squeeze( tf.linalg.triangular_solve( upper, tf.matmul(tf.transpose(unitary), rhs[:, tf.newaxis]), lower=False)) num_iters = iterand.num_iters + 1 next_backward_difference += delta next_state_vec += delta delta_norm = tf.cast(tf.norm(delta), real_dtype) lipschitz_const = delta_norm / iterand.prev_delta_norm # Stop if method has converged. approx_dist_to_sol = lipschitz_const / (1. - lipschitz_const) * delta_norm close_to_sol = approx_dist_to_sol < tol delta_norm_is_zero = tf.equal(delta_norm, tf.constant(0., dtype=real_dtype)) converged = close_to_sol | delta_norm_is_zero finished = converged # Stop if any of the following conditions are met: # (A) We have hit the maximum number of iterations. # (B) The method is converging too slowly. # (C) The method is not expected to converge. too_slow = lipschitz_const > 1. finished = finished | too_slow if max_num_iters is not None: too_many_iters = tf.equal(num_iters, max_num_iters) num_iters_left = max_num_iters - num_iters num_iters_left_cast = tf.cast(num_iters_left, real_dtype) wont_converge = ( approx_dist_to_sol * lipschitz_const**num_iters_left_cast > tol) finished = finished | too_many_iters | wont_converge return [ _NewtonIterand( converged=converged, finished=finished, next_backward_difference=next_backward_difference, next_state_vec=next_state_vec, num_iters=num_iters, prev_delta_norm=delta_norm) ] iterand = _NewtonIterand( converged=False, finished=False, next_backward_difference=tf.zeros_like(initial_guess), next_state_vec=tf.identity(initial_guess), num_iters=0, prev_delta_norm=tf.constant(np.array(-0.), dtype=real_dtype)) [iterand] = tf.while_loop(lambda iterand: tf.logical_not(iterand.finished), newton_body, [iterand]) return (iterand.converged, iterand.next_backward_difference, iterand.next_state_vec, iterand.num_iters) _NewtonIterand = collections.namedtuple('NewtonIterand', [ 'converged', 'finished', 'next_backward_difference', 'next_state_vec', 'num_iters', 'prev_delta_norm', ]) def newton_qr(jacobian_mat, newton_coefficient, step_size): """QR factorizes the matrix used in each iteration of Newton's method.""" identity = tf.eye(ps.shape(jacobian_mat)[0], dtype=jacobian_mat.dtype) step_size_cast = tf.cast(step_size, jacobian_mat.dtype) newton_matrix = ( identity - step_size_cast * newton_coefficient * jacobian_mat) factorization = tf.linalg.qr(newton_matrix) return factorization.q, factorization.r def update_backward_differences(backward_differences, next_backward_difference, next_state_vec, order): """Returns the backward differences for the next time.""" backward_differences_array = tf.TensorArray( backward_differences.dtype, size=MAX_ORDER + 3, clear_after_read=False, element_shape=next_backward_difference.shape).unstack( backward_differences) new_backward_differences_array = tf.TensorArray( backward_differences.dtype, size=MAX_ORDER + 3, clear_after_read=False, element_shape=next_backward_difference.shape) new_backward_differences_array = new_backward_differences_array.write( order + 2, next_backward_difference - backward_differences_array.read(order + 1)) new_backward_differences_array = new_backward_differences_array.write( order + 1, next_backward_difference) def body(k, new_backward_differences_array_): new_backward_differences_array_k = ( new_backward_differences_array_.read(k + 1) + backward_differences_array.read(k)) new_backward_differences_array_ = new_backward_differences_array_.write( k, new_backward_differences_array_k) return k - 1, new_backward_differences_array_ _, new_backward_differences_array = tf.while_loop( lambda k, new_backward_differences_array: k > 0, body, [order, new_backward_differences_array]) new_backward_differences_array = new_backward_differences_array.write( 0, next_state_vec) new_backward_differences = new_backward_differences_array.stack() tensorshape_util.set_shape(new_backward_differences, tf.TensorShape([MAX_ORDER + 3, None])) return new_backward_differences
{ "content_hash": "c6c4a13e4615f204d971e3c89bd0179e", "timestamp": "", "source": "github", "line_count": 239, "max_line_length": 80, "avg_line_length": 40.55648535564853, "alnum_prop": 0.6673888373052719, "repo_name": "tensorflow/probability", "id": "349456b2bba4e2d931682e759fc2dc90ae7800cd", "size": "10371", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "tensorflow_probability/python/math/ode/bdf_util.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Jupyter Notebook", "bytes": "55552121" }, { "name": "Python", "bytes": "17339674" }, { "name": "Shell", "bytes": "24852" }, { "name": "Starlark", "bytes": "663851" } ], "symlink_target": "" }
var unit = requireUnit(module.filename) exports['is correctly constructed'] = function(test) { test.ok(unit) test.equals(unit.verbose, false) test.ok(unit.testGroup) test.done() }
{ "content_hash": "11318897052996f745a4c74bd38bfd6f", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 54, "avg_line_length": 24.5, "alnum_prop": 0.6938775510204082, "repo_name": "devpaul/node-testutil", "id": "95720b1273f01cfb29f4bcbb18df3c14536da958", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/model/test-config.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "20822" } ], "symlink_target": "" }