code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
CLIENT_KEYSTORE_DIR=../client/src/main/resources SERVER_KEYSTORE_DIR=../server/src/main/resources CLIENT_KEYSTORE=$CLIENT_KEYSTORE_DIR/client-nonprod.jks SERVER_KEYSTORE=$SERVER_KEYSTORE_DIR/server-nonprod.jks JAVA_CA_CERTS=$JAVA_HOME/jre/lib/security/cacerts # Generate a client and server RSA 2048 key pair keytool -genkeypair -alias client -keyalg RSA -keysize 2048 -dname "CN=Client,OU=Client,O=PlumStep,L=San Francisco,S=CA,C=U" -keypass changeme -keystore $CLIENT_KEYSTORE -storepass changeme keytool -genkeypair -alias server -keyalg RSA -keysize 2048 -dname "CN=Server,OU=Server,O=PlumStep,L=San Francisco,S=CA,C=U" -keypass changeme -keystore $SERVER_KEYSTORE -storepass changeme # Export public certificates for both the client and server keytool -exportcert -alias client -file client-public.cer -keystore $CLIENT_KEYSTORE -storepass changeme keytool -exportcert -alias server -file server-public.cer -keystore $SERVER_KEYSTORE -storepass changeme # Import the client and server public certificates into each others keystore keytool -importcert -keystore $CLIENT_KEYSTORE -alias server-public-cert -file server-public.cer -storepass changeme -noprompt keytool -importcert -keystore $SERVER_KEYSTORE -alias client-public-cert -file client-public.cer -storepass changeme -noprompt
joutwate/mtls-springboot
bin/gen-non-prod-key.sh
Shell
unlicense
1,292
<!doctype html> <html> <title>npm</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="../../static/style.css"> <body> <div id="wrapper"> <h1><a href="../cli/npm.html">npm</a></h1> <p>node package manager</p> <h2 id="SYNOPSIS">SYNOPSIS</h2> <pre><code>npm &lt;command&gt; [args]</code></pre> <h2 id="VERSION">VERSION</h2> <p>1.3.8</p> <h2 id="DESCRIPTION">DESCRIPTION</h2> <p>npm is the package manager for the Node JavaScript platform. It puts modules in place so that node can find them, and manages dependency conflicts intelligently.</p> <p>It is extremely configurable to support a wide variety of use cases. Most commonly, it is used to publish, discover, install, and develop node programs.</p> <p>Run <code>npm help</code> to get a list of available commands.</p> <h2 id="INTRODUCTION">INTRODUCTION</h2> <p>You probably got npm because you want to install stuff.</p> <p>Use <code>npm install blerg</code> to install the latest version of &quot;blerg&quot;. Check out <code><a href="../cli/npm-install.html">npm-install(1)</a></code> for more info. It can do a lot of stuff.</p> <p>Use the <code>npm search</code> command to show everything that&#39;s available. Use <code>npm ls</code> to show everything you&#39;ve installed.</p> <h2 id="DIRECTORIES">DIRECTORIES</h2> <p>See <code><a href="../files/npm-folders.html">npm-folders(5)</a></code> to learn about where npm puts stuff.</p> <p>In particular, npm has two modes of operation:</p> <ul><li>global mode:<br />npm installs packages into the install prefix at <code>prefix/lib/node_modules</code> and bins are installed in <code>prefix/bin</code>.</li><li>local mode:<br />npm installs packages into the current project directory, which defaults to the current working directory. Packages are installed to <code>./node_modules</code>, and bins are installed to <code>./node_modules/.bin</code>.</li></ul> <p>Local mode is the default. Use <code>--global</code> or <code>-g</code> on any command to operate in global mode instead.</p> <h2 id="DEVELOPER-USAGE">DEVELOPER USAGE</h2> <p>If you&#39;re using npm to develop and publish your code, check out the following help topics:</p> <ul><li>json: Make a package.json file. See <code><a href="../files/package.json.html">package.json(5)</a></code>.</li><li>link: For linking your current working code into Node&#39;s path, so that you don&#39;t have to reinstall every time you make a change. Use <code>npm link</code> to do this.</li><li>install: It&#39;s a good idea to install things if you don&#39;t need the symbolic link. Especially, installing other peoples code from the registry is done via <code>npm install</code></li><li>adduser: Create an account or log in. Credentials are stored in the user config file.</li><li>publish: Use the <code>npm publish</code> command to upload your code to the registry.</li></ul> <h2 id="CONFIGURATION">CONFIGURATION</h2> <p>npm is extremely configurable. It reads its configuration options from 5 places.</p> <ul><li>Command line switches:<br />Set a config with <code>--key val</code>. All keys take a value, even if they are booleans (the config parser doesn&#39;t know what the options are at the time of parsing.) If no value is provided, then the option is set to boolean <code>true</code>.</li><li>Environment Variables:<br />Set any config by prefixing the name in an environment variable with <code>npm_config_</code>. For example, <code>export npm_config_key=val</code>.</li><li>User Configs:<br />The file at $HOME/.npmrc is an ini-formatted list of configs. If present, it is parsed. If the <code>userconfig</code> option is set in the cli or env, then that will be used instead.</li><li>Global Configs:<br />The file found at ../etc/npmrc (from the node executable, by default this resolves to /usr/local/etc/npmrc) will be parsed if it is found. If the <code>globalconfig</code> option is set in the cli, env, or user config, then that file is parsed instead.</li><li>Defaults:<br />npm&#39;s default configuration options are defined in lib/utils/config-defs.js. These must not be changed.</li></ul> <p>See <code><a href="../misc/npm-config.html">npm-config(7)</a></code> for much much more information.</p> <h2 id="CONTRIBUTIONS">CONTRIBUTIONS</h2> <p>Patches welcome!</p> <ul><li>code: Read through <code><a href="../misc/npm-coding-style.html">npm-coding-style(7)</a></code> if you plan to submit code. You don&#39;t have to agree with it, but you do have to follow it.</li><li>docs: If you find an error in the documentation, edit the appropriate markdown file in the &quot;doc&quot; folder. (Don&#39;t worry about generating the man page.)</li></ul> <p>Contributors are listed in npm&#39;s <code>package.json</code> file. You can view them easily by doing <code>npm view npm contributors</code>.</p> <p>If you would like to contribute, but don&#39;t know what to work on, check the issues list or ask on the mailing list.</p> <ul><li><a href="http://github.com/isaacs/npm/issues">http://github.com/isaacs/npm/issues</a></li><li><a href="mailto:npm-@googlegroups.com">npm-@googlegroups.com</a></li></ul> <h2 id="BUGS">BUGS</h2> <p>When you find issues, please report them:</p> <ul><li>web: <a href="http://github.com/isaacs/npm/issues">http://github.com/isaacs/npm/issues</a></li><li>email: <a href="mailto:npm-@googlegroups.com">npm-@googlegroups.com</a></li></ul> <p>Be sure to include <em>all</em> of the output from the npm command that didn&#39;t work as expected. The <code>npm-debug.log</code> file is also helpful to provide.</p> <p>You can also look for isaacs in #node.js on irc://irc.freenode.net. He will no doubt tell you to put the output in a gist or email.</p> <h2 id="HISTORY">HISTORY</h2> <p>See <a href="../cli/npm-changelog.html">npm-changelog(1)</a></p> <h2 id="AUTHOR">AUTHOR</h2> <p><a href="http://blog.izs.me/">Isaac Z. Schlueter</a> :: <a href="https://github.com/isaacs/">isaacs</a> :: <a href="http://twitter.com/izs">@izs</a> :: <a href="mailto:i@izs.me">i@izs.me</a></p> <h2 id="SEE-ALSO">SEE ALSO</h2> <ul><li><a href="../cli/npm-help.html">npm-help(1)</a></li><li><a href="../misc/npm-faq.html">npm-faq(7)</a></li><li><a href="../../doc/README.html">README</a></li><li><a href="../files/package.json.html">package.json(5)</a></li><li><a href="../cli/npm-install.html">npm-install(1)</a></li><li><a href="../cli/npm-config.html">npm-config(1)</a></li><li><a href="../misc/npm-config.html">npm-config(7)</a></li><li><a href="../files/npmrc.html">npmrc(5)</a></li><li><a href="../misc/npm-index.html">npm-index(7)</a></li><li><a href="../api/npm.html">npm(3)</a></li></ul> </div> <p id="footer">npm &mdash; npm@1.3.8</p> <script> ;(function () { var wrapper = document.getElementById("wrapper") var els = Array.prototype.slice.call(wrapper.getElementsByTagName("*"), 0) .filter(function (el) { return el.parentNode === wrapper && el.tagName.match(/H[1-6]/) && el.id }) var l = 2 , toc = document.createElement("ul") toc.innerHTML = els.map(function (el) { var i = el.tagName.charAt(1) , out = "" while (i > l) { out += "<ul>" l ++ } while (i < l) { out += "</ul>" l -- } out += "<li><a href='#" + el.id + "'>" + ( el.innerText || el.text || el.innerHTML) + "</a>" return out }).join("\n") toc.id = "toc" document.body.appendChild(toc) })() </script>
caplin/qa-browsers
nodejs/node_modules/npm/html/doc/cli/npm.html
HTML
unlicense
7,619
package samples; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Set; import java.util.function.Function; import javax.imageio.ImageIO; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JToolBar; import org.terifan.ui.listview.ListView; import org.terifan.ui.listview.ListViewModel; import org.terifan.ui.listview.layout.CardItemRenderer; import org.terifan.ui.listview.ColumnHeaderRenderer; import org.terifan.ui.listview.ListViewImageIcon; import org.terifan.ui.listview.ViewAdjustmentListener; import org.terifan.ui.listview.layout.DetailItemRenderer; import org.terifan.ui.listview.layout.ThumbnailItemRenderer; import org.terifan.ui.listview.layout.TileItemRenderer; import org.terifan.ui.listview.util.ImageResizer; import org.terifan.ui.listview.util.Orientation; import org.terifan.ui.listview.util.Timer; public class TestStyles { private static ListView<MyListItem> mListView; public static void main(String... args) { try { ListViewModel<MyListItem> model = new ListViewModel<>(MyListItem.class); model.addColumn("Letter").setVisible(false); model.addColumn("Name", 300).setIconWidth(16).setTitle(true); model.addColumn("Length", 100); model.addColumn("Modified", 100).setFormatter(e -> new SimpleDateFormat("yyyy-MM-dd HH:mm").format(e)); model.addColumn("Dimensions", 65); model.addColumn("Id", 30); model.addGroup(model.getColumn("Letter")); model.setItemIconFunction(item -> item.icon); ArrayList<File> files = new ArrayList<>(Arrays.asList(new File("d:\\pictures").listFiles())); Collections.shuffle(files); for (File file : files) { AnimatedListViewImageIcon icon; boolean border; if (file.isFile()) { try { icon = new AnimatedListViewImageIcon(ImageResizer.getScaledImageAspect(ImageIO.read(file), 256, 256, false, null)); border = true; } catch (Exception e) { icon = new AnimatedListViewImageIcon(ImageIO.read(TestStyles.class.getResource("icon_file_unknown.png"))); border = false; } } else { icon = new AnimatedListViewImageIcon(ImageIO.read(TestStyles.class.getResource("icon_file_directory.png"))); border = false; } model.addItem(new MyListItem(model.getItemCount(), file.getName(), file.length(), file.lastModified(), icon, border)); } mListView = new ListView<>(model); mListView.setPopupFactory((lv, p, t) -> { JPopupMenu menu = new JPopupMenu(); if (t.isItem()) { menu.add(new JMenuItem("==> " + t.getItem().name)); } if (t.isGroup()) { menu.add(new JMenuItem("==> " + t.getGroup().getGroupKey())); } menu.add(new JMenuItem("Option 1")); menu.add(new JMenuItem("Option 2")); menu.add(new JMenuItem("Option 3")); return menu; }); mListView.setAdjustmentListenerExtraFactor(0.25); mListView.addAdjustmentListener(new ViewAdjustmentListener<MyListItem>() { Timer timer; { timer = new Timer(mListView::repaint); timer.setPaused(true); timer.start(); } @Override public void viewChanged(Set<MyListItem> aVisibleItems, Set<MyListItem> aItemsEnteringView, Set<MyListItem> aItemsLeavingView) { long time = System.currentTimeMillis() + 1000; for (MyListItem item : aItemsEnteringView) { item.icon.setAnimationEnd(time); } timer.setPaused(false); timer.setPauseAt(time); } }); JScrollPane scrollPane = new JScrollPane(mListView); mListView.setSmoothScrollEnabled(true); Function<MyListItem, Boolean> fn = item -> item.border; JToolBar toolBar = new JToolBar(); toolBar.add(new Button("Details", () -> mListView.setHeaderRenderer(new ColumnHeaderRenderer()).setItemRenderer(new DetailItemRenderer<>()))); toolBar.add(new Button("V-Thumbnails", () -> mListView.setHeaderRenderer(null).setItemRenderer(new ThumbnailItemRenderer<MyListItem>(new Dimension(256, 256), Orientation.VERTICAL, 16).setBorderFunction(fn)))); toolBar.add(new Button("H-Thumbnails", () -> mListView.setHeaderRenderer(null).setItemRenderer(new ThumbnailItemRenderer<MyListItem>(new Dimension(256, 256), Orientation.HORIZONTAL, 16).setBorderFunction(fn)))); toolBar.add(new Button("V-Cards", () -> mListView.setHeaderRenderer(null).setItemRenderer(new CardItemRenderer<MyListItem>(new Dimension(200, 75), 75, Orientation.VERTICAL, 16)))); toolBar.add(new Button("H-Cards", () -> mListView.setHeaderRenderer(null).setItemRenderer(new CardItemRenderer<MyListItem>(new Dimension(200, 75), 75, Orientation.HORIZONTAL, 16)))); toolBar.add(new Button("V-Tile", () -> mListView.setHeaderRenderer(null).setItemRenderer(new TileItemRenderer<MyListItem>(new Dimension(600, 160), 256, Orientation.VERTICAL).setBorderFunction(fn)))); toolBar.add(new Button("H-Tile", () -> mListView.setHeaderRenderer(null).setItemRenderer(new TileItemRenderer<MyListItem>(new Dimension(600, 160), 256, Orientation.HORIZONTAL).setBorderFunction(fn)))); toolBar.addSeparator(); toolBar.add(new Button("SmoothScroll", () -> mListView.setSmoothScrollEnabled(!mListView.isSmoothScrollEnabled()))); JFrame frame = new JFrame(); frame.add(toolBar, BorderLayout.NORTH); frame.add(scrollPane, BorderLayout.CENTER); frame.setSize(1600, 950); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } catch (Throwable e) { e.printStackTrace(System.out); } } private static class Button extends JButton { Runnable mOnClick; public Button(String aName, Runnable aOnClick) { super(new AbstractAction(aName) { @Override public void actionPerformed(ActionEvent aE) { aOnClick.run(); mListView.setSmoothScrollSpeedMultiplier("Details".equals(aName) ? 5 : 1); mListView.requestFocusInWindow(); } }); super.setFont(new Font("Segoe UI", Font.PLAIN, 22)); } } private static class MyListItem { int id; String name; long length; long modified; String letter; AnimatedListViewImageIcon icon; boolean border; public MyListItem(int aId, String aName, long aLength, long aModified, AnimatedListViewImageIcon aIcon, boolean aBorder) { this.id = aId; this.name = aName; this.length = aLength; this.modified = aModified; this.icon = aIcon; this.border = aBorder; char c = aName.toUpperCase().charAt(0); this.letter = c < 'A' ? "0-9" : c < 'I' ? "A-H" : c < 'Q' ? "I-P" : "Q-Z"; } public String getDimensions() { return icon == null ? "" : icon.getWidth() + "x" + icon.getHeight(); } @Override public String toString() { return name; } } private static class AnimatedListViewImageIcon extends ListViewImageIcon { private long mAnimationStart; private long mAnimationEnd; public AnimatedListViewImageIcon(BufferedImage aImage) { super(aImage); } public void setAnimationEnd(long aTime) { mAnimationStart = System.currentTimeMillis(); mAnimationEnd = aTime; } @Override public void drawIcon(Graphics aGraphics, int aX, int aY, int aW, int aH) { super.drawIcon(aGraphics, aX, aY, aW, aH); long time = System.currentTimeMillis(); int a; if (time > mAnimationEnd) { a = 255; } else { a = (int)((time - mAnimationStart) * 255 / (mAnimationEnd - mAnimationStart)); } aGraphics.setColor(new Color(255, 255, 255, 255 - a)); aGraphics.fillRect(aX, aY, aW, aH); } } }
terifan/ListView
src/samples/TestStyles.java
Java
unlicense
7,926
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: [:facebook, :twitter], authentication_keys: [:login] has_many :items, dependent: :destroy has_many :user_identifications, dependent: :destroy has_many :ratings, dependent: :destroy has_many :transactions, dependent: :destroy validates_uniqueness_of :email, :username end
jennyyuejin/projectFox
app/models/user.rb
Ruby
unlicense
592
OUTNAME:=ina219.ovl TARGET = eagle ifndef PDIR # { GEN_IMAGES= eagle.app.v6.out GEN_BINS = eagle.app.v6.bin SUBDIRS = main endif # } PDIR APPDIR = . LDDIR = $(WEB_BASE)/ld LD_FILE = $(LDDIR)/overlay.ld DEPENDS_eagle.app.v6 = \ $(LD_FILE) \ $(LDDIR)/overlay.ld COMPONENTS_eagle.app.v6 = \ main/libmain.a LINK_LIBS = \ -lmgcc LINKFLAGS_eagle.app.v6 = \ -nostartfiles \ -nodefaultlibs \ -nostdlib \ -L$(WEB_BASE)/lib \ -T$(LD_FILE) \ -Wl,--no-check-sections \ -u call_user_start \ -Wl,-static \ -Wl,-Map -Wl,$(@:.out=.map) \ -Wl,--start-group \ $(LINK_LIBS) \ $(DEP_LIBS_eagle.app.v6) \ -Wl,--end-group CONFIGURATION_DEFINES += \ -DICACHE_FLASH \ -DPBUF_RSV_FOR_WLAN \ -DLWIP_OPEN_SRC \ -DEBUF_LWIP DEFINES += $(CONFIGURATION_DEFINES) DDEFINES += $(CONFIGURATION_DEFINES) ############################################################# # Recursion Magic - Don't touch this!! # # Each subtree potentially has an include directory # corresponding to the common APIs applicable to modules # rooted at that subtree. Accordingly, the INCLUDE PATH # of a module can only contain the include directories up # its parent path, and not its siblings # # Required for each makefile to inherit from the parent # INCLUDES := $(INCLUDES) -I $(PDIR)include PDIR := ../$(PDIR) sinclude $(PDIR)Makefile .PHONY: FORCE FORCE:
pvvx/esp8266web
ovls/ina219/Makefile
Makefile
unlicense
1,401
<?php /** * \Magento\Widget\Model\Widget\Instance * * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Widget\Test\Unit\Model\Widget; class InstanceTest extends \PHPUnit_Framework_TestCase { /** * @var \Magento\Widget\Model\Config\Data|PHPUnit_Framework_MockObject_MockObject */ protected $_widgetModelMock; /** * @var \Magento\Framework\View\FileSystem|PHPUnit_Framework_MockObject_MockObject */ protected $_viewFileSystemMock; /** @var \Magento\Widget\Model\NamespaceResolver |PHPUnit_Framework_MockObject_MockObject */ protected $_namespaceResolver; /** * @var \Magento\Widget\Model\Widget\Instance */ protected $_model; /** @var \Magento\Widget\Model\Config\Reader */ protected $_readerMock; /** * @var \PHPUnit_Framework_MockObject_MockObject */ protected $_cacheTypesListMock; /** * @var \PHPUnit_Framework_MockObject_MockObject */ protected $_directoryMock; protected function setUp() { $this->_widgetModelMock = $this->getMockBuilder( 'Magento\Widget\Model\Widget' )->disableOriginalConstructor()->getMock(); $this->_viewFileSystemMock = $this->getMockBuilder( 'Magento\Framework\View\FileSystem' )->disableOriginalConstructor()->getMock(); $this->_namespaceResolver = $this->getMockBuilder( '\Magento\Widget\Model\NamespaceResolver' )->disableOriginalConstructor()->getMock(); $this->_cacheTypesListMock = $this->getMock('Magento\Framework\App\Cache\TypeListInterface'); $this->_readerMock = $this->getMockBuilder( 'Magento\Widget\Model\Config\Reader' )->disableOriginalConstructor()->getMock(); $filesystemMock = $this->getMock('\Magento\Framework\Filesystem', [], [], '', false); $this->_directoryMock = $this->getMock( '\Magento\Framework\Filesystem\Directory\Read', [], [], '', false ); $filesystemMock->expects( $this->any() )->method( 'getDirectoryRead' )->will( $this->returnValue($this->_directoryMock) ); $this->_directoryMock->expects($this->any())->method('isReadable')->will($this->returnArgument(0)); $this->_directoryMock->expects($this->any())->method('getRelativePath')->will($this->returnArgument(0)); $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $args = $objectManagerHelper->getConstructArguments( 'Magento\Widget\Model\Widget\Instance', [ 'filesystem' => $filesystemMock, 'viewFileSystem' => $this->_viewFileSystemMock, 'cacheTypeList' => $this->_cacheTypesListMock, 'reader' => $this->_readerMock, 'widgetModel' => $this->_widgetModelMock, 'namespaceResolver' => $this->_namespaceResolver ] ); /** @var \Magento\Widget\Model\Widget\Instance _model */ $this->_model = $this->getMock('Magento\Widget\Model\Widget\Instance', ['_construct'], $args, '', true); } public function testGetWidgetConfigAsArray() { $widget = [ '@' => ['type' => 'Magento\Cms\Block\Widget\Page\Link', 'module' => 'Magento_Cms'], 'name' => 'CMS Page Link', 'description' => 'Link to a CMS Page', 'is_email_compatible' => 'true', 'placeholder_image' => 'Magento_Cms::images/widget_page_link.png', 'parameters' => [ 'page_id' => [ '@' => ['type' => 'complex'], 'type' => 'label', 'helper_block' => [ 'type' => 'Magento\Cms\Block\Adminhtml\Page\Widget\Chooser', 'data' => ['button' => ['open' => 'Select Page...']], ], 'visible' => 'true', 'required' => 'true', 'sort_order' => '10', 'label' => 'CMS Page', ], ], ]; $this->_widgetModelMock->expects( $this->once() )->method( 'getWidgetByClassType' )->will( $this->returnValue($widget) ); $xmlFile = __DIR__ . '/../_files/widget.xml'; $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue($xmlFile)); $themeConfigFile = __DIR__ . '/../_files/mappedConfigArrayAll.php'; $themeConfig = include $themeConfigFile; $this->_readerMock->expects( $this->once() )->method( 'readFile' )->with( $this->equalTo($xmlFile) )->will( $this->returnValue($themeConfig) ); $result = $this->_model->getWidgetConfigAsArray(); $expectedConfigFile = __DIR__ . '/../_files/mappedConfigArray1.php'; $expectedConfig = include $expectedConfigFile; $this->assertEquals($expectedConfig, $result); } public function testGetWidgetTemplates() { $expectedConfigFile = __DIR__ . '/../_files/mappedConfigArray1.php'; $widget = include $expectedConfigFile; $this->_widgetModelMock->expects( $this->once() )->method( 'getWidgetByClassType' )->will( $this->returnValue($widget) ); $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); $expectedTemplates = [ 'default' => [ 'value' => 'product/widget/link/link_block.phtml', 'label' => 'Product Link Block Template', ], 'link_inline' => [ 'value' => 'product/widget/link/link_inline.phtml', 'label' => 'Product Link Inline Template', ], ]; $this->assertEquals($expectedTemplates, $this->_model->getWidgetTemplates()); } public function testGetWidgetTemplatesValueOnly() { $widget = [ '@' => ['type' => 'Magento\Cms\Block\Widget\Page\Link', 'module' => 'Magento_Cms'], 'name' => 'CMS Page Link', 'description' => 'Link to a CMS Page', 'is_email_compatible' => 'true', 'placeholder_image' => 'Magento_Cms::images/widget_page_link.png', 'parameters' => [ 'template' => [ 'values' => [ 'default' => ['value' => 'product/widget/link/link_block.phtml', 'label' => 'Template'], ], 'type' => 'select', 'visible' => 'true', 'label' => 'Template', 'value' => 'product/widget/link/link_block.phtml', ], ], ]; $this->_widgetModelMock->expects( $this->once() )->method( 'getWidgetByClassType' )->will( $this->returnValue($widget) ); $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); $expectedTemplates = [ 'default' => ['value' => 'product/widget/link/link_block.phtml', 'label' => 'Template'], ]; $this->assertEquals($expectedTemplates, $this->_model->getWidgetTemplates()); } public function testGetWidgetTemplatesNoTemplate() { $widget = [ '@' => ['type' => 'Magento\Cms\Block\Widget\Page\Link', 'module' => 'Magento_Cms'], 'name' => 'CMS Page Link', 'description' => 'Link to a CMS Page', 'is_email_compatible' => 'true', 'placeholder_image' => 'Magento_Cms::images/widget_page_link.png', 'parameters' => [], ]; $this->_widgetModelMock->expects( $this->once() )->method( 'getWidgetByClassType' )->will( $this->returnValue($widget) ); $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); $expectedTemplates = []; $this->assertEquals($expectedTemplates, $this->_model->getWidgetTemplates()); } public function testGetWidgetSupportedContainers() { $expectedConfigFile = __DIR__ . '/../_files/mappedConfigArray1.php'; $widget = include $expectedConfigFile; $this->_widgetModelMock->expects( $this->once() )->method( 'getWidgetByClassType' )->will( $this->returnValue($widget) ); $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); $expectedContainers = ['left', 'content']; $this->assertEquals($expectedContainers, $this->_model->getWidgetSupportedContainers()); } public function testGetWidgetSupportedContainersNoContainer() { $widget = [ '@' => ['type' => 'Magento\Cms\Block\Widget\Page\Link', 'module' => 'Magento_Cms'], 'name' => 'CMS Page Link', 'description' => 'Link to a CMS Page', 'is_email_compatible' => 'true', 'placeholder_image' => 'Magento_Cms::images/widget_page_link.png', ]; $this->_widgetModelMock->expects( $this->once() )->method( 'getWidgetByClassType' )->will( $this->returnValue($widget) ); $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); $expectedContainers = []; $this->assertEquals($expectedContainers, $this->_model->getWidgetSupportedContainers()); } public function testGetWidgetSupportedTemplatesByContainers() { $expectedConfigFile = __DIR__ . '/../_files/mappedConfigArray1.php'; $widget = include $expectedConfigFile; $this->_widgetModelMock->expects( $this->once() )->method( 'getWidgetByClassType' )->will( $this->returnValue($widget) ); $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); $expectedTemplates = [ ['value' => 'product/widget/link/link_block.phtml', 'label' => 'Product Link Block Template'], ['value' => 'product/widget/link/link_inline.phtml', 'label' => 'Product Link Inline Template'], ]; $this->assertEquals($expectedTemplates, $this->_model->getWidgetSupportedTemplatesByContainer('left')); } public function testGetWidgetSupportedTemplatesByContainers2() { $expectedConfigFile = __DIR__ . '/../_files/mappedConfigArray1.php'; $widget = include $expectedConfigFile; $this->_widgetModelMock->expects( $this->once() )->method( 'getWidgetByClassType' )->will( $this->returnValue($widget) ); $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); $expectedTemplates = [ ['value' => 'product/widget/link/link_block.phtml', 'label' => 'Product Link Block Template'], ]; $this->assertEquals($expectedTemplates, $this->_model->getWidgetSupportedTemplatesByContainer('content')); } public function testGetWidgetSupportedTemplatesByContainersNoSupportedContainersSpecified() { $widget = [ '@' => ['type' => 'Magento\Cms\Block\Widget\Page\Link', 'module' => 'Magento_Cms'], 'name' => 'CMS Page Link', 'description' => 'Link to a CMS Page', 'is_email_compatible' => 'true', 'placeholder_image' => 'Magento_Cms::images/widget_page_link.png', 'parameters' => [ 'template' => [ 'values' => [ 'default' => ['value' => 'product/widget/link/link_block.phtml', 'label' => 'Template'], ], 'type' => 'select', 'visible' => 'true', 'label' => 'Template', 'value' => 'product/widget/link/link_block.phtml', ], ], ]; $this->_widgetModelMock->expects( $this->once() )->method( 'getWidgetByClassType' )->will( $this->returnValue($widget) ); $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); $expectedContainers = [ 'default' => ['value' => 'product/widget/link/link_block.phtml', 'label' => 'Template'], ]; $this->assertEquals($expectedContainers, $this->_model->getWidgetSupportedTemplatesByContainer('content')); } public function testGetWidgetSupportedTemplatesByContainersUnknownContainer() { $expectedConfigFile = __DIR__ . '/../_files/mappedConfigArray1.php'; $widget = include $expectedConfigFile; $this->_widgetModelMock->expects( $this->once() )->method( 'getWidgetByClassType' )->will( $this->returnValue($widget) ); $this->_viewFileSystemMock->expects($this->once())->method('getFilename')->will($this->returnValue('')); $expectedTemplates = []; $this->assertEquals($expectedTemplates, $this->_model->getWidgetSupportedTemplatesByContainer('unknown')); } }
fathi-hindi/oneplace
vendor/magento/module-widget/Test/Unit/Model/Widget/InstanceTest.php
PHP
unlicense
13,756
## Conversion to formula Excel doesn't allow usage of `{{tag}}`, `<<tag>>` or `[[tag]]` inside formulas. Therefore tag expressions can only be defined as standard text values. But Templater recognizes special tag `[[equals]]` which causes conversion of the text field into formula. Be careful to have all tags evaluated, otherwise Excel will complain about corrupted document.
ngs-doo/TemplaterExamples
Beginner/ToFormulaConversion/Readme.md
Markdown
unlicense
379
package de.incub8.tomeefreezetestcase; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import lombok.Data; import lombok.NoArgsConstructor; @Data @Entity @NoArgsConstructor public class DerivedDataEntity { @Id @GeneratedValue private Long id; private String data; public DerivedDataEntity(SignalEntity signalEntity) { data = signalEntity.getData(); } }
JanDoerrenhaus/tomeefreezetestcase
src/main/java/de/incub8/tomeefreezetestcase/DerivedDataEntity.java
Java
unlicense
449
#include<cstdio> const int V=999; char c[V][V],p[V]; int t; char go(int v) { if(v==t)return 1; if(p[v])return 0; p[v]=1; for(int i=1;i<=t;i++) if(c[v][i]-- && go(i)) return ++c[i][v]; else c[v][i]++; return 0; } int flow() { int i,f=0; while(1) { for(i=0;i<=t;i++) p[i]=0; if(go(0))f++; else break; } return f; } main() { int i,j,k,n; while(scanf("%d %d %d",&n,&j,&k) && n) { t=n+j+1; for(i=0;i<=t;i++) for(j=0;j<=t;j++) c[i][j]=0; while(k--) { scanf("%d",&i); scanf("%d %d",&i,&j); if(i && j) c[i][j+n]=1; } for(i=1;i<=n;i++) c[0][i]=1; for(;i<t;i++) c[i][t]=1; printf("%d\n",flow()); } }
dk00/old-stuff
ntuj/0378.cpp
C++
unlicense
878
<? include("db.inc.php"); $link = mysql_connect ("localhost", getUser(), getPassword()) or die ("Could not connect to MySQL Server"); mysql_select_db ("fsa", $link); $sql = "SELECT * FROM servers"; $result = mysql_query ($sql, $link) or die ("Query Died!"); while ($row = mysql_fetch_array ($result)) { printf("%s;%s;%s;%s;%s;",$row["name"],$row["server"],$row["path"],$row["type"],$row["indexscript"]); } mysql_close ($link); ?>
jeffrey-io/wall-of-shame
2001/FileSharingAccelerator/Beta2/ServerSide/fetch_servers.php3
PHP
unlicense
480
<!doctype html> <html lang="en" ng-app="TODOList"> <head> <meta charset="utf-8"> <title>TODOList</title> <link rel="stylesheet" href="css/app.css"/> <link rel="stylesheet" href="css/animations.css"/> <!-- jQuery --> <script src="lib/jQuery/jquery-2.0.3.min.js"></script> <!-- bootstrap --> <script src="lib/bootstrap/js/bootstrap.min.js"></script> <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css"/> <link rel="stylesheet" href="lib/bootstrap/css/bootstrap-theme.min.css"/> </head> <body> <div class="container"> <div class="row col-sm-8 col-sm-offset-2 col-md-8 col-md-offset-2 col-lg-8 col-lg-offset-2"> <div class="header"> <h3 class="text-muted">TODOList</h3> </div> <div class="container" ng-view></div> </div> </div> <!-- /container --> <script src="lib/angular/angular.min.js"></script> <script src="lib/angular/angular-route.min.js"></script> <script src="lib/angular/angular-resource.min.js"></script> <script src="lib/angular/angular-animate.min.js"></script> <script src="js/app.js"></script> <script src="js/services.js"></script> <script src="js/controllers.js"></script> <script src="js/filters.js"></script> <script src="js/directives.js"></script> </body> </html>
Alessio22/TODOList
frontend/index.html
HTML
unlicense
1,290
# Re-implementing common Unix utilities such as - cat(1) - ls(1) - grep(1) - wc(1) - nc(1) - bash(1) So that I understand Unix better. # TODO - argument parsing - usage output (--help)
tlehman/unix_utils
README.md
Markdown
unlicense
197
/* * sprite.h * * Created on: Sep 8, 2013 * Author: drb */ #ifndef SPRITE_H_ #define SPRITE_H_ #include <vector> #include "../util/Point.h" #include "ISprite.h" class sprite : public ISprite { public: sprite(); virtual ~sprite(); virtual void render (double delta , SDL_Renderer* rednerer , SDL_Point CameraOffset); virtual void update (double delta); virtual void event (SDL_Event event, double delta); SDL_Rect getBounds(void); void setBounds(SDL_Rect rect); double getAngle(void); double getArea(void); void setAngle(double angle); Point getPosition(void); void setPosition(Point pos); SDL_Point getCenter (); std::vector<SDL_Point>* getPointBounds (); SDL_Point* getPointBoundsArray (); }; #endif /* SPRITE_H_ */
zyphrus/asteroids
render/sprite.h
C
unlicense
797
import java.util.Scanner; public class Question5_44a { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter an integer. "); int input = scanner.nextInt(); String output = ""; for (int i = 1; i <= 16; i++) { output = (input & 1) + output; input = input >> 1; } System.out.println("The bits are " + output); } }
SubhamSatyajeet/JavaRough
Liang/Chapter5/Question5_44a.java
Java
unlicense
392
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- <title>Curso Bíblico - A Bíblia Fala - Estudo 1</title> --> <!-- Bootstrap core CSS --> <link href="../../css/bootstrap.css" rel="stylesheet"> <!-- Add custom CSS here --> <link href="../../css/modern-business.css" rel="stylesheet"> <link href="../../font-awesome/css/font-awesome.min.css" rel="stylesheet"> <script> function minhaFuncao(estudo){ if(estudo == 1) pagina="Riquezas Esquecidas" if(estudo == 2) pagina="Riquezas1 Esquecidas" if(estudo == 3) pagina="Riquezas1 Esquecidas" document.write("<TITLE>Curso Bíblico - " + pagina + "</TITLE>") } function funcao1(arq) { document.write('<img src="../../image/brazil.gif" width="30" height="20" title="' + arq + '">') } </SCRIPT> </SCRIPT> <SCRIPT> minhaFuncao(2) </script> </head> <body> oi <span class="acts"></span> <script> arq = 'oi'; funcao1("arq"); </script> <!-- JavaScript --> <script src="../../js/jquery-1.10.2.js"></script> <script src="../../js/bootstrap.js"></script> <script src="../../js/modern-business.js"></script> </body> </html> <HTML> <script src="biblia/js/jquery-1.10.2.js"></script> <script src="biblia/js/bootstrap.js"></script> <script src="biblia/js/modern-business.js"></script> <SCRIPT> function minhaFuncao(){ //faço algo... document.write("<TITLE>MINHA PÁGINA automatica</TITLE>") } </SCRIPT> <HEAD> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <title>Curso Bíblico - A Bíblia Fala - Estudo 1</title> <!-- Bootstrap core CSS --> <link href="../../css/bootstrap.css" rel="stylesheet"> <!-- Add custom CSS here --> <link href="../../css/modern-business.css" rel="stylesheet"> <link href="../../font-awesome/css/font-awesome.min.css" rel="stylesheet"> <SCRIPT> minhaFuncao() function funcao1() { pagina = 'Paraná'; document.write('<img src="../../image/brazil.gif" width="30" height="20" title="' + pagina + '">') } </SCRIPT> </HEAD> <BODY> o i <script> funcao1() </script> <!-- <TITLE>MINHA PÁGINA</TITLE> --> <span class="n_01"></span> </BODY> </HTML>
kfazolin/biblia
language/pt_br/teste.html
HTML
unlicense
2,456
package be.normegil.librarium.model.dao; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ UTUniverseDatabaseDAOSafety.class, UTUniverseDatabaseDAO.class }) public class UniverseDatabaseDAOTestSuite { }
Normegil/Librarium-Server
src/test/java/be/normegil/librarium/model/dao/UniverseDatabaseDAOTestSuite.java
Java
unlicense
267
#include<cstdio> int main(int argc, char **argv) { unsigned int port = 65637, id = 257; bool topo = false; for (i = 1; i + 1 < argc; ++i) { if (!strcmp(argv[i], "-p")) sscanf(argv[++i], &port); else if (!strcmp(argv[i], "-t")) topo |= serv.Load(argv[++i]); else if (!strcmp(argv[i], "-d")) sscanf(argv[++i], "%d", &id); } if (!serv.SetPort(port)) return 0; while (1) { serv.Wait(); if (!strcmp(cmd, "send")) serv.Send(); else if (!strcmp(cmd, "update")) { scanf("%d %d", &id, &cost); serv.Update(id, cost); } else if (!strcmp(cmd, "display")) serv.Display() } }
dk00/old-stuff
csie/10computer-networks/3x/main.cpp
C++
unlicense
654
#include <bits/stdc++.h> using namespace std; #pragma comment(linker,"/stack:1024000000,1024000000") #define db(x) cout<<(x)<<endl #define pf(x) push_front(x) #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define ms(x,y) memset(x,y,sizeof x) typedef long long LL; const double pi=acos(-1),eps=1e-9; const LL inf=0x3f3f3f3f,mod=1e9+7,maxn=1123456; LL n,k,t; int main(){ ios::sync_with_stdio(0); cin>>n>>k>>t; if(t>=n+k) db(0); else if(t<=k) db(t); else if(t<=n) db(k); else db(n-t+k); return 0; }
QAQrz/ACM-Codes
CodeForces/851/A - Arpa and a research in Mexican wave.cpp
C++
unlicense
522
using System; using System.Runtime.Serialization; namespace Hibernation { /// <summary> /// Represents errors that occur during Hibernation session management. /// </summary> [Serializable] public class HibernationException : Exception { /// <summary> /// Initializes a new instance of the HibernationException class. /// </summary> public HibernationException() { } /// <summary> /// Initializes a new instance of the HibernationException class /// with the specified error message. /// </summary> /// <param name="message"> /// A message describing the error that occurred. /// </param> public HibernationException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the HibernationException class /// with the specified error message and a reference to the inner /// exception that caused this exception. /// </summary> /// <param name="message"> /// A message describing the error that occurred in Hibernation. /// </param> /// <param name="innerException"> /// The inner exception that caused this exception. /// </param> public HibernationException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the HibernationException class /// with serialized data. /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected HibernationException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Initializes a new instance of the HibernationException class /// with a formatted message and a reference to the inner exception /// that caused this exception. /// </summary> /// <param name="messageFormat"> /// An optionally-formatted message describing the error that occurred. /// </param> /// <param name="innerException"> /// The inner exception that caused this exception. /// </param> /// <param name="messageData"> /// Optional data items that will replace any format string elements in /// the message parameter. /// </param> public HibernationException(string messageFormat, Exception innerException, params object[] messageData) : base(string.Format(messageFormat, messageData), innerException) { } } }
malorisdead/Hibernation
Hibernation/HibernationException.cs
C#
unlicense
2,732
package com.mobium.client.api.networking; import com.mobium.reference.utils.executing.ExecutingException; import org.json.JSONObject; /** * on 15.10.15. */ public interface IExtraApiInterface extends ApiInterface { JSONObject DoApiRequest(String method, JSONObject args, JSONObject extra) throws NetworkingException, ExecutingException; String plain_id = "plain_id"; }
naebomium/android
app/src/main/java/com/mobium/client/api/networking/IExtraApiInterface.java
Java
unlicense
383
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace FasmDebug { struct FasHeader { public uint Signature; public byte MajorVersion; public byte MinorVersion; public ushort HeaderLength; public uint InputNameOffset; public uint OutputNameOffset; public uint StringTableOffset; public uint StringTableLength; public uint SymbolTableOffset; public uint SymbolTableLength; public uint PreprocessedSourceOffset; public uint PreprocessedSourceLength; public uint AssemblyOffset; public uint AssemblyLength; public uint SectionNamesOffset; public uint SectionNamesLength; public uint SymbolReferencesOffset; public uint SymbolReferencesLength; } struct FasSymbol { public ulong Value; public FasSymbolFlags Flags; public byte DataSize; public byte ValueType; public uint ExtendedSIB; public ushort DefinedPassCount; public ushort UsedPassCount; public uint RelocatableJunk; public uint NameOffset; public uint DefinitionOffset; } struct FasPreprocessedLine { public uint FileNameOffset; public int LineNumber; public uint SourceFileLineOffset; public uint MacroPreprocessedLineOffset; public string Tokens; } struct FasAssemblyEntry { public uint OutputOffset; public uint PreprocessedSourceOffset; public ulong Address; public uint ExtendedSIB; public uint RelocatableJunk; public byte AddressType; public byte CodeType; public byte FlagStuff; public byte UpperAddressBits; } [Flags] enum FasSymbolFlags { Defined = 1, AssemblyTimeVariable = 2, CannotForwardReference = 4, Used = 8, PredictionNeededForUse = 16, LastPredictedResultForUse = 32, PredictionNeededForDefine = 64, LastPredictedResultForDefine = 128, OptimizationAdjustment = 256, Negative = 512, SpecialMarker = 1024 } class Symbol { public int NameOffset; public int Address; public string Name; } class Line { public int FileNameOffset; public int LineNumber; public int Address; public string FileName; } public class Program { private static List<Symbol> _symbols = new List<Symbol>(); private static List<Line> _lines = new List<Line>(); public static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("Converts FASM symbol files into a nicer format"); Console.WriteLine("Usage: FasmDebug <input.fas>"); return; } var input = args[0]; var output = Path.ChangeExtension(input, ".dbg"); try { ReadFasmDebug(input); } catch (Exception e) { Console.WriteLine("Failed to read input file: " + e.Message); return; } try { WriteDebug(output); } catch (Exception e) { Console.WriteLine("Failed to write output file: " + e.Message); return; } } private static void WriteDebug(string fileName) { _symbols = _symbols.DistinctBy(s => s.Address).ToList(); _lines = _lines.DistinctBy(l => l.Address).ToList(); using (var file = new FileStream(fileName, FileMode.Create)) using (var writer = new BinaryWriter(file)) { const int headerSize = 20; var symbolsSize = _symbols.Count * 8; writer.Write(0x30474244); // header - DBG0 writer.Write(headerSize); // symbol offset writer.Write(_symbols.Count); // symbol count writer.Write(headerSize + symbolsSize); // line offset writer.Write(_lines.Count); // line count file.Seek(_symbols.Count * 8, SeekOrigin.Current); file.Seek(_lines.Count * 12, SeekOrigin.Current); #region Write String Table var stringTable = new List<Tuple<string, int>>(); foreach (var s in _symbols) { var line = stringTable.FirstOrDefault(str => str.Item1 == s.Name); if (line != null) { s.NameOffset = line.Item2; continue; } var offset = (int)file.Position; s.NameOffset = offset; WriteNullTerminated(writer, s.Name); stringTable.Add(Tuple.Create(s.Name, offset)); } foreach (var l in _lines) { var line = stringTable.FirstOrDefault(str => str.Item1 == l.FileName); if (line != null) { l.FileNameOffset = line.Item2; continue; } var offset = (int)file.Position; l.FileNameOffset = offset; WriteNullTerminated(writer, l.FileName); stringTable.Add(Tuple.Create(l.FileName, offset)); } #endregion file.Seek(headerSize, SeekOrigin.Begin); #region Write Symbols foreach (var s in _symbols) { writer.Write(s.NameOffset); writer.Write(s.Address); } #endregion #region Write Lines foreach (var l in _lines) { writer.Write(l.FileNameOffset); writer.Write(l.LineNumber); writer.Write(l.Address); } #endregion } } private static void ReadFasmDebug(string fileName) { using (var file = File.OpenRead(fileName)) using (var reader = new BinaryReader(file)) { var header = ReadFasHeader(reader); var fasSymbols = new List<FasSymbol>(); var runningLength = 0; if (header.Signature != 0x1A736166) throw new Exception("Not a FASM symbol file"); file.Seek(header.SymbolTableOffset, SeekOrigin.Begin); while (runningLength < header.SymbolTableLength) { fasSymbols.Add(ReadSymbol(reader)); runningLength += 32; // sizeof(FasSymbol) } string parent = ""; int anonCount = 0; foreach (var s in fasSymbols.OrderBy(s => s.Value)) { string name; if (s.Flags.HasFlag(FasSymbolFlags.AssemblyTimeVariable)) continue; if (s.NameOffset == 0) { name = string.Format("{0}.@@_{1}", parent, anonCount); anonCount++; } else if ((s.NameOffset & 0x80000000) != 0) { var offset = s.NameOffset & 0x7FFFFFFF; file.Seek(header.StringTableOffset + offset, SeekOrigin.Begin); name = ReadNullTerminated(reader); } else { file.Seek(header.PreprocessedSourceOffset + s.NameOffset, SeekOrigin.Begin); name = reader.ReadString(); } if (name.Length >= 2 && name[0] == '.') { /*if (name[1] == '.') // macro label? continue;*/ name = parent + name; } if (s.NameOffset != 0 && !name.Contains('.')) { parent = name; anonCount = 0; } _symbols.Add(new Symbol { Name = name, Address = (int)s.Value }); } var assemblyEntries = new List<FasAssemblyEntry>(); file.Seek(header.AssemblyOffset, SeekOrigin.Begin); while (file.Position - header.AssemblyOffset <= header.AssemblyLength) { assemblyEntries.Add(ReadAssemblyEntry(reader)); } var preprocessedLines = new Dictionary<uint, FasPreprocessedLine>(); file.Seek(header.PreprocessedSourceOffset, SeekOrigin.Begin); while (file.Position - header.PreprocessedSourceOffset <= header.PreprocessedSourceLength) { var offset = file.Position - header.PreprocessedSourceOffset; var line = ReadPreprocessedLine(reader); preprocessedLines.Add((uint)offset, line); } uint prevLine = uint.MaxValue; foreach (var entry in assemblyEntries) { if (entry.Address >= int.MaxValue) break; var line = preprocessedLines[entry.PreprocessedSourceOffset]; uint lineOffset = line.SourceFileLineOffset; if ((line.LineNumber & 0x80000000) != 0) { while ((line.LineNumber & 0x80000000) != 0) { line = preprocessedLines[line.SourceFileLineOffset]; lineOffset = line.SourceFileLineOffset; } if (lineOffset == prevLine) continue; prevLine = lineOffset; } uint fileNameOffset; if (line.FileNameOffset == 0) fileNameOffset = header.StringTableOffset + header.InputNameOffset; else fileNameOffset = header.PreprocessedSourceOffset + line.FileNameOffset; file.Seek(fileNameOffset, SeekOrigin.Begin); var lineFile = ReadNullTerminated(reader); _lines.Add(new Line { FileName = lineFile, LineNumber = line.LineNumber, Address = (int)entry.Address }); } } } private static void WriteNullTerminated(BinaryWriter writer, string str) { foreach (var c in str) { writer.Write((byte)c); } writer.Write((byte)0); } private static string ReadNullTerminated(BinaryReader reader) { var result = ""; byte value; while ((value = reader.ReadByte()) != 0) { result += (char)value; } return result; } private static string ReadLength(BinaryReader reader, uint count) { var result = ""; while (count-- > 0) { result += (char)reader.ReadByte(); } return result; } private static FasAssemblyEntry ReadAssemblyEntry(BinaryReader reader) { var result = new FasAssemblyEntry { OutputOffset = reader.ReadUInt32(), PreprocessedSourceOffset = reader.ReadUInt32(), Address = reader.ReadUInt64(), ExtendedSIB = reader.ReadUInt32(), RelocatableJunk = reader.ReadUInt32(), AddressType = reader.ReadByte(), CodeType = reader.ReadByte(), FlagStuff = reader.ReadByte(), UpperAddressBits = reader.ReadByte() }; return result; } private static string ReadTokenizedLine(BinaryReader reader) { var result = ""; while (true) { var id = reader.ReadByte(); if (id == 0) // eol break; switch (id) { case 0x1A: // byte prefixed text case 0x3B: // fuck knows result += ReadLength(reader, reader.ReadByte()); break; case 0x22: // dword prefixed text result += "'" + ReadLength(reader, reader.ReadUInt32()) + "'"; break; default: result += (char)id; break; } result += " "; } return result; } private static FasPreprocessedLine ReadPreprocessedLine(BinaryReader reader) { var result = new FasPreprocessedLine { FileNameOffset = reader.ReadUInt32(), LineNumber = reader.ReadInt32(), SourceFileLineOffset = reader.ReadUInt32(), MacroPreprocessedLineOffset = reader.ReadUInt32(), Tokens = ReadTokenizedLine(reader) }; return result; } private static FasSymbol ReadSymbol(BinaryReader reader) { var result = new FasSymbol { Value = reader.ReadUInt64(), Flags = (FasSymbolFlags)reader.ReadUInt16(), DataSize = reader.ReadByte(), ValueType = reader.ReadByte(), ExtendedSIB = reader.ReadUInt32(), DefinedPassCount = reader.ReadUInt16(), UsedPassCount = reader.ReadUInt16(), RelocatableJunk = reader.ReadUInt32(), NameOffset = reader.ReadUInt32(), DefinitionOffset = reader.ReadUInt32() }; return result; } private static FasHeader ReadFasHeader(BinaryReader reader) { var result = new FasHeader { Signature = reader.ReadUInt32(), MajorVersion = reader.ReadByte(), MinorVersion = reader.ReadByte(), HeaderLength = reader.ReadUInt16(), InputNameOffset = reader.ReadUInt32(), OutputNameOffset = reader.ReadUInt32(), StringTableOffset = reader.ReadUInt32(), StringTableLength = reader.ReadUInt32(), SymbolTableOffset = reader.ReadUInt32(), SymbolTableLength = reader.ReadUInt32(), PreprocessedSourceOffset = reader.ReadUInt32(), PreprocessedSourceLength = reader.ReadUInt32(), AssemblyOffset = reader.ReadUInt32(), AssemblyLength = reader.ReadUInt32(), SectionNamesOffset = reader.ReadUInt32(), SectionNamesLength = reader.ReadUInt32(), SymbolReferencesOffset = reader.ReadUInt32(), SymbolReferencesLength = reader.ReadUInt32() }; return result; } } static class Util { // http://stackoverflow.com/a/1300116/1056845 public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> knownKeys = new HashSet<TKey>(); foreach (TSource element in source) { if (knownKeys.Add(keySelector(element))) { yield return element; } } } } }
Rohansi/LoonyVM
Tools/fasconvert/Program.cs
C#
unlicense
16,319
#/** # * Licensed to the Apache Software Foundation (ASF) under one # * or more contributor license agreements. See the NOTICE file # * distributed with this work for additional information # * regarding copyright ownership. The ASF licenses this file # * to you under the Apache License, Version 2.0 (the # * "License"); you may not use this file except in compliance # * with the License. You may obtain a copy of the License at # * # * http://www.apache.org/licenses/LICENSE-2.0 # * # * Unless required by applicable law or agreed to in writing, software # * distributed under the License is distributed on an "AS IS" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # * See the License for the specific language governing permissions and # * limitations under the License. # */ #!/usr/bin/env bash function install_cmake() { if [ ! -e "cmake-3.2.1.tar.gz" ] then wget http://www.comp.nus.edu.sg/~dbsystem/singa/assets/file/thirdparty/cmake-3.2.1.tar.gz; fi rm -rf cmake-3.2.1; tar zxvf cmake-3.2.1.tar.gz && cd cmake-3.2.1; if [ $# == 1 ] then echo "install cmake in $1"; ./configure --prefix=$1; make && make install; elif [ $# == 0 ] then echo "install cmake in default path"; ./configure; make && sudo make install; else echo "wrong commands"; fi if [ $? -ne 0 ] then cd ..; return -1; fi PATH=$1/bin:$PATH; echo $PATH; export PATH=$1/bin:$PATH; cd ..; return 0; } function install_czmq() { if [ ! -e "czmq-3.0.0-rc1.tar.gz" ] then wget http://www.comp.nus.edu.sg/~dbsystem/singa/assets/file/thirdparty/czmq-3.0.0-rc1.tar.gz; fi rm -rf czmq-3.0.0; tar zxvf czmq-3.0.0-rc1.tar.gz && cd czmq-3.0.0; if [ $# == 2 ] then if [ $1 == "null" ] then echo "install czmq in default path. libzmq path is $2"; ./configure --with-libzmq=$2; make && sudo make install; else echo "install czmq in $1. libzmq path is $2"; ./configure --prefix=$1 --with-libzmq=$2; make && make install; fi elif [ $# == 1 ] then if [ $1 == "null" ] then echo "install czmq in default path."; ./configure; make && sudo make install; else echo "install czmq in $1"; ./configure --prefix=$1; make && make install; fi else echo "ERROR: wrong command."; return -1; fi if [ $? -ne 0 ] then cd ..; return -1; fi cd ..; return 0; } function install_glog() { if [ ! -e "glog-0.3.3.tar.gz" ] then wget http://www.comp.nus.edu.sg/~dbsystem/singa/assets/file/thirdparty/glog-0.3.3.tar.gz; fi rm -rf glog-0.3.3; tar zxvf glog-0.3.3.tar.gz && cd glog-0.3.3; if [ $# == 1 ] then echo "install glog in $1"; ./configure --prefix=$1; make && make install; elif [ $# == 0 ] then echo "install glog in default path"; ./configure; make && sudo make install; else echo "wrong commands"; fi if [ $? -ne 0 ] then cd ..; return -1; fi cd ..; return 0; } function install_lmdb() { if [ ! -e "lmdb-0.9.10.tar.gz" ] then wget http://www.comp.nus.edu.sg/~dbsystem/singa/assets/file/thirdparty/lmdb-0.9.10.tar.gz; fi rm -rf mdb-mdb; tar zxvf lmdb-0.9.10.tar.gz && cd mdb-mdb/libraries/liblmdb; if [ $# == 1 ] then echo "install lmdb in $1"; sed -i "26s#^.*#prefix=$1#g" Makefile; make && make install; elif [ $# == 0 ] then echo "install lmdb in default path"; make && sudo make install; else echo "wrong commands"; fi if [ $? -ne 0 ] then cd ../../..; return -1; fi cd ../../..; return 0; } function install_openblas() { if [ ! -e "OpenBLAS.zip" ] then wget http://www.comp.nus.edu.sg/~dbsystem/singa/assets/file/thirdparty/OpenBLAS.zip; fi rm -rf OpenBLAS-develop; unzip OpenBLAS.zip && cd OpenBLAS-develop; make ONLY_CBLAS=1; if [ $? -ne 0 ] then cd ..; return -1; fi if [ $# == 1 ] then echo "install OpenBLAS in $1"; make PREFIX=$1 install; if [ $? -ne 0 ] then cd ..; return -1; fi elif [ $# == 0 ] then echo "install OpenBLAS in default path" sudo make install; if [ $? -ne 0 ] then cd ..; return -1; fi else echo "wrong commands"; fi cd ..; return 0; } function install_opencv() { if [ ! -e "opencv-2.4.10.zip" ] then wget http://www.comp.nus.edu.sg/~dbsystem/singa/assets/file/thirdparty/opencv-2.4.10.zip; fi rm -rf opencv-2.4.10; unzip opencv-2.4.10.zip && cd opencv-2.4.10; if [ $# == 1 ] then echo "install opencv in $1"; cmake -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_INSTALL_PREFIX=$1; make && make install; elif [ $# == 0 ] then echo "install opencv in default path"; cmake -DCMAKE_BUILD_TYPE=RELEASE; make && sudo make install; else echo "wrong commands"; fi if [ $? -ne 0 ] then cd ..; return -1; fi cd ..; return 0; } function install_protobuf() { if [ ! -e "protobuf-2.6.0.tar.gz" ] then wget http://www.comp.nus.edu.sg/~dbsystem/singa/assets/file/thirdparty/protobuf-2.6.0.tar.gz; fi rm -rf protobuf-2.6.0; tar zxvf protobuf-2.6.0.tar.gz && cd protobuf-2.6.0; if [ $# == 1 ] then echo "install protobuf in $1"; ./configure --prefix=$1; make && make install; #cd python; #python setup.py build; #python setup.py install --prefix=$1; #cd ..; elif [ $# == 0 ] then echo "install protobuf in default path"; #./configure; #make && sudo make install; #cd python; #python setup.py build; #sudo python setup.py install; #cd ..; else echo "wrong commands"; fi if [ $? -ne 0 ] then cd ..; return -1; fi cd ..; return 0; } function install_zeromq() { if [ ! -e "zeromq-3.2.2.tar.gz" ] then wget http://www.comp.nus.edu.sg/~dbsystem/singa/assets/file/thirdparty/zeromq-3.2.2.tar.gz; fi rm -rf zeromq-3.2.2; tar zxvf zeromq-3.2.2.tar.gz && cd zeromq-3.2.2; if [ $# == 1 ] then echo "install zeromq in $1"; ./configure --prefix=$1; make && make install; elif [ $# == 0 ] then echo "install zeromq in default path"; ./configure; make && sudo make install; else echo "wrong commands"; fi if [ $? -ne 0 ] then cd ..; return -1; fi cd ..; return 0; } function install_zookeeper() { if [ ! -e "zookeeper-3.4.6.tar.gz" ] then wget http://www.comp.nus.edu.sg/~dbsystem/singa/assets/file/thirdparty/zookeeper-3.4.6.tar.gz; fi rm -rf zookeeper-3.4.6; tar zxvf zookeeper-3.4.6.tar.gz; cd zookeeper-3.4.6/src/c; if [ $# == 1 ] then echo "install zookeeper in $1"; ./configure --prefix=$1; make && make install; elif [ $# == 0 ] then echo "install zookeeper in default path"; ./configure; make && sudo make install; # ./configure; # make && sudo make install; else echo "wrong commands"; fi if [ $? -ne 0 ] then cd ../../..; return -1; fi cd ../../..; return 0; } BIN=`dirname "${BASH_SOURCE-$0}"` BIN=`cd "$BIN">/dev/null; pwd` BASE=`cd "$BIN/..">/dev/null; pwd` cd $BIN while [ $# != 0 ] do case $1 in # "cmake") # echo "install cmake"; # if [[ $2 == */* ]];then # install_cmake $2; # if [ $? -ne 0 ] # then # echo "ERROR during cmake installation" ; # exit; # fi # shift # shift # else # install_cmake; # if [ $? -ne 0 ] # then # echo "ERROR during cmake installation" ; # exit; # fi # shift # fi # ;; "czmq") echo "install czmq"; if [ $2 == "-f" ] then if [[ $4 == */* ]] then install_czmq $4 $3; else install_czmq null $3; fi if [ $? -ne 0 ] then echo "ERROR during czmq installation" ; exit; fi shift shift shift shift elif [ $3 == "-f" ] then install_czmq $2 $4; if [ $? -ne 0 ] then echo "ERROR during czmq installation" ; exit; fi shift shift shift shift elif [[ $2 == */* ]] then install_czmq $2; if [ $? -ne 0 ] then echo "ERROR during czmq installation" ; exit; fi shift shift else install_czmq null; if [ $? -ne 0 ] then echo "ERROR during czmq installation" ; exit; fi shift fi ;; "glog") echo "install glog"; if [[ $2 == */* ]];then install_glog $2; if [ $? -ne 0 ] then echo "ERROR during glog installation" ; exit; fi shift shift else install_glog; if [ $? -ne 0 ] then echo "ERROR during glog installation" ; exit; fi shift fi ;; "lmdb") echo "install lmdb"; if [[ $2 == */* ]];then install_lmdb $2; if [ $? -ne 0 ] then echo "ERROR during lmdb installation" ; exit; fi shift shift else install_lmdb; if [ $? -ne 0 ] then echo "ERROR during lmdb installation" ; exit; fi shift fi ;; "OpenBLAS") echo "install OpenBLAS"; if [[ $2 == */* ]];then install_openblas $2; if [ $? -ne 0 ] then echo "ERROR during openblas installation" ; exit; fi shift shift else install_openblas; if [ $? -ne 0 ] then echo "ERROR during openblas installation" ; exit; fi shift fi ;; # "opencv") # echo "install opencv"; # if [[ $2 == */* ]];then # install_opencv $2; # if [ $? -ne 0 ] # then # echo "ERROR during opencv installation" ; # exit; # fi # shift # shift # else # install_opencv; # if [ $? -ne 0 ] # then # echo "ERROR during opencv installation" ; # exit; # fi # shift # fi # ;; "protobuf") echo "install protobuf"; if [[ $2 == */* ]];then install_protobuf $2; if [ $? -ne 0 ] then echo "ERROR during protobuf installation" ; exit; fi shift shift else install_protobuf; if [ $? -ne 0 ] then echo "ERROR during protobuf installation" ; exit; fi shift fi ;; "zeromq") echo "install zeromq"; if [[ $2 == */* ]];then install_zeromq $2; if [ $? -ne 0 ] then echo "ERROR during zeromq installation" ; exit; fi shift shift else install_zeromq; if [ $? -ne 0 ] then echo "ERROR during zeromq installation" ; exit; fi shift fi ;; "zookeeper") echo "install zookeeper"; if [[ $2 == */* ]];then install_zookeeper $2; if [ $? -ne 0 ] then echo "ERROR during zookeeper installation" ; exit; fi shift shift else install_zookeeper; if [ $? -ne 0 ] then echo "ERROR during zookeeper installation" ; exit; fi shift fi ;; "all") echo "install all dependencies"; if [[ $2 == */* ]];then # install_cmake $2; # if [ $? -ne 0 ] # then # echo "ERROR during cmake installation" ; # exit; # fi install_zeromq $2; if [ $? -ne 0 ] then echo "ERROR during zeromq installation" ; exit; fi install_czmq $2 $2; if [ $? -ne 0 ] then echo "ERROR during czmq installation" ; exit; fi install_glog $2; if [ $? -ne 0 ] then echo "ERROR during glog installation" ; exit; fi # install_lmdb $2; # if [ $? -ne 0 ] # then # echo "ERROR during lmdb installation" ; # exit; # fi install_openblas $2; if [ $? -ne 0 ] then echo "ERROR during openblas installation" ; exit; fi # install_opencv $2; # if [ $? -ne 0 ] # then # echo "ERROR during opencv installation" ; # exit; # fi install_protobuf $2; if [ $? -ne 0 ] then echo "ERROR during protobuf installation" ; exit; fi install_zookeeper $2; if [ $? -ne 0 ] then echo "ERROR during zookeeper installation" ; exit; fi shift shift else # install_cmake; # if [ $? -ne 0 ] # then # echo "ERROR during cmake installation" ; # exit; # fi install_zeromq; if [ $? -ne 0 ] then echo "ERROR during zeromq installation" ; exit; fi install_czmq null; if [ $? -ne 0 ] then echo "ERROR during czmq installation" ; exit; fi install_glog; if [ $? -ne 0 ] then echo "ERROR during glog installation" ; exit; fi # install_lmdb; # if [ $? -ne 0 ] # then # echo "ERROR during lmdb installation" ; # exit; # fi install_openblas; if [ $? -ne 0 ] then echo "ERROR during openblas installation" ; exit; fi # install_opencv; # if [ $? -ne 0 ] # then # echo "ERROR during opencv installation" ; # exit; # fi install_protobuf; if [ $? -ne 0 ] then echo "ERROR during protobuf installation" ; exit; fi install_zookeeper; if [ $? -ne 0 ] then echo "ERROR during zookeeper installation" ; exit; fi shift fi ;; *) echo "USAGE: ./install.sh [MISSING_LIBRARY_NAME1] [YOUR_INSTALL_PATH1] [MISSING_LIBRARY_NAME2] [YOUR_INSTALL_PATH2] ..."; echo " MISSING_LIBRARY_NAME can be: " # echo " cmake" echo " czmq" echo " glog" echo " lmdb" echo " OpenBLAS" # echo " opencv" echo " protobuf" echo " zeromq" echo " zookeeper" echo " To install all dependencies, you can run: " echo " ./install.sh all" exit; esac done
venkatsatish/incubator-singa
thirdparty/install.sh
Shell
apache-2.0
13,556
/* * Copyright 2015 Schedo Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.ncode.android.apps.schedo.gcm; import android.content.Context; public abstract class GCMCommand { public abstract void execute(Context context, String type, String extraData); }
ipalermo/schedo
android/src/main/java/com/ncode/android/apps/schedo/gcm/GCMCommand.java
Java
apache-2.0
813
package com.likebamboo.osa.android.request; import android.text.TextUtils; import com.android.volley.Request; import com.android.volley.Response; import org.json.JSONException; import org.json.JSONObject; import java.util.Map; /** * Created by likebamboo on 2015/5/12. */ public abstract class BaseRequest<T> extends Request<T> { public BaseRequest(int method, String url, Response.ErrorListener listener) { super(method, url, listener); } /** * 返回json数据中的result字段 * * @param data * @return */ protected String getResult(String data) { if (TextUtils.isEmpty(data)) { return null; } JSONObject json = null; try { json = new JSONObject(data); return json.getString("result"); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return data; } /** * 拼接URL(仅针对get方法) * * @param method * @param baseUrl * @param params * @return */ public static String formatUrl(int method, String baseUrl, Map<String, String> params) { if (method != Method.GET) { return baseUrl; } return formatUrl(baseUrl, params); } /** * 拼接URL(仅针对get方法) * * @param baseUrl * @param params * @return */ public static String formatUrl(String baseUrl, Map<String, String> params) { if (TextUtils.isEmpty(baseUrl) || params == null || params.isEmpty()) { return baseUrl; } StringBuilder sb = new StringBuilder(baseUrl); if (sb.toString().contains("?")) { // 不以问号结尾 if (!sb.toString().endsWith("?")) { sb.append("&"); } } else {// 没有问号,添加问号 sb.append("?"); } String split = ""; for (String key : params.keySet()) { sb.append(split).append(key).append("=").append(params.get(key)); split = "&"; } return sb.toString(); } }
likebamboo/AndroidBlog
app/src/main/java/com/likebamboo/osa/android/request/BaseRequest.java
Java
apache-2.0
2,200
package com.devin.util; import android.content.Context; import android.media.AudioManager; /** * <p>Description: * <p>Company: * <p>Email:bjxm2013@163.com * <p>Created by Devin Sun on 2017/11/6. */ public class SpeakerUtils { /** * 扬声器开关 * @param context * @param enableSpeaker 是否打开扬声器,true:打开,false:关闭 */ public static void switchSpeaker(Context context, boolean enableSpeaker) { try { AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); audioManager.setMode(AudioManager.ROUTE_SPEAKER); int currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL); if (enableSpeaker) { //setSpeakerphoneOn() only work when audio mode set to MODE_IN_CALL. audioManager.setMode(AudioManager.MODE_IN_CALL); audioManager.setSpeakerphoneOn(true); audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), AudioManager.STREAM_VOICE_CALL); } else { audioManager.setSpeakerphoneOn(false); audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, currVolume, AudioManager.STREAM_VOICE_CALL); } } catch (Exception e) { e.printStackTrace(); } } /** * 获取扬声器是否开启 * @param context * @return true:已打开,false:已关闭 */ public static boolean isOpenSpeaker(Context context) { try { AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); return audioManager.isSpeakerphoneOn(); } catch (Exception e) { e.printStackTrace(); } return false; } }
sundevin/utilsLibrary
utilslibrary/src/main/java/com/devin/util/SpeakerUtils.java
Java
apache-2.0
1,961
package com.taobao.tddl.repo.bdb.executor; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import com.taobao.tddl.common.exception.TddlException; import com.taobao.tddl.common.model.Group; import com.taobao.tddl.common.model.lifecycle.AbstractLifecycle; import com.taobao.tddl.executor.common.ExecutionContext; import com.taobao.tddl.executor.cursor.ISchematicCursor; import com.taobao.tddl.executor.cursor.ResultCursor; import com.taobao.tddl.executor.spi.IAtomExecutor; import com.taobao.tddl.executor.spi.IGroupExecutor; import com.taobao.tddl.optimizer.core.plan.IDataNodeExecutor; @SuppressWarnings("rawtypes") public class BDBGroupExecutor extends AbstractLifecycle implements IGroupExecutor { private final ArrayList<IAtomExecutor> executorList; private ResourceSelector slaveSelector; private ExceptionSorter<Integer> slaveExceptionSorter; private ResourceSelector masterSelector; private ExceptionSorter<Integer> masterExceptionSorter; /** * @param resultSetMap 结果集对应Map * @param executorList 执行client的list * @param rWeight 读权重 */ public BDBGroupExecutor(ArrayList<IAtomExecutor> executorList, List<Integer> rWeight){ this.executorList = executorList; this.masterExceptionSorter = new MasterExceptionSorter<Integer>(); this.slaveExceptionSorter = new SlaveExceptionSorter<Integer>(); this.masterSelector = new MasterResourceSelector(executorList.size()); this.slaveSelector = new SlaveResourceSelector(executorList.size(), rWeight); } private static int findIndexToExecute(ResourceSelector selector, Map<Integer, String> excludeKeys) throws TddlException { int index = 0; Integer specIndex = null; if (specIndex != null) { index = specIndex; } else { index = selector.select(excludeKeys); } return index; } @Override public String toString() { return "BDBGroupExecutor [masterSelector=" + masterSelector + "]"; } public ResourceSelector getSlaveSelector() { return slaveSelector; } public void setSlaveSelector(ResourceSelector slaveSelector) { this.slaveSelector = slaveSelector; } public ExceptionSorter<Integer> getSlaveExceptionSorter() { return slaveExceptionSorter; } public void setSlaveExceptionSorter(ExceptionSorter<Integer> slaveExceptionSorter) { this.slaveExceptionSorter = slaveExceptionSorter; } public ResourceSelector getMasterSelector() { return masterSelector; } public void setMasterSelector(ResourceSelector masterSelector) { this.masterSelector = masterSelector; } public ExceptionSorter<Integer> getMasterExceptionSorter() { return masterExceptionSorter; } public void setMasterExceptionSorter(ExceptionSorter<Integer> masterExceptionSorter) { this.masterExceptionSorter = masterExceptionSorter; } @Override public ISchematicCursor execByExecPlanNode(IDataNodeExecutor qc, ExecutionContext executionContext) throws TddlException { // IAtomExecutor atomExecutor = this.selectAtomExecutor(executeType, // executionContext); // try { // rsHandler = commandExecutor.execByExecPlanNode(qc, executionContext); // } catch (TddlException e) { // ReturnVal<Integer> isRetryException = // exceptionSorter.isRetryException(e.getMessage(), excludeKeys, index); // excludeKeys = isRetryException.getExcludeKeys(); // if (!isRetryException.isRetryException()) { // throw e; // } else { // // 将excludeKey 加入map后,进入下一次循环 // continue; // } // } return null; } enum ExecuteType { READ, WRITE }; IAtomExecutor selectAtomExecutor(ExecuteType executeType, ExecutionContext executionContext) throws TddlException { Map<Integer, String/* exception */> excludeKeys = null; IAtomExecutor atomExecutor = null; ResourceSelector selector = null; if (executeType == ExecuteType.READ) { selector = this.getSlaveSelector(); } else { selector = this.getMasterSelector(); } int index = findIndexToExecute(selector, excludeKeys); atomExecutor = executorList.get(index); return atomExecutor; } @Override public ResultCursor commit(ExecutionContext executionContext) throws TddlException { // TODO Auto-generated method stub return null; } @Override public ResultCursor rollback(ExecutionContext executionContext) throws TddlException { // TODO Auto-generated method stub return null; } @Override public Future<ISchematicCursor> execByExecPlanNodeFuture(IDataNodeExecutor qc, ExecutionContext executionContext) throws TddlException { // TODO Auto-generated method stub return null; } @Override public Future<ResultCursor> commitFuture(ExecutionContext executionContext) throws TddlException { // TODO Auto-generated method stub return null; } @Override public Future<ResultCursor> rollbackFuture(ExecutionContext executionContext) throws TddlException { // TODO Auto-generated method stub return null; } @Override public Group getGroupInfo() { // TODO Auto-generated method stub return null; } @Override public Object getRemotingExecutableObject() { // TODO Auto-generated method stub return null; } }
sdgdsffdsfff/tddl
tddl-repo-bdb/src/main/java/com/taobao/tddl/repo/bdb/executor/BDBGroupExecutor.java
Java
apache-2.0
6,080
package scalacookbook.chapter04 /** * Created by liguodong on 2016/6/30. */ object ProvideDefaultValueForConstructParam extends App{ import section05._ val s = new Socket println(s.timeout) val s2 = new Socket(5000) println(s2.timeout) val s3 = new Socket(timeout=5000) println(s3.timeout) //Discussion println(new Socket2) println(new Socket2(3000)) println("~~~~~~~~~~~~") println(new Socket3(3000, 4000)) println("~~~~~~~~~~~~") //Using named parameters // provide the names of constructor parameters when creating objects println(new Socket3(timeout=3000, linger=4000)) println(new Socket3(linger=4000, timeout=3000)) println(new Socket3(timeout=3000)) println(new Socket3(linger=4000)) } package section05{ class Socket (val timeout: Int = 10000) //a primary one-arg constructor and an auxiliary zero-args constructor class Socket2(val timeout: Int) { def this() = this(10000) override def toString = s"timeout: $timeout" } //Multiple parameters class Socket3(val timeout: Int = 1000, val linger: Int = 2000) { override def toString = s"timeout: $timeout, linger: $linger" } }
liguodongIOT/java-scala-mix-sbt
src/main/scala/scalacookbook/chapter04/ProvideDefaultValueForConstructParam.scala
Scala
apache-2.0
1,176
/* * Copyright 2022 Crown Copyright * * 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. * */ /* * This code was copied (unchanged except for formatting and the 'throw' in unmap()) from * https://github.com/dain/leveldb/blob/master/leveldb/src/main/java/org/iq80/leveldb/util/ByteBufferSupport.java * Original license below. * Original copyright: 2011 Dain Sundstrom dain@iq80.com */ /* * Copyright (C) 2011 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * 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 stroom.bytebuffer; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; /* * This code was copied (unchanged except for formatting and the 'throw' in unmap()) from * https://github.com/dain/leveldb/blob/master/leveldb/src/main/java/org/iq80/leveldb/util/ByteBufferSupport.java */ public class ByteBufferSupport { private static final MethodHandle INVOKE_CLEANER; static { MethodHandle invoker; try { // Java 9 added an invokeCleaner method to Unsafe to work around // module visibility issues for code that used to rely on DirectByteBuffer's cleaner() Class<?> unsafeClass = Class.forName("sun.misc.Unsafe"); Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); invoker = MethodHandles.lookup() .findVirtual( unsafeClass, "invokeCleaner", MethodType.methodType(void.class, ByteBuffer.class)) .bindTo(theUnsafe.get(null)); } catch (Exception e) { // fall back to pre-java 9 compatible behavior try { Class<?> directByteBufferClass = Class.forName("java.nio.DirectByteBuffer"); Class<?> cleanerClass = Class.forName("sun.misc.Cleaner"); Method cleanerMethod = directByteBufferClass.getDeclaredMethod("cleaner"); cleanerMethod.setAccessible(true); MethodHandle getCleaner = MethodHandles.lookup().unreflect(cleanerMethod); Method cleanMethod = cleanerClass.getDeclaredMethod("clean"); cleanerMethod.setAccessible(true); MethodHandle clean = MethodHandles.lookup().unreflect(cleanMethod); clean = MethodHandles.dropArguments(clean, 1, directByteBufferClass); invoker = MethodHandles.foldArguments(clean, getCleaner); } catch (Exception e1) { throw new AssertionError(e1); } } INVOKE_CLEANER = invoker; } private ByteBufferSupport() { } public static void unmap(MappedByteBuffer buffer) { try { INVOKE_CLEANER.invoke(buffer); } catch (Throwable e) { throw new RuntimeException(e); } } }
gchq/stroom
stroom-lmdb/src/main/java/stroom/bytebuffer/ByteBufferSupport.java
Java
apache-2.0
4,197
/*! * Ext JS Library 3.4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ // private // This is a support class used internally by the Grid components Ext.grid.HeaderDragZone = Ext.extend(Ext.dd.DragZone, { maxDragWidth: 120, constructor : function(grid, hd, hd2){ this.grid = grid; this.view = grid.getView(); this.ddGroup = "gridHeader" + this.grid.getGridEl().id; Ext.grid.HeaderDragZone.superclass.constructor.call(this, hd); if(hd2){ this.setHandleElId(Ext.id(hd)); this.setOuterHandleElId(Ext.id(hd2)); } this.scroll = false; }, getDragData : function(e){ var t = Ext.lib.Event.getTarget(e), h = this.view.findHeaderCell(t); if(h){ return {ddel: h.firstChild, header:h}; } return false; }, onInitDrag : function(e){ // keep the value here so we can restore it; this.dragHeadersDisabled = this.view.headersDisabled; this.view.headersDisabled = true; var clone = this.dragData.ddel.cloneNode(true); clone.id = Ext.id(); clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px"; this.proxy.update(clone); return true; }, afterValidDrop : function(){ this.completeDrop(); }, afterInvalidDrop : function(){ this.completeDrop(); }, completeDrop: function(){ var v = this.view, disabled = this.dragHeadersDisabled; setTimeout(function(){ v.headersDisabled = disabled; }, 50); } }); // private // This is a support class used internally by the Grid components Ext.grid.HeaderDropZone = Ext.extend(Ext.dd.DropZone, { proxyOffsets : [-4, -9], fly: Ext.Element.fly, constructor : function(grid, hd, hd2){ this.grid = grid; this.view = grid.getView(); // split the proxies so they don't interfere with mouse events this.proxyTop = Ext.DomHelper.append(document.body, { cls:"col-move-top", html:"&#160;" }, true); this.proxyBottom = Ext.DomHelper.append(document.body, { cls:"col-move-bottom", html:"&#160;" }, true); this.proxyTop.hide = this.proxyBottom.hide = function(){ this.setLeftTop(-100,-100); this.setStyle("visibility", "hidden"); }; this.ddGroup = "gridHeader" + this.grid.getGridEl().id; // temporarily disabled //Ext.dd.ScrollManager.register(this.view.scroller.dom); Ext.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom); }, getTargetFromEvent : function(e){ var t = Ext.lib.Event.getTarget(e), cindex = this.view.findCellIndex(t); if(cindex !== false){ return this.view.getHeaderCell(cindex); } }, nextVisible : function(h){ var v = this.view, cm = this.grid.colModel; h = h.nextSibling; while(h){ if(!cm.isHidden(v.getCellIndex(h))){ return h; } h = h.nextSibling; } return null; }, prevVisible : function(h){ var v = this.view, cm = this.grid.colModel; h = h.prevSibling; while(h){ if(!cm.isHidden(v.getCellIndex(h))){ return h; } h = h.prevSibling; } return null; }, positionIndicator : function(h, n, e){ var x = Ext.lib.Event.getPageX(e), r = Ext.lib.Dom.getRegion(n.firstChild), px, pt, py = r.top + this.proxyOffsets[1]; if((r.right - x) <= (r.right-r.left)/2){ px = r.right+this.view.borderWidth; pt = "after"; }else{ px = r.left; pt = "before"; } if(this.grid.colModel.isFixed(this.view.getCellIndex(n))){ return false; } px += this.proxyOffsets[0]; this.proxyTop.setLeftTop(px, py); this.proxyTop.show(); if(!this.bottomOffset){ this.bottomOffset = this.view.mainHd.getHeight(); } this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset); this.proxyBottom.show(); return pt; }, onNodeEnter : function(n, dd, e, data){ if(data.header != n){ this.positionIndicator(data.header, n, e); } }, onNodeOver : function(n, dd, e, data){ var result = false; if(data.header != n){ result = this.positionIndicator(data.header, n, e); } if(!result){ this.proxyTop.hide(); this.proxyBottom.hide(); } return result ? this.dropAllowed : this.dropNotAllowed; }, onNodeOut : function(n, dd, e, data){ this.proxyTop.hide(); this.proxyBottom.hide(); }, onNodeDrop : function(n, dd, e, data){ var h = data.header; if(h != n){ var cm = this.grid.colModel, x = Ext.lib.Event.getPageX(e), r = Ext.lib.Dom.getRegion(n.firstChild), pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before", oldIndex = this.view.getCellIndex(h), newIndex = this.view.getCellIndex(n); if(pt == "after"){ newIndex++; } if(oldIndex < newIndex){ newIndex--; } cm.moveColumn(oldIndex, newIndex); return true; } return false; } }); Ext.grid.GridView.ColumnDragZone = Ext.extend(Ext.grid.HeaderDragZone, { constructor : function(grid, hd){ Ext.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null); this.proxy.el.addClass('x-grid3-col-dd'); }, handleMouseDown : function(e){ }, callHandleMouseDown : function(e){ Ext.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e); } });
ahwxl/cms
icms/src/main/webapp/res/extjs/src/widgets/grid/ColumnDD.js
JavaScript
apache-2.0
6,400
--- title: "Streaming File Sink" nav-title: Streaming File Sink nav-parent_id: connectors nav-pos: 5 --- <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> * This will be replaced by the TOC {:toc} This connector provides a Sink that writes partitioned files to filesystems supported by the [Flink `FileSystem` abstraction]({% link deployment/filesystems/index.md %}). The streaming file sink writes incoming data into buckets. Given that the incoming streams can be unbounded, data in each bucket are organized into part files of finite size. The bucketing behaviour is fully configurable with a default time-based bucketing where we start writing a new bucket every hour. This means that each resulting bucket will contain files with records received during 1 hour intervals from the stream. Data within the bucket directories are split into part files. Each bucket will contain at least one part file for each subtask of the sink that has received data for that bucket. Additional part files will be created according to the configurable rolling policy. The default policy rolls part files based on size, a timeout that specifies the maximum duration for which a file can be open, and a maximum inactivity timeout after which the file is closed. <div class="alert alert-info"> <b>IMPORTANT:</b> Checkpointing needs to be enabled when using the StreamingFileSink. Part files can only be finalized on successful checkpoints. If checkpointing is disabled, part files will forever stay in the `in-progress` or the `pending` state, and cannot be safely read by downstream systems. </div> <img src="{% link /fig/streamfilesink_bucketing.png %}" class="center" style="width: 100%;" /> ## File Formats The `StreamingFileSink` supports both row-wise and bulk encoding formats, such as [Apache Parquet](http://parquet.apache.org). These two variants come with their respective builders that can be created with the following static methods: - Row-encoded sink: `StreamingFileSink.forRowFormat(basePath, rowEncoder)` - Bulk-encoded sink: `StreamingFileSink.forBulkFormat(basePath, bulkWriterFactory)` When creating either a row or a bulk encoded sink we have to specify the base path where the buckets will be stored and the encoding logic for our data. Please check out the JavaDoc for [StreamingFileSink]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/streaming/api/functions/sink/filesystem/StreamingFileSink.html) for all the configuration options and more documentation about the implementation of the different data formats. ### Row-encoded Formats Row-encoded formats need to specify an [Encoder]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/api/common/serialization/Encoder.html) that is used for serializing individual rows to the `OutputStream` of the in-progress part files. In addition to the bucket assigner, the [RowFormatBuilder]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/streaming/api/functions/sink/filesystem/StreamingFileSink.RowFormatBuilder.html) allows the user to specify: - Custom [RollingPolicy]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/streaming/api/functions/sink/filesystem/RollingPolicy.html) : Rolling policy to override the DefaultRollingPolicy - bucketCheckInterval (default = 1 min) : Millisecond interval for checking time based rolling policies Basic usage for writing String elements thus looks like this: <div class="codetabs" markdown="1"> <div data-lang="java" markdown="1"> {% highlight java %} import org.apache.flink.api.common.serialization.SimpleStringEncoder; import org.apache.flink.core.fs.Path; import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink; import org.apache.flink.streaming.api.functions.sink.filesystem.rollingpolicies.DefaultRollingPolicy; DataStream<String> input = ...; final StreamingFileSink<String> sink = StreamingFileSink .forRowFormat(new Path(outputPath), new SimpleStringEncoder<String>("UTF-8")) .withRollingPolicy( DefaultRollingPolicy.builder() .withRolloverInterval(TimeUnit.MINUTES.toMillis(15)) .withInactivityInterval(TimeUnit.MINUTES.toMillis(5)) .withMaxPartSize(1024 * 1024 * 1024) .build()) .build(); input.addSink(sink); {% endhighlight %} </div> <div data-lang="scala" markdown="1"> {% highlight scala %} import org.apache.flink.api.common.serialization.SimpleStringEncoder import org.apache.flink.core.fs.Path import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink import org.apache.flink.streaming.api.functions.sink.filesystem.rollingpolicies.DefaultRollingPolicy val input: DataStream[String] = ... val sink: StreamingFileSink[String] = StreamingFileSink .forRowFormat(new Path(outputPath), new SimpleStringEncoder[String]("UTF-8")) .withRollingPolicy( DefaultRollingPolicy.builder() .withRolloverInterval(TimeUnit.MINUTES.toMillis(15)) .withInactivityInterval(TimeUnit.MINUTES.toMillis(5)) .withMaxPartSize(1024 * 1024 * 1024) .build()) .build() input.addSink(sink) {% endhighlight %} </div> </div> This example creates a simple sink that assigns records to the default one hour time buckets. It also specifies a rolling policy that rolls the in-progress part file on any of the following 3 conditions: - It contains at least 15 minutes worth of data - It hasn't received new records for the last 5 minutes - The file size has reached 1 GB (after writing the last record) ### Bulk-encoded Formats Bulk-encoded sinks are created similarly to the row-encoded ones, but instead of specifying an `Encoder`, we have to specify a [BulkWriter.Factory]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/api/common/serialization/BulkWriter.Factory.html). The `BulkWriter` logic defines how new elements are added and flushed, and how a batch of records is finalized for further encoding purposes. Flink comes with four built-in BulkWriter factories: - [ParquetWriterFactory]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/formats/parquet/ParquetWriterFactory.html) - [AvroWriterFactory]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/formats/avro/AvroWriterFactory.html) - [SequenceFileWriterFactory]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/formats/sequencefile/SequenceFileWriterFactory.html) - [CompressWriterFactory]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/formats/compress/CompressWriterFactory.html) - [OrcBulkWriterFactory]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/orc/writer/OrcBulkWriterFactory.html) <div class="alert alert-info"> <b>IMPORTANT:</b> Bulk Formats can only have `OnCheckpointRollingPolicy`, which rolls (ONLY) on every checkpoint. </div> #### Parquet format Flink contains built in convenience methods for creating Parquet writer factories for Avro data. These methods and their associated documentation can be found in the [ParquetAvroWriters]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/formats/parquet/avro/ParquetAvroWriters.html) class. For writing to other Parquet compatible data formats, users need to create the ParquetWriterFactory with a custom implementation of the [ParquetBuilder]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/formats/parquet/ParquetBuilder.html) interface. To use the Parquet bulk encoder in your application you need to add the following dependency: {% highlight xml %} <dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-parquet{{ site.scala_version_suffix }}</artifactId> <version>{{ site.version }}</version> </dependency> {% endhighlight %} A StreamingFileSink that writes Avro data to Parquet format can be created like this: <div class="codetabs" markdown="1"> <div data-lang="java" markdown="1"> {% highlight java %} import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink; import org.apache.flink.formats.parquet.avro.ParquetAvroWriters; import org.apache.avro.Schema; Schema schema = ...; DataStream<GenericRecord> stream = ...; final StreamingFileSink<GenericRecord> sink = StreamingFileSink .forBulkFormat(outputBasePath, ParquetAvroWriters.forGenericRecord(schema)) .build(); input.addSink(sink); {% endhighlight %} </div> <div data-lang="scala" markdown="1"> {% highlight scala %} import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink import org.apache.flink.formats.parquet.avro.ParquetAvroWriters import org.apache.avro.Schema val schema: Schema = ... val input: DataStream[GenericRecord] = ... val sink: StreamingFileSink[GenericRecord] = StreamingFileSink .forBulkFormat(outputBasePath, ParquetAvroWriters.forGenericRecord(schema)) .build() input.addSink(sink) {% endhighlight %} </div> </div> Similarly, a StreamingFileSink that writes Protobuf data to Parquet format can be created like this: <div class="codetabs" markdown="1"> <div data-lang="java" markdown="1"> {% highlight java %} import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink; import org.apache.flink.formats.parquet.protobuf.ParquetProtoWriters; // ProtoRecord is a generated protobuf Message class. DataStream<ProtoRecord> stream = ...; final StreamingFileSink<ProtoRecord> sink = StreamingFileSink .forBulkFormat(outputBasePath, ParquetProtoWriters.forType(ProtoRecord.class)) .build(); input.addSink(sink); {% endhighlight %} </div> <div data-lang="scala" markdown="1"> {% highlight scala %} import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink import org.apache.flink.formats.parquet.protobuf.ParquetProtoWriters // ProtoRecord is a generated protobuf Message class. val input: DataStream[ProtoRecord] = ... val sink: StreamingFileSink[ProtoRecord] = StreamingFileSink .forBulkFormat(outputBasePath, ParquetProtoWriters.forType(classOf[ProtoRecord])) .build() input.addSink(sink) {% endhighlight %} </div> </div> #### Avro format Flink also provides built-in support for writing data into Avro files. A list of convenience methods to create Avro writer factories and their associated documentation can be found in the [AvroWriters]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/formats/avro/AvroWriters.html) class. To use the Avro writers in your application you need to add the following dependency: {% highlight xml %} <dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-avro</artifactId> <version>{{ site.version }}</version> </dependency> {% endhighlight %} A StreamingFileSink that writes data to Avro files can be created like this: <div class="codetabs" markdown="1"> <div data-lang="java" markdown="1"> {% highlight java %} import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink; import org.apache.flink.formats.avro.AvroWriters; import org.apache.avro.Schema; Schema schema = ...; DataStream<GenericRecord> stream = ...; final StreamingFileSink<GenericRecord> sink = StreamingFileSink .forBulkFormat(outputBasePath, AvroWriters.forGenericRecord(schema)) .build(); input.addSink(sink); {% endhighlight %} </div> <div data-lang="scala" markdown="1"> {% highlight scala %} import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink import org.apache.flink.formats.avro.AvroWriters import org.apache.avro.Schema val schema: Schema = ... val input: DataStream[GenericRecord] = ... val sink: StreamingFileSink[GenericRecord] = StreamingFileSink .forBulkFormat(outputBasePath, AvroWriters.forGenericRecord(schema)) .build() input.addSink(sink) {% endhighlight %} </div> </div> For creating customized Avro writers, e.g. enabling compression, users need to create the `AvroWriterFactory` with a custom implementation of the [AvroBuilder]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/formats/avro/AvroBuilder.html) interface: <div class="codetabs" markdown="1"> <div data-lang="java" markdown="1"> {% highlight java %} AvroWriterFactory<?> factory = new AvroWriterFactory<>((AvroBuilder<Address>) out -> { Schema schema = ReflectData.get().getSchema(Address.class); DatumWriter<Address> datumWriter = new ReflectDatumWriter<>(schema); DataFileWriter<Address> dataFileWriter = new DataFileWriter<>(datumWriter); dataFileWriter.setCodec(CodecFactory.snappyCodec()); dataFileWriter.create(schema, out); return dataFileWriter; }); DataStream<Address> stream = ... stream.addSink(StreamingFileSink.forBulkFormat( outputBasePath, factory).build()); {% endhighlight %} </div> <div data-lang="scala" markdown="1"> {% highlight scala %} val factory = new AvroWriterFactory[Address](new AvroBuilder[Address]() { override def createWriter(out: OutputStream): DataFileWriter[Address] = { val schema = ReflectData.get.getSchema(classOf[Address]) val datumWriter = new ReflectDatumWriter[Address](schema) val dataFileWriter = new DataFileWriter[Address](datumWriter) dataFileWriter.setCodec(CodecFactory.snappyCodec) dataFileWriter.create(schema, out) dataFileWriter } }) val stream: DataStream[Address] = ... stream.addSink(StreamingFileSink.forBulkFormat( outputBasePath, factory).build()); {% endhighlight %} </div> </div> #### ORC Format To enable the data to be bulk encoded in ORC format, Flink offers [OrcBulkWriterFactory]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/formats/orc/writers/OrcBulkWriterFactory.html) which takes a concrete implementation of [Vectorizer]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/orc/vector/Vectorizer.html). Like any other columnar format that encodes data in bulk fashion, Flink's `OrcBulkWriter` writes the input elements in batches. It uses ORC's `VectorizedRowBatch` to achieve this. Since the input element has to be transformed to a `VectorizedRowBatch`, users have to extend the abstract `Vectorizer` class and override the `vectorize(T element, VectorizedRowBatch batch)` method. As you can see, the method provides an instance of `VectorizedRowBatch` to be used directly by the users so users just have to write the logic to transform the input `element` to `ColumnVectors` and set them in the provided `VectorizedRowBatch` instance. For example, if the input element is of type `Person` which looks like: <div class="codetabs" markdown="1"> <div data-lang="java" markdown="1"> {% highlight java %} class Person { private final String name; private final int age; ... } {% endhighlight %} </div> </div> Then a child implementation to convert the element of type `Person` and set them in the `VectorizedRowBatch` can be like: <div class="codetabs" markdown="1"> <div data-lang="java" markdown="1"> {% highlight java %} import org.apache.hadoop.hive.ql.exec.vector.BytesColumnVector; import org.apache.hadoop.hive.ql.exec.vector.LongColumnVector; import java.io.IOException; import java.io.Serializable; import java.nio.charset.StandardCharsets; public class PersonVectorizer extends Vectorizer<Person> implements Serializable { public PersonVectorizer(String schema) { super(schema); } @Override public void vectorize(Person element, VectorizedRowBatch batch) throws IOException { BytesColumnVector nameColVector = (BytesColumnVector) batch.cols[0]; LongColumnVector ageColVector = (LongColumnVector) batch.cols[1]; int row = batch.size++; nameColVector.setVal(row, element.getName().getBytes(StandardCharsets.UTF_8)); ageColVector.vector[row] = element.getAge(); } } {% endhighlight %} </div> <div data-lang="scala" markdown="1"> {% highlight scala %} import java.nio.charset.StandardCharsets import org.apache.hadoop.hive.ql.exec.vector.{BytesColumnVector, LongColumnVector} class PersonVectorizer(schema: String) extends Vectorizer[Person](schema) { override def vectorize(element: Person, batch: VectorizedRowBatch): Unit = { val nameColVector = batch.cols(0).asInstanceOf[BytesColumnVector] val ageColVector = batch.cols(1).asInstanceOf[LongColumnVector] nameColVector.setVal(batch.size + 1, element.getName.getBytes(StandardCharsets.UTF_8)) ageColVector.vector(batch.size + 1) = element.getAge } } {% endhighlight %} </div> </div> To use the ORC bulk encoder in an application, users need to add the following dependency: {% highlight xml %} <dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-orc{{ site.scala_version_suffix }}</artifactId> <version>{{ site.version }}</version> </dependency> {% endhighlight %} And then a `StreamingFileSink` that writes data in ORC format can be created like this: <div class="codetabs" markdown="1"> <div data-lang="java" markdown="1"> {% highlight java %} import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink; import org.apache.flink.orc.writer.OrcBulkWriterFactory; String schema = "struct<_col0:string,_col1:int>"; DataStream<Person> stream = ...; final OrcBulkWriterFactory<Person> writerFactory = new OrcBulkWriterFactory<>(new PersonVectorizer(schema)); final StreamingFileSink<Person> sink = StreamingFileSink .forBulkFormat(outputBasePath, writerFactory) .build(); input.addSink(sink); {% endhighlight %} </div> <div data-lang="scala" markdown="1"> {% highlight scala %} import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink import org.apache.flink.orc.writer.OrcBulkWriterFactory val schema: String = "struct<_col0:string,_col1:int>" val input: DataStream[Person] = ... val writerFactory = new OrcBulkWriterFactory(new PersonVectorizer(schema)); val sink: StreamingFileSink[Person] = StreamingFileSink .forBulkFormat(outputBasePath, writerFactory) .build() input.addSink(sink) {% endhighlight %} </div> </div> OrcBulkWriterFactory can also take Hadoop `Configuration` and `Properties` so that a custom Hadoop configuration and ORC writer properties can be provided. <div class="codetabs" markdown="1"> <div data-lang="java" markdown="1"> {% highlight java %} String schema = ...; Configuration conf = ...; Properties writerProperties = new Properties(); writerProps.setProperty("orc.compress", "LZ4"); // Other ORC supported properties can also be set similarly. final OrcBulkWriterFactory<Person> writerFactory = new OrcBulkWriterFactory<>( new PersonVectorizer(schema), writerProperties, conf); {% endhighlight %} </div> <div data-lang="scala" markdown="1"> {% highlight scala %} val schema: String = ... val conf: Configuration = ... val writerProperties: Properties = new Properties() writerProps.setProperty("orc.compress", "LZ4") // Other ORC supported properties can also be set similarly. val writerFactory = new OrcBulkWriterFactory( new PersonVectorizer(schema), writerProperties, conf) {% endhighlight %} </div> </div> The complete list of ORC writer properties can be found [here](https://orc.apache.org/docs/hive-config.html). Users who want to add user metadata to the ORC files can do so by calling `addUserMetadata(...)` inside the overriding `vectorize(...)` method. <div class="codetabs" markdown="1"> <div data-lang="java" markdown="1"> {% highlight java %} public class PersonVectorizer extends Vectorizer<Person> implements Serializable { @Override public void vectorize(Person element, VectorizedRowBatch batch) throws IOException { ... String metadataKey = ...; ByteBuffer metadataValue = ...; this.addUserMetadata(metadataKey, metadataValue); } } {% endhighlight %} </div> <div data-lang="scala" markdown="1"> {% highlight scala %} class PersonVectorizer(schema: String) extends Vectorizer[Person](schema) { override def vectorize(element: Person, batch: VectorizedRowBatch): Unit = { ... val metadataKey: String = ... val metadataValue: ByteBuffer = ... addUserMetadata(metadataKey, metadataValue) } } {% endhighlight %} </div> </div> #### Hadoop SequenceFile format To use the SequenceFile bulk encoder in your application you need to add the following dependency: {% highlight xml %} <dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-sequence-file</artifactId> <version>{{ site.version }}</version> </dependency> {% endhighlight %} A simple SequenceFile writer can be created like this: <div class="codetabs" markdown="1"> <div data-lang="java" markdown="1"> {% highlight java %} import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink; import org.apache.flink.configuration.GlobalConfiguration; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.Text; DataStream<Tuple2<LongWritable, Text>> input = ...; Configuration hadoopConf = HadoopUtils.getHadoopConfiguration(GlobalConfiguration.loadConfiguration()); final StreamingFileSink<Tuple2<LongWritable, Text>> sink = StreamingFileSink .forBulkFormat( outputBasePath, new SequenceFileWriterFactory<>(hadoopConf, LongWritable.class, Text.class)) .build(); input.addSink(sink); {% endhighlight %} </div> <div data-lang="scala" markdown="1"> {% highlight scala %} import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink import org.apache.flink.configuration.GlobalConfiguration import org.apache.hadoop.conf.Configuration import org.apache.hadoop.io.LongWritable import org.apache.hadoop.io.SequenceFile import org.apache.hadoop.io.Text; val input: DataStream[(LongWritable, Text)] = ... val hadoopConf: Configuration = HadoopUtils.getHadoopConfiguration(GlobalConfiguration.loadConfiguration()) val sink: StreamingFileSink[(LongWritable, Text)] = StreamingFileSink .forBulkFormat( outputBasePath, new SequenceFileWriterFactory(hadoopConf, LongWritable.class, Text.class)) .build() input.addSink(sink) {% endhighlight %} </div> </div> The SequenceFileWriterFactory supports additional constructor parameters to specify compression settings. ## Bucket Assignment The bucketing logic defines how the data will be structured into subdirectories inside the base output directory. Both row and bulk formats (see [File Formats](#file-formats)) use the [DateTimeBucketAssigner]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/streaming/api/functions/sink/filesystem/bucketassigners/DateTimeBucketAssigner.html) as the default assigner. By default the `DateTimeBucketAssigner` creates hourly buckets based on the system default timezone with the following format: `yyyy-MM-dd--HH`. Both the date format (*i.e.* bucket size) and timezone can be configured manually. We can specify a custom [BucketAssigner]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/streaming/api/functions/sink/filesystem/BucketAssigner.html) by calling `.withBucketAssigner(assigner)` on the format builders. Flink comes with two built in BucketAssigners: - [DateTimeBucketAssigner]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/streaming/api/functions/sink/filesystem/bucketassigners/DateTimeBucketAssigner.html) : Default time based assigner - [BasePathBucketAssigner]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/streaming/api/functions/sink/filesystem/bucketassigners/BasePathBucketAssigner.html) : Assigner that stores all part files in the base path (single global bucket) ## Rolling Policy The [RollingPolicy]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/streaming/api/functions/sink/filesystem/RollingPolicy.html) defines when a given in-progress part file will be closed and moved to the pending and later to finished state. Part files in the "finished" state are the ones that are ready for viewing and are guaranteed to contain valid data that will not be reverted in case of failure. The Rolling Policy in combination with the checkpointing interval (pending files become finished on the next checkpoint) control how quickly part files become available for downstream readers and also the size and number of these parts. Flink comes with two built-in RollingPolicies: - [DefaultRollingPolicy]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/streaming/api/functions/sink/filesystem/rollingpolicies/DefaultRollingPolicy.html) - [OnCheckpointRollingPolicy]({{ site.javadocs_baseurl }}/api/java/org/apache/flink/streaming/api/functions/sink/filesystem/rollingpolicies/OnCheckpointRollingPolicy.html) ## Part file lifecycle In order to use the output of the `StreamingFileSink` in downstream systems, we need to understand the naming and lifecycle of the output files produced. Part files can be in one of three states: 1. **In-progress** : The part file that is currently being written to is in-progress 2. **Pending** : Closed (due to the specified rolling policy) in-progress files that are waiting to be committed 3. **Finished** : On successful checkpoints pending files transition to "Finished" Only finished files are safe to read by downstream systems as those are guaranteed to not be modified later. <div class="alert alert-info"> <b>IMPORTANT:</b> Part file indexes are strictly increasing for any given subtask (in the order they were created). However these indexes are not always sequential. When the job restarts, the next part index for all subtask will be the `max part index + 1` where `max` is computed across all subtasks. </div> Each writer subtask will have a single in-progress part file at any given time for every active bucket, but there can be several pending and finished files. **Part file example** To better understand the lifecycle of these files let's look at a simple example with 2 sink subtasks: ``` └── 2019-08-25--12 ├── part-0-0.inprogress.bd053eb0-5ecf-4c85-8433-9eff486ac334 └── part-1-0.inprogress.ea65a428-a1d0-4a0b-bbc5-7a436a75e575 ``` When the part file `part-1-0` is rolled (let's say it becomes too large), it becomes pending but it is not renamed. The sink then opens a new part file: `part-1-1`: ``` └── 2019-08-25--12 ├── part-0-0.inprogress.bd053eb0-5ecf-4c85-8433-9eff486ac334 ├── part-1-0.inprogress.ea65a428-a1d0-4a0b-bbc5-7a436a75e575 └── part-1-1.inprogress.bc279efe-b16f-47d8-b828-00ef6e2fbd11 ``` As `part-1-0` is now pending completion, after the next successful checkpoint, it is finalized: ``` └── 2019-08-25--12 ├── part-0-0.inprogress.bd053eb0-5ecf-4c85-8433-9eff486ac334 ├── part-1-0 └── part-1-1.inprogress.bc279efe-b16f-47d8-b828-00ef6e2fbd11 ``` New buckets are created as dictated by the bucketing policy, and this doesn't affect currently in-progress files: ``` └── 2019-08-25--12 ├── part-0-0.inprogress.bd053eb0-5ecf-4c85-8433-9eff486ac334 ├── part-1-0 └── part-1-1.inprogress.bc279efe-b16f-47d8-b828-00ef6e2fbd11 └── 2019-08-25--13 └── part-0-2.inprogress.2b475fec-1482-4dea-9946-eb4353b475f1 ``` Old buckets can still receive new records as the bucketing policy is evaluated on a per-record basis. ### Part file configuration Finished files can be distinguished from the in-progress ones by their naming scheme only. By default, the file naming strategy is as follows: - **In-progress / Pending**: `part-<subtaskIndex>-<partFileIndex>.inprogress.uid` - **Finished:** `part-<subtaskIndex>-<partFileIndex>` Flink allows the user to specify a prefix and/or a suffix for his/her part files. This can be done using an `OutputFileConfig`. For example for a prefix "prefix" and a suffix ".ext" the sink will create the following files: ``` └── 2019-08-25--12 ├── prefix-0-0.ext ├── prefix-0-1.ext.inprogress.bd053eb0-5ecf-4c85-8433-9eff486ac334 ├── prefix-1-0.ext └── prefix-1-1.ext.inprogress.bc279efe-b16f-47d8-b828-00ef6e2fbd11 ``` The user can specify an `OutputFileConfig` in the following way: <div class="codetabs" markdown="1"> <div data-lang="java" markdown="1"> {% highlight java %} OutputFileConfig config = OutputFileConfig .builder() .withPartPrefix("prefix") .withPartSuffix(".ext") .build(); StreamingFileSink<Tuple2<Integer, Integer>> sink = StreamingFileSink .forRowFormat((new Path(outputPath), new SimpleStringEncoder<>("UTF-8")) .withBucketAssigner(new KeyBucketAssigner()) .withRollingPolicy(OnCheckpointRollingPolicy.build()) .withOutputFileConfig(config) .build(); {% endhighlight %} </div> <div data-lang="scala" markdown="1"> {% highlight scala %} val config = OutputFileConfig .builder() .withPartPrefix("prefix") .withPartSuffix(".ext") .build() val sink = StreamingFileSink .forRowFormat(new Path(outputPath), new SimpleStringEncoder[String]("UTF-8")) .withBucketAssigner(new KeyBucketAssigner()) .withRollingPolicy(OnCheckpointRollingPolicy.build()) .withOutputFileConfig(config) .build() {% endhighlight %} </div> </div> ## Important Considerations ### General <span class="label label-danger">Important Note 1</span>: When using Hadoop < 2.7, please use the `OnCheckpointRollingPolicy` which rolls part files on every checkpoint. The reason is that if part files "traverse" the checkpoint interval, then, upon recovery from a failure the `StreamingFileSink` may use the `truncate()` method of the filesystem to discard uncommitted data from the in-progress file. This method is not supported by pre-2.7 Hadoop versions and Flink will throw an exception. <span class="label label-danger">Important Note 2</span>: Given that Flink sinks and UDFs in general do not differentiate between normal job termination (*e.g.* finite input stream) and termination due to failure, upon normal termination of a job, the last in-progress files will not be transitioned to the "finished" state. <span class="label label-danger">Important Note 3</span>: Flink and the `StreamingFileSink` never overwrites committed data. Given this, when trying to restore from an old checkpoint/savepoint which assumes an in-progress file which was committed by subsequent successful checkpoints, the `StreamingFileSink` will refuse to resume and it will throw an exception as it cannot locate the in-progress file. <span class="label label-danger">Important Note 4</span>: Currently, the `StreamingFileSink` only supports three filesystems: HDFS, S3, and Local. Flink will throw an exception when using an unsupported filesystem at runtime. ### S3-specific <span class="label label-danger">Important Note 1</span>: For S3, the `StreamingFileSink` supports only the [Hadoop-based](https://hadoop.apache.org/) FileSystem implementation, not the implementation based on [Presto](https://prestodb.io/). In case your job uses the `StreamingFileSink` to write to S3 but you want to use the Presto-based one for checkpointing, it is advised to use explicitly *"s3a://"* (for Hadoop) as the scheme for the target path of the sink and *"s3p://"* for checkpointing (for Presto). Using *"s3://"* for both the sink and checkpointing may lead to unpredictable behavior, as both implementations "listen" to that scheme. <span class="label label-danger">Important Note 2</span>: To guarantee exactly-once semantics while being efficient, the `StreamingFileSink` uses the [Multi-part Upload](https://docs.aws.amazon.com/AmazonS3/latest/dev/mpuoverview.html) feature of S3 (MPU from now on). This feature allows to upload files in independent chunks (thus the "multi-part") which can be combined into the original file when all the parts of the MPU are successfully uploaded. For inactive MPUs, S3 supports a bucket lifecycle rule that the user can use to abort multipart uploads that don't complete within a specified number of days after being initiated. This implies that if you set this rule aggressively and take a savepoint with some part-files being not fully uploaded, their associated MPUs may time-out before the job is restarted. This will result in your job not being able to restore from that savepoint as the pending part-files are no longer there and Flink will fail with an exception as it tries to fetch them and fails. {% top %}
greghogan/flink
docs/dev/connectors/streamfile_sink.md
Markdown
apache-2.0
32,733
{% extends 'herders/profile/data_logs/base.html' %} {% load static crispy_forms_tags %} {% block css %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.45/css/bootstrap-datetimepicker.min.css" /> {% endblock css %} {% block logs %} <div class="panel panel-default"> <div class="panel-heading"> {% include "./pagination.html" %} </div> {% if paginator.count == 0 %} <div class="panel-body"> <p>No logs found! Check the <a href="{% url 'herders:data_log_help' profile_name=profile_name %}">data log help section</a> to get started.</p> </div> {% else %} {% block log_table %}{% endblock log_table %} {% endif %} <div class="panel-footer">{% include "./pagination.html" %}</div> </div> {% endblock logs %}
PeteAndersen/swarfarm
herders/templates/herders/profile/data_logs/base_table.html
HTML
apache-2.0
877
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill; import static org.apache.drill.exec.expr.fn.impl.DateUtility.formatTimeStamp; import static org.hamcrest.CoreMatchers.containsString; import java.math.BigDecimal; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Arrays; import java.util.List; import org.apache.drill.categories.SqlFunctionTest; import org.apache.drill.common.exceptions.UserRemoteException; import org.apache.drill.common.types.TypeProtos; import org.apache.drill.exec.planner.physical.PlannerSettings; import org.apache.drill.exec.record.BatchSchema; import org.apache.drill.exec.record.BatchSchemaBuilder; import org.apache.drill.exec.record.metadata.SchemaBuilder; import org.apache.drill.test.BaseTestQuery; import org.hamcrest.CoreMatchers; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; @Category(SqlFunctionTest.class) public class TestFunctionsQuery extends BaseTestQuery { // enable decimal data type @BeforeClass public static void enableDecimalDataType() throws Exception { test(String.format("alter session set `%s` = true", PlannerSettings.ENABLE_DECIMAL_DATA_TYPE_KEY)); } @AfterClass public static void disableDecimalDataType() { resetSessionOption(PlannerSettings.ENABLE_DECIMAL_DATA_TYPE_KEY); } @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testAbsDecimalFunction() throws Exception{ String query = "SELECT " + "abs(cast('1234.4567' as decimal(9, 5))) as DEC9_ABS_1, " + "abs(cast('-1234.4567' as decimal(9, 5))) DEC9_ABS_2, " + "abs(cast('99999912399.4567' as decimal(18, 5))) DEC18_ABS_1, " + "abs(cast('-99999912399.4567' as decimal(18, 5))) DEC18_ABS_2, " + "abs(cast('12345678912345678912.4567' as decimal(28, 5))) DEC28_ABS_1, " + "abs(cast('-12345678912345678912.4567' as decimal(28, 5))) DEC28_ABS_2, " + "abs(cast('1234567891234567891234567891234567891.4' as decimal(38, 1))) DEC38_ABS_1, " + "abs(cast('-1234567891234567891234567891234567891.4' as decimal(38, 1))) DEC38_ABS_2"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC9_ABS_1", "DEC9_ABS_2", "DEC18_ABS_1", "DEC18_ABS_2", "DEC28_ABS_1", "DEC28_ABS_2", "DEC38_ABS_1", "DEC38_ABS_2") .baselineValues(new BigDecimal("1234.45670"), new BigDecimal("1234.45670"), new BigDecimal("99999912399.45670"), new BigDecimal("99999912399.45670"), new BigDecimal("12345678912345678912.45670"), new BigDecimal("12345678912345678912.45670"), new BigDecimal("1234567891234567891234567891234567891.4"), new BigDecimal("1234567891234567891234567891234567891.4")) .go(); } @Test public void testCeilDecimalFunction() throws Exception { String query = "SELECT " + "ceil(cast('1234.4567' as decimal(9, 5))) as DEC9_1, " + "ceil(cast('1234.0000' as decimal(9, 5))) as DEC9_2, " + "ceil(cast('-1234.4567' as decimal(9, 5))) as DEC9_3, " + "ceil(cast('-1234.000' as decimal(9, 5))) as DEC9_4, " + "ceil(cast('99999912399.4567' as decimal(18, 5))) DEC18_1, " + "ceil(cast('99999912399.0000' as decimal(18, 5))) DEC18_2, " + "ceil(cast('-99999912399.4567' as decimal(18, 5))) DEC18_3, " + "ceil(cast('-99999912399.0000' as decimal(18, 5))) DEC18_4, " + "ceil(cast('12345678912345678912.4567' as decimal(28, 5))) DEC28_1, " + "ceil(cast('999999999999999999.4567' as decimal(28, 5))) DEC28_2, " + "ceil(cast('12345678912345678912.0000' as decimal(28, 5))) DEC28_3, " + "ceil(cast('-12345678912345678912.4567' as decimal(28, 5))) DEC28_4, " + "ceil(cast('-12345678912345678912.0000' as decimal(28, 5))) DEC28_5, " + "ceil(cast('1234567891234567891234567891234567891.4' as decimal(38, 1))) DEC38_1, " + "ceil(cast('999999999999999999999999999999999999.4' as decimal(38, 1))) DEC38_2, " + "ceil(cast('1234567891234567891234567891234567891.0' as decimal(38, 1))) DEC38_3, " + "ceil(cast('-1234567891234567891234567891234567891.4' as decimal(38, 1))) DEC38_4, " + "ceil(cast('-1234567891234567891234567891234567891.0' as decimal(38, 1))) DEC38_5"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC9_1", "DEC9_2", "DEC9_3", "DEC9_4", "DEC18_1", "DEC18_2", "DEC18_3", "DEC18_4", "DEC28_1", "DEC28_2", "DEC28_3", "DEC28_4", "DEC28_5", "DEC38_1", "DEC38_2", "DEC38_3", "DEC38_4", "DEC38_5") .baselineValues(new BigDecimal("1235"), new BigDecimal("1234"), new BigDecimal("-1234"), new BigDecimal("-1234"), new BigDecimal("99999912400"), new BigDecimal("99999912399"), new BigDecimal("-99999912399"), new BigDecimal("-99999912399"), new BigDecimal("12345678912345678913"), new BigDecimal("1000000000000000000"), new BigDecimal("12345678912345678912"), new BigDecimal("-12345678912345678912"), new BigDecimal("-12345678912345678912"), new BigDecimal("1234567891234567891234567891234567892"), new BigDecimal("1000000000000000000000000000000000000"), new BigDecimal("1234567891234567891234567891234567891"), new BigDecimal("-1234567891234567891234567891234567891"), new BigDecimal("-1234567891234567891234567891234567891")) .go(); } @Test public void testFloorDecimalFunction() throws Exception { String query = "SELECT " + "floor(cast('1234.4567' as decimal(9, 5))) as DEC9_1, " + "floor(cast('1234.0000' as decimal(9, 5))) as DEC9_2, " + "floor(cast('-1234.4567' as decimal(9, 5))) as DEC9_3, " + "floor(cast('-1234.000' as decimal(9, 5))) as DEC9_4, " + "floor(cast('99999912399.4567' as decimal(18, 5))) DEC18_1, " + "floor(cast('99999912399.0000' as decimal(18, 5))) DEC18_2, " + "floor(cast('-99999912399.4567' as decimal(18, 5))) DEC18_3, " + "floor(cast('-99999912399.0000' as decimal(18, 5))) DEC18_4, " + "floor(cast('12345678912345678912.4567' as decimal(28, 5))) DEC28_1, " + "floor(cast('999999999999999999.4567' as decimal(28, 5))) DEC28_2, " + "floor(cast('12345678912345678912.0000' as decimal(28, 5))) DEC28_3, " + "floor(cast('-12345678912345678912.4567' as decimal(28, 5))) DEC28_4, " + "floor(cast('-12345678912345678912.0000' as decimal(28, 5))) DEC28_5, " + "floor(cast('1234567891234567891234567891234567891.4' as decimal(38, 1))) DEC38_1, " + "floor(cast('999999999999999999999999999999999999.4' as decimal(38, 1))) DEC38_2, " + "floor(cast('1234567891234567891234567891234567891.0' as decimal(38, 1))) DEC38_3, " + "floor(cast('-1234567891234567891234567891234567891.4' as decimal(38, 1))) DEC38_4, " + "floor(cast('-999999999999999999999999999999999999.4' as decimal(38, 1))) DEC38_5"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC9_1", "DEC9_2", "DEC9_3", "DEC9_4", "DEC18_1", "DEC18_2", "DEC18_3", "DEC18_4", "DEC28_1", "DEC28_2", "DEC28_3", "DEC28_4", "DEC28_5", "DEC38_1", "DEC38_2", "DEC38_3", "DEC38_4", "DEC38_5") .baselineValues(new BigDecimal("1234"), new BigDecimal("1234"), new BigDecimal("-1235"), new BigDecimal("-1234"), new BigDecimal("99999912399"), new BigDecimal("99999912399"), new BigDecimal("-99999912400"), new BigDecimal("-99999912399"), new BigDecimal("12345678912345678912"), new BigDecimal("999999999999999999"), new BigDecimal("12345678912345678912"), new BigDecimal("-12345678912345678913"), new BigDecimal("-12345678912345678912"), new BigDecimal("1234567891234567891234567891234567891"), new BigDecimal("999999999999999999999999999999999999"), new BigDecimal("1234567891234567891234567891234567891"), new BigDecimal("-1234567891234567891234567891234567892"), new BigDecimal("-1000000000000000000000000000000000000")) .go(); } @Test public void testTruncateDecimalFunction() throws Exception { String query = "SELECT " + "trunc(cast('1234.4567' as decimal(9, 5))) as DEC9_1, " + "trunc(cast('1234.0000' as decimal(9, 5))) as DEC9_2, " + "trunc(cast('-1234.4567' as decimal(9, 5))) as DEC9_3, " + "trunc(cast('0.111' as decimal(9, 5))) as DEC9_4, " + "trunc(cast('99999912399.4567' as decimal(18, 5))) DEC18_1, " + "trunc(cast('99999912399.0000' as decimal(18, 5))) DEC18_2, " + "trunc(cast('-99999912399.4567' as decimal(18, 5))) DEC18_3, " + "trunc(cast('-99999912399.0000' as decimal(18, 5))) DEC18_4, " + "trunc(cast('12345678912345678912.4567' as decimal(28, 5))) DEC28_1, " + "trunc(cast('999999999999999999.4567' as decimal(28, 5))) DEC28_2, " + "trunc(cast('12345678912345678912.0000' as decimal(28, 5))) DEC28_3, " + "trunc(cast('-12345678912345678912.4567' as decimal(28, 5))) DEC28_4, " + "trunc(cast('-12345678912345678912.0000' as decimal(28, 5))) DEC28_5, " + "trunc(cast('1234567891234567891234567891234567891.4' as decimal(38, 1))) DEC38_1, " + "trunc(cast('999999999999999999999999999999999999.4' as decimal(38, 1))) DEC38_2, " + "trunc(cast('1234567891234567891234567891234567891.0' as decimal(38, 1))) DEC38_3, " + "trunc(cast('-1234567891234567891234567891234567891.4' as decimal(38, 1))) DEC38_4, " + "trunc(cast('-999999999999999999999999999999999999.4' as decimal(38, 1))) DEC38_5"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC9_1", "DEC9_2", "DEC9_3", "DEC9_4", "DEC18_1", "DEC18_2", "DEC18_3", "DEC18_4", "DEC28_1", "DEC28_2", "DEC28_3", "DEC28_4", "DEC28_5", "DEC38_1", "DEC38_2", "DEC38_3", "DEC38_4", "DEC38_5") .baselineValues(new BigDecimal("1234"), new BigDecimal("1234"), new BigDecimal("-1234"), new BigDecimal("0"), new BigDecimal("99999912399"), new BigDecimal("99999912399"), new BigDecimal("-99999912399"), new BigDecimal("-99999912399"), new BigDecimal("12345678912345678912"), new BigDecimal("999999999999999999"), new BigDecimal("12345678912345678912"), new BigDecimal("-12345678912345678912"), new BigDecimal("-12345678912345678912"), new BigDecimal("1234567891234567891234567891234567891"), new BigDecimal("999999999999999999999999999999999999"), new BigDecimal("1234567891234567891234567891234567891"), new BigDecimal("-1234567891234567891234567891234567891"), new BigDecimal("-999999999999999999999999999999999999")) .go(); } @Test public void testTruncateWithParamDecimalFunction() throws Exception { String query = "SELECT " + "trunc(cast('1234.4567' as decimal(9, 5)), 2) as DEC9_1, " + "trunc(cast('1234.45' as decimal(9, 2)), 4) as DEC9_2, " + "trunc(cast('-1234.4567' as decimal(9, 5)), 0) as DEC9_3, " + "trunc(cast('0.111' as decimal(9, 5)), 2) as DEC9_4, " + "trunc(cast('99999912399.4567' as decimal(18, 5)), 2) DEC18_1, " + "trunc(cast('99999912399.0000' as decimal(18, 5)), 2) DEC18_2, " + "trunc(cast('-99999912399.45' as decimal(18, 2)), 6) DEC18_3, " + "trunc(cast('-99999912399.0000' as decimal(18, 5)), 4) DEC18_4, " + "trunc(cast('12345678912345678912.4567' as decimal(28, 5)), 1) DEC28_1, " + "trunc(cast('999999999999999999.456' as decimal(28, 3)), 6) DEC28_2, " + "trunc(cast('12345678912345678912.0000' as decimal(28, 5)), 2) DEC28_3, " + "trunc(cast('-12345678912345678912.45' as decimal(28, 2)), 0) DEC28_4, " + "trunc(cast('-12345678912345678912.0000' as decimal(28, 5)), 1) DEC28_5, " + "trunc(cast('999999999.123456789' as decimal(38, 9)), 7) DEC38_1, " + "trunc(cast('999999999.4' as decimal(38, 1)), 8) DEC38_2, " + "trunc(cast('999999999.1234' as decimal(38, 4)), 12) DEC38_3, " + "trunc(cast('-123456789123456789.4' as decimal(38, 1)), 10) DEC38_4, " + "trunc(cast('-999999999999999999999999999999999999.4' as decimal(38, 1)), 1) DEC38_5"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC9_1", "DEC9_2", "DEC9_3", "DEC9_4", "DEC18_1", "DEC18_2", "DEC18_3", "DEC18_4", "DEC28_1", "DEC28_2", "DEC28_3", "DEC28_4", "DEC28_5", "DEC38_1", "DEC38_2", "DEC38_3", "DEC38_4", "DEC38_5") .baselineValues(new BigDecimal("1234.45"), new BigDecimal("1234.4500"), new BigDecimal("-1234"), new BigDecimal("0.11"), new BigDecimal("99999912399.45"), new BigDecimal("99999912399.00"), new BigDecimal("-99999912399.450000"), new BigDecimal("-99999912399.0000"), new BigDecimal("12345678912345678912.4"), new BigDecimal("999999999999999999.456000"), new BigDecimal("12345678912345678912.00"), new BigDecimal("-12345678912345678912"), new BigDecimal("-12345678912345678912.0"), new BigDecimal("999999999.1234567"), new BigDecimal("999999999.40000000"), new BigDecimal("999999999.123400000000"), new BigDecimal("-123456789123456789.4000000000"), new BigDecimal("-999999999999999999999999999999999999.4")) .go(); } @Test public void testRoundDecimalFunction() throws Exception { String query = "SELECT " + "round(cast('1234.5567' as decimal(9, 5))) as DEC9_1, " + "round(cast('1234.1000' as decimal(9, 5))) as DEC9_2, " + "round(cast('-1234.5567' as decimal(9, 5))) as DEC9_3, " + "round(cast('-1234.1234' as decimal(9, 5))) as DEC9_4, " + "round(cast('99999912399.9567' as decimal(18, 5))) DEC18_1, " + "round(cast('99999912399.0000' as decimal(18, 5))) DEC18_2, " + "round(cast('-99999912399.5567' as decimal(18, 5))) DEC18_3, " + "round(cast('-99999912399.0000' as decimal(18, 5))) DEC18_4, " + "round(cast('12345678912345678912.5567' as decimal(28, 5))) DEC28_1, " + "round(cast('999999999999999999.5567' as decimal(28, 5))) DEC28_2, " + "round(cast('12345678912345678912.0000' as decimal(28, 5))) DEC28_3, " + "round(cast('-12345678912345678912.5567' as decimal(28, 5))) DEC28_4, " + "round(cast('-12345678912345678912.0000' as decimal(28, 5))) DEC28_5, " + "round(cast('999999999999999999999999999.5' as decimal(38, 1))) DEC38_1, " + "round(cast('99999999.512345678123456789' as decimal(38, 18))) DEC38_2, " + "round(cast('999999999999999999999999999999999999.5' as decimal(38, 1))) DEC38_3, " + "round(cast('1234567891234567891234567891234567891.2' as decimal(38, 1))) DEC38_4, " + "round(cast('-1234567891234567891234567891234567891.4' as decimal(38, 1))) DEC38_5, " + "round(cast('-999999999999999999999999999999999999.9' as decimal(38, 1))) DEC38_6"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC9_1", "DEC9_2", "DEC9_3", "DEC9_4", "DEC18_1", "DEC18_2", "DEC18_3", "DEC18_4", "DEC28_1", "DEC28_2", "DEC28_3", "DEC28_4", "DEC28_5", "DEC38_1", "DEC38_2", "DEC38_3", "DEC38_4", "DEC38_5", "DEC38_6") .baselineValues(new BigDecimal("1235"), new BigDecimal("1234"), new BigDecimal("-1235"), new BigDecimal("-1234"), new BigDecimal("99999912400"), new BigDecimal("99999912399"), new BigDecimal("-99999912400"), new BigDecimal("-99999912399"), new BigDecimal("12345678912345678913"), new BigDecimal("1000000000000000000"), new BigDecimal("12345678912345678912"), new BigDecimal("-12345678912345678913"), new BigDecimal("-12345678912345678912"), new BigDecimal("1000000000000000000000000000"), new BigDecimal("100000000"), new BigDecimal("1000000000000000000000000000000000000"), new BigDecimal("1234567891234567891234567891234567891"), new BigDecimal("-1234567891234567891234567891234567891"), new BigDecimal("-1000000000000000000000000000000000000")) .go(); } @Ignore("DRILL-3909") @Test public void testRoundWithScaleDecimalFunction() throws Exception { String query = "SELECT " + "round(cast('1234.5567' as decimal(9, 5)), 3) as DEC9_1, " + "round(cast('1234.1000' as decimal(9, 5)), 2) as DEC9_2, " + "round(cast('-1234.5567' as decimal(9, 5)), 4) as DEC9_3, " + "round(cast('-1234.1234' as decimal(9, 5)), 3) as DEC9_4, " + "round(cast('-1234.1234' as decimal(9, 2)), 4) as DEC9_5, " + "round(cast('99999912399.9567' as decimal(18, 5)), 3) DEC18_1, " + "round(cast('99999912399.0000' as decimal(18, 5)), 2) DEC18_2, " + "round(cast('-99999912399.5567' as decimal(18, 5)), 2) DEC18_3, " + "round(cast('-99999912399.0000' as decimal(18, 5)), 0) DEC18_4, " + "round(cast('12345678912345678912.5567' as decimal(28, 5)), 2) DEC28_1, " + "round(cast('999999999999999999.5567' as decimal(28, 5)), 1) DEC28_2, " + "round(cast('12345678912345678912.0000' as decimal(28, 5)), 8) DEC28_3, " + "round(cast('-12345678912345678912.5567' as decimal(28, 5)), 3) DEC28_4, " + "round(cast('-12345678912345678912.0000' as decimal(28, 5)), 0) DEC28_5, " + "round(cast('999999999999999999999999999.5' as decimal(38, 1)), 1) DEC38_1, " + "round(cast('99999999.512345678923456789' as decimal(38, 18)), 9) DEC38_2, " + "round(cast('999999999.9999999995678' as decimal(38, 18)), 9) DEC38_3, " + "round(cast('999999999.9999999995678' as decimal(38, 18)), 11) DEC38_4, " + "round(cast('999999999.9999999995678' as decimal(38, 18)), 21) DEC38_5, " + "round(cast('-1234567891234567891234567891234567891.4' as decimal(38, 1)), 1) DEC38_6, " + "round(cast('-999999999999999999999999999999999999.9' as decimal(38, 1)), 0) DEC38_7"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC9_1", "DEC9_2", "DEC9_3", "DEC9_4", "DEC9_5", "DEC18_1", "DEC18_2", "DEC18_3", "DEC18_4", "DEC28_1", "DEC28_2", "DEC28_3", "DEC28_4", "DEC28_5", "DEC38_1", "DEC38_2", "DEC38_3", "DEC38_4", "DEC38_5", "DEC38_6", "DEC38_7") .baselineValues(new BigDecimal("1234.557"), new BigDecimal("1234.10"), new BigDecimal("-1234.5567"), new BigDecimal("-1234.123"), new BigDecimal("-1234.1200"), new BigDecimal("99999912399.957"), new BigDecimal("99999912399.00"), new BigDecimal("-99999912399.56"), new BigDecimal("-99999912399"), new BigDecimal("12345678912345678912.56"), new BigDecimal("999999999999999999.6"), new BigDecimal("12345678912345678912.00000000"), new BigDecimal("-12345678912345678912.557"), new BigDecimal("-12345678912345678912"), new BigDecimal("999999999999999999999999999.5"), new BigDecimal("99999999.512345679"), new BigDecimal("1000000000.000000000"), new BigDecimal("999999999.99999999957"), new BigDecimal("999999999.999999999567800000000"), new BigDecimal("-1234567891234567891234567891234567891.4"), new BigDecimal("-1000000000000000000000000000000000000")) .go(); } @Ignore("we don't have decimal division") @Test public void testCastDecimalDivide() throws Exception { String query = "select (cast('9' as decimal(9, 1)) / cast('2' as decimal(4, 1))) as DEC9_DIV, " + "cast('999999999' as decimal(9,0)) / cast('0.000000000000000000000000001' as decimal(28,28)) as DEC38_DIV, " + "cast('123456789.123456789' as decimal(18, 9)) * cast('123456789.123456789' as decimal(18, 9)) as DEC18_MUL"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC9_DIV", "DEC38_DIV", "DEC18_MUL") .baselineValues(new BigDecimal("4.500000000"), new BigDecimal("999999999000000000000000000000000000.0"), new BigDecimal("15241578780673678.515622620750190521")) .go(); } // From DRILL-2668: "CAST ( 1.1 AS FLOAT )" yielded TYPE DOUBLE: /** * Test for DRILL-2668, that "CAST ( 1.5 AS FLOAT )" really yields type FLOAT * (rather than type DOUBLE). */ @Test public void testLiteralCastToFLOATYieldsFLOAT() throws Exception { testBuilder() .sqlQuery( "SELECT CAST( 1.5 AS FLOAT ) AS ShouldBeFLOAT") .unOrdered() .baselineColumns("ShouldBeFLOAT") .baselineValues(1.5f) .go(); } @Test public void testLiteralCastToDOUBLEYieldsDOUBLE() throws Exception { testBuilder() .sqlQuery( "SELECT CAST( 1.25 AS DOUBLE PRECISION ) AS ShouldBeDOUBLE") .unOrdered() .baselineColumns("ShouldBeDOUBLE") .baselineValues(1.25) .go(); } @Test public void testLiteralCastToBIGINTYieldsBIGINT() throws Exception { testBuilder() .sqlQuery( "SELECT CAST( 64 AS BIGINT ) AS ShouldBeBIGINT") .unOrdered() .baselineColumns("ShouldBeBIGINT") .baselineValues(64L) .go(); } @Test public void testLiteralCastToINTEGERYieldsINTEGER() throws Exception { testBuilder() .sqlQuery( "SELECT CAST( 32 AS INTEGER ) AS ShouldBeINTEGER") .unOrdered() .baselineColumns("ShouldBeINTEGER") .baselineValues(32) .go(); } @Ignore( "until SMALLINT is supported (DRILL-2470)" ) @Test public void testLiteralCastToSMALLINTYieldsSMALLINT() throws Exception { testBuilder() .sqlQuery( "SELECT CAST( 16 AS SMALLINT ) AS ShouldBeSMALLINT") .unOrdered() .baselineColumns("ShouldBeSMALLINT") .baselineValues((short) 16) .go(); } @Ignore( "until TINYINT is supported (~DRILL-2470)" ) @Test public void testLiteralCastToTINYINTYieldsTINYINT() throws Exception { testBuilder() .sqlQuery( "SELECT CAST( 8 AS TINYINT ) AS ShouldBeTINYINT") .unOrdered() .baselineColumns("ShouldBeTINYINT") .baselineValues((byte) 8) .go(); } @Test public void testDecimalMultiplicationOverflowNegativeScale() throws Exception { String query = "select cast('1000000000000000001.000000000000000000' as decimal(38, 18)) * " + "cast('99999999999999999999.999999999999999999' as decimal(38, 18)) as DEC38_1"; expectedException.expect(UserRemoteException.class); expectedException.expectMessage(CoreMatchers.containsString("VALIDATION ERROR: Value 100000000000000000100000000000000000000 overflows specified precision 38 with scale 0.")); test(query); } @Test public void testDecimalMultiplicationOverflowHandling() throws Exception { String query = "select cast('1' as decimal(9, 5)) * cast ('999999999999999999999999999.999999999' as decimal(38, 9)) as DEC38_1, " + "cast('1000000000000000001.000000000000000000' as decimal(38, 18)) * cast('0.999999999999999999' as decimal(38, 18)) as DEC38_2, " + "cast('3' as decimal(9, 8)) * cast ('333333333.3333333333333333333' as decimal(38, 19)) as DEC38_3 " + "from cp.`employee.json` where employee_id = 1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC38_1", "DEC38_2", "DEC38_3") .baselineValues(new BigDecimal("1000000000000000000000000000.00000"), new BigDecimal("1000000000000000000"), new BigDecimal("1000000000.000000000000000000")) .go(); } @Test public void testDecimalRoundUp() throws Exception { String query = "select cast('999999999999999999.9999999999999999995' as decimal(38, 18)) as DEC38_1, " + "cast('999999999999999999.9999999999999999994' as decimal(38, 18)) as DEC38_2, " + "cast('999999999999999999.1234567895' as decimal(38, 9)) as DEC38_3, " + "cast('99999.12345' as decimal(18, 4)) as DEC18_1, " + "cast('99999.99995' as decimal(18, 4)) as DEC18_2"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC38_1", "DEC38_2", "DEC38_3", "DEC18_1", "DEC18_2") .baselineValues(new BigDecimal("1000000000000000000.000000000000000000"), new BigDecimal("999999999999999999.999999999999999999"), new BigDecimal("999999999999999999.123456790"), new BigDecimal("99999.1235"), new BigDecimal("100000.0000")) .go(); } @Test public void testDecimalDownwardCast() throws Exception { String query = "select cast((cast('12345.6789' as decimal(18, 4))) as decimal(9, 4)) as DEC18_DEC9_1, " + "cast((cast('12345.6789' as decimal(18, 4))) as decimal(9, 2)) as DEC18_DEC9_2, " + "cast((cast('-12345.6789' as decimal(18, 4))) as decimal(9, 0)) as DEC18_DEC9_3, " + "cast((cast('99999999.6789' as decimal(38, 4))) as decimal(9, 0)) as DEC38_DEC19_1, " + "cast((cast('-999999999999999.6789' as decimal(38, 4))) as decimal(18, 2)) as DEC38_DEC18_1, " + "cast((cast('-999999999999999.6789' as decimal(38, 4))) as decimal(18, 0)) as DEC38_DEC18_2, " + "cast((cast('100000000999999999.6789' as decimal(38, 4))) as decimal(28, 0)) as DEC38_DEC28_1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC18_DEC9_1", "DEC18_DEC9_2", "DEC18_DEC9_3", "DEC38_DEC19_1", "DEC38_DEC18_1", "DEC38_DEC18_2", "DEC38_DEC28_1") .baselineValues(new BigDecimal("12345.6789"), new BigDecimal("12345.68"), new BigDecimal("-12346"), new BigDecimal("100000000"), new BigDecimal("-999999999999999.68"), new BigDecimal("-1000000000000000"), new BigDecimal("100000001000000000")) .go(); } @Test public void testTruncateWithParamFunction() throws Exception { String query = "SELECT\n" + "trunc(cast('1234.4567' as double), 2) as T_1,\n" + "trunc(cast('-1234.4567' as double), 2) as T_2,\n" + "trunc(cast('1234.4567' as double), -2) as T_3,\n" + "trunc(cast('-1234.4567' as double), -2) as T_4,\n" + "trunc(cast('1234' as double), 4) as T_5,\n" + "trunc(cast('-1234' as double), 4) as T_6,\n" + "trunc(cast('1234' as double), -4) as T_7,\n" + "trunc(cast('-1234' as double), -4) as T_8,\n" + "trunc(cast('8124674407369523212' as double), 0) as T_9,\n" + "trunc(cast('81246744073695.395' as double), 1) as T_10\n"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("T_1", "T_2", "T_3", "T_4", "T_5", "T_6", "T_7", "T_8", "T_9", "T_10") .baselineValues(Double.valueOf("1234.45"), Double.valueOf("-1234.45"), Double.valueOf("1200.0"), Double.valueOf("-1200.0"), Double.valueOf("1234.0"), Double.valueOf("-1234.0"), Double.valueOf("0.0"), Double.valueOf("0.0"), Double.valueOf("8.1246744073695232E18"), Double.valueOf("8.12467440736953E13")) .go(); } @Test public void testRoundWithParamFunction() throws Exception { String query = "SELECT\n" + "round(cast('1234.4567' as double), 2) as T_1,\n" + "round(cast('-1234.4567' as double), 2) as T_2,\n" + "round(cast('1234.4567' as double), -2) as T_3,\n" + "round(cast('-1234.4567' as double), -2) as T_4,\n" + "round(cast('1234' as double), 4) as T_5,\n" + "round(cast('-1234' as double), 4) as T_6,\n" + "round(cast('1234' as double), -4) as T_7,\n" + "round(cast('-1234' as double), -4) as T_8,\n" + "round(cast('8124674407369523212' as double), -4) as T_9,\n" + "round(cast('81246744073695.395' as double), 1) as T_10\n"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("T_1", "T_2", "T_3", "T_4", "T_5", "T_6", "T_7", "T_8", "T_9", "T_10") .baselineValues(Double.valueOf("1234.46"), Double.valueOf("-1234.46"), Double.valueOf("1200.0"), Double.valueOf("-1200.0"), Double.valueOf("1234.0"), Double.valueOf("-1234.0"), Double.valueOf("0.0"), Double.valueOf("0.0"), Double.valueOf("8.1246744073695201E18"), Double.valueOf("8.12467440736954E13")) .go(); } @Test public void testRoundWithOneParam() throws Exception { String query = "select\n" + "round(8124674407369523212) round_bigint,\n" + "round(9999999) round_int,\n" + "round(cast('23.45' as float)) round_float_1,\n" + "round(cast('23.55' as float)) round_float_2,\n" + "round(cast('8124674407369.2345' as double)) round_double_1,\n" + "round(cast('8124674407369.589' as double)) round_double_2\n"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("round_bigint", "round_int", "round_float_1", "round_float_2", "round_double_1", "round_double_2") .baselineValues(8124674407369523212L, 9999999, 23.0f, 24.0f, 8124674407369.0d, 8124674407370.0d) .go(); } @Test public void testToCharFunction() throws Exception { String query = "SELECT " + "to_char(1234.5567, '#,###.##') as FLOAT8_1, " + "to_char(1234.5, '$#,###.00') as FLOAT8_2, " + "to_char(cast('1234.5567' as decimal(9, 5)), '#,###.##') as DEC9_1, " + "to_char(cast('99999912399.9567' as decimal(18, 5)), '#.#####') DEC18_1, " + "to_char(cast('12345678912345678912.5567' as decimal(28, 5)), '#,###.#####') DEC28_1, " + "to_char(cast('999999999999999999999999999.5' as decimal(38, 1)), '#.#') DEC38_1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("FLOAT8_1", "FLOAT8_2", "DEC9_1", "DEC18_1", "DEC28_1", "DEC38_1") .baselineValues("1,234.56", "$1,234.50", "1,234.56", "99999912399.9567", "12,345,678,912,345,678,912.5567", "999999999999999999999999999.5") .go(); } @Test public void testConcatFunction() throws Exception { String query = "SELECT " + "concat('1234', ' COL_VALUE ', R_REGIONKEY, ' - STRING') as STR_1 " + "FROM cp.`tpch/region.parquet` limit 1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("STR_1") .baselineValues("1234 COL_VALUE 0 - STRING") .go(); } @Test public void testTimeStampConstant() throws Exception { String query = "SELECT " + "timestamp '2008-2-23 12:23:23' as TS"; LocalDateTime date = LocalDateTime.parse("2008-02-23 12:23:23.0", formatTimeStamp); testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("TS") .baselineValues(date) .go(); } @Test public void testNullConstantsTimeTimeStampAndDate() throws Exception { String query = "SELECT " + "CAST(NULL AS TIME) AS t, " + "CAST(NULL AS TIMESTAMP) AS ts, " + "CAST(NULL AS DATE) AS d"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("t", "ts", "d") .baselineValues(null, null, null) .go(); } @Test public void testIntMinToDecimal() throws Exception { String query = "select cast((employee_id - employee_id + -2147483648) as decimal(28, 2)) as DEC_28," + "cast((employee_id - employee_id + -2147483648) as decimal(18, 2)) as DEC_18 from " + "cp.`employee.json` limit 1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC_28", "DEC_18") .baselineValues(new BigDecimal("-2147483648.00"), new BigDecimal("-2147483648.00")) .go(); } @Test public void testDecimalAddConstant() throws Exception { String query = "select (cast('-1' as decimal(37, 3)) + cast (employee_id as decimal(37, 3))) as CNT " + "from cp.`employee.json` where employee_id <= 4"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("CNT") .baselineValues(new BigDecimal("0.000")) .baselineValues(new BigDecimal("1.000")) .baselineValues(new BigDecimal("3.000")) .go(); } @Test public void testDecimalAddIntConstant() throws Exception { String query = "select 1 + cast(employee_id as decimal(9, 3)) as DEC_9 , 1 + cast(employee_id as decimal(37, 5)) as DEC_38 " + "from cp.`employee.json` where employee_id <= 2"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC_9", "DEC_38") .baselineValues(new BigDecimal("2.000"), new BigDecimal("2.00000")) .baselineValues(new BigDecimal("3.000"), new BigDecimal("3.00000")) .go(); } @Test public void testSignFunction() throws Exception { String query = "select sign(cast('1.23' as float)) as SIGN_FLOAT, sign(-1234.4567) as SIGN_DOUBLE, " + "sign(23) as SIGN_INT"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("SIGN_FLOAT", "SIGN_DOUBLE", "SIGN_INT") .baselineValues(1, -1, 1) .go(); } @Test public void testPadFunctions() throws Exception { String query = "select rpad(first_name, 10) as RPAD_DEF, rpad(first_name, 10, '*') as RPAD_STAR, " + "lpad(first_name, 10) as LPAD_DEF, lpad(first_name, 10, '*') as LPAD_STAR, lpad(first_name, 2) as LPAD_TRUNC, " + "rpad(first_name, 2) as RPAD_TRUNC from cp.`employee.json` where employee_id = 1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("RPAD_DEF", "RPAD_STAR", "LPAD_DEF", "LPAD_STAR", "LPAD_TRUNC", "RPAD_TRUNC") .baselineValues("Sheri ", "Sheri*****", " Sheri", "*****Sheri", "Sh", "Sh") .go(); } @Test public void testExtractSecond() throws Exception { String query = "select extract(second from date '2008-2-23') as DATE_EXT, " + "extract(second from timestamp '2008-2-23 10:00:20.123') as TS_EXT, " + "extract(second from time '10:20:30.303') as TM_EXT"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DATE_EXT", "TS_EXT", "TM_EXT") .baselineValues(0.0d, 20.123d, 30.303d) .go(); } @Test public void testCastDecimalDouble() throws Exception { String query = "select cast((cast('1.0001' as decimal(18, 9))) as double) DECIMAL_DOUBLE_CAST"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DECIMAL_DOUBLE_CAST") .baselineValues(1.0001d) .go(); } @Test public void testExtractSecondFromInterval() throws Exception { String query = "select extract (second from interval '1 2:30:45.100' day to second) as EXT_INTDAY"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("EXT_INTDAY") .baselineValues(45.1d) .go(); } @Test public void testFunctionCaseInsensitiveNames() throws Exception { String query = "SELECT to_date('2003/07/09', 'yyyy/MM/dd') as col1, " + "TO_DATE('2003/07/09', 'yyyy/MM/dd') as col2, " + "To_DaTe('2003/07/09', 'yyyy/MM/dd') as col3"; LocalDate date = LocalDate.parse("2003-07-09"); testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("col1", "col2", "col3") .baselineValues(date, date, date) .go(); } @Test public void testDecimal18Decimal38Comparison() throws Exception { String query = "select cast('-999999999.999999999' as decimal(18, 9)) = cast('-999999999.999999999' as " + "decimal(38, 18)) as CMP"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("CMP") .baselineValues(true) .go(); } @Test public void testOptiqDecimalCapping() throws Exception { String query = "select cast('12345.678900000' as decimal(18, 9))=cast('12345.678900000' as decimal(38, 9)) as CMP"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("CMP") .baselineValues(true) .go(); } @Test public void testNegative() throws Exception { String query = "select negative(cast(2 as bigint)) as NEG\n"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("NEG") .baselineValues(-2L) .go(); } @Test public void testOptiqValidationFunctions() throws Exception { String query = "select trim(first_name) as TRIM_STR, substring(first_name, 2) as SUB_STR " + "from cp.`employee.json` where employee_id = 1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("TRIM_STR", "SUB_STR") .baselineValues("Sheri", "heri") .go(); } @Test public void testToTimeStamp() throws Exception { String query = "select to_timestamp(cast('800120400.12312' as decimal(38, 5))) as DEC38_TS, " + "to_timestamp(200120400) as INT_TS\n"; LocalDateTime result1 = Instant.ofEpochMilli(800120400123L).atZone(ZoneOffset.systemDefault()).toLocalDateTime(); LocalDateTime result2 = Instant.ofEpochMilli(200120400000L).atZone(ZoneOffset.systemDefault()).toLocalDateTime(); testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("DEC38_TS", "INT_TS") .baselineValues(result1, result2) .go(); } @Test public void testCaseWithDecimalExpressions() throws Exception { String query = "select " + "case when true then cast(employee_id as decimal(15, 5)) else cast('0.0' as decimal(2, 1)) end as col1 " + "from cp.`employee.json` where employee_id = 1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("col1") .baselineValues(new BigDecimal("1.00000")) .go(); } /* * We may apply implicit casts in Hash Join while dealing with different numeric data types * For this to work we need to distribute the data based on a common key, below method * makes sure the hash value for different numeric types is the same for the same key */ @Test public void testHash64() throws Exception { String query = "select " + "hash64AsDouble(cast(employee_id as int)) = hash64AsDouble(cast(employee_id as bigint)) col1, " + "hash64AsDouble(cast(employee_id as bigint)) = hash64AsDouble(cast(employee_id as float)) col2, " + "hash64AsDouble(cast(employee_id as float)) = hash64AsDouble(cast(employee_id as double)) col3, " + "hash64AsDouble(cast(employee_id as double)) = hash64AsDouble(cast(employee_id as decimal(9, 0))) col4, " + "hash64AsDouble(cast(employee_id as decimal(9, 0))) = hash64AsDouble(cast(employee_id as decimal(18, 0))) col5, " + "hash64AsDouble(cast(employee_id as decimal(18, 0))) = hash64AsDouble(cast(employee_id as decimal(28, 0))) col6, " + "hash64AsDouble(cast(employee_id as decimal(28, 0))) = hash64AsDouble(cast(employee_id as decimal(38, 0))) col7 " + "from cp.`employee.json` where employee_id = 1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("col1", "col2", "col3", "col4", "col5", "col6", "col7") .baselineValues(true, true, true, true, true, true, true) .go(); java.util.Random seedGen = new java.util.Random(); seedGen.setSeed(System.currentTimeMillis()); int seed = seedGen.nextInt(); String querytemplate = "select " + "hash64AsDouble(cast(employee_id as int), #RAND_SEED#) = hash64AsDouble(cast(employee_id as bigint), #RAND_SEED#) col1, " + "hash64AsDouble(cast(employee_id as bigint), #RAND_SEED#) = hash64AsDouble(cast(employee_id as float), #RAND_SEED#) col2, " + "hash64AsDouble(cast(employee_id as float), #RAND_SEED#) = hash64AsDouble(cast(employee_id as double), #RAND_SEED#) col3, " + "hash64AsDouble(cast(employee_id as double), #RAND_SEED#) = hash64AsDouble(cast(employee_id as decimal(9, 0)), #RAND_SEED#) col4, " + "hash64AsDouble(cast(employee_id as decimal(9, 0)), #RAND_SEED#) = hash64AsDouble(cast(employee_id as decimal(18, 0)), #RAND_SEED#) col5, " + "hash64AsDouble(cast(employee_id as decimal(18, 0)), #RAND_SEED#) = hash64AsDouble(cast(employee_id as decimal(28, 0)), #RAND_SEED#) col6, " + "hash64AsDouble(cast(employee_id as decimal(28, 0)), #RAND_SEED#) = hash64AsDouble(cast(employee_id as decimal(38, 0)), #RAND_SEED#) col7 " + "from cp.`employee.json` where employee_id = 1"; String queryWithSeed = querytemplate.replaceAll("#RAND_SEED#", String.format("%d",seed)); testBuilder() .sqlQuery(queryWithSeed) .unOrdered() .baselineColumns("col1", "col2", "col3", "col4", "col5", "col6", "col7") .baselineValues(true, true, true, true, true, true, true) .go(); } @Test public void testHash32() throws Exception { String query = "select " + "hash32AsDouble(cast(employee_id as int)) = hash32AsDouble(cast(employee_id as bigint)) col1, " + "hash32AsDouble(cast(employee_id as bigint)) = hash32AsDouble(cast(employee_id as float)) col2, " + "hash32AsDouble(cast(employee_id as float)) = hash32AsDouble(cast(employee_id as double)) col3, " + "hash32AsDouble(cast(employee_id as double)) = hash32AsDouble(cast(employee_id as decimal(9, 0))) col4, " + "hash32AsDouble(cast(employee_id as decimal(9, 0))) = hash32AsDouble(cast(employee_id as decimal(18, 0))) col5, " + "hash32AsDouble(cast(employee_id as decimal(18, 0))) = hash32AsDouble(cast(employee_id as decimal(28, 0))) col6, " + "hash32AsDouble(cast(employee_id as decimal(28, 0))) = hash32AsDouble(cast(employee_id as decimal(38, 0))) col7 " + "from cp.`employee.json` where employee_id = 1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("col1", "col2", "col3", "col4", "col5", "col6", "col7") .baselineValues(true, true, true, true, true, true, true) .go(); java.util.Random seedGen = new java.util.Random(); seedGen.setSeed(System.currentTimeMillis()); int seed = seedGen.nextInt(); String querytemplate = "select " + "hash32AsDouble(cast(employee_id as int), #RAND_SEED#) = hash32AsDouble(cast(employee_id as bigint), #RAND_SEED#) col1, " + "hash32AsDouble(cast(employee_id as bigint), #RAND_SEED#) = hash32AsDouble(cast(employee_id as float), #RAND_SEED#) col2, " + "hash32AsDouble(cast(employee_id as float), #RAND_SEED#) = hash32AsDouble(cast(employee_id as double), #RAND_SEED#) col3, " + "hash32AsDouble(cast(employee_id as double), #RAND_SEED#) = hash32AsDouble(cast(employee_id as decimal(9, 0)), #RAND_SEED#) col4, " + "hash32AsDouble(cast(employee_id as decimal(9, 0)), #RAND_SEED#) = hash32AsDouble(cast(employee_id as decimal(18, 0)), #RAND_SEED#) col5, " + "hash32AsDouble(cast(employee_id as decimal(18, 0)), #RAND_SEED#) = hash32AsDouble(cast(employee_id as decimal(28, 0)), #RAND_SEED#) col6, " + "hash32AsDouble(cast(employee_id as decimal(28, 0)), #RAND_SEED#) = hash32AsDouble(cast(employee_id as decimal(38, 0)), #RAND_SEED#) col7 " + "from cp.`employee.json` where employee_id = 1"; String queryWithSeed = querytemplate.replaceAll("#RAND_SEED#", String.format("%d",seed)); testBuilder() .sqlQuery(queryWithSeed) .unOrdered() .baselineColumns("col1", "col2", "col3", "col4", "col5", "col6", "col7") .baselineValues(true, true, true, true, true, true, true) .go(); } @Test public void testImplicitCastVarcharToDouble() throws Exception { // tests implicit cast from varchar to double testBuilder() .sqlQuery("select `integer` i, `float` f from cp.`jsoninput/input1.json` where `float` = '1.2'") .unOrdered() .baselineColumns("i", "f") .baselineValues(2001L, 1.2d) .go(); } @Test public void testConcatSingleInput() throws Exception { String query = "select concat(employee_id) as col1 from cp.`employee.json` where employee_id = 1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("col1") .baselineValues("1") .go(); query = "select concat(null_column) as col1 from cp.`employee.json` where employee_id = 1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("col1") .baselineValues("") .go(); query = "select concat('foo') as col1 from cp.`employee.json` where employee_id = 1"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("col1") .baselineValues("foo") .go(); } @Test public void testRandom() throws Exception { String query = "select 2*random()=2*random() as col1 from (values (1))"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("col1") .baselineValues(false) .go(); } /** * Test for DRILL-5645, where negation of expressions that do not contain * a RelNode input results in a NullPointerException */ @Test public void testNegate() throws Exception { String query = "select -(2 * 2) as col1 from ( values ( 1 ) ) T ( C1 )"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("col1") .baselineValues(-4) .go(); // Test float query = "select -(1.1 * 1) as col1 from ( values ( 1 ) ) T ( C1 )"; testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("col1") .baselineValues(new BigDecimal("-1.1")) .go(); } @Test public void testBooleanConditionsMode() throws Exception { List<String> conditions = Arrays.asList( "employee_id IS NULL", "employee_id IS NOT NULL", "employee_id > 0 IS TRUE", "employee_id > 0 IS NOT TRUE", "employee_id > 0 IS FALSE", "employee_id > 0 IS NOT FALSE", "employee_id IS NULL OR position_id IS NULL", "employee_id IS NULL AND position_id IS NULL", "isdate(employee_id)", "NOT (employee_id IS NULL)"); SchemaBuilder schemaBuilder = new SchemaBuilder() .add("col1", TypeProtos.MinorType.BIT); BatchSchema expectedSchema = new BatchSchemaBuilder() .withSchemaBuilder(schemaBuilder) .build(); for (String condition : conditions) { testBuilder() .sqlQuery("SELECT %s AS col1 FROM cp.`employee.json` LIMIT 0", condition) .schemaBaseLine(expectedSchema) .go(); } } @Test // DRILL-7297 public void testErrorInUdf() throws Exception { expectedException.expect(UserRemoteException.class); expectedException.expectMessage(containsString("Error from UDF")); test("select error_function()"); } }
kkhatua/drill
exec/java-exec/src/test/java/org/apache/drill/TestFunctionsQuery.java
Java
apache-2.0
47,791
:host { --light-grey: hsl(0 0% 90%); --grey: hsl(0 0% 60%); --dark-grey: hsl(0 0% 40%); }
GoogleChromeLabs/ProjectVisBug
app/components/hotkey-map/base.element_light.css
CSS
apache-2.0
96
#pragma once class COrderItem { public: COrderItem(void); ~COrderItem(void); public: CString orderID; CString orderTel; CString orderStatus; CString orderType; float orderPayed; float orderDiscount; int orderBig; int orderSmall; CString orderName; int iIndex; };
DanielShangHai/ChangxipuOrderManager
ChangxipuAdmin/ChangxipuAdmin/OrderItem.h
C
apache-2.0
297
/** * Copyright Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. 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.codelab.smartlock; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SplashFragment extends Fragment { @Override public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) { return layoutInflater.inflate(R.layout.fragment_splash, container, false); } }
googlecodelabs/android-smart-lock
app/src/main/java/com/google/codelab/smartlock/SplashFragment.java
Java
apache-2.0
1,068
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); ?> <div class="large"> <div class="center"> <?php echo _('Search series'); ?>:<br/> <?php echo form_open("search/"); echo form_input(array('name' => 'search', 'placeholder' => _('To search series, type and hit enter'), 'id' => 'searchbox')); echo form_close(); ?> </div> </div>
FoolCode/FoOlSlide
content/themes/default/views/search_pre.php
PHP
apache-2.0
366
'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } /* * Complete the reverseString function * Use console.log() to print to stdout. */ function reverseString(s) { try { var splitString = s.split(""); var reverseArray = splitString.reverse(); var joinArray = reverseArray.join(""); console.log(joinArray); } catch (error) { console.log(error.message); console.log(s); } } function main() { const s = eval(readLine()); reverseString(s); }
MithileshCParab/HackerRank-10DaysOfStatistics
Tutorials/10 Days Of Javascript/Day 3/try_catch_finally.js
JavaScript
apache-2.0
907
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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. # # Generated code. DO NOT EDIT! # # Snippet for BatchRunPivotReports # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-analytics-data # [START analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_async] from google.analytics import data_v1beta async def sample_batch_run_pivot_reports(): # Create a client client = data_v1beta.BetaAnalyticsDataAsyncClient() # Initialize request argument(s) request = data_v1beta.BatchRunPivotReportsRequest( ) # Make the request response = await client.batch_run_pivot_reports(request=request) # Handle the response print(response) # [END analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_async]
googleapis/python-analytics-data
samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py
Python
apache-2.0
1,518
<?php # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads/v8/enums/campaign_status.proto namespace Google\Ads\GoogleAds\V8\Enums; use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** * Container for enum describing possible statuses of a campaign. * * Generated from protobuf message <code>google.ads.googleads.v8.enums.CampaignStatusEnum</code> */ class CampaignStatusEnum extends \Google\Protobuf\Internal\Message { /** * Constructor. * * @param array $data { * Optional. Data for populating the Message object. * * } */ public function __construct($data = NULL) { \GPBMetadata\Google\Ads\GoogleAds\V8\Enums\CampaignStatus::initOnce(); parent::__construct($data); } }
googleads/google-ads-php
src/Google/Ads/GoogleAds/V8/Enums/CampaignStatusEnum.php
PHP
apache-2.0
856
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.codeInsight.daemon.impl; import com.intellij.codeHighlighting.BackgroundEditorHighlighter; import com.intellij.codeHighlighting.HighlightingPass; import com.intellij.codeHighlighting.Pass; import com.intellij.codeHighlighting.TextEditorHighlightingPass; import com.intellij.codeInsight.AutoPopupController; import com.intellij.codeInsight.daemon.*; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.intention.impl.FileLevelIntentionComponent; import com.intellij.codeInsight.intention.impl.IntentionHintComponent; import com.intellij.diagnostic.ThreadDumper; import com.intellij.ide.PowerSaveMode; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.ex.RangeHighlighterEx; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.fileEditor.impl.text.AsyncEditorLoader; import com.intellij.openapi.fileEditor.impl.text.TextEditorImpl; import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.RefreshQueueImpl; import com.intellij.packageDependencies.DependencyValidationManager; import com.intellij.psi.*; import com.intellij.psi.impl.PsiDocumentManagerBase; import com.intellij.psi.search.scope.packageSet.NamedScopeManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.*; import com.intellij.util.concurrency.EdtExecutorService; import com.intellij.util.io.storage.HeavyProcessLatch; import com.intellij.util.ui.UIUtil; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.util.*; import java.util.concurrent.*; import java.util.stream.Collectors; /** * This class also controls the auto-reparse and auto-hints. */ @State( name = "DaemonCodeAnalyzer", storages = @Storage(StoragePathMacros.WORKSPACE_FILE) ) public class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzerEx implements PersistentStateComponent<Element>, Disposable { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl"); private static final Key<List<HighlightInfo>> FILE_LEVEL_HIGHLIGHTS = Key.create("FILE_LEVEL_HIGHLIGHTS"); private final Project myProject; private final DaemonCodeAnalyzerSettings mySettings; @NotNull private final EditorTracker myEditorTracker; @NotNull private final PsiDocumentManager myPsiDocumentManager; private DaemonProgressIndicator myUpdateProgress = new DaemonProgressIndicator(); //guarded by this private final UpdateRunnable myUpdateRunnable; // use scheduler instead of Alarm because the latter requires ModalityState.current() which is obtainable from EDT only which requires too many invokeLaters private final ScheduledExecutorService myAlarm = EdtExecutorService.getScheduledExecutorInstance(); @NotNull private volatile Future<?> myUpdateRunnableFuture = CompletableFuture.completedFuture(null); private boolean myUpdateByTimerEnabled = true; private final Collection<VirtualFile> myDisabledHintsFiles = new THashSet<>(); private final Collection<VirtualFile> myDisabledHighlightingFiles = new THashSet<>(); private final FileStatusMap myFileStatusMap; private DaemonCodeAnalyzerSettings myLastSettings; private volatile IntentionHintComponent myLastIntentionHint; private volatile boolean myDisposed; // the only possible transition: false -> true private volatile boolean myInitialized; // the only possible transition: false -> true @NonNls private static final String DISABLE_HINTS_TAG = "disable_hints"; @NonNls private static final String FILE_TAG = "file"; @NonNls private static final String URL_ATT = "url"; private final PassExecutorService myPassExecutorService; public DaemonCodeAnalyzerImpl(@NotNull Project project, @NotNull DaemonCodeAnalyzerSettings daemonCodeAnalyzerSettings, @NotNull EditorTracker editorTracker, @NotNull PsiDocumentManager psiDocumentManager, @SuppressWarnings("UnusedParameters") @NotNull final NamedScopeManager namedScopeManager, @SuppressWarnings("UnusedParameters") @NotNull final DependencyValidationManager dependencyValidationManager) { myProject = project; mySettings = daemonCodeAnalyzerSettings; myEditorTracker = editorTracker; myPsiDocumentManager = psiDocumentManager; myLastSettings = ((DaemonCodeAnalyzerSettingsImpl)daemonCodeAnalyzerSettings).clone(); myFileStatusMap = new FileStatusMap(project); myPassExecutorService = new PassExecutorService(project); Disposer.register(this, myPassExecutorService); Disposer.register(this, myFileStatusMap); DaemonProgressIndicator.setDebug(LOG.isDebugEnabled()); assert !myInitialized : "Double Initializing"; Disposer.register(this, new StatusBarUpdater(project)); myInitialized = true; myDisposed = false; myFileStatusMap.markAllFilesDirty("DCAI init"); myUpdateRunnable = new UpdateRunnable(myProject); Disposer.register(this, () -> { assert myInitialized : "Disposing not initialized component"; assert !myDisposed : "Double dispose"; myUpdateRunnable.clearFieldsOnDispose(); stopProcess(false, "Dispose"); myDisposed = true; myLastSettings = null; }); } @Override public synchronized void dispose() { myUpdateProgress = new DaemonProgressIndicator(); // leak of highlight session via user data myUpdateRunnableFuture.cancel(true); } @NotNull @TestOnly public static List<HighlightInfo> getHighlights(@NotNull Document document, HighlightSeverity minSeverity, @NotNull Project project) { List<HighlightInfo> infos = new ArrayList<>(); processHighlights(document, project, minSeverity, 0, document.getTextLength(), Processors.cancelableCollectProcessor(infos)); return infos; } @Override @NotNull @TestOnly public List<HighlightInfo> getFileLevelHighlights(@NotNull Project project, @NotNull PsiFile file) { VirtualFile vFile = file.getViewProvider().getVirtualFile(); final FileEditorManager manager = FileEditorManager.getInstance(project); return Arrays.stream(manager.getEditors(vFile)) .map(fileEditor -> fileEditor.getUserData(FILE_LEVEL_HIGHLIGHTS)) .filter(Objects::nonNull) .flatMap(Collection::stream) .collect(Collectors.toList()); } @Override public void cleanFileLevelHighlights(@NotNull Project project, final int group, PsiFile psiFile) { if (psiFile == null) return; FileViewProvider provider = psiFile.getViewProvider(); VirtualFile vFile = provider.getVirtualFile(); final FileEditorManager manager = FileEditorManager.getInstance(project); for (FileEditor fileEditor : manager.getEditors(vFile)) { final List<HighlightInfo> infos = fileEditor.getUserData(FILE_LEVEL_HIGHLIGHTS); if (infos == null) continue; List<HighlightInfo> infosToRemove = new ArrayList<>(); for (HighlightInfo info : infos) { if (info.getGroup() == group) { manager.removeTopComponent(fileEditor, info.fileLevelComponent); infosToRemove.add(info); } } infos.removeAll(infosToRemove); } } @Override public void addFileLevelHighlight(@NotNull final Project project, final int group, @NotNull final HighlightInfo info, @NotNull final PsiFile psiFile) { VirtualFile vFile = psiFile.getViewProvider().getVirtualFile(); final FileEditorManager manager = FileEditorManager.getInstance(project); for (FileEditor fileEditor : manager.getEditors(vFile)) { if (fileEditor instanceof TextEditor) { FileLevelIntentionComponent component = new FileLevelIntentionComponent(info.getDescription(), info.getSeverity(), info.getGutterIconRenderer(), info.quickFixActionRanges, project, psiFile, ((TextEditor)fileEditor).getEditor(), info.getToolTip()); manager.addTopComponent(fileEditor, component); List<HighlightInfo> fileLevelInfos = fileEditor.getUserData(FILE_LEVEL_HIGHLIGHTS); if (fileLevelInfos == null) { fileLevelInfos = new ArrayList<>(); fileEditor.putUserData(FILE_LEVEL_HIGHLIGHTS, fileLevelInfos); } info.fileLevelComponent = component; info.setGroup(group); fileLevelInfos.add(info); } } } @Override @NotNull public List<HighlightInfo> runMainPasses(@NotNull PsiFile psiFile, @NotNull Document document, @NotNull final ProgressIndicator progress) { if (ApplicationManager.getApplication().isDispatchThread()) { throw new IllegalStateException("Must not run highlighting from under EDT"); } if (!ApplicationManager.getApplication().isReadAccessAllowed()) { throw new IllegalStateException("Must run highlighting from under read action"); } ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); if (!(indicator instanceof DaemonProgressIndicator)) { throw new IllegalStateException("Must run highlighting under progress with DaemonProgressIndicator"); } // clear status maps to run passes from scratch so that refCountHolder won't conflict and try to restart itself on partially filled maps myFileStatusMap.markAllFilesDirty("prepare to run main passes"); stopProcess(false, "disable background daemon"); myPassExecutorService.cancelAll(true); final List<HighlightInfo> result; try { result = new ArrayList<>(); final VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile != null && !virtualFile.getFileType().isBinary()) { List<TextEditorHighlightingPass> passes = TextEditorHighlightingPassRegistrarEx.getInstanceEx(myProject).instantiateMainPasses(psiFile, document, HighlightInfoProcessor.getEmpty()); Collections.sort(passes, (o1, o2) -> { if (o1 instanceof GeneralHighlightingPass) return -1; if (o2 instanceof GeneralHighlightingPass) return 1; return 0; }); try { for (TextEditorHighlightingPass pass : passes) { pass.doCollectInformation(progress); result.addAll(pass.getInfos()); } } catch (ProcessCanceledException e) { LOG.debug("Canceled: " + progress); throw e; } } } finally { stopProcess(true, "re-enable background daemon after main passes run"); } return result; } @NotNull @TestOnly public List<HighlightInfo> runPasses(@NotNull PsiFile file, @NotNull Document document, @NotNull TextEditor textEditor, @NotNull int[] toIgnore, boolean canChangeDocument, @Nullable Runnable callbackWhileWaiting) throws ProcessCanceledException { return runPasses(file, document, Collections.singletonList(textEditor), toIgnore, canChangeDocument, callbackWhileWaiting); } private volatile boolean mustWaitForSmartMode = true; @TestOnly public void mustWaitForSmartMode(final boolean mustWait, @NotNull Disposable parent) { final boolean old = mustWaitForSmartMode; mustWaitForSmartMode = mustWait; Disposer.register(parent, () -> mustWaitForSmartMode = old); } @NotNull @TestOnly public List<HighlightInfo> runPasses(@NotNull PsiFile file, @NotNull Document document, @NotNull List<TextEditor> textEditors, @NotNull int[] toIgnore, boolean canChangeDocument, @Nullable final Runnable callbackWhileWaiting) throws ProcessCanceledException { assert myInitialized; assert !myDisposed; ApplicationEx application = ApplicationManagerEx.getApplicationEx(); application.assertIsDispatchThread(); if (application.isWriteAccessAllowed()) { throw new AssertionError("Must not start highlighting from within write action, or deadlock is imminent"); } DaemonProgressIndicator.setDebug(!ApplicationInfoImpl.isInStressTest()); ((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue(); // pump first so that queued event do not interfere UIUtil.dispatchAllInvocationEvents(); // refresh will fire write actions interfering with highlighting while (RefreshQueueImpl.isRefreshInProgress() || HeavyProcessLatch.INSTANCE.isRunning()) { UIUtil.dispatchAllInvocationEvents(); } long dstart = System.currentTimeMillis(); while (mustWaitForSmartMode && DumbService.getInstance(myProject).isDumb()) { if (System.currentTimeMillis() > dstart + 100000) { throw new IllegalStateException("Timeout waiting for smart mode. If you absolutely want to be dumb, please use DaemonCodeAnalyzerImpl.mustWaitForSmartMode(false)."); } UIUtil.dispatchAllInvocationEvents(); } UIUtil.dispatchAllInvocationEvents(); Project project = file.getProject(); FileStatusMap fileStatusMap = getFileStatusMap(); fileStatusMap.allowDirt(canChangeDocument); Map<FileEditor, HighlightingPass[]> map = new HashMap<>(); for (TextEditor textEditor : textEditors) { if (textEditor instanceof TextEditorImpl) { try { ((TextEditorImpl)textEditor).waitForLoaded(10, TimeUnit.SECONDS); } catch (TimeoutException e) { throw new RuntimeException(textEditor + " has not completed loading in 10 seconds"); } } TextEditorBackgroundHighlighter highlighter = (TextEditorBackgroundHighlighter)textEditor.getBackgroundHighlighter(); if (highlighter == null) { Editor editor = textEditor.getEditor(); throw new RuntimeException("Null highlighter from " + textEditor + "; loaded: " + AsyncEditorLoader.isEditorLoaded(editor)); } final List<TextEditorHighlightingPass> passes = highlighter.getPasses(toIgnore); HighlightingPass[] array = passes.toArray(new HighlightingPass[passes.size()]); assert array.length != 0 : "Highlighting is disabled for the file " + file; map.put(textEditor, array); } for (int ignoreId : toIgnore) { fileStatusMap.markFileUpToDate(document, ignoreId); } myUpdateRunnableFuture.cancel(false); final DaemonProgressIndicator progress = createUpdateProgress(); myPassExecutorService.submitPasses(map, progress); try { long start = System.currentTimeMillis(); while (progress.isRunning() && System.currentTimeMillis() < start + 5*60*1000) { wrap(() -> { progress.checkCanceled(); if (callbackWhileWaiting != null) { callbackWhileWaiting.run(); } waitInOtherThread(50, canChangeDocument); UIUtil.dispatchAllInvocationEvents(); Throwable savedException = PassExecutorService.getSavedException(progress); if (savedException != null) throw savedException; }); } if (progress.isRunning() && !progress.isCanceled()) { throw new RuntimeException("Highlighting still running after "+(System.currentTimeMillis()-start)/1000+" seconds.\n"+ ThreadDumper.dumpThreadsToString()); } final HighlightingSessionImpl session = (HighlightingSessionImpl)HighlightingSessionImpl.getOrCreateHighlightingSession(file, textEditors.get(0).getEditor(), progress, null); wrap(() -> { if (!waitInOtherThread(60000, canChangeDocument)) { throw new TimeoutException("Unable to complete in 60s"); } session.waitForHighlightInfosApplied(); }); UIUtil.dispatchAllInvocationEvents(); UIUtil.dispatchAllInvocationEvents(); assert progress.isCanceled() && progress.isDisposed(); return getHighlights(document, null, project); } finally { DaemonProgressIndicator.setDebug(false); fileStatusMap.allowDirt(true); waitForTermination(); } } @TestOnly private boolean waitInOtherThread(int millis, boolean canChangeDocument) throws Throwable { Disposable disposable = Disposer.newDisposable(); // last hope protection against PsiModificationTrackerImpl.incCounter() craziness (yes, Kotlin) myProject.getMessageBus().connect(disposable).subscribe(PsiModificationTracker.TOPIC, () -> { throw new IllegalStateException("You must not perform PSI modifications from inside highlighting"); }); if (!canChangeDocument) { myProject.getMessageBus().connect(disposable).subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, new DaemonListenerAdapter() { @Override public void daemonCancelEventOccurred(@NotNull String reason) { throw new IllegalStateException("You must not cancel daemon inside highlighting test: "+reason); } }); } try { Future<Boolean> future = ApplicationManager.getApplication().executeOnPooledThread(() -> { try { return myPassExecutorService.waitFor(millis); } catch (Throwable e) { throw new RuntimeException(e); } }); return future.get(); } finally { Disposer.dispose(disposable); } } @TestOnly public void prepareForTest() { setUpdateByTimerEnabled(false); waitForTermination(); } @TestOnly public void cleanupAfterTest() { if (myProject.isOpen()) { prepareForTest(); } } @TestOnly public void waitForTermination() { myPassExecutorService.cancelAll(true); } @Override public void settingsChanged() { DaemonCodeAnalyzerSettings settings = DaemonCodeAnalyzerSettings.getInstance(); if (settings.isCodeHighlightingChanged(myLastSettings)) { restart(); } myLastSettings = ((DaemonCodeAnalyzerSettingsImpl)settings).clone(); } @Override public void updateVisibleHighlighters(@NotNull Editor editor) { ApplicationManager.getApplication().assertIsDispatchThread(); // no need, will not work anyway } @Override public void setUpdateByTimerEnabled(boolean value) { myUpdateByTimerEnabled = value; stopProcess(value, "Update by timer change"); } private int myDisableCount; @Override public void disableUpdateByTimer(@NotNull Disposable parentDisposable) { setUpdateByTimerEnabled(false); myDisableCount++; ApplicationManager.getApplication().assertIsDispatchThread(); Disposer.register(parentDisposable, () -> { myDisableCount--; if (myDisableCount == 0) { setUpdateByTimerEnabled(true); } }); } boolean isUpdateByTimerEnabled() { return myUpdateByTimerEnabled; } @Override public void setImportHintsEnabled(@NotNull PsiFile file, boolean value) { VirtualFile vFile = file.getVirtualFile(); if (value) { myDisabledHintsFiles.remove(vFile); stopProcess(true, "Import hints change"); } else { myDisabledHintsFiles.add(vFile); HintManager.getInstance().hideAllHints(); } } @Override public void resetImportHintsEnabledForProject() { myDisabledHintsFiles.clear(); } @Override public void setHighlightingEnabled(@NotNull PsiFile file, boolean value) { VirtualFile virtualFile = PsiUtilCore.getVirtualFile(file); if (value) { myDisabledHighlightingFiles.remove(virtualFile); } else { myDisabledHighlightingFiles.add(virtualFile); } } @Override public boolean isHighlightingAvailable(@Nullable PsiFile file) { if (file == null || !file.isPhysical()) return false; if (myDisabledHighlightingFiles.contains(PsiUtilCore.getVirtualFile(file))) return false; if (file instanceof PsiCompiledElement) return false; final FileType fileType = file.getFileType(); // To enable T.O.D.O. highlighting return !fileType.isBinary(); } @Override public boolean isImportHintsEnabled(@NotNull PsiFile file) { return isAutohintsAvailable(file) && !myDisabledHintsFiles.contains(file.getVirtualFile()); } @Override public boolean isAutohintsAvailable(PsiFile file) { return isHighlightingAvailable(file) && !(file instanceof PsiCompiledElement); } @Override public void restart() { doRestart(); } // return true if the progress was really canceled boolean doRestart() { myFileStatusMap.markAllFilesDirty("Global restart"); return stopProcess(true, "Global restart"); } @Override public void restart(@NotNull PsiFile file) { Document document = myPsiDocumentManager.getCachedDocument(file); if (document == null) return; String reason = "Psi file restart: " + file.getName(); myFileStatusMap.markFileScopeDirty(document, new TextRange(0, document.getTextLength()), file.getTextLength(), reason); stopProcess(true, reason); } @NotNull public List<TextEditorHighlightingPass> getPassesToShowProgressFor(Document document) { List<TextEditorHighlightingPass> allPasses = myPassExecutorService.getAllSubmittedPasses(); List<TextEditorHighlightingPass> result = new ArrayList<>(allPasses.size()); for (TextEditorHighlightingPass pass : allPasses) { if (pass.getDocument() == document || pass.getDocument() == null) { result.add(pass); } } return result; } boolean isAllAnalysisFinished(@NotNull PsiFile file) { if (myDisposed) return false; Document document = myPsiDocumentManager.getCachedDocument(file); return document != null && document.getModificationStamp() == file.getViewProvider().getModificationStamp() && myFileStatusMap.allDirtyScopesAreNull(document); } @Override public boolean isErrorAnalyzingFinished(@NotNull PsiFile file) { if (myDisposed) return false; Document document = myPsiDocumentManager.getCachedDocument(file); return document != null && document.getModificationStamp() == file.getViewProvider().getModificationStamp() && myFileStatusMap.getFileDirtyScope(document, Pass.UPDATE_ALL) == null; } @Override @NotNull public FileStatusMap getFileStatusMap() { return myFileStatusMap; } public synchronized boolean isRunning() { return !myUpdateProgress.isCanceled(); } @TestOnly public boolean isRunningOrPending() { ApplicationManager.getApplication().assertIsDispatchThread(); return isRunning() || !myUpdateRunnableFuture.isDone(); } // return true if the progress really was canceled synchronized boolean stopProcess(boolean toRestartAlarm, @NotNull @NonNls String reason) { boolean canceled = cancelUpdateProgress(toRestartAlarm, reason); // optimisation: this check is to avoid too many re-schedules in case of thousands of events spikes boolean restart = toRestartAlarm && !myDisposed && myInitialized; if (restart && myUpdateRunnableFuture.isDone()) { myUpdateRunnableFuture.cancel(false); myUpdateRunnableFuture = myAlarm.schedule(myUpdateRunnable, mySettings.AUTOREPARSE_DELAY, TimeUnit.MILLISECONDS); } return canceled; } // return true if the progress really was canceled private synchronized boolean cancelUpdateProgress(boolean toRestartAlarm, @NonNls String reason) { DaemonProgressIndicator updateProgress = myUpdateProgress; if (myDisposed) return false; boolean wasCanceled = updateProgress.isCanceled(); myPassExecutorService.cancelAll(false); if (!wasCanceled) { PassExecutorService.log(updateProgress, null, "Cancel", reason, toRestartAlarm); updateProgress.cancel(); return true; } return false; } static boolean processHighlightsNearOffset(@NotNull Document document, @NotNull Project project, @NotNull final HighlightSeverity minSeverity, final int offset, final boolean includeFixRange, @NotNull final Processor<HighlightInfo> processor) { return processHighlights(document, project, null, 0, document.getTextLength(), info -> { if (!isOffsetInsideHighlightInfo(offset, info, includeFixRange)) return true; int compare = info.getSeverity().compareTo(minSeverity); return compare < 0 || processor.process(info); }); } @Nullable public HighlightInfo findHighlightByOffset(@NotNull Document document, final int offset, final boolean includeFixRange) { return findHighlightByOffset(document, offset, includeFixRange, HighlightSeverity.INFORMATION); } @Nullable HighlightInfo findHighlightByOffset(@NotNull Document document, final int offset, final boolean includeFixRange, @NotNull HighlightSeverity minSeverity) { final List<HighlightInfo> foundInfoList = new SmartList<>(); processHighlightsNearOffset(document, myProject, minSeverity, offset, includeFixRange, info -> { if (info.getSeverity() == HighlightInfoType.ELEMENT_UNDER_CARET_SEVERITY) { return true; } if (!foundInfoList.isEmpty()) { HighlightInfo foundInfo = foundInfoList.get(0); int compare = foundInfo.getSeverity().compareTo(info.getSeverity()); if (compare < 0) { foundInfoList.clear(); } else if (compare > 0) { return true; } } foundInfoList.add(info); return true; }); if (foundInfoList.isEmpty()) return null; if (foundInfoList.size() == 1) return foundInfoList.get(0); return new HighlightInfoComposite(foundInfoList); } private static boolean isOffsetInsideHighlightInfo(int offset, @NotNull HighlightInfo info, boolean includeFixRange) { RangeHighlighterEx highlighter = info.getHighlighter(); if (highlighter == null || !highlighter.isValid()) return false; int startOffset = highlighter.getStartOffset(); int endOffset = highlighter.getEndOffset(); if (startOffset <= offset && offset <= endOffset) { return true; } if (!includeFixRange) return false; RangeMarker fixMarker = info.fixMarker; if (fixMarker != null) { // null means its range is the same as highlighter if (!fixMarker.isValid()) return false; startOffset = fixMarker.getStartOffset(); endOffset = fixMarker.getEndOffset(); return startOffset <= offset && offset <= endOffset; } return false; } @NotNull public static List<LineMarkerInfo> getLineMarkers(@NotNull Document document, @NotNull Project project) { ApplicationManager.getApplication().assertIsDispatchThread(); List<LineMarkerInfo> result = new ArrayList<>(); LineMarkersUtil.processLineMarkers(project, document, new TextRange(0, document.getTextLength()), -1, new CommonProcessors.CollectProcessor<>(result)); return result; } void setLastIntentionHint(@NotNull Project project, @NotNull PsiFile file, @NotNull Editor editor, @NotNull ShowIntentionsPass.IntentionsInfo intentions, boolean hasToRecreate) { if (!editor.getSettings().isShowIntentionBulb()) { return; } ApplicationManager.getApplication().assertIsDispatchThread(); hideLastIntentionHint(); if (editor.getCaretModel().getCaretCount() > 1) return; IntentionHintComponent hintComponent = IntentionHintComponent.showIntentionHint(project, file, editor, intentions, false); if (hasToRecreate) { hintComponent.recreate(); } myLastIntentionHint = hintComponent; } void hideLastIntentionHint() { ApplicationManager.getApplication().assertIsDispatchThread(); IntentionHintComponent hint = myLastIntentionHint; if (hint != null && hint.isVisible()) { hint.hide(); myLastIntentionHint = null; } } @Nullable public IntentionHintComponent getLastIntentionHint() { return myLastIntentionHint; } @Nullable @Override public Element getState() { Element state = new Element("state"); if (myDisabledHintsFiles.isEmpty()) { return state; } List<String> array = new SmartList<>(); for (VirtualFile file : myDisabledHintsFiles) { if (file.isValid()) { array.add(file.getUrl()); } } if (!array.isEmpty()) { Collections.sort(array); Element disableHintsElement = new Element(DISABLE_HINTS_TAG); state.addContent(disableHintsElement); for (String url : array) { disableHintsElement.addContent(new Element(FILE_TAG).setAttribute(URL_ATT, url)); } } return state; } @Override public void loadState(Element state) { myDisabledHintsFiles.clear(); Element element = state.getChild(DISABLE_HINTS_TAG); if (element != null) { for (Element e : element.getChildren(FILE_TAG)) { String url = e.getAttributeValue(URL_ATT); if (url != null) { VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url); if (file != null) { myDisabledHintsFiles.add(file); } } } } } private final Runnable submitPassesRunnable = new Runnable() { @Override public void run() { PassExecutorService.log(getUpdateProgress(), null, "Update Runnable. myUpdateByTimerEnabled:", myUpdateByTimerEnabled, " something disposed:", PowerSaveMode.isEnabled() || myDisposed || !myProject.isInitialized(), " activeEditors:", myProject.isDisposed() ? null : getSelectedEditors()); if (!myUpdateByTimerEnabled) return; if (myDisposed) return; ApplicationManager.getApplication().assertIsDispatchThread(); final Collection<FileEditor> activeEditors = getSelectedEditors(); if (activeEditors.isEmpty()) return; if (ApplicationManager.getApplication().isWriteAccessAllowed()) { // makes no sense to start from within write action, will cancel anyway // we'll restart when the write action finish return; } final PsiDocumentManagerBase documentManager = (PsiDocumentManagerBase)myPsiDocumentManager; if (documentManager.hasUncommitedDocuments()) { documentManager.cancelAndRunWhenAllCommitted("restart daemon when all committed", this); return; } if (RefResolveService.ENABLED && !RefResolveService.getInstance(myProject).isUpToDate() && RefResolveService.getInstance(myProject).getQueueSize() == 1) { return; // if the user have just typed in something, wait until the file is re-resolved // (or else it will blink like crazy since unused symbols calculation depends on resolve service) } Map<FileEditor, HighlightingPass[]> passes = new THashMap<>(activeEditors.size()); for (FileEditor fileEditor : activeEditors) { BackgroundEditorHighlighter highlighter = fileEditor.getBackgroundHighlighter(); if (highlighter != null) { HighlightingPass[] highlightingPasses = highlighter.createPassesForEditor(); passes.put(fileEditor, highlightingPasses); } } // cancel all after calling createPasses() since there are perverts {@link com.intellij.util.xml.ui.DomUIFactoryImpl} who are changing PSI there cancelUpdateProgress(true, "Cancel by alarm"); myUpdateRunnableFuture.cancel(false); DaemonProgressIndicator progress = createUpdateProgress(); myPassExecutorService.submitPasses(passes, progress); } }; // made this class static and fields cleareable to avoid leaks when this object stuck in invokeLater queue private static class UpdateRunnable implements Runnable { private Project myProject; private UpdateRunnable(@NotNull Project project) { myProject = project; } @Override public void run() { ApplicationManager.getApplication().assertIsDispatchThread(); Project project = myProject; DaemonCodeAnalyzerImpl daemonCodeAnalyzer; if (project == null || !project.isInitialized() || project.isDisposed() || PowerSaveMode.isEnabled() || (daemonCodeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project)).myDisposed) { return; } // wait for heavy processing to stop, re-schedule daemon but not too soon if (HeavyProcessLatch.INSTANCE.isRunning()) { HeavyProcessLatch.INSTANCE.executeOutOfHeavyProcess(() -> daemonCodeAnalyzer.stopProcess(true, "re-scheduled to execute after heavy processing finished")); return; } Editor activeEditor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (activeEditor == null) { AutoPopupController.runTransactionWithEverythingCommitted(project, daemonCodeAnalyzer.submitPassesRunnable); } else { ((PsiDocumentManagerBase)PsiDocumentManager.getInstance(project)).cancelAndRunWhenAllCommitted("start daemon when all committed", daemonCodeAnalyzer.submitPassesRunnable); } } private void clearFieldsOnDispose() { myProject = null; } } @NotNull private synchronized DaemonProgressIndicator createUpdateProgress() { DaemonProgressIndicator old = myUpdateProgress; if (!old.isCanceled()) { old.cancel(); } DaemonProgressIndicator progress = new DaemonProgressIndicator() { @Override public void stopIfRunning() { super.stopIfRunning(); myProject.getMessageBus().syncPublisher(DAEMON_EVENT_TOPIC).daemonFinished(); } }; progress.setModalityProgress(null); progress.start(); myUpdateProgress = progress; return progress; } @Override public void autoImportReferenceAtCursor(@NotNull Editor editor, @NotNull PsiFile file) { for (ReferenceImporter importer : Extensions.getExtensions(ReferenceImporter.EP_NAME)) { if (importer.autoImportReferenceAtCursor(editor, file)) break; } } @TestOnly @NotNull public synchronized DaemonProgressIndicator getUpdateProgress() { return myUpdateProgress; } @NotNull private Collection<FileEditor> getSelectedEditors() { ApplicationManager.getApplication().assertIsDispatchThread(); // Editors in modal context List<Editor> editors = getActiveEditors(); Collection<FileEditor> activeTextEditors = new THashSet<>(editors.size()); for (Editor editor : editors) { if (editor.isDisposed()) continue; TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(editor); activeTextEditors.add(textEditor); } if (ApplicationManager.getApplication().getCurrentModalityState() != ModalityState.NON_MODAL) { return activeTextEditors; } // Editors in tabs. Collection<FileEditor> result = new THashSet<>(); Collection<VirtualFile> files = new THashSet<>(activeTextEditors.size()); final FileEditor[] tabEditors = FileEditorManager.getInstance(myProject).getSelectedEditors(); for (FileEditor tabEditor : tabEditors) { if (!tabEditor.isValid()) continue; VirtualFile file = ((FileEditorManagerEx)FileEditorManager.getInstance(myProject)).getFile(tabEditor); if (file != null) { files.add(file); } result.add(tabEditor); } // do not duplicate documents for (FileEditor fileEditor : activeTextEditors) { VirtualFile file = ((FileEditorManagerEx)FileEditorManager.getInstance(myProject)).getFile(fileEditor); if (file != null && files.contains(file)) continue; result.add(fileEditor); } return result; } @NotNull private List<Editor> getActiveEditors() { return myEditorTracker.getActiveEditors(); } @TestOnly private static void wrap(@NotNull ThrowableRunnable runnable) { try { runnable.run(); } catch (RuntimeException | Error e) { throw e; } catch (Throwable e) { throw new RuntimeException(e); } } }
semonte/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java
Java
apache-2.0
39,395
// // SheetWindowController.h // b-music // // Created by Sergey P on 02.10.13. // Copyright (c) 2013 Sergey P. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // 1. The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // 2. This Software cannot be used to archive or collect data such as (but not // limited to) that of events, news, experiences and activities, for the // purpose of any concept relating to diary/journal keeping. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #import <Cocoa/Cocoa.h> #import <WebKit/WebKit.h> @protocol SheetDelegate <NSObject> -(void) cancelSheet:(NSString*)token user_id:(NSInteger)user_id execute:(SEL)someFunc; @end @interface SheetWindowController : NSWindowController @property (weak) id <SheetDelegate> delegate; @property (weak) IBOutlet WebView *webview; -(IBAction)cancel:(id)sender; -(void)clearCookie; -(void) loadURL:(NSString *) URLsring execute:(SEL)someFunc; @end
Serjip/b-music
b-music/SheetWindowController.h
C
apache-2.0
1,903
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_25) on Fri Jun 05 10:51:23 EDT 2015 --> <title>Uses of Class org.apache.cassandra.hadoop.cql3.CqlBulkOutputFormat (apache-cassandra API)</title> <meta name="date" content="2015-06-05"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.cassandra.hadoop.cql3.CqlBulkOutputFormat (apache-cassandra API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/cassandra/hadoop/cql3/CqlBulkOutputFormat.html" title="class in org.apache.cassandra.hadoop.cql3">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/cassandra/hadoop/cql3/class-use/CqlBulkOutputFormat.html" target="_top">Frames</a></li> <li><a href="CqlBulkOutputFormat.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.cassandra.hadoop.cql3.CqlBulkOutputFormat" class="title">Uses of Class<br>org.apache.cassandra.hadoop.cql3.CqlBulkOutputFormat</h2> </div> <div class="classUseContainer">No usage of org.apache.cassandra.hadoop.cql3.CqlBulkOutputFormat</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/cassandra/hadoop/cql3/CqlBulkOutputFormat.html" title="class in org.apache.cassandra.hadoop.cql3">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/cassandra/hadoop/cql3/class-use/CqlBulkOutputFormat.html" target="_top">Frames</a></li> <li><a href="CqlBulkOutputFormat.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2015 The Apache Software Foundation</small></p> </body> </html>
Jcamilorada/Cassandra
Instalacion/javadoc/org/apache/cassandra/hadoop/cql3/class-use/CqlBulkOutputFormat.html
HTML
apache-2.0
4,751
package comm import ( "testing" "github.com/stretchr/testify/assert" ) func TestQueryType_String(t *testing.T) { assert.Equal(t, "REQUEST", Request.String()) assert.Equal(t, "RESPONSE", Response.String()) } func TestOutcome_String(t *testing.T) { assert.Equal(t, "SUCCESS", Success.String()) assert.Equal(t, "ERROR", Error.String()) } func TestMetrics_Record(t *testing.T) { m := newScalarMetrics() m.Record() assert.NotEmpty(t, m.Earliest) assert.Equal(t, m.Earliest, m.Latest) assert.Equal(t, uint64(1), m.Count) m.Record() assert.True(t, m.Earliest.Before(m.Latest)) assert.Equal(t, uint64(2), m.Count) }
drausin/libri
libri/librarian/server/comm/outcomes_test.go
GO
apache-2.0
629
package org.tendons.manager; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
wind-clothes/tendons
tendons-manager/src/test/java/org/tendons/manager/AppTest.java
Java
apache-2.0
685
package com.jpettersson.wearify; import android.content.Context; import android.net.Uri; import android.util.Log; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.data.FreezableUtils; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.DataMap; import com.google.android.gms.wearable.DataMapItem; import com.google.android.gms.wearable.Wearable; import com.google.android.gms.wearable.WearableListenerService; import java.io.FileOutputStream; import java.util.List; import java.util.concurrent.TimeUnit; /** * Created by jpettersson on 12/14/14. */ public class DataLayerListenerService extends WearableListenerService { private static final String TAG = "DataLayerListenerService"; public static final String PLAYLISTS_PATH = "/spotify/playlists"; @Override public void onDataChanged(DataEventBuffer dataEvents) { Log.i(TAG, "onDataChanged: " + dataEvents); final List<DataEvent> events = FreezableUtils .freezeIterable(dataEvents); // Loop through the events and send a message // to the node that created the data item. for (DataEvent event : events) { Log.i(TAG, event.toString()); if(event.getType() == DataEvent.TYPE_CHANGED) { String path = event.getDataItem().getUri().getPath(); if (path.equals(PLAYLISTS_PATH)) { DataMap dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap(); Log.v("myTag", "DataMap received on watch: " + dataMap.toString()); writeFile(dataMap.toByteArray()); } } } } private void writeFile(byte[] byteArray) { Log.i(TAG, "Writing data to file.."); String filename = "playlists"; FileOutputStream outputStream; try { outputStream = openFileOutput(filename, Context.MODE_PRIVATE); outputStream.write(byteArray); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } }
jpettersson/wearify
wear/src/main/java/com/jpettersson/wearify/DataLayerListenerService.java
Java
apache-2.0
2,265
/* * Copyright 2016 the original author or authors. * * 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 org.gradle.launcher.exec; import org.gradle.api.internal.StartParameterInternal; import org.gradle.composite.internal.IncludedBuildControllers; import org.gradle.internal.invocation.BuildAction; import org.gradle.internal.invocation.BuildActionRunner; import org.gradle.internal.invocation.BuildController; import org.gradle.internal.operations.BuildOperationContext; import org.gradle.internal.operations.BuildOperationDescriptor; import org.gradle.internal.operations.BuildOperationExecutor; import org.gradle.internal.operations.RunnableBuildOperation; /** * An {@link BuildActionRunner} that wraps all work in a build operation. */ public class RunAsBuildOperationBuildActionRunner implements BuildActionRunner { private final BuildActionRunner delegate; private static final RunBuildBuildOperationType.Details DETAILS = new RunBuildBuildOperationType.Details() {}; private static final RunBuildBuildOperationType.Result RESULT = new RunBuildBuildOperationType.Result() {}; public RunAsBuildOperationBuildActionRunner(BuildActionRunner delegate) { this.delegate = delegate; } @Override public void run(final BuildAction action, final BuildController buildController) { BuildOperationExecutor buildOperationExecutor = buildController.getGradle().getServices().get(BuildOperationExecutor.class); buildOperationExecutor.run(new RunnableBuildOperation() { @Override public void run(BuildOperationContext context) { checkDeprecations((StartParameterInternal)buildController.getGradle().getStartParameter()); buildController.getGradle().getServices().get(IncludedBuildControllers.class).rootBuildOperationStarted(); delegate.run(action, buildController); context.setResult(RESULT); } @Override public BuildOperationDescriptor.Builder description() { return BuildOperationDescriptor.displayName("Run build").details(DETAILS); } }); } private void checkDeprecations(StartParameterInternal startParameter) { startParameter.checkDeprecation(); } }
lsmaira/gradle
subprojects/launcher/src/main/java/org/gradle/launcher/exec/RunAsBuildOperationBuildActionRunner.java
Java
apache-2.0
2,807
/* @flow */ import React, { PureComponent } from 'react'; import { checkCompatibility } from '../api'; import CompatibilityScreen from '../start/CompatibilityScreen'; export default class CompatibilityChecker extends PureComponent { state = { compatibilityCheckFail: false, }; componentDidMount() { checkCompatibility().then(res => { if (res.status === 400) { this.setState({ compatibilityCheckFail: true, }); } }); } render() { const { compatibilityCheckFail } = this.state; return compatibilityCheckFail ? <CompatibilityScreen /> : this.props.children; } }
nashvail/zulip-mobile
src/boot/CompatibilityChecker.js
JavaScript
apache-2.0
634
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ru"> <head> <title>AxisLineFormatRecord (POI API Documentation)</title> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="AxisLineFormatRecord (POI API Documentation)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/AxisLineFormatRecord.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/poi/hssf/record/chart/AreaRecord.html" title="class in org.apache.poi.hssf.record.chart"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisOptionsRecord.html" title="class in org.apache.poi.hssf.record.chart"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html" target="_top">Frames</a></li> <li><a href="AxisLineFormatRecord.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.poi.hssf.record.chart</div> <h2 title="Class AxisLineFormatRecord" class="title">Class AxisLineFormatRecord</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../../../org/apache/poi/hssf/record/RecordBase.html" title="class in org.apache.poi.hssf.record">org.apache.poi.hssf.record.RecordBase</a></li> <li> <ul class="inheritance"> <li><a href="../../../../../../org/apache/poi/hssf/record/Record.html" title="class in org.apache.poi.hssf.record">org.apache.poi.hssf.record.Record</a></li> <li> <ul class="inheritance"> <li><a href="../../../../../../org/apache/poi/hssf/record/StandardRecord.html" title="class in org.apache.poi.hssf.record">org.apache.poi.hssf.record.StandardRecord</a></li> <li> <ul class="inheritance"> <li>org.apache.poi.hssf.record.chart.AxisLineFormatRecord</li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public final class <span class="strong">AxisLineFormatRecord</span> extends <a href="../../../../../../org/apache/poi/hssf/record/StandardRecord.html" title="class in org.apache.poi.hssf.record">StandardRecord</a></pre> <div class="block">The axis line format record defines the axis type details.<p/></div> <dl><dt><span class="strong">Author:</span></dt> <dd>Glen Stampoultzis (glens at apache.org)</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static short</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#AXIS_TYPE_AXIS_LINE">AXIS_TYPE_AXIS_LINE</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static short</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#AXIS_TYPE_MAJOR_GRID_LINE">AXIS_TYPE_MAJOR_GRID_LINE</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static short</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#AXIS_TYPE_MINOR_GRID_LINE">AXIS_TYPE_MINOR_GRID_LINE</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static short</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#AXIS_TYPE_WALLS_OR_FLOOR">AXIS_TYPE_WALLS_OR_FLOOR</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static short</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#sid">sid</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#AxisLineFormatRecord()">AxisLineFormatRecord</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#AxisLineFormatRecord(org.apache.poi.hssf.record.RecordInputStream)">AxisLineFormatRecord</a></strong>(<a href="../../../../../../org/apache/poi/hssf/record/RecordInputStream.html" title="class in org.apache.poi.hssf.record">RecordInputStream</a>&nbsp;in)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.Object</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#clone()">clone</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>short</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#getAxisType()">getAxisType</a></strong>()</code> <div class="block">Get the axis type field for the AxisLineFormat record.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected int</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#getDataSize()">getDataSize</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>short</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#getSid()">getSid</a></strong>()</code> <div class="block">return the non static version of the id for this record.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#serialize(org.apache.poi.util.LittleEndianOutput)">serialize</a></strong>(<a href="../../../../../../org/apache/poi/util/LittleEndianOutput.html" title="interface in org.apache.poi.util">LittleEndianOutput</a>&nbsp;out)</code> <div class="block">Write the data content of this BIFF record.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#setAxisType(short)">setAxisType</a></strong>(short&nbsp;field_1_axisType)</code> <div class="block">Set the axis type field for the AxisLineFormat record.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html#toString()">toString</a></strong>()</code> <div class="block">get a string representation of the record (for biffview/debugging)</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.apache.poi.hssf.record.StandardRecord"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.apache.poi.hssf.record.<a href="../../../../../../org/apache/poi/hssf/record/StandardRecord.html" title="class in org.apache.poi.hssf.record">StandardRecord</a></h3> <code><a href="../../../../../../org/apache/poi/hssf/record/StandardRecord.html#getRecordSize()">getRecordSize</a>, <a href="../../../../../../org/apache/poi/hssf/record/StandardRecord.html#serialize(int, byte[])">serialize</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.apache.poi.hssf.record.Record"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.apache.poi.hssf.record.<a href="../../../../../../org/apache/poi/hssf/record/Record.html" title="class in org.apache.poi.hssf.record">Record</a></h3> <code><a href="../../../../../../org/apache/poi/hssf/record/Record.html#cloneViaReserialise()">cloneViaReserialise</a>, <a href="../../../../../../org/apache/poi/hssf/record/Record.html#serialize()">serialize</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="sid"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>sid</h4> <pre>public static final&nbsp;short sid</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../constant-values.html#org.apache.poi.hssf.record.chart.AxisLineFormatRecord.sid">Constant Field Values</a></dd></dl> </li> </ul> <a name="AXIS_TYPE_AXIS_LINE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>AXIS_TYPE_AXIS_LINE</h4> <pre>public static final&nbsp;short AXIS_TYPE_AXIS_LINE</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../constant-values.html#org.apache.poi.hssf.record.chart.AxisLineFormatRecord.AXIS_TYPE_AXIS_LINE">Constant Field Values</a></dd></dl> </li> </ul> <a name="AXIS_TYPE_MAJOR_GRID_LINE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>AXIS_TYPE_MAJOR_GRID_LINE</h4> <pre>public static final&nbsp;short AXIS_TYPE_MAJOR_GRID_LINE</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../constant-values.html#org.apache.poi.hssf.record.chart.AxisLineFormatRecord.AXIS_TYPE_MAJOR_GRID_LINE">Constant Field Values</a></dd></dl> </li> </ul> <a name="AXIS_TYPE_MINOR_GRID_LINE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>AXIS_TYPE_MINOR_GRID_LINE</h4> <pre>public static final&nbsp;short AXIS_TYPE_MINOR_GRID_LINE</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../constant-values.html#org.apache.poi.hssf.record.chart.AxisLineFormatRecord.AXIS_TYPE_MINOR_GRID_LINE">Constant Field Values</a></dd></dl> </li> </ul> <a name="AXIS_TYPE_WALLS_OR_FLOOR"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>AXIS_TYPE_WALLS_OR_FLOOR</h4> <pre>public static final&nbsp;short AXIS_TYPE_WALLS_OR_FLOOR</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../constant-values.html#org.apache.poi.hssf.record.chart.AxisLineFormatRecord.AXIS_TYPE_WALLS_OR_FLOOR">Constant Field Values</a></dd></dl> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="AxisLineFormatRecord()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>AxisLineFormatRecord</h4> <pre>public&nbsp;AxisLineFormatRecord()</pre> </li> </ul> <a name="AxisLineFormatRecord(org.apache.poi.hssf.record.RecordInputStream)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>AxisLineFormatRecord</h4> <pre>public&nbsp;AxisLineFormatRecord(<a href="../../../../../../org/apache/poi/hssf/record/RecordInputStream.html" title="class in org.apache.poi.hssf.record">RecordInputStream</a>&nbsp;in)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="toString()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../../org/apache/poi/hssf/record/Record.html#toString()">Record</a></code></strong></div> <div class="block">get a string representation of the record (for biffview/debugging)</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../../org/apache/poi/hssf/record/Record.html#toString()">toString</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../../org/apache/poi/hssf/record/Record.html" title="class in org.apache.poi.hssf.record">Record</a></code></dd> </dl> </li> </ul> <a name="serialize(org.apache.poi.util.LittleEndianOutput)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>serialize</h4> <pre>public&nbsp;void&nbsp;serialize(<a href="../../../../../../org/apache/poi/util/LittleEndianOutput.html" title="interface in org.apache.poi.util">LittleEndianOutput</a>&nbsp;out)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../../org/apache/poi/hssf/record/StandardRecord.html#serialize(org.apache.poi.util.LittleEndianOutput)">StandardRecord</a></code></strong></div> <div class="block">Write the data content of this BIFF record. The 'ushort sid' and 'ushort size' header fields have already been written by the superclass.<br/> The number of bytes written must equal the record size reported by <a href="../../../../../../org/apache/poi/hssf/record/RecordBase.html#getRecordSize()"><code>RecordBase.getRecordSize()</code></a>} minus four ( record header consiting of a 'ushort sid' and 'ushort reclength' has already been written by thye superclass).</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../../org/apache/poi/hssf/record/StandardRecord.html#serialize(org.apache.poi.util.LittleEndianOutput)">serialize</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../../org/apache/poi/hssf/record/StandardRecord.html" title="class in org.apache.poi.hssf.record">StandardRecord</a></code></dd> </dl> </li> </ul> <a name="getDataSize()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getDataSize</h4> <pre>protected&nbsp;int&nbsp;getDataSize()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../../org/apache/poi/hssf/record/StandardRecord.html#getDataSize()">getDataSize</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../../org/apache/poi/hssf/record/StandardRecord.html" title="class in org.apache.poi.hssf.record">StandardRecord</a></code></dd> </dl> </li> </ul> <a name="getSid()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getSid</h4> <pre>public&nbsp;short&nbsp;getSid()</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../../org/apache/poi/hssf/record/Record.html#getSid()">Record</a></code></strong></div> <div class="block">return the non static version of the id for this record.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../../org/apache/poi/hssf/record/Record.html#getSid()">getSid</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../../org/apache/poi/hssf/record/Record.html" title="class in org.apache.poi.hssf.record">Record</a></code></dd> </dl> </li> </ul> <a name="clone()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>clone</h4> <pre>public&nbsp;java.lang.Object&nbsp;clone()</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../../../org/apache/poi/hssf/record/Record.html#clone()">clone</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../../org/apache/poi/hssf/record/Record.html" title="class in org.apache.poi.hssf.record">Record</a></code></dd> </dl> </li> </ul> <a name="getAxisType()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getAxisType</h4> <pre>public&nbsp;short&nbsp;getAxisType()</pre> <div class="block">Get the axis type field for the AxisLineFormat record.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>One of AXIS_TYPE_AXIS_LINE AXIS_TYPE_MAJOR_GRID_LINE AXIS_TYPE_MINOR_GRID_LINE AXIS_TYPE_WALLS_OR_FLOOR</dd></dl> </li> </ul> <a name="setAxisType(short)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>setAxisType</h4> <pre>public&nbsp;void&nbsp;setAxisType(short&nbsp;field_1_axisType)</pre> <div class="block">Set the axis type field for the AxisLineFormat record.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>field_1_axisType</code> - One of AXIS_TYPE_AXIS_LINE AXIS_TYPE_MAJOR_GRID_LINE AXIS_TYPE_MINOR_GRID_LINE AXIS_TYPE_WALLS_OR_FLOOR</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/AxisLineFormatRecord.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/poi/hssf/record/chart/AreaRecord.html" title="class in org.apache.poi.hssf.record.chart"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../org/apache/poi/hssf/record/chart/AxisOptionsRecord.html" title="class in org.apache.poi.hssf.record.chart"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html" target="_top">Frames</a></li> <li><a href="AxisLineFormatRecord.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright 2014 The Apache Software Foundation or its licensors, as applicable.</i> </small></p> </body> </html>
pedro93/ifarmaStudents
poi-3.10-FINAL/docs/apidocs/org/apache/poi/hssf/record/chart/AxisLineFormatRecord.html
HTML
apache-2.0
22,617
// Package logic implements the Azure ARM Logic service API version 2016-06-01. // // REST API for Azure Logic Apps. package logic // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // 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. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "net/http" ) const ( // DefaultBaseURI is the default URI used for the service Logic DefaultBaseURI = "https://management.azure.com" ) // ManagementClient is the base client for Logic. type ManagementClient struct { autorest.Client BaseURI string SubscriptionID string } // New creates an instance of the ManagementClient client. func New(subscriptionID string) ManagementClient { return NewWithBaseURI(DefaultBaseURI, subscriptionID) } // NewWithBaseURI creates an instance of the ManagementClient client. func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { return ManagementClient{ Client: autorest.NewClientWithUserAgent(UserAgent()), BaseURI: baseURI, SubscriptionID: subscriptionID, } } // ListOperations lists all of the available Logic REST API operations. func (client ManagementClient) ListOperations() (result OperationListResult, err error) { req, err := client.ListOperationsPreparer() if err != nil { return result, autorest.NewErrorWithError(err, "logic.ManagementClient", "ListOperations", nil, "Failure preparing request") } resp, err := client.ListOperationsSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "logic.ManagementClient", "ListOperations", resp, "Failure sending request") } result, err = client.ListOperationsResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "logic.ManagementClient", "ListOperations", resp, "Failure responding to request") } return } // ListOperationsPreparer prepares the ListOperations request. func (client ManagementClient) ListOperationsPreparer() (*http.Request, error) { const APIVersion = "2016-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPath("/providers/Microsoft.Logic/operations"), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{}) } // ListOperationsSender sends the ListOperations request. The method will close the // http.Response Body if it receives an error. func (client ManagementClient) ListOperationsSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req) } // ListOperationsResponder handles the response to the ListOperations request. The method always // closes the http.Response Body. func (client ManagementClient) ListOperationsResponder(resp *http.Response) (result OperationListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ListOperationsNextResults retrieves the next set of results, if any. func (client ManagementClient) ListOperationsNextResults(lastResults OperationListResult) (result OperationListResult, err error) { req, err := lastResults.OperationListResultPreparer() if err != nil { return result, autorest.NewErrorWithError(err, "logic.ManagementClient", "ListOperations", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListOperationsSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "logic.ManagementClient", "ListOperations", resp, "Failure sending next results request") } result, err = client.ListOperationsResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "logic.ManagementClient", "ListOperations", resp, "Failure responding to next results request") } return }
colemickens/azure-sdk-for-go
arm/logic/client.go
GO
apache-2.0
4,778
/* Generic definitions */ /* Assertions (useful to generate conditional code) */ /* Current type and class (and size, if applicable) */ /* Value methods */ /* Interfaces (keys) */ /* Interfaces (values) */ /* Abstract implementations (keys) */ /* Abstract implementations (values) */ /* Static containers (keys) */ /* Static containers (values) */ /* Implementations */ /* Synchronized wrappers */ /* Unmodifiable wrappers */ /* Other wrappers */ /* Methods (keys) */ /* Methods (values) */ /* Methods (keys/values) */ /* Methods that have special names depending on keys (but the special names depend on values) */ /* Equality */ /* Object/Reference-only definitions (keys) */ /* Primitive-type-only definitions (keys) */ /* Object/Reference-only definitions (values) */ /* * Copyright (C) 2002-2013 Sebastiano Vigna * * 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 it.unimi.dsi.fastutil.ints; import it.unimi.dsi.fastutil.objects.ObjectSet; import it.unimi.dsi.fastutil.objects.ObjectSets; import it.unimi.dsi.fastutil.objects.ReferenceCollection; import it.unimi.dsi.fastutil.objects.ReferenceCollections; import it.unimi.dsi.fastutil.objects.ReferenceSets; import java.util.Map; /** A class providing static methods and objects that do useful things with type-specific maps. * * @see it.unimi.dsi.fastutil.Maps * @see java.util.Collections */ public class Int2ReferenceMaps { private Int2ReferenceMaps() {} /** An immutable class representing an empty type-specific map. * * <P>This class may be useful to implement your own in case you subclass * a type-specific map. */ public static class EmptyMap <V> extends Int2ReferenceFunctions.EmptyFunction <V> implements Int2ReferenceMap <V>, java.io.Serializable, Cloneable { private static final long serialVersionUID = -7046029254386353129L; protected EmptyMap() {} public boolean containsValue( final Object v ) { return false; } public void putAll( final Map<? extends Integer, ? extends V> m ) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") public ObjectSet<Int2ReferenceMap.Entry <V> > int2ReferenceEntrySet() { return ObjectSets.EMPTY_SET; } @SuppressWarnings("unchecked") public IntSet keySet() { return IntSets.EMPTY_SET; } @SuppressWarnings("unchecked") public ReferenceCollection <V> values() { return ReferenceSets.EMPTY_SET; } private Object readResolve() { return EMPTY_MAP; } public Object clone() { return EMPTY_MAP; } public boolean isEmpty() { return true; } @SuppressWarnings({ "rawtypes", "unchecked" }) public ObjectSet<Map.Entry<Integer, V>> entrySet() { return (ObjectSet)int2ReferenceEntrySet(); } public int hashCode() { return 0; } public boolean equals( final Object o ) { if ( ! ( o instanceof Map ) ) return false; return ((Map<?,?>)o).isEmpty(); } public String toString() { return "{}"; } } /** An empty type-specific map (immutable). It is serializable and cloneable. */ @SuppressWarnings("rawtypes") public static final EmptyMap EMPTY_MAP = new EmptyMap(); /** An immutable class representing a type-specific singleton map. * * <P>This class may be useful to implement your own in case you subclass * a type-specific map. */ public static class Singleton <V> extends Int2ReferenceFunctions.Singleton <V> implements Int2ReferenceMap <V>, java.io.Serializable, Cloneable { private static final long serialVersionUID = -7046029254386353129L; protected transient volatile ObjectSet<Int2ReferenceMap.Entry <V> > entries; protected transient volatile IntSet keys; protected transient volatile ReferenceCollection <V> values; protected Singleton( final int key, final V value ) { super( key, value ); } public boolean containsValue( final Object v ) { return ( (value) == (v) ); } public void putAll( final Map<? extends Integer, ? extends V> m ) { throw new UnsupportedOperationException(); } public ObjectSet<Int2ReferenceMap.Entry <V> > int2ReferenceEntrySet() { if ( entries == null ) entries = ObjectSets.singleton( (Int2ReferenceMap.Entry <V>)new SingletonEntry() ); return entries; } public IntSet keySet() { if ( keys == null ) keys = IntSets.singleton( key ); return keys; } public ReferenceCollection <V> values() { if ( values == null ) values = ReferenceSets.singleton( value ); return values; } protected class SingletonEntry implements Int2ReferenceMap.Entry <V>, Map.Entry<Integer,V> { public Integer getKey() { return (Integer.valueOf(Singleton.this.key)); } public V getValue() { return (Singleton.this.value); } public int getIntKey() { return Singleton.this.key; } public V setValue( final V value ) { throw new UnsupportedOperationException(); } public boolean equals( final Object o ) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; return ( (Singleton.this.key) == (((((Integer)(e.getKey())).intValue()))) ) && ( (Singleton.this.value) == ((e.getValue())) ); } public int hashCode() { return (Singleton.this.key) ^ ( (Singleton.this.value) == null ? 0 : System.identityHashCode(Singleton.this.value) ); } public String toString() { return Singleton.this.key + "->" + Singleton.this.value; } } public boolean isEmpty() { return false; } @SuppressWarnings({ "rawtypes", "unchecked" }) public ObjectSet<Map.Entry<Integer, V>> entrySet() { return (ObjectSet)int2ReferenceEntrySet(); } public int hashCode() { return (key) ^ ( (value) == null ? 0 : System.identityHashCode(value) ); } public boolean equals( final Object o ) { if ( o == this ) return true; if ( ! ( o instanceof Map ) ) return false; Map<?,?> m = (Map<?,?>)o; if ( m.size() != 1 ) return false; return entrySet().iterator().next().equals( m.entrySet().iterator().next() ); } public String toString() { return "{" + key + "=>" + value + "}"; } } /** Returns a type-specific immutable map containing only the specified pair. The returned map is serializable and cloneable. * * <P>Note that albeit the returned map is immutable, its default return value may be changed. * * @param key the only key of the returned map. * @param value the only value of the returned map. * @return a type-specific immutable map containing just the pair <code>&lt;key,value></code>. */ public static <V> Int2ReferenceMap <V> singleton( final int key, V value ) { return new Singleton <V>( key, value ); } /** Returns a type-specific immutable map containing only the specified pair. The returned map is serializable and cloneable. * * <P>Note that albeit the returned map is immutable, its default return value may be changed. * * @param key the only key of the returned map. * @param value the only value of the returned map. * @return a type-specific immutable map containing just the pair <code>&lt;key,value></code>. */ public static <V> Int2ReferenceMap <V> singleton( final Integer key, final V value ) { return new Singleton <V>( ((key).intValue()), (value) ); } /** A synchronized wrapper class for maps. */ public static class SynchronizedMap <V> extends Int2ReferenceFunctions.SynchronizedFunction <V> implements Int2ReferenceMap <V>, java.io.Serializable { private static final long serialVersionUID = -7046029254386353129L; protected final Int2ReferenceMap <V> map; protected transient volatile ObjectSet<Int2ReferenceMap.Entry <V> > entries; protected transient volatile IntSet keys; protected transient volatile ReferenceCollection <V> values; protected SynchronizedMap( final Int2ReferenceMap <V> m, final Object sync ) { super( m, sync ); this.map = m; } protected SynchronizedMap( final Int2ReferenceMap <V> m ) { super( m ); this.map = m; } public int size() { synchronized( sync ) { return map.size(); } } public boolean containsKey( final int k ) { synchronized( sync ) { return map.containsKey( k ); } } public boolean containsValue( final Object v ) { synchronized( sync ) { return map.containsValue( v ); } } public V defaultReturnValue() { synchronized( sync ) { return map.defaultReturnValue(); } } public void defaultReturnValue( final V defRetValue ) { synchronized( sync ) { map.defaultReturnValue( defRetValue ); } } public V put( final int k, final V v ) { synchronized( sync ) { return map.put( k, v ); } } //public void putAll( final MAP KEY_VALUE_EXTENDS_GENERIC c ) { synchronized( sync ) { map.putAll( c ); } } public void putAll( final Map<? extends Integer, ? extends V> m ) { synchronized( sync ) { map.putAll( m ); } } public ObjectSet<Int2ReferenceMap.Entry <V> > int2ReferenceEntrySet() { if ( entries == null ) entries = ObjectSets.synchronize( map.int2ReferenceEntrySet(), sync ); return entries; } public IntSet keySet() { if ( keys == null ) keys = IntSets.synchronize( map.keySet(), sync ); return keys; } public ReferenceCollection <V> values() { if ( values == null ) return ReferenceCollections.synchronize( map.values(), sync ); return values; } public void clear() { synchronized( sync ) { map.clear(); } } public String toString() { synchronized( sync ) { return map.toString(); } } public V put( final Integer k, final V v ) { synchronized( sync ) { return map.put( k, v ); } } public V remove( final int k ) { synchronized( sync ) { return map.remove( k ); } } public V get( final int k ) { synchronized( sync ) { return map.get( k ); } } public boolean containsKey( final Object ok ) { synchronized( sync ) { return map.containsKey( ok ); } } public boolean isEmpty() { synchronized( sync ) { return map.isEmpty(); } } public ObjectSet<Map.Entry<Integer, V>> entrySet() { synchronized( sync ) { return map.entrySet(); } } public int hashCode() { synchronized( sync ) { return map.hashCode(); } } public boolean equals( final Object o ) { synchronized( sync ) { return map.equals( o ); } } } /** Returns a synchronized type-specific map backed by the given type-specific map. * * @param m the map to be wrapped in a synchronized map. * @return a synchronized view of the specified map. * @see java.util.Collections#synchronizedMap(Map) */ public static <V> Int2ReferenceMap <V> synchronize( final Int2ReferenceMap <V> m ) { return new SynchronizedMap <V>( m ); } /** Returns a synchronized type-specific map backed by the given type-specific map, using an assigned object to synchronize. * * @param m the map to be wrapped in a synchronized map. * @param sync an object that will be used to synchronize the access to the map. * @return a synchronized view of the specified map. * @see java.util.Collections#synchronizedMap(Map) */ public static <V> Int2ReferenceMap <V> synchronize( final Int2ReferenceMap <V> m, final Object sync ) { return new SynchronizedMap <V>( m, sync ); } /** An unmodifiable wrapper class for maps. */ public static class UnmodifiableMap <V> extends Int2ReferenceFunctions.UnmodifiableFunction <V> implements Int2ReferenceMap <V>, java.io.Serializable { private static final long serialVersionUID = -7046029254386353129L; protected final Int2ReferenceMap <V> map; protected transient volatile ObjectSet<Int2ReferenceMap.Entry <V> > entries; protected transient volatile IntSet keys; protected transient volatile ReferenceCollection <V> values; protected UnmodifiableMap( final Int2ReferenceMap <V> m ) { super( m ); this.map = m; } public int size() { return map.size(); } public boolean containsKey( final int k ) { return map.containsKey( k ); } public boolean containsValue( final Object v ) { return map.containsValue( v ); } public V defaultReturnValue() { throw new UnsupportedOperationException(); } public void defaultReturnValue( final V defRetValue ) { throw new UnsupportedOperationException(); } public V put( final int k, final V v ) { throw new UnsupportedOperationException(); } //public void putAll( final MAP KEY_VALUE_EXTENDS_GENERIC c ) { throw new UnsupportedOperationException(); } public void putAll( final Map<? extends Integer, ? extends V> m ) { throw new UnsupportedOperationException(); } public ObjectSet<Int2ReferenceMap.Entry <V> > int2ReferenceEntrySet() { if ( entries == null ) entries = ObjectSets.unmodifiable( map.int2ReferenceEntrySet() ); return entries; } public IntSet keySet() { if ( keys == null ) keys = IntSets.unmodifiable( map.keySet() ); return keys; } public ReferenceCollection <V> values() { if ( values == null ) return ReferenceCollections.unmodifiable( map.values() ); return values; } public void clear() { throw new UnsupportedOperationException(); } public String toString() { return map.toString(); } public V remove( final int k ) { throw new UnsupportedOperationException(); } public V get( final int k ) { return map.get( k ); } public boolean containsKey( final Object ok ) { return map.containsKey( ok ); } public V remove( final Object k ) { throw new UnsupportedOperationException(); } public V get( final Object k ) { return map.get( k ); } public boolean isEmpty() { return map.isEmpty(); } public ObjectSet<Map.Entry<Integer, V>> entrySet() { return ObjectSets.unmodifiable( map.entrySet() ); } } /** Returns an unmodifiable type-specific map backed by the given type-specific map. * * @param m the map to be wrapped in an unmodifiable map. * @return an unmodifiable view of the specified map. * @see java.util.Collections#unmodifiableMap(Map) */ public static <V> Int2ReferenceMap <V> unmodifiable( final Int2ReferenceMap <V> m ) { return new UnmodifiableMap <V>( m ); } }
karussell/fastutil
src/it/unimi/dsi/fastutil/ints/Int2ReferenceMaps.java
Java
apache-2.0
14,114
/* * Copyright 2014 Red Hat, Inc. and/or its affiliates. * * 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 org.dashbuilder.dataprovider.sql; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import org.dashbuilder.dataset.DataSet; import org.dashbuilder.dataset.DataSetColumnTest; import org.dashbuilder.dataset.DataSetFilterTest; import org.dashbuilder.dataset.DataSetGroupTest; import org.dashbuilder.dataset.DataSetLookupFactory; import org.dashbuilder.dataset.DataSetNestedGroupTest; import org.dashbuilder.dataset.filter.FilterFactory; import org.dashbuilder.dataset.group.DateIntervalType; import org.junit.Test; import static org.dashbuilder.dataset.ExpenseReportsData.*; import static org.dashbuilder.dataprovider.sql.SQLFactory.*; import static org.dashbuilder.dataset.filter.FilterFactory.*; import static org.dashbuilder.dataset.group.AggregateFunctionType.*; import static org.fest.assertions.api.Assertions.*; import static org.junit.Assert.*; public class SQLTableDataSetLookupTest extends SQLDataSetTestBase { @Override public void testAll() throws Exception { testNullValues(); testCurrentDate(); testAvoidDuplicatedGroupColumn(); testDataSetTrim(); testDataSetColumns(); testDataSetFilter(); testDataSetGroup(); testDataSetGroupByHour(); testDataSetNestedGroup(); testEmptyArguments(); } public void insertExtraRow(String city, String dept, String employee, Date date, Double amount) throws Exception { insert(conn).into(EXPENSES) .set(ID, 9999) .set(CITY, city) .set(DEPT, dept) .set(EMPLOYEE, employee) .set(DATE, date) .set(AMOUNT, amount) .execute(); } public void deleteExtraRow() throws Exception { delete(conn) .from(EXPENSES) .where((ID.equalsTo(9999))) .execute(); } @Test public void testNullValues() throws Exception { try { insertExtraRow(null, null, null, null, null); DataSet result = dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(equalsTo(ID.getName(), 9999)) .buildLookup()); assertThat(result.getRowCount()).isEqualTo(1); assertThat(result.getValueAt(0, 1)).isNull(); assertThat(result.getValueAt(0, 2)).isNull(); assertThat(result.getValueAt(0, 3)).isNull(); assertThat(result.getValueAt(0, 4)).isNull(); // Skip next since some DBs like Mysql return the current date when the value inserted is null, // assertThat(result.getValueAt(0, 5)).isNull(); } finally { deleteExtraRow(); } } @Test public void testCurrentDate() throws Exception { try { Date currentDate = new Date(); insertExtraRow(null, null, null, currentDate, null); DataSet result = dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(equalsTo(ID.getName(), 9999)) .buildLookup()); // Seconds comparison is enough as there are some DBs that either leave out nanos or round them adding an extra second. Date fromDb = (Date) result.getValueAt(0, 5); long seconds1 = currentDate.toInstant().getEpochSecond(); long seconds2 = fromDb.toInstant().getEpochSecond(); assertTrue(seconds1 == seconds2 || seconds1 == seconds2-1); } finally { deleteExtraRow(); } } @Test public void testAvoidDuplicatedGroupColumn() throws Exception { // In some DBs (MonetDB for instance), duplicated columns in "group by" fails dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .group(COLUMN_DEPARTMENT) .column("Department") .column(COLUMN_AMOUNT, SUM) .rowNumber(3) .rowOffset(0) .buildLookup()); } @Test public void testDataSetTrim() throws Exception { DataSet result = dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .rowNumber(10) .buildLookup()); assertThat(result.getRowCount()).isEqualTo(10); assertThat(result.getValueAt(0, 0)).isEqualTo(1d); assertThat(result.getValueAt(9, 0)).isEqualTo(10d); result = dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .rowNumber(10) .rowOffset(40) .buildLookup()); assertThat(result.getRowCount()).isEqualTo(10); assertThat(result.getValueAt(0, 0)).isEqualTo(41d); assertThat(result.getValueAt(9, 0)).isEqualTo(50d); result = dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .group(DEPT.getName()) .column(DEPT.getName()) .column(AMOUNT.getName(), SUM) .rowNumber(3) .rowOffset(0) .buildLookup()); assertThat(result.getRowCount()).isEqualTo(3); assertThat(result.getRowCountNonTrimmed()).isEqualTo(5); result = dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(CITY.getName(), equalsTo("Barcelona")) .rowNumber(3) .rowOffset(0) .buildLookup()); assertThat(result.getRowCount()).isEqualTo(3); assertThat(result.getRowCountNonTrimmed()).isEqualTo(6); } @Test public void testDataSetGroupByHour() throws Exception { DataSet result = dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(ID.getName(), FilterFactory.AND( FilterFactory.greaterOrEqualsTo(40), FilterFactory.lowerOrEqualsTo(41))) .group(DATE.getName()).dynamic(9999, DateIntervalType.HOUR, true) .column(DATE.getName()) .buildLookup()); assertThat(result.getRowCount()).isEqualTo(25); assertThat(result.getValueAt(0,0)).isEqualTo("2012-06-12 12"); } @Test public void testDataSetColumns() throws Exception { DataSetColumnTest subTest = new DataSetColumnTest(); subTest.testDataSetLookupColumns(); subTest.testDataSetMetadataColumns(); } @Test public void testDataSetGroup() throws Exception { DataSetGroupTest subTest = new DataSetGroupTest(); subTest.testDataSetFunctions(); subTest.testGroupByLabelDynamic(); subTest.testGroupByYearDynamic(); subTest.testGroupByMonthDynamic(); subTest.testGroupByMonthDynamicNonEmpty(); subTest.testGroupByDayDynamic(); // TODO: Not supported by DB subTest.testGroupByWeek(); subTest.testGroupByMonthReverse(); subTest.testGroupByMonthFixed(); subTest.testGroupByMonthFirstMonth(); subTest.testGroupByMonthFirstMonthReverse(); subTest.testGroupByQuarter(); subTest.testGroupByDateOneRow(); subTest.testGroupByDateOneDay(); subTest.testGroupAndCountSameColumn(); subTest.testGroupNumberAsLabel(); } @Test public void testDataSetNestedGroup() throws Exception { DataSetNestedGroupTest subTest = new DataSetNestedGroupTest(); subTest.testGroupSelectionFilter(); if (!testSettings.isMonetDB()) { subTest.testNestedGroupFromMultipleSelection(); } subTest.testNestedGroupRequiresSelection(); subTest.testThreeNestedLevels(); subTest.testNoResultsSelection(); } @Test public void testDataSetFilter() throws Exception { DataSetFilterTest subTest = new DataSetFilterTest(); subTest.testColumnTypes(); subTest.testFilterByString(); subTest.testFilterByDate(); subTest.testFilterByNumber(); subTest.testFilterMultiple(); subTest.testFilterUntilToday(); subTest.testANDExpression(); subTest.testNOTExpression(); subTest.testORExpression(); subTest.testORExpressionMultilple(); subTest.testLogicalExprNonEmpty(); subTest.testCombinedExpression(); subTest.testCombinedExpression2(); subTest.testCombinedExpression3(); subTest.testLikeOperatorNonCaseSensitive(); subTest.testInOperator(); subTest.testNotInOperator(); // Skip this test since MySQL,SQLServer & Sybase are non case sensitive by default if (!testSettings.isMySQL() && !testSettings.isMariaDB() && !testSettings.isSqlServer()&& !testSettings.isSybase()) { subTest.testLikeOperatorCaseSensitive(); } } /** * When a function does not receive an expected argument(s), * the function must be ruled out from the lookup call. * * See https://issues.jboss.org/browse/DASHBUILDE-90 */ @Test public void testEmptyArguments() throws Exception { try { insertExtraRow(null, null, null, null, null); assertThat(dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(equalsTo(CITY.getName(), (Comparable) null)) .buildLookup()).getRowCount()).isEqualTo(1); assertThat(dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(equalsTo(CITY.getName(), new ArrayList<Comparable>())) .buildLookup()).getRowCount()).isEqualTo(51); assertThat(dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(notEqualsTo(CITY.getName(), null)) .buildLookup()).getRowCount()).isEqualTo(50); assertThat(dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(between(AMOUNT.getName(), null, null)) .buildLookup()).getRowCount()).isEqualTo(51); assertThat(dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(in(CITY.getName(), null)) .buildLookup()).getRowCount()).isEqualTo(51); assertThat(dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(in(CITY.getName(), new ArrayList<Comparable>())) .buildLookup()).getRowCount()).isEqualTo(51); assertThat(dataSetManager.lookupDataSet( DataSetLookupFactory.newDataSetLookupBuilder() .dataset(DataSetGroupTest.EXPENSE_REPORTS) .filter(notIn(CITY.getName(), new ArrayList<Comparable>())) .buildLookup()).getRowCount()).isEqualTo(51); } finally { deleteExtraRow(); } } }
fariagu/dashbuilder
dashbuilder-backend/dashbuilder-dataset-sql/src/test/java/org/dashbuilder/dataprovider/sql/SQLTableDataSetLookupTest.java
Java
apache-2.0
13,322
package com.google.android.apps.forscience.whistlepunk.cloudsync; import android.content.Context; import java.io.IOException; /** An interface that defines a service used to sync data to and from a cloud storage provider. */ public interface CloudSyncManager { /** Syncs the Experiment Library file to cloud storage */ void syncExperimentLibrary(Context context, String logMessage) throws IOException; /** Logs diagnostic info to the console * */ void logCloudInfo(String tag); }
googlearchive/science-journal
OpenScienceJournal/whistlepunk_library/src/main/java/com/google/android/apps/forscience/whistlepunk/cloudsync/CloudSyncManager.java
Java
apache-2.0
492
#!/usr/bin/env python3 # coding=utf-8 """ This module, debugging.py, will contain code related to debugging (such as printing error messages). """ #import sys #sys.path.insert(0, '/home/dev_usr/urbtek') #from universal_code import system_operations as so class MyException(Exception): """ Just something useful to have to throw some of my own custom exception. """ pass class ParameterException(Exception): """ A custom exception for when a function receives bad parameter data. """ def __init__(self, message): super(ParameterException, self).__init__(message) class AbstractMethodNotImplementedException(Exception): """ A custom exception for when a function gets called that hasn't been set in a child class. """ def __init(self, message): super(AbstractMethodNotImplementedException, self).__init__(message) def raise_exception(exception, message): raise exception(message) TCP_LOCAL_HOST = 'tcp://127.0.0.1:' LOCAL_HOST = '127.0.0.1' NEXUS_DEV_RECEIVE_PORT = 40000 NEXUS_DEV_MANUAL_COMMUNICATION_PORT = 40001 NEXUS_DEV_AUTOMATED_COMMUNICATION_PORT = 40002 starting_port = NEXUS_DEV_AUTOMATED_COMMUNICATION_PORT + 1 def get_a_free_port(): global starting_port # We can assume ports are free because ports above 30000 have been sealed off. # TODO: THIS WILL BREAK WHEN MORE THAN DEV EXISTS. starting_port += 1 return starting_port - 1 # Terminal font coloring and styling. class TextColors: HEADER = '\033[95m' OK_BLUE = '\033[94m' OK_GREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def print_text_with_color(text, color, end=None): if end is None: print(color + text + TextColors.ENDC + '\n') else: print(color + text + TextColors.ENDC, end='') def terminate(termination_message=''): if termination_message is '': print_text_with_color('Program termination has been initiated, good bye!', TextColors.FAIL) else: print_text_with_color(termination_message, TextColors.WARNING, '') if not termination_message.endswith('.'): print_text_with_color('. The program will now terminate.', TextColors.FAIL) else: print_text_with_color(' The program will now terminate.', TextColors.FAIL) exit()
utarsuno/urbtek
universal_code/debugging.py
Python
apache-2.0
2,265
package cs.si.stavor.settings; import cs.si.stavor.R; import cs.si.stavor.MainActivity; import cs.si.stavor.StavorApplication; import android.app.Activity; import android.os.Bundle; import android.preference.PreferenceFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * General settings of the application * @author Xavier Gibert * */ public class SettingsGeneralFragment extends PreferenceFragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; private static String screenName = "Settings - General"; /** * Returns a new instance of this fragment for the given section number. */ public static SettingsGeneralFragment newInstance(int sectionNumber) { SettingsGeneralFragment fragment = new SettingsGeneralFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainActivity) activity).onSectionAttached(getArguments().getInt( ARG_SECTION_NUMBER)); ((MainActivity) activity).raiseLoadBrowserFlag(); ((MainActivity) activity).raiseLoadBrowserFlagOrbit(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences); //((MainActivity)getActivity()).showTutorialConfig(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); view.setBackgroundColor(getResources().getColor(android.R.color.background_dark)); return view; } }
CS-SI/Stavor
stavor/src/main/java/cs/si/stavor/settings/SettingsGeneralFragment.java
Java
apache-2.0
1,968
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.openapi.components.impl.stores; import com.intellij.notification.Notification; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.notification.NotificationsManager; import com.intellij.openapi.application.*; import com.intellij.openapi.components.*; import com.intellij.openapi.components.store.ReadOnlyModificationException; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.project.ex.ProjectEx; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileEvent; import com.intellij.util.ArrayUtil; import com.intellij.util.LineSeparator; import com.intellij.util.SmartList; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.jdom.Element; import org.jdom.Parent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.event.HyperlinkEvent; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.LinkedHashSet; import java.util.List; public class StorageUtil { static final Logger LOG = Logger.getInstance(StorageUtil.class); @TestOnly public static String DEBUG_LOG = ""; private static final byte[] XML_PROLOG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes(CharsetToolkit.UTF8_CHARSET); private static final Pair<byte[], String> NON_EXISTENT_FILE_DATA = Pair.create(null, SystemProperties.getLineSeparator()); private StorageUtil() { } public static boolean isChangedByStorageOrSaveSession(@NotNull VirtualFileEvent event) { return event.getRequestor() instanceof StateStorage.SaveSession || event.getRequestor() instanceof StateStorage; } public static void checkUnknownMacros(@NotNull final ComponentManager componentManager, @NotNull final Project project) { Application application = ApplicationManager.getApplication(); if (!application.isHeadlessEnvironment() && !application.isUnitTestMode()) { // should be invoked last StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { @Override public void run() { TrackingPathMacroSubstitutor substitutor = ComponentsPackage.getStateStore(componentManager).getStateStorageManager().getMacroSubstitutor(); if (substitutor != null) { notifyUnknownMacros(substitutor, project, null); } } }); } } public static void notifyUnknownMacros(@NotNull TrackingPathMacroSubstitutor substitutor, @NotNull final Project project, @Nullable final String componentName) { final LinkedHashSet<String> macros = new LinkedHashSet<String>(substitutor.getUnknownMacros(componentName)); if (macros.isEmpty()) { return; } UIUtil.invokeLaterIfNeeded(new Runnable() { @Override public void run() { List<String> notified = null; NotificationsManager manager = NotificationsManager.getNotificationsManager(); for (UnknownMacroNotification notification : manager.getNotificationsOfType(UnknownMacroNotification.class, project)) { if (notified == null) { notified = new SmartList<String>(); } notified.addAll(notification.getMacros()); } if (!ContainerUtil.isEmpty(notified)) { macros.removeAll(notified); } if (!macros.isEmpty()) { LOG.debug("Reporting unknown path macros " + macros + " in component " + componentName); String format = "<p><i>%s</i> %s undefined. <a href=\"define\">Fix it</a></p>"; String productName = ApplicationNamesInfo.getInstance().getProductName(); String content = String.format(format, StringUtil.join(macros, ", "), macros.size() == 1 ? "is" : "are") + "<br>Path variables are used to substitute absolute paths " + "in " + productName + " project files " + "and allow project file sharing in version control systems.<br>" + "Some of the files describing the current project settings contain unknown path variables " + "and " + productName + " cannot restore those paths."; new UnknownMacroNotification("Load Error", "Load error: undefined path variables", content, NotificationType.ERROR, new NotificationListener() { @Override public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { ((ProjectEx)project).checkUnknownMacros(true); } }, macros).notify(project); } } }); } @NotNull public static VirtualFile writeFile(@Nullable File file, @NotNull Object requestor, @Nullable VirtualFile virtualFile, @NotNull Element element, @Nullable LineSeparator lineSeparatorIfPrependXmlProlog) throws IOException { final VirtualFile result; if (file != null && (virtualFile == null || !virtualFile.isValid())) { result = getOrCreateVirtualFile(requestor, file); } else { result = virtualFile; assert result != null; } if (LOG.isDebugEnabled() || ApplicationManager.getApplication().isUnitTestMode()) { BufferExposingByteArrayOutputStream content = writeToBytes(element, (lineSeparatorIfPrependXmlProlog == null ? LineSeparator.LF : lineSeparatorIfPrependXmlProlog).getSeparatorString()); if (isEqualContent(result, lineSeparatorIfPrependXmlProlog, content)) { if (result.getName().equals("project.default.xml")) { LOG.warn("todo fix project.default.xml"); return result; } else { throw new IllegalStateException("Content equals, but it must be handled not on this level: " + result.getName()); } } else if (DEBUG_LOG != null && ApplicationManager.getApplication().isUnitTestMode()) { DEBUG_LOG = result.getPath() + ":\n" + content + "\nOld Content:\n" + LoadTextUtil.loadText(result) + "\n---------"; } } doWrite(requestor, result, element, lineSeparatorIfPrependXmlProlog); return result; } private static void doWrite(@NotNull final Object requestor, @NotNull final VirtualFile file, @NotNull Object content, @Nullable final LineSeparator lineSeparatorIfPrependXmlProlog) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Save " + file.getPresentableUrl()); } String lineSeparator = (lineSeparatorIfPrependXmlProlog == null ? LineSeparator.LF : lineSeparatorIfPrependXmlProlog).getSeparatorString(); AccessToken token = WriteAction.start(); try { OutputStream out = file.getOutputStream(requestor); try { if (lineSeparatorIfPrependXmlProlog != null) { out.write(XML_PROLOG); out.write(lineSeparatorIfPrependXmlProlog.getSeparatorBytes()); } if (content instanceof Element) { JDOMUtil.writeParent((Element)content, out, lineSeparator); } else { ((BufferExposingByteArrayOutputStream)content).writeTo(out); } } finally { out.close(); } } catch (FileNotFoundException e) { // may be element is not long-lived, so, we must write it to byte array final BufferExposingByteArrayOutputStream byteArray = content instanceof Element ? writeToBytes((Element)content, lineSeparator) : ((BufferExposingByteArrayOutputStream)content); throw new ReadOnlyModificationException(file, e, new StateStorage.SaveSession() { @Override public void save() throws IOException { doWrite(requestor, file, byteArray, lineSeparatorIfPrependXmlProlog); } }); } finally { token.finish(); } } private static boolean isEqualContent(@NotNull VirtualFile result, @Nullable LineSeparator lineSeparatorIfPrependXmlProlog, @NotNull BufferExposingByteArrayOutputStream content) throws IOException { int headerLength = lineSeparatorIfPrependXmlProlog == null ? 0 : XML_PROLOG.length + lineSeparatorIfPrependXmlProlog.getSeparatorBytes().length; if (result.getLength() != (headerLength + content.size())) { return false; } byte[] oldContent = result.contentsToByteArray(); if (lineSeparatorIfPrependXmlProlog != null && (!ArrayUtil.startsWith(oldContent, XML_PROLOG) || !ArrayUtil.startsWith(oldContent, XML_PROLOG.length, lineSeparatorIfPrependXmlProlog.getSeparatorBytes()))) { return false; } for (int i = headerLength; i < oldContent.length; i++) { if (oldContent[i] != content.getInternalBuffer()[i - headerLength]) { return false; } } return true; } public static void deleteFile(@NotNull File file, @NotNull final Object requestor, @Nullable final VirtualFile virtualFile) throws IOException { if (virtualFile == null) { LOG.warn("Cannot find virtual file " + file.getAbsolutePath()); } if (virtualFile == null) { if (file.exists()) { FileUtil.delete(file); } } else if (virtualFile.exists()) { try { deleteFile(requestor, virtualFile); } catch (FileNotFoundException e) { throw new ReadOnlyModificationException(virtualFile, e, new StateStorage.SaveSession() { @Override public void save() throws IOException { deleteFile(requestor, virtualFile); } }); } } } public static void deleteFile(@NotNull Object requestor, @NotNull VirtualFile virtualFile) throws IOException { AccessToken token = WriteAction.start(); try { virtualFile.delete(requestor); } finally { token.finish(); } } @NotNull public static BufferExposingByteArrayOutputStream writeToBytes(@NotNull Parent element, @NotNull String lineSeparator) throws IOException { BufferExposingByteArrayOutputStream out = new BufferExposingByteArrayOutputStream(512); JDOMUtil.writeParent(element, out, lineSeparator); return out; } @NotNull public static VirtualFile getOrCreateVirtualFile(@Nullable final Object requestor, @NotNull final File file) throws IOException { VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); if (virtualFile != null) { return virtualFile; } File absoluteFile = file.getAbsoluteFile(); FileUtil.createParentDirs(absoluteFile); File parentFile = absoluteFile.getParentFile(); // need refresh if the directory has just been created final VirtualFile parentVirtualFile = StringUtil.isEmpty(parentFile.getPath()) ? null : LocalFileSystem.getInstance().refreshAndFindFileByIoFile(parentFile); if (parentVirtualFile == null) { throw new IOException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile)); } if (ApplicationManager.getApplication().isWriteAccessAllowed()) { return parentVirtualFile.createChildData(requestor, file.getName()); } return ApplicationManager.getApplication().runWriteAction(new ThrowableComputable<VirtualFile, IOException>() { @Override public VirtualFile compute() throws IOException { return parentVirtualFile.createChildData(requestor, file.getName()); } }); } /** * @return pair.first - file contents (null if file does not exist), pair.second - file line separators */ @NotNull public static Pair<byte[], String> loadFile(@Nullable final VirtualFile file) throws IOException { if (file == null || !file.exists()) { return NON_EXISTENT_FILE_DATA; } byte[] bytes = file.contentsToByteArray(); String lineSeparator = file.getDetectedLineSeparator(); if (lineSeparator == null) { lineSeparator = detectLineSeparators(CharsetToolkit.UTF8_CHARSET.decode(ByteBuffer.wrap(bytes)), null).getSeparatorString(); } return Pair.create(bytes, lineSeparator); } @NotNull public static LineSeparator detectLineSeparators(@NotNull CharSequence chars, @Nullable LineSeparator defaultSeparator) { for (int i = 0, n = chars.length(); i < n; i++) { char c = chars.charAt(i); if (c == '\r') { return LineSeparator.CRLF; } else if (c == '\n') { // if we are here, there was no \r before return LineSeparator.LF; } } return defaultSeparator == null ? LineSeparator.getSystemLineSeparator() : defaultSeparator; } public static void delete(@NotNull StreamProvider provider, @NotNull String fileSpec, @NotNull RoamingType type) { if (provider.isApplicable(fileSpec, type)) { provider.delete(fileSpec, type); } } /** * You must call {@link StreamProvider#isApplicable(String, com.intellij.openapi.components.RoamingType)} before */ public static void sendContent(@NotNull StreamProvider provider, @NotNull String fileSpec, @NotNull Element element, @NotNull RoamingType type) throws IOException { // we should use standard line-separator (\n) - stream provider can share file content on any OS BufferExposingByteArrayOutputStream content = writeToBytes(element, "\n"); provider.saveContent(fileSpec, content.getInternalBuffer(), content.size(), type); } public static boolean isProjectOrModuleFile(@NotNull String fileSpec) { return StoragePathMacros.PROJECT_FILE.equals(fileSpec) || fileSpec.startsWith(StoragePathMacros.PROJECT_CONFIG_DIR) || fileSpec.equals(StoragePathMacros.MODULE_FILE); } @NotNull public static VirtualFile getFile(@NotNull String fileName, @NotNull VirtualFile parent, @NotNull Object requestor) throws IOException { VirtualFile file = parent.findChild(fileName); if (file != null) { return file; } AccessToken token = WriteAction.start(); try { return parent.createChildData(requestor, fileName); } finally { token.finish(); } } }
pwoodworth/intellij-community
platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StorageUtil.java
Java
apache-2.0
15,918
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_0940 { }
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_0940.java
Java
apache-2.0
151
// // UIImage+AKCryptography.h // AmazeKit // // Created by Jeff Kelley on 8/13/12. // Copyright (c) 2013 Detroit Labs. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // 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. // #import <UIKit/UIKit.h> @interface UIImage (AKCryptography) - (NSString *)AK_sha1Hash; @end
detroit-labs/AmazeKit
AmazeKit/AmazeKit/UIImage+AKCryptography.h
C
apache-2.0
809
package com.github.yuukis.businessmap.util; public class StringJUtils { private static final char[] HANKAKU_KATAKANA = { '。', '「', '」', '、', '・', 'ヲ', 'ァ', 'ィ', 'ゥ', 'ェ', 'ォ', 'ャ', 'ュ', 'ョ', 'ッ', 'ー', 'ア', 'イ', 'ウ', 'エ', 'オ', 'カ', 'キ', 'ク', 'ケ', 'コ', 'サ', 'シ', 'ス', 'セ', 'ソ', 'タ', 'チ', 'ツ', 'テ', 'ト', 'ナ', 'ニ', 'ヌ', 'ネ', 'ノ', 'ハ', 'ヒ', 'フ', 'ヘ', 'ホ', 'マ', 'ミ', 'ム', 'メ', 'モ', 'ヤ', 'ユ', 'ヨ', 'ラ', 'リ', 'ル', 'レ', 'ロ', 'ワ', 'ン', '゙', '゚' }; private static final char[] ZENKAKU_KATAKANA = { '。', '「', '」', '、', '・', 'ヲ', 'ァ', 'ィ', 'ゥ', 'ェ', 'ォ', 'ャ', 'ュ', 'ョ', 'ッ', 'ー', 'ア', 'イ', 'ウ', 'エ', 'オ', 'カ', 'キ', 'ク', 'ケ', 'コ', 'サ', 'シ', 'ス', 'セ', 'ソ', 'タ', 'チ', 'ツ', 'テ', 'ト', 'ナ', 'ニ', 'ヌ', 'ネ', 'ノ', 'ハ', 'ヒ', 'フ', 'ヘ', 'ホ', 'マ', 'ミ', 'ム', 'メ', 'モ', 'ヤ', 'ユ', 'ヨ', 'ラ', 'リ', 'ル', 'レ', 'ロ', 'ワ', 'ン', '゛', '゜' }; private static final char HANKAKU_KATAKANA_FIRST_CHAR = HANKAKU_KATAKANA[0]; private static final char HANKAKU_KATAKANA_LAST_CHAR = HANKAKU_KATAKANA[HANKAKU_KATAKANA.length - 1]; /** * 半角カタカナから全角カタカナへ変換します。 * * @param c * 変換前の文字 * @return 変換後の文字 */ public static char hankakuKatakanaToZenkakuKatakana(char c) { if (c >= HANKAKU_KATAKANA_FIRST_CHAR && c <= HANKAKU_KATAKANA_LAST_CHAR) { return ZENKAKU_KATAKANA[c - HANKAKU_KATAKANA_FIRST_CHAR]; } else { return c; } } public static char mergeChar(char c1, char c2) { if (c2 == '゙') { if ("カキクケコサシスセソタチツテトハヒフヘホ".indexOf(c1) > 0) { switch (c1) { case 'カ': return 'ガ'; case 'キ': return 'ギ'; case 'ク': return 'グ'; case 'ケ': return 'ゲ'; case 'コ': return 'ゴ'; case 'サ': return 'ザ'; case 'シ': return 'ジ'; case 'ス': return 'ズ'; case 'セ': return 'ゼ'; case 'ソ': return 'ゾ'; case 'タ': return 'ダ'; case 'チ': return 'ヂ'; case 'ツ': return 'ヅ'; case 'テ': return 'デ'; case 'ト': return 'ド'; case 'ハ': return 'バ'; case 'ヒ': return 'ビ'; case 'フ': return 'ブ'; case 'ヘ': return 'ベ'; case 'ホ': return 'ボ'; } } } else if (c2 == '゚') { if ("ハヒフヘホ".indexOf(c1) > 0) { switch (c1) { case 'ハ': return 'パ'; case 'ヒ': return 'ピ'; case 'フ': return 'プ'; case 'ヘ': return 'ペ'; case 'ホ': return 'ポ'; } } } return c1; } public static String hankakuKatakanaToZenkakuKatakana(String s) { if (s.length() == 0) { return s; } else if (s.length() == 1) { return hankakuKatakanaToZenkakuKatakana(s.charAt(0)) + ""; } else { StringBuffer sb = new StringBuffer(s); int i = 0; for (i = 0; i < sb.length() - 1; i++) { char originalChar1 = sb.charAt(i); char originalChar2 = sb.charAt(i + 1); char margedChar = mergeChar(originalChar1, originalChar2); if (margedChar != originalChar1) { sb.setCharAt(i, margedChar); sb.deleteCharAt(i + 1); } else { char convertedChar = hankakuKatakanaToZenkakuKatakana(originalChar1); if (convertedChar != originalChar1) { sb.setCharAt(i, convertedChar); } } } if (i < sb.length()) { char originalChar1 = sb.charAt(i); char convertedChar = hankakuKatakanaToZenkakuKatakana(originalChar1); if (convertedChar != originalChar1) { sb.setCharAt(i, convertedChar); } } return sb.toString(); } } public static String zenkakuHiraganaToZenkakuKatakana(String s) { StringBuffer sb = new StringBuffer(s); for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if (c >= 'ぁ' && c <= 'ん') { sb.setCharAt(i, (char) (c - 'ぁ' + 'ァ')); } } return sb.toString(); } public static String convertToKatakana(String s) { s = hankakuKatakanaToZenkakuKatakana(s); s = zenkakuHiraganaToZenkakuKatakana(s); return s; } }
yuukis/businessmap
src/com/github/yuukis/businessmap/util/StringJUtils.java
Java
apache-2.0
4,463
/******************************************************************************* * * Copyright 2011-2014 Spiffy UI Team * * 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 org.spiffyui.client.rest; /** * RESTility and the AuthUtil try to make login and authentication * transparent to the calling code. Most of the time this works well. * However, when we upload large files (like importing reports) we * can't make that call through RESTility and we need to know that a * login happened. This listener provides a mechanism to let us know * that happened. */ public interface RESTLoginCallBack { /** * Indicates that a login prompt happened. This is * separate from submitting the login or getting authenticated. */ void loginPrompt(); /** * Called when a login is successful * */ void onLoginSuccess(); }
spiffyui/spiffyui
spiffyui/src/main/java/org/spiffyui/client/rest/RESTLoginCallBack.java
Java
apache-2.0
1,518
"""Tests for the kraken sensor platform.""" from datetime import timedelta from unittest.mock import patch from pykrakenapi.pykrakenapi import KrakenAPIError from homeassistant.components.kraken.const import ( CONF_TRACKED_ASSET_PAIRS, DEFAULT_SCAN_INTERVAL, DEFAULT_TRACKED_ASSET_PAIR, DOMAIN, ) from homeassistant.const import CONF_SCAN_INTERVAL, EVENT_HOMEASSISTANT_START import homeassistant.util.dt as dt_util from .const import ( MISSING_PAIR_TICKER_INFORMATION_RESPONSE, MISSING_PAIR_TRADEABLE_ASSET_PAIR_RESPONSE, TICKER_INFORMATION_RESPONSE, TRADEABLE_ASSET_PAIR_RESPONSE, ) from tests.common import MockConfigEntry, async_fire_time_changed async def test_sensor(hass): """Test that sensor has a value.""" utcnow = dt_util.utcnow() # Patching 'utcnow' to gain more control over the timed update. with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch( "pykrakenapi.KrakenAPI.get_tradable_asset_pairs", return_value=TRADEABLE_ASSET_PAIR_RESPONSE, ), patch( "pykrakenapi.KrakenAPI.get_ticker_information", return_value=TICKER_INFORMATION_RESPONSE, ): entry = MockConfigEntry( domain=DOMAIN, unique_id="0123456789", options={ CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL, CONF_TRACKED_ASSET_PAIRS: [ "ADA/XBT", "ADA/ETH", "XBT/EUR", "XBT/GBP", "XBT/USD", "XBT/JPY", ], }, ) entry.add_to_hass(hass) registry = await hass.helpers.entity_registry.async_get_registry() # Pre-create registry entries for disabled by default sensors registry.async_get_or_create( "sensor", DOMAIN, "xbt_usd_ask_volume", suggested_object_id="xbt_usd_ask_volume", disabled_by=None, ) registry.async_get_or_create( "sensor", DOMAIN, "xbt_usd_last_trade_closed", suggested_object_id="xbt_usd_last_trade_closed", disabled_by=None, ) registry.async_get_or_create( "sensor", DOMAIN, "xbt_usd_bid_volume", suggested_object_id="xbt_usd_bid_volume", disabled_by=None, ) registry.async_get_or_create( "sensor", DOMAIN, "xbt_usd_volume_today", suggested_object_id="xbt_usd_volume_today", disabled_by=None, ) registry.async_get_or_create( "sensor", DOMAIN, "xbt_usd_volume_last_24h", suggested_object_id="xbt_usd_volume_last_24h", disabled_by=None, ) registry.async_get_or_create( "sensor", DOMAIN, "xbt_usd_volume_weighted_average_today", suggested_object_id="xbt_usd_volume_weighted_average_today", disabled_by=None, ) registry.async_get_or_create( "sensor", DOMAIN, "xbt_usd_volume_weighted_average_last_24h", suggested_object_id="xbt_usd_volume_weighted_average_last_24h", disabled_by=None, ) registry.async_get_or_create( "sensor", DOMAIN, "xbt_usd_number_of_trades_today", suggested_object_id="xbt_usd_number_of_trades_today", disabled_by=None, ) registry.async_get_or_create( "sensor", DOMAIN, "xbt_usd_number_of_trades_last_24h", suggested_object_id="xbt_usd_number_of_trades_last_24h", disabled_by=None, ) registry.async_get_or_create( "sensor", DOMAIN, "xbt_usd_low_last_24h", suggested_object_id="xbt_usd_low_last_24h", disabled_by=None, ) registry.async_get_or_create( "sensor", DOMAIN, "xbt_usd_high_last_24h", suggested_object_id="xbt_usd_high_last_24h", disabled_by=None, ) registry.async_get_or_create( "sensor", DOMAIN, "xbt_usd_opening_price_today", suggested_object_id="xbt_usd_opening_price_today", disabled_by=None, ) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() xbt_usd_sensor = hass.states.get("sensor.xbt_usd_ask") assert xbt_usd_sensor.state == "0.0003494" assert xbt_usd_sensor.attributes["icon"] == "mdi:currency-usd" xbt_eur_sensor = hass.states.get("sensor.xbt_eur_ask") assert xbt_eur_sensor.state == "0.0003494" assert xbt_eur_sensor.attributes["icon"] == "mdi:currency-eur" ada_xbt_sensor = hass.states.get("sensor.ada_xbt_ask") assert ada_xbt_sensor.state == "0.0003494" assert ada_xbt_sensor.attributes["icon"] == "mdi:currency-btc" xbt_jpy_sensor = hass.states.get("sensor.xbt_jpy_ask") assert xbt_jpy_sensor.state == "0.0003494" assert xbt_jpy_sensor.attributes["icon"] == "mdi:currency-jpy" xbt_gbp_sensor = hass.states.get("sensor.xbt_gbp_ask") assert xbt_gbp_sensor.state == "0.0003494" assert xbt_gbp_sensor.attributes["icon"] == "mdi:currency-gbp" ada_eth_sensor = hass.states.get("sensor.ada_eth_ask") assert ada_eth_sensor.state == "0.0003494" assert ada_eth_sensor.attributes["icon"] == "mdi:cash" xbt_usd_ask_volume = hass.states.get("sensor.xbt_usd_ask_volume") assert xbt_usd_ask_volume.state == "15949" xbt_usd_last_trade_closed = hass.states.get("sensor.xbt_usd_last_trade_closed") assert xbt_usd_last_trade_closed.state == "0.0003478" xbt_usd_bid_volume = hass.states.get("sensor.xbt_usd_bid_volume") assert xbt_usd_bid_volume.state == "20792" xbt_usd_volume_today = hass.states.get("sensor.xbt_usd_volume_today") assert xbt_usd_volume_today.state == "146300.24906838" xbt_usd_volume_last_24h = hass.states.get("sensor.xbt_usd_volume_last_24h") assert xbt_usd_volume_last_24h.state == "253478.04715403" xbt_usd_volume_weighted_average_today = hass.states.get( "sensor.xbt_usd_volume_weighted_average_today" ) assert xbt_usd_volume_weighted_average_today.state == "0.000348573" xbt_usd_volume_weighted_average_last_24h = hass.states.get( "sensor.xbt_usd_volume_weighted_average_last_24h" ) assert xbt_usd_volume_weighted_average_last_24h.state == "0.000344881" xbt_usd_number_of_trades_today = hass.states.get( "sensor.xbt_usd_number_of_trades_today" ) assert xbt_usd_number_of_trades_today.state == "82" xbt_usd_number_of_trades_last_24h = hass.states.get( "sensor.xbt_usd_number_of_trades_last_24h" ) assert xbt_usd_number_of_trades_last_24h.state == "128" xbt_usd_low_last_24h = hass.states.get("sensor.xbt_usd_low_last_24h") assert xbt_usd_low_last_24h.state == "0.0003446" xbt_usd_high_last_24h = hass.states.get("sensor.xbt_usd_high_last_24h") assert xbt_usd_high_last_24h.state == "0.0003521" xbt_usd_opening_price_today = hass.states.get( "sensor.xbt_usd_opening_price_today" ) assert xbt_usd_opening_price_today.state == "0.0003513" async def test_missing_pair_marks_sensor_unavailable(hass): """Test that a missing tradable asset pair marks the sensor unavailable.""" utcnow = dt_util.utcnow() # Patching 'utcnow' to gain more control over the timed update. with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch( "pykrakenapi.KrakenAPI.get_tradable_asset_pairs", return_value=TRADEABLE_ASSET_PAIR_RESPONSE, ) as tradeable_asset_pairs_mock, patch( "pykrakenapi.KrakenAPI.get_ticker_information", return_value=TICKER_INFORMATION_RESPONSE, ) as ticket_information_mock: entry = MockConfigEntry( domain=DOMAIN, options={ CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL, CONF_TRACKED_ASSET_PAIRS: [DEFAULT_TRACKED_ASSET_PAIR], }, ) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() sensor = hass.states.get("sensor.xbt_usd_ask") assert sensor.state == "0.0003494" tradeable_asset_pairs_mock.return_value = ( MISSING_PAIR_TRADEABLE_ASSET_PAIR_RESPONSE ) ticket_information_mock.side_effect = KrakenAPIError( "EQuery:Unknown asset pair" ) async_fire_time_changed( hass, utcnow + timedelta(seconds=DEFAULT_SCAN_INTERVAL * 2) ) await hass.async_block_till_done() ticket_information_mock.side_effect = None ticket_information_mock.return_value = MISSING_PAIR_TICKER_INFORMATION_RESPONSE async_fire_time_changed( hass, utcnow + timedelta(seconds=DEFAULT_SCAN_INTERVAL * 2) ) await hass.async_block_till_done() sensor = hass.states.get("sensor.xbt_usd_ask") assert sensor.state == "unavailable"
lukas-hetzenecker/home-assistant
tests/components/kraken/test_sensor.py
Python
apache-2.0
9,736
var nock = require('nock') //, sinon = require('sinon') , chai = require('chai') , fixtures = require('./portal-fixtures') , EsriPortal = require('../index'); var expect = chai.expect; var scope; var prodUrl = 'https://www.arcgis.com'; describe('search ', function () { beforeEach(function() { ago = new EsriPortal(); }); afterEach(function() { nock.cleanAll() }); it("encodes the query string", function(done) { var options = {query:'title:"San Francisco" AND type:"layer package"'}; scope = nock(prodUrl) //.log(console.log) .get('/sharing/rest/search?q=title%3A%22San%20Francisco%22%20AND%20type%3A%22layer%20package%22&f=json') .reply(200, {}); ago.search(options) .then(function(selfJson){ scope.done(); done(); }) .done(); }); it("accepts a simple query string", function(done) { var options = {query:'colorado'}; scope = nock(prodUrl) .get('/sharing/rest/search?q=colorado&f=json') .reply(200, {}); ago.search(options) .then(function(selfJson){ scope.done(); done(); }) .done(); }); it("accepts start", function(done) { var options = { query:'colorado', start:12 }; scope = nock(prodUrl) .get('/sharing/rest/search?q=colorado&start=12&f=json') .reply(200, {}); ago.search(options) .then(function(selfJson){ scope.done(); done(); }) .done(); }); it("accepts num", function(done) { var options = { query:'colorado', num:45 }; scope = nock(prodUrl) .get('/sharing/rest/search?q=colorado&num=45&f=json') .reply(200, {}); ago.search(options) .then(function(selfJson){ scope.done(); done(); }) .done(); }); it("accepts sortOrder", function(done) { var options = { query:'colorado', sortOrder:'asc' }; scope = nock(prodUrl) .get('/sharing/rest/search?q=colorado&sortOrder=asc&f=json') .reply(200, {}); ago.search(options) .then(function(selfJson){ scope.done(); done(); }) .done(); }); it("accepts sortField", function(done) { var options = { query:'colorado', sortField:'title' }; scope = nock(prodUrl) .get('/sharing/rest/search?q=colorado&sortField=title&f=json') .reply(200, {}); ago.search(options) .then(function(selfJson){ scope.done(); done(); }) .done(); }); it("accepts a token", function(done) { var options = { query:'colorado', token:'sometoken' }; scope = nock(prodUrl) .get('/sharing/rest/search?q=colorado&token=sometoken&f=json') .reply(200, {}); ago.search(options) .then(function(selfJson){ scope.done(); done(); }) .done(); }); it("accepts everything", function(done) { var options = { query:'colorado', sortOrder:'asc', sortField:'title', num:10, start:100, token:'sometoken' }; scope = nock(prodUrl) .get('/sharing/rest/search?q=colorado&start=100&num=10&sortField=title&sortOrder=asc&token=sometoken&f=json') .reply(200, {}); ago.search(options) .then(function(selfJson){ scope.done(); done(); }) .done(); }); });
dbouwman/esri-portal-api
test/search.spec.js
JavaScript
apache-2.0
3,577
# Cochlearia lancifolia Stokes SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Cochlearia/Cochlearia lancifolia/README.md
Markdown
apache-2.0
178
# Opuntia zacana Howell SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Opuntia/Opuntia zacana/README.md
Markdown
apache-2.0
171
# Stilpnopappus pratensis var. crotonifolius Mart. ex DC. VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Stilpnopappus pratensis/Stilpnopappus pratensis crotonifolius/README.md
Markdown
apache-2.0
205
# Carpocanistrum cephalum Haeckel, 1887 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Haeckel, E. (1887). Report on the Radiolaria collected by H. M. S. Challenger during the years 1873-76. London: Eyre & Spottiswoode. #### Original name null ### Remarks null
mdoering/backbone
life/Chromista/Radiozoa/Nassellaria/Carpocaniidae/Carpocanistrum/Carpocanistrum cephalum/README.md
Markdown
apache-2.0
323
# Porphyra augustinae Kützing SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Rhodophyta/Bangiophyceae/Bangiales/Bangiaceae/Porphyra/Porphyra augustinae/README.md
Markdown
apache-2.0
186
# Marasmius schulzeri Quél. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Marasmius schulzeri Quél. ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Marasmiaceae/Marasmius/Marasmius schulzeri/README.md
Markdown
apache-2.0
181
/** * Copyright 2017 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ import {camelCaseToTitleCase, setStyle} from '../../src/style'; import {isObject} from '../../src/types'; import {loadScript} from '../../3p/3p'; import {tryParseJson} from '../../src/json'; /** * Possible player states. * @enum {number} * @private */ const PlayerStates = { PLAYING: 1, PAUSED: 2, }; /*eslint-disable */ const icons = { 'play': `<path d="M8 5v14l11-7z"></path> <path d="M0 0h24v24H0z" fill="none"></path>`, 'pause': `<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"></path> <path d="M0 0h24v24H0z" fill="none"></path>`, 'fullscreen': `<path d="M0 0h24v24H0z" fill="none"/> <path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>`, 'mute': `<path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"></path> <path d="M0 0h24v24H0z" fill="none"></path>`, 'volume_max': `<path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"></path> <path d="M0 0h24v24H0z" fill="none"></path>`, 'seek': `<circle cx="12" cy="12" r="12" />`, } const controlsBg = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAABkCAQAAADtJZLrAAAAQklEQVQY03WOwQoAIAxC1fX/v1yHaCgVeHg6wWFCAEABJl7glgZtmVaHZYmDjpxblVCfZPPIhHl9NntovBaZnf12LeWZAm6dMYNCAAAAAElFTkSuQmCC'; /*eslint-enable */ // Div wrapping our entire DOM. let wrapperDiv; // Div containing big play button. Rendered before player starts. let bigPlayDiv; // Div contianing play button. Double-nested for alignment. let playButtonDiv; // Div containing player controls. let controlsDiv; // Div containing play or pause button. let playPauseDiv; // Div containing player time. let timeDiv; // Node containing the player time text. let timeNode; // Wrapper for progress bar DOM elements. let progressBarWrapperDiv; // Line for progress bar. let progressLine; // Line for total time in progress bar. let totalTimeLine; // Div containing the marker for the progress. let progressMarkerDiv; // Div for fullscreen icon. let fullscreenDiv; // Div for ad container. let adContainerDiv; // Div for content player. let contentDiv; // Content player. let videoPlayer; // Event indicating user interaction. let interactEvent; // Event for mouse down. let mouseDownEvent; // Event for mouse move. let mouseMoveEvent; // Event for mouse up. let mouseUpEvent; // Percent of the way through the video the user has seeked. Used for seek // events. let seekPercent; // Flag tracking whether or not content has played to completion. let contentComplete; // Flag tracking if an ad request has failed. let adRequestFailed; // IMA SDK AdDisplayContainer object. let adDisplayContainer; // IMA SDK AdsLoader object. let adsLoader; // IMA SDK AdsManager object; let adsManager; // Timer for UI updates. let uiTicker; // Tracks the current state of the player. let playerState; // Flag for whether or not we are currently in fullscreen mode. let fullscreen; // Width the player should be in fullscreen mode. let fullscreenWidth; // Height the player should be in fullscreen mode. let fullscreenHeight; // Flag tracking if ads are currently active. let adsActive; // Flag tracking if playback has started. let playbackStarted; // Timer used to hide controls after user action. let hideControlsTimeout; // Flag tracking if we need to mute the ads manager once it loads. Used for // autoplay. let muteAdsManagerOnLoaded; // Flag tracking if we are in native fullscreen mode. Used for iPhone. let nativeFullscreen; // Used if the adsManager needs to be resized on load. let adsManagerWidthOnLoad, adsManagerHeightOnLoad; // Initial video dimensions. let videoWidth, videoHeight; // IMASettings provided via <script> tag in parent element. let imaSettings; /** * Loads the IMA SDK library. */ function getIma(global, cb) { loadScript(global, 'https://imasdk.googleapis.com/js/sdkloader/ima3.js', cb); //loadScript(global, 'https://storage.googleapis.com/gvabox/sbusolits/h5/debug/ima3.js', cb); } /** * The business. */ export function imaVideo(global, data) { videoWidth = global./*OK*/innerWidth; videoHeight = global./*OK*/innerHeight; // Wraps *everything*. wrapperDiv = global.document.createElement('div'); wrapperDiv.id = 'ima-wrapper'; setStyle(wrapperDiv, 'width', videoWidth + 'px'); setStyle(wrapperDiv, 'height', videoHeight + 'px'); setStyle(wrapperDiv, 'background-color', 'black'); // Wraps the big play button we show before video start. bigPlayDiv = global.document.createElement('div'); bigPlayDiv.id = 'ima-big-play'; setStyle(bigPlayDiv, 'position', 'relative'); setStyle(bigPlayDiv, 'width', videoWidth + 'px'); setStyle(bigPlayDiv, 'height', videoHeight + 'px'); setStyle(bigPlayDiv, 'display', 'table-cell'); setStyle(bigPlayDiv, 'vertical-align', 'middle'); setStyle(bigPlayDiv, 'text-align', 'center'); setStyle(bigPlayDiv, 'cursor', 'pointer'); // Inner div so we can v and h align. playButtonDiv = createIcon(global, 'play'); playButtonDiv.id = 'ima-play-button'; setStyle(playButtonDiv, 'display', 'inline-block'); setStyle(playButtonDiv, 'max-width', '120px'); setStyle(playButtonDiv, 'max-height', '120px'); bigPlayDiv.appendChild(playButtonDiv); // Video controls. controlsDiv = global.document.createElement('div'); controlsDiv.id = 'ima-controls'; setStyle(controlsDiv, 'position', 'absolute'); setStyle(controlsDiv, 'bottom', '0px'); setStyle(controlsDiv, 'width', '100%'); setStyle(controlsDiv, 'height', '100px'); setStyle(controlsDiv, 'box-sizing', 'border-box'); setStyle(controlsDiv, 'padding', '10px'); setStyle(controlsDiv, 'padding-top', '60px'); setStyle(controlsDiv, 'background-image', 'url(' + controlsBg + ')'); setStyle(controlsDiv, 'background-position', 'bottom'); setStyle(controlsDiv, 'color', 'white'); setStyle(controlsDiv, 'display', 'none'); setStyle(controlsDiv, 'justify-content', 'center'); setStyle(controlsDiv, 'align-items', 'center'); setStyle(controlsDiv, '-webkit-touch-callout', 'none'); setStyle(controlsDiv, '-webkit-user-select', 'none'); setStyle(controlsDiv, '-khtml-user-select', 'none'); setStyle(controlsDiv, '-moz-user-select', 'none'); setStyle(controlsDiv, '-ms-user-select', 'none'); setStyle(controlsDiv, 'user-select', 'none'); // Play button playPauseDiv = createIcon(global, 'play'); playPauseDiv.id = 'ima-play-pause'; setStyle(playPauseDiv, 'width', '30px'); setStyle(playPauseDiv, 'height', '30px'); setStyle(playPauseDiv, 'margin-right', '20px'); setStyle(playPauseDiv, 'font-size', '1.25em'); setStyle(playPauseDiv, 'cursor', 'pointer'); controlsDiv.appendChild(playPauseDiv); // Current time and duration. timeDiv = global.document.createElement('div'); timeDiv.id = 'ima-time'; setStyle(timeDiv, 'margin-right', '20px'); setStyle(timeDiv, 'text-align', 'center'); setStyle(timeDiv, 'font-family', 'Helvetica, Arial, Sans-serif'); setStyle(timeDiv, 'font-size', '14px'); setStyle(timeDiv, 'text-shadow', '0px 0px 10px black'); timeNode = global.document.createTextNode('-:- / 0:00'); timeDiv.appendChild(timeNode); controlsDiv.appendChild(timeDiv); // Progress bar. progressBarWrapperDiv = global.document.createElement('div'); progressBarWrapperDiv.id = 'ima-progress-wrapper'; setStyle(progressBarWrapperDiv, 'height', '30px'); setStyle(progressBarWrapperDiv, 'flex-grow', '1'); setStyle(progressBarWrapperDiv, 'position', 'relative'); setStyle(progressBarWrapperDiv, 'margin-right', '20px'); progressLine = global.document.createElement('div'); progressLine.id = 'progress-line'; setStyle(progressLine, 'background-color', 'rgb(255, 255, 255)'); setStyle(progressLine, 'height', '2px'); setStyle(progressLine, 'margin-top', '14px'); setStyle(progressLine, 'width', '0%'); setStyle(progressLine, 'float', 'left'); totalTimeLine = global.document.createElement('div'); totalTimeLine.id = 'total-time-line'; setStyle(totalTimeLine, 'background-color', 'rgba(255, 255, 255, 0.45)'); setStyle(totalTimeLine, 'height', '2px'); setStyle(totalTimeLine, 'width', '100%'); setStyle(totalTimeLine, 'margin-top', '14px'); progressMarkerDiv = global.document.createElement('div'); progressMarkerDiv.id = 'ima-progress-marker'; setStyle(progressMarkerDiv, 'height', '14px'); setStyle(progressMarkerDiv, 'width', '14px'); setStyle(progressMarkerDiv, 'position', 'absolute'); setStyle(progressMarkerDiv, 'left', '0%'); setStyle(progressMarkerDiv, 'top', '50%'); setStyle(progressMarkerDiv, 'margin-top', '-7px'); setStyle(progressMarkerDiv, 'cursor', 'pointer'); progressMarkerDiv.appendChild(createIcon(global, 'seek')); progressBarWrapperDiv.appendChild(progressLine); progressBarWrapperDiv.appendChild(progressMarkerDiv); progressBarWrapperDiv.appendChild(totalTimeLine); controlsDiv.appendChild(progressBarWrapperDiv); // Fullscreen button fullscreenDiv = createIcon(global, 'fullscreen'); fullscreenDiv.id = 'ima-fullscreen'; setStyle(fullscreenDiv, 'width', '30px'); setStyle(fullscreenDiv, 'height', '30px'); setStyle(fullscreenDiv, 'font-size', '1.25em'); setStyle(fullscreenDiv, 'cursor', 'pointer'); setStyle(fullscreenDiv, 'text-align', 'center'); setStyle(fullscreenDiv, 'font-weight', 'bold'); setStyle(fullscreenDiv, 'line-height', '1.4em'); controlsDiv.appendChild(fullscreenDiv); // Ad container. adContainerDiv = global.document.createElement('div'); adContainerDiv.id = 'ima-ad-container'; setStyle(adContainerDiv, 'position', 'absolute'); setStyle(adContainerDiv, 'top', '0px'); setStyle(adContainerDiv, 'left', '0px'); setStyle(adContainerDiv, 'width', '100%'); setStyle(adContainerDiv, 'height', '100%'); // Wraps our content video. contentDiv = global.document.createElement('div'); contentDiv.id = 'ima-content'; setStyle(contentDiv, 'position', 'absolute'); setStyle(contentDiv, 'top', '0px'); setStyle(contentDiv, 'left', '0px'); setStyle(contentDiv, 'width', '100%'); setStyle(contentDiv, 'height', '100%'); // The video player videoPlayer = global.document.createElement('video'); videoPlayer.id = 'ima-content-player'; setStyle(videoPlayer, 'width', '100%'); setStyle(videoPlayer, 'height', '100%'); setStyle(videoPlayer, 'background-color', 'black'); videoPlayer.setAttribute('poster', data.poster); videoPlayer.setAttribute('playsinline', true); if (data.src) { const sourceElement = document.createElement('source'); sourceElement.setAttribute('src', data.src); videoPlayer.appendChild(sourceElement); } if (data.childElements) { const children = JSON.parse(data.childElements); children.forEach(child => { videoPlayer.appendChild(htmlToElement(child)); }); } if (data.imaSettings) { imaSettings = tryParseJson(data.imaSettings); } contentDiv.appendChild(videoPlayer); wrapperDiv.appendChild(contentDiv); wrapperDiv.appendChild(adContainerDiv); wrapperDiv.appendChild(controlsDiv); wrapperDiv.appendChild(bigPlayDiv); global.document.getElementById('c').appendChild(wrapperDiv); window.addEventListener('message', onMessage.bind(null, global)); /** * Set-up code that can't run until the IMA lib loads. */ getIma(global, function() { // This is the first place where we have access to any IMA objects. contentComplete = false; adsActive = false; playbackStarted = false; nativeFullscreen = false; interactEvent = 'click'; mouseDownEvent = 'mousedown'; mouseMoveEvent = 'mousemove'; mouseUpEvent = 'mouseup'; if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/Android/i)) { interactEvent = 'touchend'; mouseDownEvent = 'touchstart'; mouseMoveEvent = 'touchmove'; mouseUpEvent = 'touchend'; } bigPlayDiv.addEventListener(interactEvent, onClick.bind(null, global)); playPauseDiv.addEventListener(interactEvent, onPlayPauseClick); progressBarWrapperDiv.addEventListener(mouseDownEvent, onProgressClick); fullscreenDiv.addEventListener(interactEvent, onFullscreenClick.bind(null, global)); const fullScreenEvents = [ 'fullscreenchange', 'mozfullscreenchange', 'webkitfullscreenchange']; fullScreenEvents.forEach(fsEvent => { global.document.addEventListener(fsEvent, onFullscreenChange.bind(null, global), false); }); // Handle settings that need to be set before the AdDisplayContainer is // created. if (imaSettings) { if (imaSettings['locale']) { global.google.ima.settings.setLocale(imaSettings['locale']); } if (imaSettings['vpaidMode']) { global.google.ima.settings.setVpaidMode(imaSettings['vpaidMode']); } } adDisplayContainer = new global.google.ima.AdDisplayContainer(adContainerDiv, videoPlayer); adsLoader = new global.google.ima.AdsLoader(adDisplayContainer); adsLoader.getSettings().setPlayerType('amp-ima'); adsLoader.getSettings().setPlayerVersion('0.1'); // Propogate settings provided via child script tag. // locale and vpaidMode are set above, as they must be set before we create // an AdDisplayContainer. // playerType and playerVersion are used by the developers to track usage, // so we do not want to allow users to overwrite those values. const skippedSettings = ['locale', 'vpaidMode', 'playerType', 'playerVersion']; for (const setting in imaSettings) { if (!skippedSettings.includes(setting)) { // Change e.g. 'ppid' to 'setPpid'. const methodName = 'set' + camelCaseToTitleCase(setting); if (typeof adsLoader.getSettings()[methodName] === 'function') { adsLoader.getSettings()[methodName](imaSettings[setting]); } } } adsLoader.addEventListener( global.google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, onAdsManagerLoaded.bind(null, global), false); adsLoader.addEventListener( global.google.ima.AdErrorEvent.Type.AD_ERROR, onAdsLoaderError, false); videoPlayer.addEventListener('ended', onContentEnded); const adsRequest = new global.google.ima.AdsRequest(); adsRequest.adTagUrl = data.tag; adsRequest.linearAdSlotWidth = videoWidth; adsRequest.linearAdSlotHeight = videoHeight; adsRequest.nonLinearAdSlotWidth = videoWidth; adsRequest.nonLinearAdSlotHeight = videoHeight / 3; adRequestFailed = false; adsLoader.requestAds(adsRequest); }); } function htmlToElement(html) { const template = document.createElement('template'); template./*OK*/innerHTML = html; return template.content.firstChild; } function createIcon(global, name, fill = '#FFFFFF') { const doc = global.document; const icon = doc.createElementNS('http://www.w3.org/2000/svg', 'svg'); icon.setAttributeNS(null, 'fill', fill); icon.setAttributeNS(null, 'height', '100%'); icon.setAttributeNS(null, 'width', '100%'); icon.setAttributeNS(null, 'viewBox', '0 0 24 24'); setStyle(icon, 'filter', 'drop-shadow(0px 0px 14px rgba(0,0,0,0.4))'); setStyle(icon, '-webkit-filter', 'drop-shadow(0px 0px 14px rgba(0,0,0,0.4))'); icon./*OK*/innerHTML = icons[name]; return icon; } function changeIcon(element, name, fill = '#FFFFFF') { element./*OK*/innerHTML = icons[name]; if (fill != element.getAttributeNS(null, 'fill')) { element.setAttributeNS(null, 'fill', fill); } } /** * Triggered when the user clicks on the big play button div. * * @visibleForTesting */ export function onClick(global) { playbackStarted = true; uiTicker = setInterval(uiTickerClick, 500); bigPlayDiv.removeEventListener(interactEvent, onClick); setStyle(bigPlayDiv, 'display', 'none'); adDisplayContainer.initialize(); videoPlayer.load(); playAds(global); } /** * Starts ad playback. If the ad request has not yte resolved, calls itself * again after 250ms. * * @visibleForTesting */ export function playAds(global) { if (adsManager) { // Ad request resolved. try { adsManager.init( videoWidth, videoHeight, global.google.ima.ViewMode.NORMAL); window.parent./*OK*/postMessage({event: VideoEvents.PLAYING}, '*'); adsManager.start(); } catch (adError) { window.parent./*OK*/postMessage({event: VideoEvents.PLAYING}, '*'); playVideo(); } } else if (!adRequestFailed) { // Ad request did not yet resolve but also did not yet fail. setTimeout(playAds.bind(null, global), 250); } else { // Ad request failed. window.parent./*OK*/postMessage({event: VideoEvents.PLAYING}, '*'); playVideo(); } } /** * Called when the content completes. * * @visibleForTesting */ export function onContentEnded() { contentComplete = true; adsLoader.contentComplete(); } /** * Called when the IMA SDK has an AdsManager ready for us. * * @visibleForTesting */ export function onAdsManagerLoaded(global, adsManagerLoadedEvent) { const adsRenderingSettings = new global.google.ima.AdsRenderingSettings(); adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true; adsRenderingSettings.uiElements = [global.google.ima.UiElements.AD_ATTRIBUTION, global.google.ima.UiElements.COUNTDOWN]; adsManager = adsManagerLoadedEvent.getAdsManager(videoPlayer, adsRenderingSettings); adsManager.addEventListener(global.google.ima.AdErrorEvent.Type.AD_ERROR, onAdError); adsManager.addEventListener( global.google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, onContentPauseRequested.bind(null, global)); adsManager.addEventListener( global.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, onContentResumeRequested); if (muteAdsManagerOnLoaded) { adsManager.setVolume(0); } window.parent./*OK*/postMessage({event: VideoEvents.LOAD}, '*'); } /** * Called when we encounter an error trying to load ads. * * @visibleForTesting */ export function onAdsLoaderError() { adRequestFailed = true; playVideo(); } /** * Called when we encounter an error trying to play ads. * * @visibleForTesting */ export function onAdError() { if (adsManager) { adsManager.destroy(); } playVideo(); } /** * Called by the IMA SDK. Pauses the content and readies the player for ads. * * @visibleForTesting */ export function onContentPauseRequested(global) { if (adsManagerWidthOnLoad) { adsManager.resize( adsManagerWidthOnLoad, adsManagerHeightOnLoad, global.google.ima.ViewMode.NORMAL); adsManagerWidthOnLoad = null; adsManagerHeightOnLoad = null; } adsActive = true; videoPlayer.removeEventListener(interactEvent, showControls); setStyle(adContainerDiv, 'display', 'block'); videoPlayer.removeEventListener('ended', onContentEnded); hideControls(); videoPlayer.pause(); } /** * Called by the IMA SDK. Resumes content after an ad break. * * @visibleForTesting */ export function onContentResumeRequested() { adsActive = false; videoPlayer.addEventListener(interactEvent, showControls); if (!contentComplete) { // CONTENT_RESUME will fire after post-rolls as well, and we don't want to // resume content in that case. videoPlayer.addEventListener('ended', onContentEnded); playVideo(); } } /** * Called when our ui timer goes off. Updates the player UI. */ function uiTickerClick() { updateUi(videoPlayer.currentTime, videoPlayer.duration); } /** * Updates the video player UI. * * @visibleForTesting */ export function updateUi(currentTime, duration) { timeNode.textContent = formatTime(currentTime) + ' / ' + formatTime(duration); const progressPercent = Math.floor((currentTime / duration) * 100); setStyle(progressLine, 'width', progressPercent + '%'); setStyle(progressMarkerDiv, 'left', (progressPercent - 1) + '%'); } /** * Formats an int in seconds into a string of the format X:XX:XX. Omits the * hour if the content is less than one hour. * * @visibleForTesting */ export function formatTime(time) { if (isNaN(time)) { return '0:00'; } let timeString = ''; const hours = Math.floor(time / 3600); if (hours > 0) { timeString += hours + ':'; } const minutes = Math.floor((time % 3600) / 60); if (hours > 0) { timeString += zeroPad(minutes) + ':'; } else { timeString += minutes + ':'; } const seconds = Math.floor(time - ((hours * 3600) + (minutes * 60))); timeString += zeroPad(seconds); return timeString; } /** * Zero-pads the provided int and returns a string of length 2. * * @visibleForTesting */ export function zeroPad(input) { input = String(input); return input.length == 1 ? '0' + input : input; } /** * Detects clicks on the progress bar. */ function onProgressClick(event) { // Call this logic once to make sure we still seek if the user just clicks // instead of clicking and dragging. clearInterval(hideControlsTimeout); onProgressMove(event); clearInterval(uiTicker); document.addEventListener(mouseMoveEvent, onProgressMove); document.addEventListener(mouseUpEvent, onProgressClickEnd); } /** * Detects the end of interaction on the progress bar. */ function onProgressClickEnd() { document.removeEventListener(mouseMoveEvent, onProgressMove); document.removeEventListener(mouseUpEvent, onProgressClickEnd); uiTicker = setInterval(uiTickerClick, 500); videoPlayer.currentTime = videoPlayer.duration * seekPercent; // Reset hide controls timeout. showControls(); } /** * Detects when the user clicks and drags on the progress bar. */ function onProgressMove(event) { const progressWrapperPosition = getPagePosition(progressBarWrapperDiv); const progressListStart = progressWrapperPosition.x; const progressListWidth = progressBarWrapperDiv./*OK*/offsetWidth; // Handle Android Chrome touch events. const eventX = event.clientX || event.touches[0].pageX; seekPercent = (eventX - progressListStart) / progressListWidth; if (seekPercent < 0) { seekPercent = 0; } else if (seekPercent > 1) { seekPercent = 1; } updateUi(videoPlayer.duration * seekPercent, videoPlayer.duration); } /** * Returns the x,y coordinates of the given element relative to the window. */ function getPagePosition(el) { let lx, ly; for (lx = 0, ly = 0; el != null; lx += el./*OK*/offsetLeft, ly += el./*OK*/offsetTop, el = el./*OK*/offsetParent) {}; return {x: lx,y: ly}; } /** * Called when the user clicks on the play / pause button. * * @visibleForTesting */ export function onPlayPauseClick() { if (playerState == PlayerStates.PLAYING) { pauseVideo(null); } else { playVideo(); } } /** * Plays the content video. * * @visibleForTesting */ export function playVideo() { setStyle(adContainerDiv, 'display', 'none'); playerState = PlayerStates.PLAYING; // Kick off the hide controls timer. showControls(); changeIcon(playPauseDiv, 'pause'); window.parent./*OK*/postMessage({event: VideoEvents.PLAYING}, '*'); videoPlayer.play(); } /** * Pauses the video player. * * @visibleForTesting */ export function pauseVideo(event) { videoPlayer.pause(); playerState = PlayerStates.PAUSED; // Show controls and keep them there because we're paused. clearInterval(hideControlsTimeout); if (!adsActive) { showControls(); } changeIcon(playPauseDiv, 'play'); window.parent./*OK*/postMessage({event: VideoEvents.PAUSE}, '*'); if (event && event.type == 'webkitendfullscreen') { // Video was paused because we exited fullscreen. videoPlayer.removeEventListener('webkitendfullscreen', pauseVideo); } } /** * Called when the user clicks on the fullscreen button. Makes the video player * fullscreen */ function onFullscreenClick(global) { if (fullscreen) { // The video is currently in fullscreen mode const cancelFullscreen = global.document.exitFullscreen || global.document.exitFullScreen || global.document.webkitCancelFullScreen || global.document.mozCancelFullScreen; if (cancelFullscreen) { cancelFullscreen.call(document); } } else { // Try to enter fullscreen mode in the browser const requestFullscreen = global.document.documentElement.requestFullscreen || global.document.documentElement.webkitRequestFullscreen || global.document.documentElement.mozRequestFullscreen || global.document.documentElement.requestFullScreen || global.document.documentElement.webkitRequestFullScreen || global.document.documentElement.mozRequestFullScreen; if (requestFullscreen) { fullscreenWidth = window.screen.width; fullscreenHeight = window.screen.height; requestFullscreen.call(global.document.documentElement); } else { // Figure out how to make iPhone fullscren work here - I've got nothing. videoPlayer.webkitEnterFullscreen(); // Pause the video when we leave fullscreen. iPhone does this // automatically, but we still use pauseVideo as an event handler to // sync the UI. videoPlayer.addEventListener('webkitendfullscreen', pauseVideo); nativeFullscreen = true; onFullscreenChange(global); } } } /** * Called when the fullscreen mode of the browser or content player changes. */ function onFullscreenChange(global) { if (fullscreen) { // Resize the ad container adsManager.resize( videoWidth, videoHeight, global.google.ima.ViewMode.NORMAL); adsManagerWidthOnLoad = null; adsManagerHeightOnLoad = null; // Return the video to its original size and position setStyle(wrapperDiv, 'width', videoWidth + 'px'); setStyle(wrapperDiv, 'height', videoHeight + 'px'); fullscreen = false; } else { // The user just entered fullscreen if (!nativeFullscreen) { // Resize the ad container adsManager.resize( fullscreenWidth, fullscreenHeight, global.google.ima.ViewMode.FULLSCREEN); adsManagerWidthOnLoad = null; adsManagerHeightOnLoad = null; // Make the video take up the entire screen setStyle(wrapperDiv, 'width', fullscreenWidth + 'px'); setStyle(wrapperDiv, 'height', fullscreenHeight + 'px'); hideControls(); } fullscreen = true; } } /** * Show video controls and reset hide controls timeout. * * @visibleForTesting */ export function showControls() { setStyle(controlsDiv, 'display', 'flex'); // Hide controls after 3 seconds if (playerState == PlayerStates.PLAYING) { // Reset hide controls timer. clearInterval(hideControlsTimeout); hideControlsTimeout = setTimeout(hideControls, 3000); } } /** * Hide video controls. * * @visibleForTesting */ export function hideControls() { setStyle(controlsDiv, 'display', 'none'); } /** * Handles messages from the top window. */ function onMessage(global, event) { const msg = isObject(event.data) ? event.data : tryParseJson(event.data); if (msg === undefined) { return; // We only process valid JSON. } if (msg.event && msg.func) { switch (msg.func) { case 'playVideo': if (adsActive) { adsManager.resume(); window.parent./*OK*/postMessage({event: VideoEvents.PLAYING}, '*'); } else if (playbackStarted) { playVideo(); } else { // Auto-play support onClick(global); } break; case 'pauseVideo': if (adsActive) { adsManager.pause(); window.parent./*OK*/postMessage({event: VideoEvents.PAUSE}, '*'); } else if (playbackStarted) { pauseVideo(null); } break; case 'mute': videoPlayer.volume = 0; videoPlayer.muted = true; if (adsManager) { adsManager.setVolume(0); } else { muteAdsManagerOnLoaded = true; } window.parent./*OK*/postMessage({event: VideoEvents.MUTED}, '*'); break; case 'unMute': videoPlayer.volume = 1; videoPlayer.muted = false; if (adsManager) { adsManager.setVolume(1); } else { muteAdsManagerOnLoaded = false; } window.parent./*OK*/postMessage({event: VideoEvents.UNMUTED}, '*'); break; case 'resize': if (msg.args && msg.args.width && msg.args.height) { setStyle(wrapperDiv, 'width', msg.args.width + 'px'); setStyle(wrapperDiv, 'height', msg.args.height + 'px'); setStyle(bigPlayDiv, 'width', msg.args.width + 'px'); setStyle(bigPlayDiv, 'height', msg.args.height + 'px'); if (adsActive) { adsManager.resize( msg.args.width, msg.args.height, global.google.ima.ViewMode.NORMAL); } else { adsManagerWidthOnLoad = msg.args.width; adsManagerHeightOnLoad = msg.args.height; } } break; } } } /** * Returns the properties we need to access for testing. * * @visibleForTesting */ export function getPropertiesForTesting() { return {adContainerDiv, adRequestFailed, adsActive, adsManagerWidthOnLoad, adsManagerHeightOnLoad, contentComplete, controlsDiv, hideControlsTimeout, interactEvent, playbackStarted, playerState, PlayerStates, playPauseDiv, progressLine, progressMarkerDiv, timeNode, uiTicker, videoPlayer}; } /** * Sets the big play button div. * * @visibleForTesting */ export function setBigPlayDivForTesting(div) { bigPlayDiv = div; } /** * Sets the ad display container. * * @visibleForTesting */ export function setAdDisplayContainerForTesting(adc) { adDisplayContainer = adc; } /** * Sets the video width and height. * * @visibleForTesting */ export function setVideoWidthAndHeightForTesting(width, height) { videoWidth = width; videoHeight = height; } /** * Sets the ad request failed flag. * * @visibleForTesting */ export function setAdRequestFailedForTesting(newValue) { adRequestFailed = newValue; } /** * Sets the ads loader. * * @visibleForTesting */ export function setAdsLoaderForTesting(newAdsLoader) { adsLoader = newAdsLoader; } /** * Sets the flag to mute the ads manager when it loads. * * @visibleForTesting */ export function setMuteAdsManagerOnLoadedForTesting(shouldMute) { muteAdsManagerOnLoaded = shouldMute; } /** * Sets the ads manager. * * @visibleForTesting */ export function setAdsManagerForTesting(newAdsManager) { adsManager = newAdsManager; } /** * Sets the ads manager dimensions on load. * * @visibleForTesting */ export function setAdsManagerDimensionsOnLoadForTesting(width, height) { adsManagerWidthOnLoad = width; adsManagerHeightOnLoad = height; } /** * Sets the content complete flag. * * @visibleForTesting */ export function setContentCompleteForTesting(newContentComplete) { contentComplete = newContentComplete; } /** * Sets the video player. * * @visibleForTesting */ export function setVideoPlayerForTesting(newPlayer) { videoPlayer = newPlayer; } /** * Sets the player state. * * @visibleForTesting */ export function setPlayerStateForTesting(newState) { playerState = newState; } /** * Sets the hideControlsTimeout * * @visibleForTesting */ export function setHideControlsTimeoutForTesting(newTimeout) { hideControlsTimeout = newTimeout; } /** * Events * * Copied from src/video-interface.js. * * @constant {!Object<string, string>} */ const VideoEvents = { /** * load * * Fired when the video player is loaded and calls to methods such as `play()` * are allowed. * * @event load */ LOAD: 'load', /** * play * * Fired when the video plays. * * @event play */ PLAYING: 'playing', /** * pause * * Fired when the video pauses. * * @event pause */ PAUSE: 'pause', /** * muted * * Fired when the video is muted. * * @event play */ MUTED: 'muted', /** * unmuted * * Fired when the video is unmuted. * * @event pause */ UNMUTED: 'unmuted', /** * amp:video:visibility * * Fired when the video's visibility changes. Normally fired * from `viewportCallback`. * * @event amp:video:visibility * @property {boolean} visible Whether the video player is visible or not. */ VISIBILITY: 'amp:video:visibility', /** * reload * * Fired when the video's src changes. * * @event reload */ RELOAD: 'reloaded', };
wjfang/amphtml
ads/google/imaVideo.js
JavaScript
apache-2.0
33,640
import * as _ from 'lodash'; import { Component } from '@angular/core'; import {HeroesService} from "../../services/heroes-service"; @Component({ selector: 'home', templateUrl: './home.component.html' }) export class HomeComponent { public heroes = []; constructor(private heroesService: HeroesService) { this.heroesService.getHeroes(); } ngOnInit() { this.heroesService.heroes.subscribe(data => { if (data) { this.heroes = _.concat(this.heroes, data); } }); } getHeroes() { this.heroesService.getHeroes(); } }
mmayorivera/ng-preloader
src/app/components/home/home.component.ts
TypeScript
apache-2.0
569
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CSS Test: z-index parsing - decimal value</title> <meta name="assert" content="An integer value for z-index must be used" /> <style type="text/css"> #test { position: relative; height: 20px; font-size: 50px; } #fail { color: red; z-index: 99.9; position: absolute; top: 0; left: 0 } #pass { color: green; position: absolute; top: 0; left: 0 } </style> </head> <body> <h1>A decimal <code>z-index</code> value is incorrectly used</h1> <div id="test"> <span id="fail">This text should be green</span> <span id="pass">This text should be green</span> </div> </body> </html>
jameshopkins/ie8-bugs
tests/zindex-decimal.html
HTML
apache-2.0
914
package com.orangeclk.service; import com.orangeclk.model.entity.CityEntity; import java.util.Optional; /** * Created by orangeclk on 1/9/17. */ public interface CityService { Optional<CityEntity> findByName(String name); CityEntity save(String name); CityEntity findOne(int id); }
orangeclk/huiyin
src/main/java/com/orangeclk/service/CityService.java
Java
apache-2.0
299
/** * * Copyright (C) 2014 Ash (Tuxdude) <tuxdude.github@gmail.com> * * This file is part of logback-colorizer. * * 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. * * * Set of unit tests for the log colorizer extension. * * @since 1.0 * @author Ash (Tuxdude) <tuxdude.github@gmail.com> * @version 1.0 */ package org.tuxdude.logback.extensions.tests;
Tuxdude/logback-colorizer
colorizer/src/test/java/org/tuxdude/logback/extensions/tests/package-info.java
Java
apache-2.0
880
<html> <body> This inspection reports synchronization on static fields. While not strictly incorrect, synchronization on static fields can lead to bad performance because of contention. <p> <small>New in 10, Powered by InspectionGadgets</small> </body> </html>
joewalnes/idea-community
plugins/InspectionGadgets/src/inspectionDescriptions/SynchronizationOnStaticField.html
HTML
apache-2.0
261
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.databasemigrationservice.model.transform; import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.Map; import java.util.List; import java.util.regex.Pattern; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.databasemigrationservice.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.util.json.*; /** * DescribeReplicationTasksRequest Marshaller */ public class DescribeReplicationTasksRequestMarshaller implements Marshaller<Request<DescribeReplicationTasksRequest>, DescribeReplicationTasksRequest> { public Request<DescribeReplicationTasksRequest> marshall( DescribeReplicationTasksRequest describeReplicationTasksRequest) { if (describeReplicationTasksRequest == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } Request<DescribeReplicationTasksRequest> request = new DefaultRequest<DescribeReplicationTasksRequest>( describeReplicationTasksRequest, "AWSDatabaseMigrationService"); request.addHeader("X-Amz-Target", "AmazonDMSv20160101.DescribeReplicationTasks"); request.setHttpMethod(HttpMethodName.POST); request.setResourcePath(""); try { final StructuredJsonGenerator jsonGenerator = SdkJsonProtocolFactory .createWriter(false, "1.1"); jsonGenerator.writeStartObject(); java.util.List<Filter> filtersList = describeReplicationTasksRequest .getFilters(); if (filtersList != null) { jsonGenerator.writeFieldName("Filters"); jsonGenerator.writeStartArray(); for (Filter filtersListValue : filtersList) { if (filtersListValue != null) { FilterJsonMarshaller.getInstance().marshall( filtersListValue, jsonGenerator); } } jsonGenerator.writeEndArray(); } if (describeReplicationTasksRequest.getMaxRecords() != null) { jsonGenerator.writeFieldName("MaxRecords").writeValue( describeReplicationTasksRequest.getMaxRecords()); } if (describeReplicationTasksRequest.getMarker() != null) { jsonGenerator.writeFieldName("Marker").writeValue( describeReplicationTasksRequest.getMarker()); } jsonGenerator.writeEndObject(); byte[] content = jsonGenerator.getBytes(); request.setContent(new ByteArrayInputStream(content)); request.addHeader("Content-Length", Integer.toString(content.length)); request.addHeader("Content-Type", jsonGenerator.getContentType()); } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } return request; } }
mhurne/aws-sdk-java
aws-java-sdk-dms/src/main/java/com/amazonaws/services/databasemigrationservice/model/transform/DescribeReplicationTasksRequestMarshaller.java
Java
apache-2.0
4,015
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MEPH.util.FileWatcher { class Program { static FileWatcherManager fileWatcherManager; static void Main(string[] args) { fileWatcherManager = new FileWatcherManager(args); if (fileWatcherManager.IsReady) { string res = String.Empty; res = Console.ReadLine(); } } } }
mephisto83/FileWatcher
MEPH.util.FileWatcher/MEPH.util.FileWatcher/Program.cs
C#
apache-2.0
521
package com.altarit.berry.persist.service.impl; import com.altarit.berry.model.entity.User; import com.altarit.berry.persist.dao.UserDao; import com.altarit.berry.persist.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service("userService") @Transactional public class UserServiceImpl implements UserService { @Autowired UserDao dao; @Override public User findById(int id) { return dao.findById(id); } @Override public User findByUsername(String name) { return dao.findByUsername(name); } @Override public void saveUser(User user) { dao.save(user); } @Override public void updateUser(User user) { if (user.getId() == null) { return; } User entity = dao.findById(user.getId()); if (entity != null) { //entity.se(user.getSsoId()); entity.setPassword(user.getPassword()); entity.setEmail(user.getEmail()); entity.setUserProfiles(user.getUserProfiles()); } else { //TODO: handle this cause } } @Override public void deleteUserByUsername(String name) { dao.deleteByUsername(name); } @Override public List<User> findAllUsers() { return dao.findAllUsers(); } @Override public boolean isUsernameUnique(Integer id, String name) { User entity = dao.findByUsername(name); return (entity == null || (id != null) && (entity.getId() == id)); } }
altarit/spring-berry
berry-parent/berry-persist/src/main/java/com/altarit/berry/persist/service/impl/UserServiceImpl.java
Java
apache-2.0
1,684
/** * (c) Copyright 2016 Admios. The software in this package is published under the terms of the Apache License Version 2.0, a copy of which has been included with this distribution in the LICENSE.md file. */ package org.mule.modules.watsonalchemylanguage.model; import org.mule.api.annotations.param.Optional; /** * Class with all the options for the sentiment analysis operation. * * @author Admios */ public class SentimentAnalysisRequest { /** * The text, HTML document or URL to process */ @Optional private String source; /** * Check this to include the source text in the response */ @Optional private Boolean showSourceText; /** * A visual constraints query to apply to the web page. Required when sourceText is set to cquery */ @Optional private String cquery; /** * An XPath query to apply to the web page. Required when sourceText is set to one of the XPath values */ @Optional private String xpath; /** * How to obtain the source text from the web page */ @Optional private String sourceText; public SentimentAnalysisRequest() { } public SentimentAnalysisRequest(String source) { super(); this.source = source; } /** * The text, HTML document or URL to process * * @return the source */ public String getSource() { return source; } /** * Flag value, check this to include the source text in the response * * @return the showSourceText */ public Boolean getShowSourceText() { return showSourceText; } /** * A visual constraints query to apply to the web page. Required when sourceText is set to cquery * * @return the cquery */ public String getCquery() { return cquery; } /** * An XPath query to apply to the web page. Required when sourceText is set to one of the XPath values * * @return the xpath */ public String getXpath() { return xpath; } /** * How to obtain the source text from the web page * * @return the sourceText */ public String getSourceText() { return sourceText; } /** * @param source the source to set */ public void setSource(String source) { this.source = source; } /** * @param showSourceText the showSourceText to set */ public void setShowSourceText(Boolean showSourceText) { this.showSourceText = showSourceText; } /** * @param cquery the cquery to set */ public void setCquery(String cquery) { this.cquery = cquery; } /** * @param xpath the xpath to set */ public void setXpath(String xpath) { this.xpath = xpath; } /** * @param sourceText the sourceText to set */ public void setSourceText(String sourceText) { this.sourceText = sourceText; } }
Admios/watson-alchemy-language-connector
src/main/java/org/mule/modules/watsonalchemylanguage/model/SentimentAnalysisRequest.java
Java
apache-2.0
2,670
/* Copyright 2013 Demon Developers Ltd 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.demondevelopers.tandemscroll; import java.util.Vector; public class TandemController { private Vector<TandemListener> mListeners = new Vector<TandemListener>(); private boolean mInDispatch = false; public boolean registerTandemListener(TandemListener listener) { return mListeners.add(listener); } public boolean unregisterTandemListener(TandemListener listener) { return mListeners.remove(listener); } public boolean isInDispatch() { return mInDispatch; } public void dispatchTandemScroll(int x, int y) { mInDispatch = true; for(TandemListener listener : mListeners){ listener.tandemScroll(x, y); } mInDispatch = false; } } interface TandemListener { public boolean registerTandemListener(TandemListener listener); public boolean unregisterTandemListener(TandemListener listener); public void tandemScroll(int x, int y); }
slightfoot/android-tandem-scroll
Library/src/com/demondevelopers/tandemscroll/TandemController.java
Java
apache-2.0
1,510
<!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.5.0_11) on Tue Jun 12 22:14:09 BST 2007 --> <TITLE> All Classes </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameHeadingFont"> <B>All Classes</B></FONT> <BR> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT CLASS="FrameItemFont"><A HREF="com/rattat/micro/game/aster/elements/Asteroid.html" title="class in com.rattat.micro.game.aster.elements" target="classFrame">Asteroid</A> <BR> <A HREF="com/rattat/micro/game/aster/AsteroidsRecords.html" title="class in com.rattat.micro.game.aster" target="classFrame">AsteroidsRecords</A> <BR> <A HREF="com/rattat/micro/game/aster/elements/ExplodingPolygon.html" title="class in com.rattat.micro.game.aster.elements" target="classFrame">ExplodingPolygon</A> <BR> <A HREF="com/rattat/micro/game/aster/elements/FloatingObject.html" title="class in com.rattat.micro.game.aster.elements" target="classFrame">FloatingObject</A> <BR> <A HREF="com/rattat/micro/game/aster/elements/FlyingSaucer.html" title="class in com.rattat.micro.game.aster.elements" target="classFrame">FlyingSaucer</A> <BR> <A HREF="com/rattat/micro/game/aster/mvc/GameController.html" title="class in com.rattat.micro.game.aster.mvc" target="classFrame">GameController</A> <BR> <A HREF="com/rattat/micro/game/aster/mvc/GameListener.html" title="interface in com.rattat.micro.game.aster.mvc" target="classFrame"><I>GameListener</I></A> <BR> <A HREF="com/rattat/micro/game/aster/MenuCanvas.html" title="class in com.rattat.micro.game.aster" target="classFrame">MenuCanvas</A> <BR> <A HREF="com/rattat/micro/game/aster/Midlet.html" title="class in com.rattat.micro.game.aster" target="classFrame">Midlet</A> <BR> <A HREF="com/rattat/micro/game/aster/elements/Missile.html" title="class in com.rattat.micro.game.aster.elements" target="classFrame">Missile</A> <BR> <A HREF="com/rattat/micro/game/aster/mvc/Model.html" title="class in com.rattat.micro.game.aster.mvc" target="classFrame">Model</A> <BR> <A HREF="com/rattat/micro/game/aster/mvc/ShipController.html" title="class in com.rattat.micro.game.aster.mvc" target="classFrame">ShipController</A> <BR> <A HREF="com/rattat/micro/game/aster/mvc/ShipListener.html" title="interface in com.rattat.micro.game.aster.mvc" target="classFrame"><I>ShipListener</I></A> <BR> <A HREF="com/rattat/micro/game/aster/SoundManager.html" title="class in com.rattat.micro.game.aster" target="classFrame">SoundManager</A> <BR> <A HREF="com/rattat/micro/game/aster/elements/SpaceShip.html" title="class in com.rattat.micro.game.aster.elements" target="classFrame">SpaceShip</A> <BR> <A HREF="com/rattat/micro/game/aster/elements/Star.html" title="class in com.rattat.micro.game.aster.elements" target="classFrame">Star</A> <BR> <A HREF="com/rattat/micro/game/aster/VibrationManager.html" title="class in com.rattat.micro.game.aster" target="classFrame">VibrationManager</A> <BR> <A HREF="com/rattat/micro/game/aster/mvc/View.html" title="class in com.rattat.micro.game.aster.mvc" target="classFrame">View</A> <BR> </FONT></TD> </TR> </TABLE> </BODY> </HTML>
wjsrobertson/j2menace
AsteroidBelt/docs/javadoc/AsteroidBelt-0.0.1-javadoc/allclasses-frame.html
HTML
apache-2.0
3,279
/******************************************************************************* * Copyright 2019 See AUTHORS file * * 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 org.mini2Dx.ui.effect; /** * Describes the direction to slide towards */ public enum SlideDirection { UP, DOWN, LEFT, RIGHT }
mini2Dx/mini2Dx
ui/src/main/java/org/mini2Dx/ui/effect/SlideDirection.java
Java
apache-2.0
894
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2013, GridWay Project Leads (GridWay.org) */ /* */ /* 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 org.ggf.drmaa; import java.util.*; public class SimpleJobTemplate implements JobTemplate { /** Attribute to refer to the command to be executed on the remote * host. The remoteCommand attribute MUST BE RELATIVE to the working directory * (workingDirectory). Architecture-dependent remoteCommand can be generated * with GW_ARCH. */ protected java.lang.String remoteCommand = null; /** String array attribute to refer to the remoteCommand arguments. */ protected java.util.List args = null; /** Integer attribute to refer to the job state at submission, the job will * enter either the QUEUED_ACTIVE state or HOLD state when submitted. The * preprocessor directives ACTIVE_STATE and * HOLD_STATE SHOULD be used to assign the value of this attribute. * The default value is ACTIVE_STATE. */ protected int jobSubmissionState = ACTIVE_STATE; /** String attribute to refer to the {@link #remoteCommand} environment * variables. */ protected java.util.Map jobEnvironment = null; /** String attribute to refer to the JOB working directory. The current * GridWay DRMAA implementation will generate a job template file with * name {@link #jobName} in the job working directory (workingDirectory). It is a * MANDATORY attribute value and MUST BE DEFINED. Plase note that ALL FILES * ARE NAMED RELATIVE TO THE WORKING DIRECTORY. Also this is a LOCAL PATH NAME, * this directory will be recreated in the remote host, and it will be the * working directory of the job on the execution host. */ protected java.lang.String workingDirectory = null; /** Not relevant for the current GridWay implementation, will be ignored */ protected java.lang.String jobCategory = null; /** Not relevant for the current GridWay implementation, will be ignored */ protected java.lang.String nativeSpecification = null; /** Not relevant for the current GridWay implementation, will be ignored */ protected java.util.Set email = null; /** Not relevant for the current GridWay implementation, will be ignored */ protected boolean blockEmail = false; /** Not relevant for the current GridWay implementation, will be ignored */ protected java.util.Date startTime = null; /** String attribute to refer to the DRMAA job-name. The current GridWay * DRMAA implementation will generate a job template file with name * jobName in the job working directory (workingDirectory). jobName is * a MANDATORY attribute value and MUST BE DEFINED. The default value is * "job_template". */ protected java.lang.String jobName = null; /** String attribute to refer to standard input file for the * {@link #remoteCommand}. The standard input file IS RELATIVE TO THE * WORKING DIRECTORY. */ protected java.lang.String inputPath = null; /** String attribute to refer to standard output file for the * {@link #remoteCommand}. The standard ouput file IS RELATIVE TO THE * WORKING DIRECTORY. */ protected java.lang.String outputPath = null; /** String attribute to refer to standard error file for the * {@link #remoteCommand}. The standard error file IS RELATIVE TO THE * WORKING DIRECTORY. */ protected java.lang.String errorPath = null; /** Not relevant for the current GridWay implementation, will be ignored */ protected boolean joinFiles = false; /** Not relevant for the current GridWay implementation, will be ignored */ protected FileTransferMode transferFiles = null; /**Pre-defined string to represent a deadline for job execution. GridWay WILL NOT * terminate a job after the deadline, neither guarantees that the job is executed before the * deadline. A deadline is specified absolute to job submission time. */ protected PartialTimestamp deadlineTime = null; /** Not relevant for the current GridWay implementation, will be ignored */ protected long hardWallclockTimeLimit = 0; /** Not relevant for the current GridWay implementation, will be ignored */ protected long softWallclockTimeLimit = 0; /** Not relevant for the current GridWay implementation, will be ignored */ protected long hardRunDurationLimit = 0; /** Not relevant for the current GridWay implementation, will be ignored */ protected long softRunDurationLimit = 0; /* Specific attributes*/ protected java.util.Set attributeNames = null ; private java.util.HashMap jobTemplateString = null; /** The SimpleJobTemplate() constructor creates a new instance of a SimpleJobTemplate. In most cases, a * DRMAA implementation will require that JobTemplates be created through the * {@link Session#createJobTemplate} method, however. In those cases, passing a JobTemplate created * through the JobTemplate() constructor to the {@link Session#deleteJobTemplate}, {@link Session#runJob}, * or {@link Session#runBulkJobs} methods will result in an {@link InvalidJobTemplateException} being thrown. */ public SimpleJobTemplate() { this.jobName = new String("SimpleJobTemplate"); this.attributeNames = new java.util.HashSet(); attributeNames.add("remoteCommand"); attributeNames.add("args"); attributeNames.add("jobSubmissionState"); attributeNames.add("jobEnvironment"); attributeNames.add("workingDirectory"); attributeNames.add("jobName"); attributeNames.add("inputPath"); attributeNames.add("outputPath"); attributeNames.add("errorPath"); attributeNames.add("deadlineTime"); } /** This method set the attribute {@link #remoteCommand}. * * @param command A command to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setRemoteCommand(java.lang.String command) throws DrmaaException { if (command == null) throw new InvalidAttributeValueException("The command attribute is NULL"); else this.remoteCommand = new String(command); } /** This method set the attribute {@link #args}. * * @param args The attributes to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setArgs(java.util.List args) throws DrmaaException { if (args == null) throw new InvalidAttributeValueException("The args attribute is NULL"); else this.args = new ArrayList<String>((ArrayList<String>) args); } /** This method set the attribute {@link #jobSubmissionState}. * * @param state The state to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setJobSubmissionState(int state) throws DrmaaException { this.jobSubmissionState = state; } /** This method set the attribute {@link #jobEnvironment}. * * @param env The jobEnvironment to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setJobEnvironment(java.util.Map env) throws DrmaaException { if (env == null) throw new InvalidAttributeValueException("The env attribute is NULL"); else { this.jobEnvironment = new Properties(); Enumeration e = ((Properties) env).propertyNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = ((Properties) env).getProperty(name); ((Properties) this.jobEnvironment).setProperty(name, value); } } } /** This method set the attribute {@link #workingDirectory}. * * @param wd The working directoy to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setWorkingDirectory(String wd) throws DrmaaException { if (wd == null) throw new InvalidAttributeValueException("The workingDirectory attribute is NULL"); else this.workingDirectory = new String(wd); } /** This method set the attribute {@link #jobCategory}. * * @param category The category to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setJobCategory(String category) throws DrmaaException { if (category == null) throw new InvalidAttributeValueException("The category attribute is NULL"); else this.jobCategory = new String(category); } /** This method set the attribute {@link #nativeSpecification}. * * @param spec The native specification to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setNativeSpecification(String spec) throws DrmaaException { if (spec == null) throw new InvalidAttributeValueException("The nativeSpecification attribute is NULL"); else this.nativeSpecification = new String(spec); } /** This method set the attribute {@link #email}. * * @param email The email to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setEmail(Set email) throws DrmaaException { if (email == null) throw new InvalidAttributeValueException("The email attribute is NULL"); else this.email = new HashSet<String>((HashSet<String>)email); } /** This method set the attribute {@link #blockEmail}. * * @param blockEmail The blockEmail to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setBlockEmail(boolean blockEmail) throws DrmaaException { this.blockEmail = blockEmail; } /** This method set the attribute {@link #startTime}. * * @param startTime The startTime to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setStartTime(Date startTime) throws DrmaaException { if (startTime == null) throw new InvalidAttributeValueException("The startTime attribute is NULL"); else this.startTime = startTime; } /** This method set the attribute {@link #jobName}. * * @param name The Job name to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setJobName(String name) throws DrmaaException { if (name == null) throw new InvalidAttributeValueException("The JobTemplate name attribute is NULL"); else this.jobName = new String(name); } /** This method set the attribute {@link #inputPath}. * * @param inputPath The input path to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setInputPath(String inputPath) throws DrmaaException { if (inputPath == null) throw new InvalidAttributeValueException("The inputPath attribute is NULL"); else this.inputPath = new String(inputPath); } /** This method set the attribute {@link #outputPath}. * * @param outputPath The output path to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setOutputPath(String outputPath) throws DrmaaException { if (outputPath == null) throw new InvalidAttributeValueException("The outputPath attribute is NULL"); else this.outputPath = new String(outputPath); } /** This method set the attribute {@link #errorPath}. * * @param errorPath The error path to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setErrorPath(String errorPath) throws DrmaaException { if (errorPath == null) throw new InvalidAttributeValueException("The errorPath attribute is NULL"); else this.errorPath = new String(errorPath); } /** This method set the attribute {@link #joinFiles}. * * @param joinFiles The joinFiles to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setJoinFiles(boolean joinFiles) throws DrmaaException { this.joinFiles = joinFiles; } /** This method set the attribute {@link #transferFiles}. * * @param mode The transfer mode to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setTransferFiles(FileTransferMode mode) throws DrmaaException { if (mode == null) throw new InvalidAttributeValueException("The fileTransferMode attribute is NULL"); else this.transferFiles = mode; } /** This method set the attribute {@link #deadlineTime}. * * @param deadline The deadline to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setDeadlineTime(PartialTimestamp deadline) throws DrmaaException { if (deadline == null) throw new InvalidAttributeValueException("The deadline attribute is NULL"); else this.deadlineTime = deadline; } /** This method set the attribute {@link #hardWallclockTimeLimit}. * * @param limit The hard wall clock time limit to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setHardWallclockTimeLimit(long limit) throws DrmaaException { this.hardWallclockTimeLimit = limit; } /** This method set the attribute {@link #softWallclockTimeLimit}. * * @param limit The soft wall clock time timit to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setSoftWallclockTimeLimit(long limit) throws DrmaaException { this.softWallclockTimeLimit = limit; } /** This method set the attribute {@link #hardRunDurationLimit}. * * @param limit The hard run duration limit to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setHardRunDurationLimit(long limit) throws DrmaaException { this.hardRunDurationLimit = limit; } /** This method set the attribute {@link #softRunDurationLimit}. * * @param limit The soft run duration limit to set * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public void setSoftRunDurationLimit(long limit) throws DrmaaException { this.softRunDurationLimit = limit; } /** This method get the attribute {@link #remoteCommand}. * * @return A {@link String} with the remoteCommand value * */ public String getRemoteCommand() { return this.remoteCommand; } /** This method get the attribute {@link #args}. * * @return A {@link List} object with the args value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public java.util.List getArgs() { return this.args; } /** This method get the attribute {@link #jobSubmissionState}. * * @return A int with the jobSubmissionState value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public int getJobSubmissionState() { return this.jobSubmissionState; } /** This method get the attribute {@link #jobEnvironment}. * * @return A {@link Map} object with the jobEnvironment value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public java.util.Map getJobEnvironment() { return this.jobEnvironment; } /** This method get the attribute {@link #workingDirectory}. * * @return A {@link String} with the workingDirectory value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public String getWorkingDirectory() { return this.workingDirectory; } /** This method get the attribute {@link #jobCategory}. * * @return A {@link String} with the jobCategory value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public String getJobCategory() { return this.jobCategory; } /** This method get the attribute {@link #nativeSpecification}. * * @return A {@link String} with the nativeSpecification value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public String getNativeSpecification() { return this.nativeSpecification; } /** This method get the attribute {@link #email}. * * @return A {@link Set} object with the email value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public Set getEmail() { return this.email; } /** This method get the attribute {@link #blockEmail}. * * @return A boolean with the blockEmail value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public boolean getBlockEmail() { return this.blockEmail; } /** This method get the attribute {@link #startTime}. * * @return A Date object with the startTime value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException */ public Date getStartTime() { return this.startTime; } /** This method get the attribute {@link #jobName}. * * @return A {@link String} with the jobName value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public String getJobName() { return this.jobName; } /** This method get the attribute {@link #inputPath}. * * @return A {@link String} with the inputPath value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public String getInputPath() { return this.inputPath; } /** This method get the attribute {@link #outputPath}. * * @return A {@link String} with the outputPath value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public String getOutputPath() { return this.outputPath; } /** This method get the attribute {@link #errorPath}. * * @return A {@link String} with the errorPath value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public String getErrorPath() { return this.errorPath; } /** This method get the attribute {@link #joinFiles}. * * @return A boolean with the joinFiles value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public boolean getJoinFiles() { return this.joinFiles; } /** This method get the attribute {@link #transferFiles}. * * @return A FileTransferMode object with the transferFiles value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public FileTransferMode getTransferFiles() { return this.transferFiles; } /** This method get the attribute {@link #deadlineTime}. * * @return A PartialTimestamp object with the deadlineTime value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public PartialTimestamp getDeadlineTime() { return this.deadlineTime; } /** This method get the attribute {@link #hardWallclockTimeLimit}. * * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public long getHardWallclockTimeLimit() { return this.hardWallclockTimeLimit; } /** This method get the attribute {@link #softWallclockTimeLimit}. * * @return A long with the softWallclockTimeLimit value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public long getSoftWallclockTimeLimit() { return this.softWallclockTimeLimit; } /** This method get the attribute {@link #hardRunDurationLimit}. * * @return A long with the hardRunDurationLimit value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public long getHardRunDurationLimit() { return this.hardRunDurationLimit; } /** This method get the attribute {@link #softRunDurationLimit}. * * @return A long with the softRunDurationLimit value * * @throws InvalidAttributeValueException * @throws ConflictingAttributeValuesException * @throws NoActiveSessionException * @throws java.lang.OutOfMemoryError * @throws DrmCommunicationException * @throws AuthorizationException * @throws java.lang.IllegalArgumentException * @throws InternalException */ public long getSoftRunDurationLimit() { return this.softRunDurationLimit; } /** This method return the list of supported property names. * The required Gridway property names are: * <ul> * <li> {@link #remoteCommand}, {@link #args}, {@link #jobSubmissionState}</li> * <li> {@link #jobEnvironment}, {@link #workingDirectory}, {@link #jobName}, {@link #inputPath}</li> * <li> {@link #outputPath}, {@link #errorPath}</li> * </ul> * * The optional Gridway property names (implemented in {@link GridWayJobTemplate}) are: * <ul> * <li> inputFiles, outputFiles, restartFiles</li> * <li> rescheduleOnFailure, numberOfRetries, rank</li> * <li> requirements</li> * </ul> */ public java.util.Set getAttributeNames() { return attributeNames; } /** This method returns a string representation of the job template instance * */ public java.lang.String toString() { String result; result = "Name: " + this.jobName + "\n"; result += "Remote Command: " + this.remoteCommand + "\n"; result += "Arguments: " + this.args + "\n"; result += "Job Submission State: " + this.jobSubmissionState + "\n"; result += "Environment: " + this.jobEnvironment + "\n"; result += "Input Path: " + this.inputPath + "\n"; result += "Output Path: " + this.outputPath + "\n"; result += "Error Path: " + this.errorPath + "\n"; result += "Deadline Time: " + this.deadlineTime + "\n"; return result; } /** This method marks the job template to indicate that its properties have been modified. * Not relevant for the current GridWay implementation, will be ignored. * */ public void modified() { return; } /** This method return the list of the optional Gridway property names * (implemented in {@link GridWayJobTemplate}): * * <ul> * <li> inputFiles, outputFiles, restartFiles</li> * <li> rescheduleOnFailure, numberOfRetries, rank</li> * <li> requirements</li> * </ul> */ protected java.util.Set getOptionalAttributeNames() { return null; } }
GridWay/gridway
src/drmaa/drmaa1.0/org/ggf/drmaa/SimpleJobTemplate.java
Java
apache-2.0
33,332
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Fri Apr 06 09:47:29 MST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.wildfly.swarm.config.webservices.EndpointConfig.EndpointConfigResources (BOM: * : All 2018.4.2 API)</title> <meta name="date" content="2018-04-06"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.wildfly.swarm.config.webservices.EndpointConfig.EndpointConfigResources (BOM: * : All 2018.4.2 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/wildfly/swarm/config/webservices/EndpointConfig.EndpointConfigResources.html" title="class in org.wildfly.swarm.config.webservices">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2018.4.2</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/config/webservices/class-use/EndpointConfig.EndpointConfigResources.html" target="_top">Frames</a></li> <li><a href="EndpointConfig.EndpointConfigResources.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.wildfly.swarm.config.webservices.EndpointConfig.EndpointConfigResources" class="title">Uses of Class<br>org.wildfly.swarm.config.webservices.EndpointConfig.EndpointConfigResources</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/wildfly/swarm/config/webservices/EndpointConfig.EndpointConfigResources.html" title="class in org.wildfly.swarm.config.webservices">EndpointConfig.EndpointConfigResources</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.webservices">org.wildfly.swarm.config.webservices</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config.webservices"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/webservices/EndpointConfig.EndpointConfigResources.html" title="class in org.wildfly.swarm.config.webservices">EndpointConfig.EndpointConfigResources</a> in <a href="../../../../../../org/wildfly/swarm/config/webservices/package-summary.html">org.wildfly.swarm.config.webservices</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/webservices/package-summary.html">org.wildfly.swarm.config.webservices</a> that return <a href="../../../../../../org/wildfly/swarm/config/webservices/EndpointConfig.EndpointConfigResources.html" title="class in org.wildfly.swarm.config.webservices">EndpointConfig.EndpointConfigResources</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/webservices/EndpointConfig.EndpointConfigResources.html" title="class in org.wildfly.swarm.config.webservices">EndpointConfig.EndpointConfigResources</a></code></td> <td class="colLast"><span class="typeNameLabel">EndpointConfig.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/webservices/EndpointConfig.html#subresources--">subresources</a></span>()</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/wildfly/swarm/config/webservices/EndpointConfig.EndpointConfigResources.html" title="class in org.wildfly.swarm.config.webservices">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2018.4.2</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/config/webservices/class-use/EndpointConfig.EndpointConfigResources.html" target="_top">Frames</a></li> <li><a href="EndpointConfig.EndpointConfigResources.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2018.4.2/apidocs/org/wildfly/swarm/config/webservices/class-use/EndpointConfig.EndpointConfigResources.html
HTML
apache-2.0
7,674
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60) on Thu Nov 05 22:43:47 MST 2015 --> <title>Uses of Class ca.ualberta.cs.swapmyride.EditProfileActivity</title> <meta name="date" content="2015-11-05"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class ca.ualberta.cs.swapmyride.EditProfileActivity"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../ca/ualberta/cs/swapmyride/package-summary.html">Package</a></li> <li><a href="../../../../../ca/ualberta/cs/swapmyride/EditProfileActivity.html" title="class in ca.ualberta.cs.swapmyride">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?ca/ualberta/cs/swapmyride/class-use/EditProfileActivity.html" target="_top">Frames</a></li> <li><a href="EditProfileActivity.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class ca.ualberta.cs.swapmyride.EditProfileActivity" class="title">Uses of Class<br>ca.ualberta.cs.swapmyride.EditProfileActivity</h2> </div> <div class="classUseContainer">No usage of ca.ualberta.cs.swapmyride.EditProfileActivity</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../ca/ualberta/cs/swapmyride/package-summary.html">Package</a></li> <li><a href="../../../../../ca/ualberta/cs/swapmyride/EditProfileActivity.html" title="class in ca.ualberta.cs.swapmyride">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?ca/ualberta/cs/swapmyride/class-use/EditProfileActivity.html" target="_top">Frames</a></li> <li><a href="EditProfileActivity.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
CMPUT301F15T05/cuddly-quack
Documentation/JavaDoc/ca/ualberta/cs/swapmyride/class-use/EditProfileActivity.html
HTML
apache-2.0
4,273
package com.caul.modules.sys.controller; import com.caul.modules.base.AdminBaseController; import net.sf.json.JSONObject; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by BlueDream on 2016-05-29. */ @RestController public class PermissionController extends AdminBaseController { private static final String MODULE_NAME = "/permission"; @RequestMapping(value = MODULE_NAME + "/check") public JSONObject check() { checkPermission("对不起,您没有该操作权限!"); return jsonWithStandardStatus(); } }
sdliang1013/account-import
src/main/java/com/caul/modules/sys/controller/PermissionController.java
Java
apache-2.0
637
""" pluginconf.d configuration file - Files ======================================= Shared mappers for parsing and extracting data from ``/etc/yum/pluginconf.d/*.conf`` files. Parsers contained in this module are: PluginConfD - files ``/etc/yum/pluginconf.d/*.conf`` --------------------------------------------------- PluginConfDIni - files ``/etc/yum/pluginconf.d/*.conf`` ------------------------------------------------------- """ from insights.core import IniConfigFile, LegacyItemAccess, Parser from insights.core.plugins import parser from insights.parsers import get_active_lines from insights.specs import Specs from insights.util import deprecated @parser(Specs.pluginconf_d) class PluginConfD(LegacyItemAccess, Parser): """ .. warning:: This parser is deprecated, please use :py:class:`insights.parsers.pluginconf_d.PluginConfDIni` instead Class to parse configuration file under ``pluginconf.d`` Sample configuration:: [main] enabled = 0 gpgcheck = 1 timeout = 120 # You can specify options per channel, e.g.: # #[rhel-i386-server-5] #enabled = 1 # #[some-unsigned-custom-channel] #gpgcheck = 0 """ def parse_content(self, content): deprecated(PluginConfD, "Deprecated. Use 'PluginConfDIni' instead.") plugin_dict = {} section_dict = {} key = None for line in get_active_lines(content): if line.startswith('['): section_dict = {} plugin_dict[line[1:-1]] = section_dict elif '=' in line: key, _, value = line.partition("=") key = key.strip() section_dict[key] = value.strip() else: if key: section_dict[key] = ','.join([section_dict[key], line]) self.data = plugin_dict def __iter__(self): for sec in self.data: yield sec @parser(Specs.pluginconf_d) class PluginConfDIni(IniConfigFile): """ Read yum plugin config files, in INI format, using the standard INI file parser class. Sample configuration:: [main] enabled = 0 gpgcheck = 1 timeout = 120 # You can specify options per channel, e.g.: # #[rhel-i386-server-5] #enabled = 1 # #[some-unsigned-custom-channel] #gpgcheck = 0 [test] test_multiline_config = http://example.com/repos/test/ http://mirror_example.com/repos/test/ Examples: >>> type(conf) <class 'insights.parsers.pluginconf_d.PluginConfDIni'> >>> conf.sections() ['main', 'test'] >>> conf.has_option('main', 'gpgcheck') True >>> conf.get("main", "enabled") '0' >>> conf.getint("main", "timeout") 120 >>> conf.getboolean("main", "enabled") False >>> conf.get("test", "test_multiline_config") 'http://example.com/repos/test/ http://mirror_example.com/repos/test/' """ pass
RedHatInsights/insights-core
insights/parsers/pluginconf_d.py
Python
apache-2.0
3,141
from cobra.core.loading import get_model from cobra.core import json class UserConfig(object): default_config = { 'guide.task.participant': '1', 'guide.document.share': '1', 'guide.customer.share': '1', 'guide.workflow.operation': '1', 'guide.workflow.createform': '1', 'order.task.search': 'default', 'order.task.searchDirection': 'DESC', 'portal.workdyna': 'subordinates-task', 'system.menu.display':'', 'viewState.task': 'list', 'guide.biaoge.showintro': '1', 'workreport.push.set': '1', 'agenda.push.set': '1' } def __init__(self, user): self.__user_config = self.__build_user_config(user) def __build_user_config(self, user): UserOption = get_model('option', 'UserOption') u_c = {} for k, v in self.default_config.items(): u_c[k] = UserOption.objects.get_value(user, None, k, v) return u_c def to_python(self): configs = [] for k, v in self.__user_config.items(): m = { 'configKey': k, 'configValue': v } configs.append(m) return configs def to_json(self): return json.dumps(self.to_python())
lyoniionly/django-cobra
src/cobra/core/configure/user_config.py
Python
apache-2.0
1,284
extern crate byteorder; use byteorder::{ByteOrder, BigEndian}; use std::io::{Read, Write, Result}; /// A byte buffer object specifically turned to easily read and write binary values pub struct ByteBuffer { data: Vec<u8>, wpos: usize, rpos: usize, rbit: usize, wbit: usize, } impl ByteBuffer { /// Construct a new, empty, ByteBuffer pub fn new() -> ByteBuffer { ByteBuffer { data: vec![], wpos: 0, rpos: 0, rbit: 0, wbit: 0, } } /// Construct a new ByteBuffer filled with the data array. pub fn from_bytes(bytes: &[u8]) -> ByteBuffer { let mut buffer = ByteBuffer::new(); buffer.write_bytes(bytes); buffer } /// Return the buffer size pub fn len(&self) -> usize { self.data.len() } /// Clear the buffer and reinitialize the reading and writing cursor pub fn clear(&mut self) { self.data.clear(); self.wpos = 0; self.rpos = 0; } /// Change the buffer size to size. /// /// _Note_: You cannot shrink a buffer with this method pub fn resize(&mut self, size: usize) { let diff = size - self.data.len(); if diff > 0 { self.data.extend(std::iter::repeat(0).take(diff)) } } // Write operations /// Append a byte array to the buffer. The buffer is automatically extended if needed /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::new(); /// buffer.write_bytes(&vec![0x1, 0xFF, 0x45]); // buffer contains [0x1, 0xFF, 0x45] /// ``` pub fn write_bytes(&mut self, bytes: &[u8]) { self.flush_bit(); let size = bytes.len() + self.wpos; if size > self.data.len() { self.resize(size); } for v in bytes { self.data[self.wpos] = *v; self.wpos += 1; } } /// Append a byte (8 bits value) to the buffer /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::new(); /// buffer.write_u8(1) // buffer contains [0x1] /// ``` pub fn write_u8(&mut self, val: u8) { self.write_bytes(&[val]); } /// Same as `write_u8()` but for signed values pub fn write_i8(&mut self, val: i8) { self.write_u8(val as u8); } /// Append a word (16 bits value) to the buffer /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::new(); /// buffer.write_u16(1) // buffer contains [0x00, 0x1] if little endian /// ``` pub fn write_u16(&mut self, val: u16) { let mut buf = [0; 2]; BigEndian::write_u16(&mut buf, val); self.write_bytes(&buf); } /// Same as `write_u16()` but for signed values pub fn write_i16(&mut self, val: i16) { self.write_u16(val as u16); } /// Append a double word (32 bits value) to the buffer /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::new(); /// buffer.write_u32(1) // buffer contains [0x00, 0x00, 0x00, 0x1] if little endian /// ``` pub fn write_u32(&mut self, val: u32) { let mut buf = [0; 4]; BigEndian::write_u32(&mut buf, val); self.write_bytes(&buf); } /// Same as `write_u32()` but for signed values pub fn write_i32(&mut self, val: i32) { self.write_u32(val as u32); } /// Append a quaddruple word (64 bits value) to the buffer /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::new(); /// buffer.write_u64(1) // buffer contains [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1] if little endian /// ``` pub fn write_u64(&mut self, val: u64) { let mut buf = [0; 8]; BigEndian::write_u64(&mut buf, val); self.write_bytes(&buf); } /// Same as `write_u64()` but for signed values pub fn write_i64(&mut self, val: i64) { self.write_u64(val as u64); } /// Append a 32 bits floating point number to the buffer. /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::new(); /// buffer.write_f32(0.1) /// ``` pub fn write_f32(&mut self, val: f32) { let mut buf = [0; 4]; BigEndian::write_f32(&mut buf, val); self.write_bytes(&buf); } /// Append a 64 bits floating point number to the buffer. /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::new(); /// buffer.write_f64(0.1) /// ``` pub fn write_f64(&mut self, val: f64) { let mut buf = [0; 8]; BigEndian::write_f64(&mut buf, val); self.write_bytes(&buf); } /// Append a string to the buffer. /// /// *Format* The format is `(u32)size + size * (u8)characters` /// /// #Exapmle /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::new(); /// buffer.write_string("Hello") /// ``` pub fn write_string(&mut self, val: &str) { self.write_u32(val.len() as u32); self.write_bytes(val.as_bytes()); } // Read operations /// Read a defined amount of raw bytes. The program crash if not enough bytes are available pub fn read_bytes(&mut self, size: usize) -> Vec<u8> { self.flush_bit(); assert!(self.rpos + size <= self.data.len()); let range = self.rpos..self.rpos + size; let mut res = Vec::<u8>::new(); res.write(&self.data[range]).unwrap(); self.rpos += size; res } /// Read one byte. The program crash if not enough bytes are available /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::from_bytes(&vec![0x1]); /// let value = buffer.read_u8(); //Value contains 1 /// ``` pub fn read_u8(&mut self) -> u8 { self.flush_bit(); assert!(self.rpos < self.data.len()); let pos = self.rpos; self.rpos += 1; self.data[pos] } /// Same as `read_u8()` but for signed values pub fn read_i8(&mut self) -> i8 { self.read_u8() as i8 } /// Read a 2-bytes long value. The program crash if not enough bytes are available /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::from_bytes(&vec![0x0, 0x1]); /// let value = buffer.read_u16(); //Value contains 1 /// ``` pub fn read_u16(&mut self) -> u16 { self.flush_bit(); assert!(self.rpos + 2 <= self.data.len()); let range = self.rpos..self.rpos + 2; self.rpos += 2; BigEndian::read_u16(&self.data[range]) } /// Same as `read_u16()` but for signed values pub fn read_i16(&mut self) -> i16 { self.read_u16() as i16 } /// Read a four-bytes long value. The program crash if not enough bytes are available /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::from_bytes(&vec![0x0, 0x0, 0x0, 0x1]); /// let value = buffer.read_u32(); // Value contains 1 /// ``` pub fn read_u32(&mut self) -> u32 { self.flush_bit(); assert!(self.rpos + 4 <= self.data.len()); let range = self.rpos..self.rpos + 4; self.rpos += 4; BigEndian::read_u32(&self.data[range]) } /// Same as `read_u32()` but for signed values pub fn read_i32(&mut self) -> i32 { self.read_u32() as i32 } /// Read an eight bytes long value. The program crash if not enough bytes are available /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::from_bytes(&vec![0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1]); /// let value = buffer.read_u64(); //Value contains 1 /// ``` pub fn read_u64(&mut self) -> u64 { self.flush_bit(); assert!(self.rpos + 8 <= self.data.len()); let range = self.rpos..self.rpos + 8; self.rpos += 8; BigEndian::read_u64(&self.data[range]) } /// Same as `read_u64()` but for signed values pub fn read_i64(&mut self) -> i64 { self.read_u64() as i64 } /// Read a 32 bits floating point value. The program crash if not enough bytes are available pub fn read_f32(&mut self) -> f32 { self.flush_bit(); assert!(self.rpos + 4 <= self.data.len()); let range = self.rpos..self.rpos + 4; self.rpos += 4; BigEndian::read_f32(&self.data[range]) } /// Read a 64 bits floating point value. The program crash if not enough bytes are available pub fn read_f64(&mut self) -> f64 { self.flush_bit(); assert!(self.rpos + 8 <= self.data.len()); let range = self.rpos..self.rpos + 8; self.rpos += 8; BigEndian::read_f64(&self.data[range]) } /// Read a string. /// /// *Note* : First it reads a 32 bits value representing the size, the read 'size' raw bytes. pub fn read_string(&mut self) -> String { let size = self.read_u32(); String::from_utf8(self.read_bytes(size as usize)).unwrap() } // Other /// Dump the byte buffer to a string. pub fn to_string(&self) -> String { let mut str = String::new(); for b in &self.data { str = str + &format!("0x{:01$x} ", b, 2); } str.pop(); str } /// Return the position of the reading cursor pub fn get_rpos(&self) -> usize { self.rpos } /// Set the reading cursor position. /// *Note* : Set the reading cursor to `min(newPosition, self.len())` to prevent overflow pub fn set_rpos(&mut self, rpos: usize) { self.rpos = std::cmp::min(rpos, self.data.len()); } /// Return the writing cursor position pub fn get_wpos(&self) -> usize { self.wpos } /// Set the writing cursor position. /// *Note* : Set the writing cursor to `min(newPosition, self.len())` to prevent overflow pub fn set_wpos(&mut self, wpos: usize) { self.wpos = std::cmp::min(wpos, self.data.len()); } /// Return the raw byte buffer. pub fn to_bytes(&self) -> Vec<u8> { self.data.to_vec() } //Bit manipulation functions /// Read 1 bit. Return true if the bit is set to 1, otherwhise, return false. /// /// **Note** Bits are read from left to right /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::from_bytes(&vec![128]); // 10000000b /// let value1 = buffer.read_bit(); //value1 contains true (eg: bit is 1) /// let value2 = buffer.read_bit(); //value2 contains false (eg: bit is 0) /// ``` pub fn read_bit(&mut self) -> bool { assert!(self.rpos <= self.data.len()); let bit = self.data[self.rpos] & (1 << 7 - self.rbit) != 0; self.rbit += 1; if self.rbit > 7 { self.rbit = 0; self.rpos += 1; } bit } /// Read n bits. an return the corresponding value an u64. /// /// **Note 1** : We cannot read more than 64 bits /// /// **Note 2** Bits are read from left to right /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::from_bytes(&vec![128]); // 10000000b /// let value = buffer.read_bits(3); // value contains 4 (eg: 100b) /// ``` pub fn read_bits(&mut self, n: u8) -> u64 { // TODO : Assert that n <= 64 if n > 0 { ((if self.read_bit() { 1 } else { 0 }) << n - 1) | self.read_bits(n - 1) } else { 0 } } /// Discard all the pending bits available for reading or writing and place the the corresponding cursor to the next byte. /// /// **Note 1** : If no bits are currently read or written, this function does nothing. /// **Note 2** : This function is automatically called for each write or read operations. /// #Example /// /// ```text /// 10010010 | 00000001 /// ^ /// 10010010 | 00000001 // read_bit called /// ^ /// 10010010 | 00000001 // flush_bit() called /// ^ /// ``` pub fn flush_bit(&mut self) { if self.rbit > 0 { self.rpos += 1; self.rbit = 0 } if self.wbit > 0 { self.wpos += 1; self.wbit = 0 } } /// Append 1 bit value to the buffer. /// The bit is happened like this : /// /// ```text /// ...| XXXXXXXX | 10000000 |.... /// ``` pub fn write_bit(&mut self, bit: bool) { let size = self.wpos + 1; if size > self.data.len() { self.resize(size); } if bit { self.data[self.wpos] |= 1 << (7 - self.wbit); } self.wbit += 1; if self.wbit > 7 { self.wbit = 0; self.wpos += 1; } } /// Write the given value as a sequence of n bits /// /// #Example /// /// ``` /// # use bytebuffer::*; /// let mut buffer = ByteBuffer::new(); /// buffer.write_bits(4, 3); // append 100b /// ``` pub fn write_bits(&mut self, value: u64, n: u8) { if n > 0 { self.write_bit((value >> n - 1) & 1 != 0); self.write_bits(value, n - 1); } else { self.write_bit((value & 1) != 0); } } } impl Read for ByteBuffer { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { self.flush_bit(); let read_len = std::cmp::min(self.data.len() - self.rpos, buf.len()); let range = self.rpos..self.rpos + read_len; for (i, val) in (&self.data[range]).iter().enumerate() { buf[i] = *val; } self.rpos += read_len; Ok(read_len) } } impl Write for ByteBuffer { fn write(&mut self, buf: &[u8]) -> Result<usize> { self.write_bytes(buf); Ok(buf.len()) } fn flush(&mut self) -> Result<()> { Ok(()) } } impl std::fmt::Debug for ByteBuffer { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let rpos = if self.rbit > 0 { self.rpos + 1 } else { self.rpos }; let read_len = self.data.len() - rpos; let mut remaining_data = vec![0; read_len]; let range = rpos..rpos + read_len; for (i, val) in (&self.data[range]).iter().enumerate() { remaining_data[i] = *val; } write!(f, "ByteBuffer {{ remaining_data: {:?}, total_data: {:?} }}", remaining_data, self.data) } }
mmitteregger/rust-bytebuffer
src/lib.rs
Rust
apache-2.0
14,910
package com.baidu.beidou.navi.client.attachment; import com.baidu.beidou.navi.server.vo.RequestDTO; import com.baidu.beidou.navi.util.StringUtil; /** * ClassName: AuthAttachmentHandler <br/> * Function: 带有权限处理的handler * * @author Zhang Xu */ public class AuthAttachmentHandler implements AttachmentHandler { /** * 装饰作用,指代其他的handler */ private AttachmentHandler handler; /** * Creates a new instance of AuthAttachmentHandler. */ public AuthAttachmentHandler() { super(); } /** * Creates a new instance of AuthAttachmentHandler. * * @param handler * 带装饰的handler */ public AuthAttachmentHandler(AttachmentHandler handler) { super(); this.handler = handler; } /** * 处理附加信息 * * @param requestDTO * 请求DTO * @param attachment * 附加信息 * @see com.baidu.beidou.navi.client.attachment.AttachmentHandler#handle(com.baidu.beidou.navi.server.vo.RequestDTO, * com.baidu.beidou.navi.client.attachment.Attachment) */ @Override public void handle(RequestDTO requestDTO, Attachment attachment) { if (handler != null) { handler.handle(requestDTO, attachment); } if (attachment != null && attachment.getAppIdToken() != null && StringUtil.isNotEmpty(attachment.getAppIdToken().getAppId()) && StringUtil.isNotEmpty(attachment.getAppIdToken().getToken())) { requestDTO.setAppId(attachment.getAppIdToken().getAppId()); requestDTO.setToken(attachment.getAppIdToken().getToken()); } } public AttachmentHandler getHandler() { return handler; } public void setHandler(AttachmentHandler handler) { this.handler = handler; } }
neoremind/navi
navi/src/main/java/com/baidu/beidou/navi/client/attachment/AuthAttachmentHandler.java
Java
apache-2.0
1,909
/* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * 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 org.opensingular.requirement.connector.sei30.ws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import java.util.ArrayList; import java.util.List; /** * <p>Classe Java de ArrayOfUnidade complex type. * * <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe. * * <pre> * &lt;complexType name="ArrayOfUnidade"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="item" type="{Sei}Unidade" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ArrayOfUnidade", propOrder = { "item" }) public class ArrayOfUnidade { @XmlElement(nillable = true) protected List<Unidade> item; /** * Gets the value of the item property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the item property. * * <p> * For example, to add a new item, do as follows: * <pre> * getItem().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Unidade } * * */ public List<Unidade> getItem() { if (item == null) { item = new ArrayList<Unidade>(); } return this.item; } }
opensingular/singular-server
requirement/requirement-sei-30-connector/src/main/java/org/opensingular/requirement/connector/sei30/ws/ArrayOfUnidade.java
Java
apache-2.0
2,461
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver14; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; import java.util.Arrays; class OFBsnPduTxRequestVer14 implements OFBsnPduTxRequest { private static final Logger logger = LoggerFactory.getLogger(OFBsnPduTxRequestVer14.class); // version: 1.4 final static byte WIRE_VERSION = 5; final static int MINIMUM_LENGTH = 28; // maximum OF message length: 16 bit, unsigned final static int MAXIMUM_LENGTH = 0xFFFF; private final static long DEFAULT_XID = 0x0L; private final static long DEFAULT_TX_INTERVAL_MS = 0x0L; private final static OFPort DEFAULT_PORT_NO = OFPort.ANY; private final static short DEFAULT_SLOT_NUM = (short) 0x0; private final static byte[] DEFAULT_DATA = new byte[0]; // OF message fields private final long xid; private final long txIntervalMs; private final OFPort portNo; private final short slotNum; private final byte[] data; // // Immutable default instance final static OFBsnPduTxRequestVer14 DEFAULT = new OFBsnPduTxRequestVer14( DEFAULT_XID, DEFAULT_TX_INTERVAL_MS, DEFAULT_PORT_NO, DEFAULT_SLOT_NUM, DEFAULT_DATA ); // package private constructor - used by readers, builders, and factory OFBsnPduTxRequestVer14(long xid, long txIntervalMs, OFPort portNo, short slotNum, byte[] data) { if(portNo == null) { throw new NullPointerException("OFBsnPduTxRequestVer14: property portNo cannot be null"); } if(data == null) { throw new NullPointerException("OFBsnPduTxRequestVer14: property data cannot be null"); } this.xid = U32.normalize(xid); this.txIntervalMs = U32.normalize(txIntervalMs); this.portNo = portNo; this.slotNum = U8.normalize(slotNum); this.data = data; } // Accessors for OF message fields @Override public OFVersion getVersion() { return OFVersion.OF_14; } @Override public OFType getType() { return OFType.EXPERIMENTER; } @Override public long getXid() { return xid; } @Override public long getExperimenter() { return 0x5c16c7L; } @Override public long getSubtype() { return 0x1fL; } @Override public long getTxIntervalMs() { return txIntervalMs; } @Override public OFPort getPortNo() { return portNo; } @Override public short getSlotNum() { return slotNum; } @Override public byte[] getData() { return data; } public OFBsnPduTxRequest.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFBsnPduTxRequest.Builder { final OFBsnPduTxRequestVer14 parentMessage; // OF message fields private boolean xidSet; private long xid; private boolean txIntervalMsSet; private long txIntervalMs; private boolean portNoSet; private OFPort portNo; private boolean slotNumSet; private short slotNum; private boolean dataSet; private byte[] data; BuilderWithParent(OFBsnPduTxRequestVer14 parentMessage) { this.parentMessage = parentMessage; } @Override public OFVersion getVersion() { return OFVersion.OF_14; } @Override public OFType getType() { return OFType.EXPERIMENTER; } @Override public long getXid() { return xid; } @Override public OFBsnPduTxRequest.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public long getExperimenter() { return 0x5c16c7L; } @Override public long getSubtype() { return 0x1fL; } @Override public long getTxIntervalMs() { return txIntervalMs; } @Override public OFBsnPduTxRequest.Builder setTxIntervalMs(long txIntervalMs) { this.txIntervalMs = txIntervalMs; this.txIntervalMsSet = true; return this; } @Override public OFPort getPortNo() { return portNo; } @Override public OFBsnPduTxRequest.Builder setPortNo(OFPort portNo) { this.portNo = portNo; this.portNoSet = true; return this; } @Override public short getSlotNum() { return slotNum; } @Override public OFBsnPduTxRequest.Builder setSlotNum(short slotNum) { this.slotNum = slotNum; this.slotNumSet = true; return this; } @Override public byte[] getData() { return data; } @Override public OFBsnPduTxRequest.Builder setData(byte[] data) { this.data = data; this.dataSet = true; return this; } @Override public OFBsnPduTxRequest build() { long xid = this.xidSet ? this.xid : parentMessage.xid; long txIntervalMs = this.txIntervalMsSet ? this.txIntervalMs : parentMessage.txIntervalMs; OFPort portNo = this.portNoSet ? this.portNo : parentMessage.portNo; if(portNo == null) throw new NullPointerException("Property portNo must not be null"); short slotNum = this.slotNumSet ? this.slotNum : parentMessage.slotNum; byte[] data = this.dataSet ? this.data : parentMessage.data; if(data == null) throw new NullPointerException("Property data must not be null"); // return new OFBsnPduTxRequestVer14( xid, txIntervalMs, portNo, slotNum, data ); } } static class Builder implements OFBsnPduTxRequest.Builder { // OF message fields private boolean xidSet; private long xid; private boolean txIntervalMsSet; private long txIntervalMs; private boolean portNoSet; private OFPort portNo; private boolean slotNumSet; private short slotNum; private boolean dataSet; private byte[] data; @Override public OFVersion getVersion() { return OFVersion.OF_14; } @Override public OFType getType() { return OFType.EXPERIMENTER; } @Override public long getXid() { return xid; } @Override public OFBsnPduTxRequest.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public long getExperimenter() { return 0x5c16c7L; } @Override public long getSubtype() { return 0x1fL; } @Override public long getTxIntervalMs() { return txIntervalMs; } @Override public OFBsnPduTxRequest.Builder setTxIntervalMs(long txIntervalMs) { this.txIntervalMs = txIntervalMs; this.txIntervalMsSet = true; return this; } @Override public OFPort getPortNo() { return portNo; } @Override public OFBsnPduTxRequest.Builder setPortNo(OFPort portNo) { this.portNo = portNo; this.portNoSet = true; return this; } @Override public short getSlotNum() { return slotNum; } @Override public OFBsnPduTxRequest.Builder setSlotNum(short slotNum) { this.slotNum = slotNum; this.slotNumSet = true; return this; } @Override public byte[] getData() { return data; } @Override public OFBsnPduTxRequest.Builder setData(byte[] data) { this.data = data; this.dataSet = true; return this; } // @Override public OFBsnPduTxRequest build() { long xid = this.xidSet ? this.xid : DEFAULT_XID; long txIntervalMs = this.txIntervalMsSet ? this.txIntervalMs : DEFAULT_TX_INTERVAL_MS; OFPort portNo = this.portNoSet ? this.portNo : DEFAULT_PORT_NO; if(portNo == null) throw new NullPointerException("Property portNo must not be null"); short slotNum = this.slotNumSet ? this.slotNum : DEFAULT_SLOT_NUM; byte[] data = this.dataSet ? this.data : DEFAULT_DATA; if(data == null) throw new NullPointerException("Property data must not be null"); return new OFBsnPduTxRequestVer14( xid, txIntervalMs, portNo, slotNum, data ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFBsnPduTxRequest> { @Override public OFBsnPduTxRequest readFrom(ByteBuf bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property version == 5 byte version = bb.readByte(); if(version != (byte) 0x5) throw new OFParseError("Wrong version: Expected=OFVersion.OF_14(5), got="+version); // fixed value property type == 4 byte type = bb.readByte(); if(type != (byte) 0x4) throw new OFParseError("Wrong type: Expected=OFType.EXPERIMENTER(4), got="+type); int length = U16.f(bb.readShort()); if(length < MINIMUM_LENGTH) throw new OFParseError("Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length); if(bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if(logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); long xid = U32.f(bb.readInt()); // fixed value property experimenter == 0x5c16c7L int experimenter = bb.readInt(); if(experimenter != 0x5c16c7) throw new OFParseError("Wrong experimenter: Expected=0x5c16c7L(0x5c16c7L), got="+experimenter); // fixed value property subtype == 0x1fL int subtype = bb.readInt(); if(subtype != 0x1f) throw new OFParseError("Wrong subtype: Expected=0x1fL(0x1fL), got="+subtype); long txIntervalMs = U32.f(bb.readInt()); OFPort portNo = OFPort.read4Bytes(bb); short slotNum = U8.f(bb.readByte()); // pad: 3 bytes bb.skipBytes(3); byte[] data = ChannelUtils.readBytes(bb, length - (bb.readerIndex() - start)); OFBsnPduTxRequestVer14 bsnPduTxRequestVer14 = new OFBsnPduTxRequestVer14( xid, txIntervalMs, portNo, slotNum, data ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", bsnPduTxRequestVer14); return bsnPduTxRequestVer14; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFBsnPduTxRequestVer14Funnel FUNNEL = new OFBsnPduTxRequestVer14Funnel(); static class OFBsnPduTxRequestVer14Funnel implements Funnel<OFBsnPduTxRequestVer14> { private static final long serialVersionUID = 1L; @Override public void funnel(OFBsnPduTxRequestVer14 message, PrimitiveSink sink) { // fixed value property version = 5 sink.putByte((byte) 0x5); // fixed value property type = 4 sink.putByte((byte) 0x4); // FIXME: skip funnel of length sink.putLong(message.xid); // fixed value property experimenter = 0x5c16c7L sink.putInt(0x5c16c7); // fixed value property subtype = 0x1fL sink.putInt(0x1f); sink.putLong(message.txIntervalMs); message.portNo.putTo(sink); sink.putShort(message.slotNum); // skip pad (3 bytes) sink.putBytes(message.data); } } public void writeTo(ByteBuf bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFBsnPduTxRequestVer14> { @Override public void write(ByteBuf bb, OFBsnPduTxRequestVer14 message) { int startIndex = bb.writerIndex(); // fixed value property version = 5 bb.writeByte((byte) 0x5); // fixed value property type = 4 bb.writeByte((byte) 0x4); // length is length of variable message, will be updated at the end int lengthIndex = bb.writerIndex(); bb.writeShort(U16.t(0)); bb.writeInt(U32.t(message.xid)); // fixed value property experimenter = 0x5c16c7L bb.writeInt(0x5c16c7); // fixed value property subtype = 0x1fL bb.writeInt(0x1f); bb.writeInt(U32.t(message.txIntervalMs)); message.portNo.write4Bytes(bb); bb.writeByte(U8.t(message.slotNum)); // pad: 3 bytes bb.writeZero(3); bb.writeBytes(message.data); // update length field int length = bb.writerIndex() - startIndex; if (length > MAXIMUM_LENGTH) { throw new IllegalArgumentException("OFBsnPduTxRequestVer14: message length (" + length + ") exceeds maximum (0xFFFF)"); } bb.setShort(lengthIndex, length); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFBsnPduTxRequestVer14("); b.append("xid=").append(xid); b.append(", "); b.append("txIntervalMs=").append(txIntervalMs); b.append(", "); b.append("portNo=").append(portNo); b.append(", "); b.append("slotNum=").append(slotNum); b.append(", "); b.append("data=").append(Arrays.toString(data)); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFBsnPduTxRequestVer14 other = (OFBsnPduTxRequestVer14) obj; if( xid != other.xid) return false; if( txIntervalMs != other.txIntervalMs) return false; if (portNo == null) { if (other.portNo != null) return false; } else if (!portNo.equals(other.portNo)) return false; if( slotNum != other.slotNum) return false; if (!Arrays.equals(data, other.data)) return false; return true; } @Override public boolean equalsIgnoreXid(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFBsnPduTxRequestVer14 other = (OFBsnPduTxRequestVer14) obj; // ignore XID if( txIntervalMs != other.txIntervalMs) return false; if (portNo == null) { if (other.portNo != null) return false; } else if (!portNo.equals(other.portNo)) return false; if( slotNum != other.slotNum) return false; if (!Arrays.equals(data, other.data)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * (int) (xid ^ (xid >>> 32)); result = prime * (int) (txIntervalMs ^ (txIntervalMs >>> 32)); result = prime * result + ((portNo == null) ? 0 : portNo.hashCode()); result = prime * result + slotNum; result = prime * result + Arrays.hashCode(data); return result; } @Override public int hashCodeIgnoreXid() { final int prime = 31; int result = 1; // ignore XID result = prime * (int) (txIntervalMs ^ (txIntervalMs >>> 32)); result = prime * result + ((portNo == null) ? 0 : portNo.hashCode()); result = prime * result + slotNum; result = prime * result + Arrays.hashCode(data); return result; } }
floodlight/loxigen-artifacts
openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/ver14/OFBsnPduTxRequestVer14.java
Java
apache-2.0
18,089
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- * Copyright (c) 2012, Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 * --> <html> <head> <meta name="viewport" content="width=device-width target-densitydpi=device-dpi initial-scale=1 maximum-scale=1 user-scalable=0" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Sweet Spot</title> <link rel="stylesheet" type="text/css" href="css/main.css"></link> <link rel="stylesheet" type="text/css" href="css/license.css"></link> <link rel="stylesheet" type="text/css" href="css/help.css"></link> <script src="js/help.js"></script> <script src="js/license.js"></script> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/main.js"></script> </head> <body> <div id="intro_page" class="game_page"> <div id="intro_bg"></div> <div id="intro_candyblue"></div> <div id="intro_candygreen"></div> <div id="intro_candyred"></div> <div id="intro_candyorange"></div> <div id="intro_playbutton">Play</div> <div id="licensebtnl" style="top: 564px; left: 977px;"> i </div> </div> <div id="help_dialog" class="helpdialog"> <div class="inner"> <div id="help_close" class="close"> x </div> <div id="help_contents" class="contents"> Try to be the first to get four of your candies in a row. <br><br> First, choose what color your candies will be. Then choose a single game, best two out of three, or best three out of five. <br><br> Take turns, with a friend, clicking to drop your candies down the column where you want your candy to go. The first to get four of their candies lined up in any direction (vertical, horizontal, or diagonal) wins! If the board fills up without anyone winning, everything is cleared off, and the game continues. <br><br> If you want to restart a game, click the X at the bottom-right of the screen, and click Yes and you’ll be taken back to the beginning. If you do this by mistake, click No, and your current game continues. </div> </div> </div> <div id="players_page" class="game_page" style="display: none"> <div id="player_bg"></div> <div id="player_player1_static">Player 1</div> <div id="player_player1"><input type="text" id="player1name" size=13/></div> <div id="player_player2_static">Player 2</div> <div id="player_player2"><input type="text" id="player2name" size=13/></div> <div id="player_text_chooseyour">Choose Your</div> <div id="player_text_color">Color</div> <div id="player_player1red"><div class="pickred"></div></div> <div id="player_player1blue"><div class="pickblue"></div></div> <div id="player_player1green"><div class="pickgreen"></div></div> <div id="player_player1orange"><div class="pickorange"></div></div> <div id="player_player2red"><div class="pickred"></div></div> <div id="player_player2blue"><div class="pickblue"></div></div> <div id="player_player2green"><div class="pickgreen"></div></div> <div id="player_player2orange"><div class="pickorange"></div></div> <div id="player_nextbutton" class="inactive_button">Next</div> </div> <div id="type_page" class="game_page" style="display: none"> <div id="type_bg"></div> <div id="type_onegame_text">1 Game</div> <div id="type_onegame"></div> <div id="type_bestofthree_text">Best 2 of 3</div> <div id="type_bestofthree"></div> <div id="type_bestoffive_text">Best 3 of 5</div> <div id="type_bestoffive"></div> <div id="type_startbutton" class="inactive_button">Start</div> </div> <div id="game_page" class="game_page" style="display: none"> <div id="game_bg"></div> <div id="game_player1marquee"><div id="game_player1name"></div></div> <div id="game_player2marquee"><div id="game_player2name"></div></div> <div id="game_player1active"></div> <div id="game_player2active" style="display: none"></div> <div id="game_column_selector" style="display: none"></div> <div id="game_column_selector_candy" style="display: none"></div> <div id="game_grid"></div> <div id="game_column1"></div> <div id="game_column2"></div> <div id="game_column3"></div> <div id="game_column4"></div> <div id="game_column5"></div> <div id="game_column6"></div> <div id="game_column7"></div> <div id="game_player1_wins">0</div> <div id="game_player2_wins">0</div> <div id="game_quit"></div> <div id="quit_dlg" style="display: none"> <div id="quit_dlg_bg"></div> <div id="quit_dlg_img">Start Over?</div> <div id="quit_dlg_no">No</div> <div id="quit_dlg_yes">Yes</div> </div> </div> <div id="main_help" class="helplaunch"> ? </div> <div id="licensepage" style="display: none"> <iframe id="licensetext" src="README.txt"></iframe> <div id="licensebtnu" class="licensebtn">&uarr;</div> <div id="licensebtnd" class="licensebtn">&darr;</div> <div id="licensebtnq" class="licensebtn">Back</div> </div> <div id="win_page" class="game_page" style="display: none"> <div id="win_bg"></div> <div id="win_banner">Winner</div> <div id="win_playername"></div> <div id="win_playagain"></div> <div id="win_startover"></div> <div id="win_playagain_text">Play Again</div> <div id="win_startover_text">Start Over</div> </div> <audio class="gamepiece" preload="auto"><source src="audio/GamePiece.wav" type="audio/wav" /></audio> <audio class="menu" preload="auto"><source src="audio/MenuNavigation.wav" type="audio/wav" /></audio> <audio class="select" preload="auto"><source src="audio/Select.wav" type="audio/wav" /></audio> <audio class="win" preload="auto"><source src="audio/Winner.wav" type="audio/wav" /></audio> </body> </html>
pplaquette/webapps-sweetspot
index.html
HTML
apache-2.0
6,531
<!--[metadata]> +++ title = "Using Compose with Swarm" description = "How to use Compose and Swarm together to deploy apps to multi-host clusters" keywords = ["documentation, docs, docker, compose, orchestration, containers, swarm"] [menu.main] parent="workw_compose" +++ <![end-metadata]--> # Using Compose with Swarm Docker Compose and [Docker Swarm](/swarm/overview.md) aim to have full integration, meaning you can point a Compose app at a Swarm cluster and have it all just work as if you were using a single Docker host. The actual extent of integration depends on which version of the [Compose file format](compose-file.md#versioning) you are using: 1. If you're using version 1 along with `links`, your app will work, but Swarm will schedule all containers on one host, because links between containers do not work across hosts with the old networking system. 2. If you're using version 2, your app should work with no changes: - subject to the [limitations](#limitations) described below, - as long as the Swarm cluster is configured to use the [overlay driver](https://docs.docker.com/engine/userguide/networking/dockernetworks/#an-overlay-network), or a custom driver which supports multi-host networking. Read [Get started with multi-host networking](https://docs.docker.com/engine/userguide/networking/get-started-overlay/) to see how to set up a Swarm cluster with [Docker Machine](/machine/overview.md) and the overlay driver. Once you've got it running, deploying your app to it should be as simple as: $ eval "$(docker-machine env --swarm <name of swarm master machine>)" $ docker-compose up ## Limitations ### Building images Swarm can build an image from a Dockerfile just like a single-host Docker instance can, but the resulting image will only live on a single node and won't be distributed to other nodes. If you want to use Compose to scale the service in question to multiple nodes, you'll have to build it yourself, push it to a registry (e.g. the Docker Hub) and reference it from `docker-compose.yml`: $ docker build -t myusername/web . $ docker push myusername/web $ cat docker-compose.yml web: image: myusername/web $ docker-compose up -d $ docker-compose scale web=3 ### Multiple dependencies If a service has multiple dependencies of the type which force co-scheduling (see [Automatic scheduling](#automatic-scheduling) below), it's possible that Swarm will schedule the dependencies on different nodes, making the dependent service impossible to schedule. For example, here `foo` needs to be co-scheduled with `bar` and `baz`: version: "2" services: foo: image: foo volumes_from: ["bar"] network_mode: "service:baz" bar: image: bar baz: image: baz The problem is that Swarm might first schedule `bar` and `baz` on different nodes (since they're not dependent on one another), making it impossible to pick an appropriate node for `foo`. To work around this, use [manual scheduling](#manual-scheduling) to ensure that all three services end up on the same node: version: "2" services: foo: image: foo volumes_from: ["bar"] network_mode: "service:baz" environment: - "constraint:node==node-1" bar: image: bar environment: - "constraint:node==node-1" baz: image: baz environment: - "constraint:node==node-1" ### Host ports and recreating containers If a service maps a port from the host, e.g. `80:8000`, then you may get an error like this when running `docker-compose up` on it after the first time: docker: Error response from daemon: unable to find a node that satisfies container==6ab2dfe36615ae786ef3fc35d641a260e3ea9663d6e69c5b70ce0ca6cb373c02. The usual cause of this error is that the container has a volume (defined either in its image or in the Compose file) without an explicit mapping, and so in order to preserve its data, Compose has directed Swarm to schedule the new container on the same node as the old container. This results in a port clash. There are two viable workarounds for this problem: - Specify a named volume, and use a volume driver which is capable of mounting the volume into the container regardless of what node it's scheduled on. Compose does not give Swarm any specific scheduling instructions if a service uses only named volumes. version: "2" services: web: build: . ports: - "80:8000" volumes: - web-logs:/var/log/web volumes: web-logs: driver: custom-volume-driver - Remove the old container before creating the new one. You will lose any data in the volume. $ docker-compose stop web $ docker-compose rm -f web $ docker-compose up web ## Scheduling containers ### Automatic scheduling Some configuration options will result in containers being automatically scheduled on the same Swarm node to ensure that they work correctly. These are: - `network_mode: "service:..."` and `network_mode: "container:..."` (and `net: "container:..."` in the version 1 file format). - `volumes_from` - `links` ### Manual scheduling Swarm offers a rich set of scheduling and affinity hints, enabling you to control where containers are located. They are specified via container environment variables, so you can use Compose's `environment` option to set them. # Schedule containers on a specific node environment: - "constraint:node==node-1" # Schedule containers on a node that has the 'storage' label set to 'ssd' environment: - "constraint:storage==ssd" # Schedule containers where the 'redis' image is already pulled environment: - "affinity:image==redis" For the full set of available filters and expressions, see the [Swarm documentation](/swarm/scheduler/filter.md).
denverdino/compose
docs/swarm.md
Markdown
apache-2.0
6,047
<?php declare(strict_types=1); namespace Framework\Syscrack\Game\Softwares; /** * Lewis Lancaster 2017 * * Class Firewall * * @package Framework\Syscrack\Game\Softwares */ use Framework\Syscrack\Game\Bases\BaseSoftware; /** * Class Firewall * @package Framework\Syscrack\Game\Softwares */ class Firewall extends BaseSoftware { /** * The configuration of this Structure * * @return array */ public function configuration() { return [ 'uniquename' => 'firewall', 'extension' => '.fwall', 'type' => 'firewall', 'installable' => true, 'executable' => false ]; } }
dialtoneuk/Syscrack2017
src/Syscrack/Game/Softwares/Firewall.php
PHP
apache-2.0
638
/* * Copyright 2013 The GDG Frisbee 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 org.gdg.frisbee.android.app; import android.content.Context; import android.graphics.Bitmap; import android.util.Log; import com.android.volley.RequestQueue; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.Volley; import org.gdg.frisbee.android.api.GdgStack; import timber.log.Timber; import uk.co.senab.bitmapcache.CacheableBitmapDrawable; /** * GDG Aachen * org.gdg.frisbee.android.api * <p/> * User: maui * Date: 26.05.13 * Time: 19:25 */ public class GdgVolley { public static final String LOG_TAG = "GDG-GdgVolley"; private static GdgVolley mInstance; public static GdgVolley getInstance() { return mInstance; } private RequestQueue mRequestQueue, mImageRequestQueue; private ImageLoader mImageLoader; static void init(Context ctx) { mInstance = new GdgVolley(ctx); } private GdgVolley(Context ctx) { mRequestQueue = Volley.newRequestQueue(ctx, new GdgStack()); mImageRequestQueue = Volley.newRequestQueue(ctx, new GdgStack()); mImageLoader = new ImageLoader(mImageRequestQueue, new ImageLoader.ImageCache() { @Override public Bitmap getBitmap(String url) { // Check memcache here...disk cache lookup will be done by GdgStack Timber.d("Looking up " + url + " in cache"); CacheableBitmapDrawable bitmap = App.getInstance().getBitmapCache().get(url); if(bitmap != null) { Timber.d("Bitmap Memcache hit"); return bitmap.getBitmap(); } else return null; } @Override public void putBitmap(final String url, final Bitmap bitmap) { new Thread() { @Override public void run() { String myurl = url.substring(6); Timber.d("Saving "+ myurl + " to cache"); App.getInstance().getBitmapCache().put(myurl, bitmap); } }.start(); } }); } public RequestQueue getRequestQueue() { if (mRequestQueue != null) { return mRequestQueue; } else { throw new IllegalStateException("RequestQueue not initialized"); } } public ImageLoader getImageLoader() { if (mImageLoader != null) { return mImageLoader; } else { throw new IllegalStateException("ImageLoader not initialized"); } } }
gdgjodhpur/gdgapp
app/src/main/java/org/gdg/frisbee/android/app/GdgVolley.java
Java
apache-2.0
3,200
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>ChocolateyChecksumType - FAKE - F# Make</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull"> <script src="https://code.jquery.com/jquery-1.8.0.js"></script> <script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script> <script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" /> <script type="text/javascript" src="http://fsharp.github.io/FAKE/content/tips.js"></script> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="masthead"> <ul class="nav nav-pills pull-right"> <li><a href="http://fsharp.org">fsharp.org</a></li> <li><a href="http://github.com/fsharp/fake">github page</a></li> </ul> <h3 class="muted"><a href="http://fsharp.github.io/FAKE/index.html">FAKE - F# Make</a></h3> </div> <hr /> <div class="row"> <div class="span9" id="main"> <h1>ChocolateyChecksumType</h1> <div class="xmldoc"> </div> <h3>Union Cases</h3> <table class="table table-bordered member-list"> <thead> <tr><td>Union Case</td><td>Description</td></tr> </thead> <tbody> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1454', 1454)" onmouseover="showTip(event, '1454', 1454)"> Md5 </code> <div class="tip" id="1454"> <strong>Signature:</strong> <br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/ChocoHelper.fs#L18-18" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1455', 1455)" onmouseover="showTip(event, '1455', 1455)"> Sha1 </code> <div class="tip" id="1455"> <strong>Signature:</strong> <br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/ChocoHelper.fs#L19-19" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1456', 1456)" onmouseover="showTip(event, '1456', 1456)"> Sha256 </code> <div class="tip" id="1456"> <strong>Signature:</strong> <br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/ChocoHelper.fs#L20-20" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1457', 1457)" onmouseover="showTip(event, '1457', 1457)"> Sha512 </code> <div class="tip" id="1457"> <strong>Signature:</strong> <br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/ChocoHelper.fs#L21-21" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> </tbody> </table> </div> <div class="span3"> <a href="http://fsharp.github.io/FAKE/index.html"> <img src="http://fsharp.github.io/FAKE/pics/logo.png" style="width:140px;height:140px;margin:10px 0px 0px 35px;border-style:none;" /> </a> <ul class="nav nav-list" id="menu"> <li class="nav-header">FAKE - F# Make</li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/index.html">Home page</a></li> <li class="divider"></li> <li><a href="https://www.nuget.org/packages/FAKE">Get FAKE - F# Make via NuGet</a></li> <li><a href="http://github.com/fsharp/fake">Source Code on GitHub</a></li> <li><a href="http://github.com/fsharp/fake/blob/master/License.txt">License (Apache 2)</a></li> <li><a href="http://fsharp.github.io/FAKE/RELEASE_NOTES.html">Release Notes</a></li> <li><a href="http://fsharp.github.io/FAKE//contributing.html">Contributing to FAKE - F# Make</a></li> <li><a href="http://fsharp.github.io/FAKE/users.html">Who is using FAKE?</a></li> <li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li> <li class="nav-header">Tutorials</li> <li><a href="http://fsharp.github.io/FAKE/gettingstarted.html">Getting started</a></li> <li><a href="http://fsharp.github.io/FAKE/cache.html">Build script caching</a></li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/nuget.html">NuGet package restore</a></li> <li><a href="http://fsharp.github.io/FAKE/fxcop.html">Using FxCop in a build</a></li> <li><a href="http://fsharp.github.io/FAKE/assemblyinfo.html">Generating AssemblyInfo</a></li> <li><a href="http://fsharp.github.io/FAKE/create-nuget-package.html">Create NuGet packages</a></li> <li><a href="http://fsharp.github.io/FAKE/specifictargets.html">Running specific targets</a></li> <li><a href="http://fsharp.github.io/FAKE/commandline.html">Running FAKE from command line</a></li> <li><a href="http://fsharp.github.io/FAKE/parallel-build.html">Running targets in parallel</a></li> <li><a href="http://fsharp.github.io/FAKE/fsc.html">Using the F# compiler from FAKE</a></li> <li><a href="http://fsharp.github.io/FAKE/customtasks.html">Creating custom tasks</a></li> <li><a href="http://fsharp.github.io/FAKE/soft-dependencies.html">Soft dependencies</a></li> <li><a href="http://fsharp.github.io/FAKE/teamcity.html">TeamCity integration</a></li> <li><a href="http://fsharp.github.io/FAKE/canopy.html">Running canopy tests</a></li> <li><a href="http://fsharp.github.io/FAKE/octopusdeploy.html">Octopus Deploy</a></li> <li><a href="http://fsharp.github.io/FAKE/typescript.html">TypeScript support</a></li> <li><a href="http://fsharp.github.io/FAKE/azurewebjobs.html">Azure WebJobs support</a></li> <li><a href="http://fsharp.github.io/FAKE/azurecloudservices.html">Azure Cloud Services support</a></li> <li><a href="http://fsharp.github.io/FAKE/fluentmigrator.html">FluentMigrator support</a></li> <li><a href="http://fsharp.github.io/FAKE/androidpublisher.html">Android publisher</a></li> <li><a href="http://fsharp.github.io/FAKE/watch.html">File Watcher</a></li> <li><a href="http://fsharp.github.io/FAKE/wix.html">WiX Setup Generation</a></li> <li><a href="http://fsharp.github.io/FAKE/chocolatey.html">Using Chocolatey</a></li> <li><a href="http://fsharp.github.io/FAKE/slacknotification.html">Using Slack</a></li> <li><a href="http://fsharp.github.io/FAKE/sonarcube.html">Using SonarQube</a></li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/deploy.html">Fake.Deploy</a></li> <li><a href="http://fsharp.github.io/FAKE/iis.html">Fake.IIS</a></li> <li class="nav-header">Reference</li> <li><a href="http://fsharp.github.io/FAKE/apidocs/index.html">API Reference</a></li> </ul> </div> </div> </div> <a href="http://github.com/fsharp/fake"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a> </body> </html>
kirill-gerasimenko/fseye
packages/FAKE/docs/apidocs/fake-choco-chocolateychecksumtype.html
HTML
apache-2.0
9,264
package com.quakearts.appbase.test.experiments; public interface TestSubInject { void doSomething(); }
kwakutwumasi/Quakearts-JSF-Webtools
qa-appbase/src/test/java/com/quakearts/appbase/test/experiments/TestSubInject.java
Java
apache-2.0
105
/** * Copyright 2015-2016 Debmalya Jash * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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 scrapper; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; /** * @author debmalyajash * */ public class ThoughtOfTheDay { private static String URL = "http://www.radiosai.org/pages/thought.asp"; private static String TEXT_URL = "http://www.radiosai.org/pages/ThoughtText.asp?mydate="; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { LocalDate dateNow = LocalDate.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); PrintWriter thoughtOfTheDay = null; try { thoughtOfTheDay = new PrintWriter(new File("ThoughtOfTheDay.txt")); while (true) { dateNow = dateNow.minusDays(1); String quote = getQuote(TEXT_URL + formatter.format(dateNow)); if ("".equals(quote)) { break; } thoughtOfTheDay.println(getQuote(TEXT_URL + formatter.format(dateNow))); thoughtOfTheDay.println("------------------------------------------------"); } thoughtOfTheDay.println(getQuote(URL)); thoughtOfTheDay.println("------------------------------------------------"); } finally { System.out.println("Till :" + formatter.format(dateNow)); if (thoughtOfTheDay != null) { thoughtOfTheDay.flush(); thoughtOfTheDay.close(); } } } private static String getQuote(String url) throws IOException { Element doc = Jsoup.connect(url).get(); Element content = doc.getElementById("content"); if (content == null) { content = doc.getElementById("Content"); } if (content != null) return content.text(); return ""; } }
debmalya/mapDB
src/main/java/scrapper/ThoughtOfTheDay.java
Java
apache-2.0
2,360
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Noef.UnitTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Noef.UnitTests")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fec379cc-2d6f-485e-8444-bafd06109315")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
sam-meacham/Noef
src/Noef.UnitTests/Properties/AssemblyInfo.cs
C#
apache-2.0
1,418
Score ===== Simple &amp; scalable orchestration engine
dimarassin/Score
README.md
Markdown
apache-2.0
56
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_13b.html">Class Test_AbaRouteValidator_13b</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_27622_bad </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_13b.html?line=10192#src-10192" >testAbaNumberCheck_27622_bad</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:42:36 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_27622_bad</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=16976#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a> </td> <td> <span class="sortValue">0.5714286</span>57.1% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td> </tr> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=16976#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a> </td> <td> <span class="sortValue">0.5714286</span>57.1% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td> </tr> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=16976#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.29411766</span>29.4% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
dcarda/aba.route.validator
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_13b_testAbaNumberCheck_27622_bad_d3k.html
HTML
apache-2.0
10,990