code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/** * Copyright 2018 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. */ 'use strict'; const colors = require('ansi-colors'); const log = require('fancy-log'); const {VERSION: internalRuntimeVersion} = require('./internal-version'); /** * @enum {string} */ const TYPES = (exports.TYPES = { AD: '_base_ad', MEDIA: '_base_media', MISC: '_base_misc', }); /** * Used to generate top-level JS build targets */ exports.jsBundles = { 'polyfills.js': { srcDir: './src/', srcFilename: 'polyfills.js', destDir: './build/', minifiedDestDir: './build/', }, 'alp.max.js': { srcDir: './ads/alp/', srcFilename: 'install-alp.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'alp.max.js', includePolyfills: true, minifiedName: 'alp.js', }, }, 'examiner.max.js': { srcDir: './src/examiner/', srcFilename: 'examiner.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'examiner.max.js', includePolyfills: true, minifiedName: 'examiner.js', }, }, 'ww.max.js': { srcDir: './src/web-worker/', srcFilename: 'web-worker.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'ww.max.js', minifiedName: 'ww.js', includePolyfills: true, }, }, 'integration.js': { srcDir: './3p/', srcFilename: 'integration.js', destDir: './dist.3p/current', minifiedDestDir: './dist.3p/' + internalRuntimeVersion, options: { minifiedName: 'f.js', externs: ['./ads/ads.extern.js'], include3pDirectories: true, includePolyfills: true, }, }, 'ampcontext-lib.js': { srcDir: './3p/', srcFilename: 'ampcontext-lib.js', destDir: './dist.3p/current', minifiedDestDir: './dist.3p/' + internalRuntimeVersion, options: { minifiedName: 'ampcontext-v0.js', externs: ['./ads/ads.extern.js'], include3pDirectories: true, includePolyfills: false, }, }, 'iframe-transport-client-lib.js': { srcDir: './3p/', srcFilename: 'iframe-transport-client-lib.js', destDir: './dist.3p/current', minifiedDestDir: './dist.3p/' + internalRuntimeVersion, options: { minifiedName: 'iframe-transport-client-v0.js', externs: ['./ads/ads.extern.js'], include3pDirectories: true, includePolyfills: false, }, }, 'recaptcha.js': { srcDir: './3p/', srcFilename: 'recaptcha.js', destDir: './dist.3p/current', minifiedDestDir: './dist.3p/' + internalRuntimeVersion, options: { minifiedName: 'recaptcha.js', externs: [], include3pDirectories: true, includePolyfills: true, }, }, 'amp-viewer-host.max.js': { srcDir: './extensions/amp-viewer-integration/0.1/examples/', srcFilename: 'amp-viewer-host.js', destDir: './dist/v0/examples', minifiedDestDir: './dist/v0/examples', options: { toName: 'amp-viewer-host.max.js', minifiedName: 'amp-viewer-host.js', incudePolyfills: true, extraGlobs: ['extensions/amp-viewer-integration/**/*.js'], compilationLevel: 'WHITESPACE_ONLY', skipUnknownDepsCheck: true, }, }, 'video-iframe-integration.js': { srcDir: './src/', srcFilename: 'video-iframe-integration.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'video-iframe-integration-v0.js', includePolyfills: false, }, }, 'amp-story-player.js': { srcDir: './src/', srcFilename: 'amp-story-player.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'amp-story-player-v0.js', includePolyfills: false, }, }, 'amp-inabox-host.js': { srcDir: './ads/inabox/', srcFilename: 'inabox-host.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'amp-inabox-host.js', minifiedName: 'amp4ads-host-v0.js', includePolyfills: false, }, }, 'amp.js': { srcDir: './src/', srcFilename: 'amp.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'v0.js', includePolyfills: true, }, }, 'amp-shadow.js': { srcDir: './src/', srcFilename: 'amp-shadow.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'shadow-v0.js', includePolyfills: true, }, }, 'amp-inabox.js': { srcDir: './src/inabox/', srcFilename: 'amp-inabox.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'amp-inabox.js', minifiedName: 'amp4ads-v0.js', includePolyfills: true, extraGlobs: ['src/inabox/*.js', '3p/iframe-messaging-client.js'], }, }, }; /** * Used to generate extension build targets */ exports.extensionBundles = [ { name: 'amp-3d-gltf', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-3q-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-access', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-access-laterpay', version: ['0.1', '0.2'], latestVersion: '0.2', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-access-scroll', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-access-poool', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-accordion', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-action-macro', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-ad', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.AD, }, { name: 'amp-ad-custom', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-adsense-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-adzerk-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-doubleclick-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-fake-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-triplelift-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-cloudflare-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-gmossp-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-mytarget-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-exit', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-addthis', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-analytics', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-anim', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-animation', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-apester-media', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MEDIA, }, { name: 'amp-app-banner', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-audio', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-auto-ads', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-autocomplete', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-auto-lightbox', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-base-carousel', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-beopinion', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-bind', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-bodymovin-animation', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-brid-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-delight-player', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MEDIA, }, { name: 'amp-brightcove', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-byside-content', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-kaltura-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-call-tracking', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-carousel', version: ['0.1', '0.2'], latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-consent', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-connatix-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-crypto-polyfill', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-dailymotion', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-date-countdown', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-date-display', version: ['0.1', '0.2'], latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-google-document-embed', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-dynamic-css-classes', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-embedly-card', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-experiment', version: ['0.1', '1.0'], latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-facebook', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-facebook-comments', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-facebook-like', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-facebook-page', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-fit-text', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-font', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-form', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-fx-collection', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-fx-flying-carpet', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-geo', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-gfycat', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-gist', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-gwd-animation', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-hulu', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-iframe', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-ima-video', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-image-lightbox', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-image-slider', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-imgur', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-inline-gallery', version: '0.1', latestVersion: '0.1', options: { hasCss: true, cssBinaries: [ 'amp-inline-gallery', 'amp-inline-gallery-pagination', 'amp-inline-gallery-thumbnails', ], }, type: TYPES.MISC, }, { name: 'amp-inputmask', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, postPrepend: ['third_party/inputmask/bundle.js'], }, { name: 'amp-instagram', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-install-serviceworker', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-izlesene', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-jwplayer', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-lightbox', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-lightbox-gallery', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-list', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-live-list', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-loader', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-mathml', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-mega-menu', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-megaphone', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-mustache', version: ['0.1', '0.2'], latestVersion: '0.2', type: TYPES.MISC, }, { name: 'amp-nested-menu', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-next-page', version: ['0.1', '1.0'], latestVersion: '1.0', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-nexxtv-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-o2-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-ooyala-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-pinterest', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-playbuzz', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MEDIA, }, { name: 'amp-reach-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-redbull-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-reddit', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-riddle-quiz', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-script', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-share-tracking', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-sidebar', version: ['0.1', '0.2'], latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-skimlinks', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-smartlinks', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-soundcloud', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-springboard-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-standalone', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-sticky-ad', version: '1.0', latestVersion: '1.0', options: {hasCss: true}, type: TYPES.AD, }, { name: 'amp-story', version: '0.1', latestVersion: '1.0', options: { hasCss: true, cssBinaries: [ 'amp-story-bookend', 'amp-story-consent', 'amp-story-hint', 'amp-story-unsupported-browser-layer', 'amp-story-viewport-warning-layer', 'amp-story-info-dialog', 'amp-story-share', 'amp-story-share-menu', 'amp-story-system-layer', ], }, type: TYPES.MISC, }, { name: 'amp-story', version: '1.0', latestVersion: '1.0', options: { hasCss: true, cssBinaries: [ 'amp-story-bookend', 'amp-story-consent', 'amp-story-draggable-drawer-header', 'amp-story-hint', 'amp-story-info-dialog', 'amp-story-quiz', 'amp-story-share', 'amp-story-share-menu', 'amp-story-system-layer', 'amp-story-tooltip', 'amp-story-unsupported-browser-layer', 'amp-story-viewport-warning-layer', ], }, type: TYPES.MISC, }, { name: 'amp-story-auto-ads', version: '0.1', latestVersion: '0.1', options: { hasCss: true, cssBinaries: [ 'amp-story-auto-ads-ad-badge', 'amp-story-auto-ads-attribution', ], }, type: TYPES.MISC, }, { name: 'amp-stream-gallery', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-selector', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-web-push', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-wistia-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-position-observer', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-orientation-observer', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-date-picker', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, postPrepend: ['third_party/react-dates/bundle.js'], }, { name: 'amp-image-viewer', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-subscriptions', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-subscriptions-google', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-pan-zoom', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-recaptcha-input', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, /** * @deprecated `amp-slides` is deprecated and will be deleted before 1.0. * Please see {@link AmpCarousel} with `type=slides` attribute instead. */ { name: 'amp-slides', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-social-share', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-timeago', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-truncate-text', version: '0.1', latestVersion: '0.1', options: { hasCss: true, cssBinaries: ['amp-truncate-text', 'amp-truncate-text-shadow'], }, type: TYPES.MISC, }, { name: 'amp-twitter', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-user-notification', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-vimeo', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-vine', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-viz-vega', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, postPrepend: [ 'third_party/d3/d3.js', 'third_party/d3-geo-projection/d3-geo-projection.js', 'third_party/vega/vega.js', ], }, { name: 'amp-google-vrview-image', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-viewer-assistance', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-viewer-integration', version: '0.1', latestVersion: '0.1', options: { // The viewer integration code needs to run asap, so that viewers // can influence document state asap. Otherwise the document may take // a long time to learn that it should start process other extensions // faster. loadPriority: 'high', }, type: TYPES.MISC, }, { name: 'amp-video', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-video-docking', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MEDIA, }, { name: 'amp-video-iframe', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-viqeo-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-vk', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-yotpo', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-youtube', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-mowplayer', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-powr-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-mraid', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-link-rewriter', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-minute-media-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, ]; /** * Used to alias a version of an extension to an older deprecated version. */ exports.extensionAliasBundles = { 'amp-sticky-ad': { version: '1.0', aliasedVersion: '0.1', }, }; /** * Used to generate alternative JS build targets */ exports.altMainBundles = [ { path: 'src/amp-shadow.js', name: 'shadow-v0', version: '0.1', latestVersion: '0.1', }, { path: 'src/inabox/amp-inabox.js', name: 'amp4ads-v0', version: '0.1', latestVersion: '0.1', }, ]; /** * @param {boolean} condition * @param {string} field * @param {string} message * @param {string} name * @param {string} found */ function verifyBundle_(condition, field, message, name, found) { if (!condition) { log( colors.red('ERROR:'), colors.cyan(field), message, colors.cyan(name), '\n' + found ); process.exit(1); } } exports.verifyExtensionBundles = function() { exports.extensionBundles.forEach(bundle => { const bundleString = JSON.stringify(bundle, null, 2); verifyBundle_( 'name' in bundle, 'name', 'is missing from', '', bundleString ); verifyBundle_( 'version' in bundle, 'version', 'is missing from', bundle.name, bundleString ); verifyBundle_( 'latestVersion' in bundle, 'latestVersion', 'is missing from', bundle.name, bundleString ); const duplicates = exports.extensionBundles.filter( duplicate => duplicate.name === bundle.name ); verifyBundle_( duplicates.every( duplicate => duplicate.latestVersion === bundle.latestVersion ), 'latestVersion', 'is not the same for all versions of', bundle.name, JSON.stringify(duplicates, null, 2) ); verifyBundle_( 'type' in bundle, 'type', 'is missing from', bundle.name, bundleString ); const validTypes = Object.keys(TYPES).map(x => TYPES[x]); verifyBundle_( validTypes.some(validType => validType === bundle.type), 'type', `is not one of ${validTypes.join(',')} in`, bundle.name, bundleString ); }); };
cory-work/amphtml
build-system/compile/bundles.config.js
JavaScript
apache-2.0
26,274
/* * Copyright 2021 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 * * https://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.ads.googleads.v10.resources; import com.google.api.pathtemplate.PathTemplate; import com.google.api.resourcenames.ResourceName; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. @Generated("by gapic-generator-java") public class BiddingStrategySimulationName implements ResourceName { private static final PathTemplate CUSTOMER_ID_BIDDING_STRATEGY_ID_TYPE_MODIFICATION_METHOD_START_DATE_END_DATE = PathTemplate.createWithoutUrlEncoding( "customers/{customer_id}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}"); private volatile Map<String, String> fieldValuesMap; private final String customerId; private final String biddingStrategyId; private final String type; private final String modificationMethod; private final String startDate; private final String endDate; @Deprecated protected BiddingStrategySimulationName() { customerId = null; biddingStrategyId = null; type = null; modificationMethod = null; startDate = null; endDate = null; } private BiddingStrategySimulationName(Builder builder) { customerId = Preconditions.checkNotNull(builder.getCustomerId()); biddingStrategyId = Preconditions.checkNotNull(builder.getBiddingStrategyId()); type = Preconditions.checkNotNull(builder.getType()); modificationMethod = Preconditions.checkNotNull(builder.getModificationMethod()); startDate = Preconditions.checkNotNull(builder.getStartDate()); endDate = Preconditions.checkNotNull(builder.getEndDate()); } public String getCustomerId() { return customerId; } public String getBiddingStrategyId() { return biddingStrategyId; } public String getType() { return type; } public String getModificationMethod() { return modificationMethod; } public String getStartDate() { return startDate; } public String getEndDate() { return endDate; } public static Builder newBuilder() { return new Builder(); } public Builder toBuilder() { return new Builder(this); } public static BiddingStrategySimulationName of( String customerId, String biddingStrategyId, String type, String modificationMethod, String startDate, String endDate) { return newBuilder() .setCustomerId(customerId) .setBiddingStrategyId(biddingStrategyId) .setType(type) .setModificationMethod(modificationMethod) .setStartDate(startDate) .setEndDate(endDate) .build(); } public static String format( String customerId, String biddingStrategyId, String type, String modificationMethod, String startDate, String endDate) { return newBuilder() .setCustomerId(customerId) .setBiddingStrategyId(biddingStrategyId) .setType(type) .setModificationMethod(modificationMethod) .setStartDate(startDate) .setEndDate(endDate) .build() .toString(); } public static BiddingStrategySimulationName parse(String formattedString) { if (formattedString.isEmpty()) { return null; } Map<String, String> matchMap = CUSTOMER_ID_BIDDING_STRATEGY_ID_TYPE_MODIFICATION_METHOD_START_DATE_END_DATE.validatedMatch( formattedString, "BiddingStrategySimulationName.parse: formattedString not in valid format"); return of( matchMap.get("customer_id"), matchMap.get("bidding_strategy_id"), matchMap.get("type"), matchMap.get("modification_method"), matchMap.get("start_date"), matchMap.get("end_date")); } public static List<BiddingStrategySimulationName> parseList(List<String> formattedStrings) { List<BiddingStrategySimulationName> list = new ArrayList<>(formattedStrings.size()); for (String formattedString : formattedStrings) { list.add(parse(formattedString)); } return list; } public static List<String> toStringList(List<BiddingStrategySimulationName> values) { List<String> list = new ArrayList<>(values.size()); for (BiddingStrategySimulationName value : values) { if (value == null) { list.add(""); } else { list.add(value.toString()); } } return list; } public static boolean isParsableFrom(String formattedString) { return CUSTOMER_ID_BIDDING_STRATEGY_ID_TYPE_MODIFICATION_METHOD_START_DATE_END_DATE.matches( formattedString); } @Override public Map<String, String> getFieldValuesMap() { if (fieldValuesMap == null) { synchronized (this) { if (fieldValuesMap == null) { ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder(); if (customerId != null) { fieldMapBuilder.put("customer_id", customerId); } if (biddingStrategyId != null) { fieldMapBuilder.put("bidding_strategy_id", biddingStrategyId); } if (type != null) { fieldMapBuilder.put("type", type); } if (modificationMethod != null) { fieldMapBuilder.put("modification_method", modificationMethod); } if (startDate != null) { fieldMapBuilder.put("start_date", startDate); } if (endDate != null) { fieldMapBuilder.put("end_date", endDate); } fieldValuesMap = fieldMapBuilder.build(); } } } return fieldValuesMap; } public String getFieldValue(String fieldName) { return getFieldValuesMap().get(fieldName); } @Override public String toString() { return CUSTOMER_ID_BIDDING_STRATEGY_ID_TYPE_MODIFICATION_METHOD_START_DATE_END_DATE.instantiate( "customer_id", customerId, "bidding_strategy_id", biddingStrategyId, "type", type, "modification_method", modificationMethod, "start_date", startDate, "end_date", endDate); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o != null || getClass() == o.getClass()) { BiddingStrategySimulationName that = ((BiddingStrategySimulationName) o); return Objects.equals(this.customerId, that.customerId) && Objects.equals(this.biddingStrategyId, that.biddingStrategyId) && Objects.equals(this.type, that.type) && Objects.equals(this.modificationMethod, that.modificationMethod) && Objects.equals(this.startDate, that.startDate) && Objects.equals(this.endDate, that.endDate); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= Objects.hashCode(customerId); h *= 1000003; h ^= Objects.hashCode(biddingStrategyId); h *= 1000003; h ^= Objects.hashCode(type); h *= 1000003; h ^= Objects.hashCode(modificationMethod); h *= 1000003; h ^= Objects.hashCode(startDate); h *= 1000003; h ^= Objects.hashCode(endDate); return h; } /** * Builder for * customers/{customer_id}/biddingStrategySimulations/{bidding_strategy_id}~{type}~{modification_method}~{start_date}~{end_date}. */ public static class Builder { private String customerId; private String biddingStrategyId; private String type; private String modificationMethod; private String startDate; private String endDate; protected Builder() {} public String getCustomerId() { return customerId; } public String getBiddingStrategyId() { return biddingStrategyId; } public String getType() { return type; } public String getModificationMethod() { return modificationMethod; } public String getStartDate() { return startDate; } public String getEndDate() { return endDate; } public Builder setCustomerId(String customerId) { this.customerId = customerId; return this; } public Builder setBiddingStrategyId(String biddingStrategyId) { this.biddingStrategyId = biddingStrategyId; return this; } public Builder setType(String type) { this.type = type; return this; } public Builder setModificationMethod(String modificationMethod) { this.modificationMethod = modificationMethod; return this; } public Builder setStartDate(String startDate) { this.startDate = startDate; return this; } public Builder setEndDate(String endDate) { this.endDate = endDate; return this; } private Builder(BiddingStrategySimulationName biddingStrategySimulationName) { this.customerId = biddingStrategySimulationName.customerId; this.biddingStrategyId = biddingStrategySimulationName.biddingStrategyId; this.type = biddingStrategySimulationName.type; this.modificationMethod = biddingStrategySimulationName.modificationMethod; this.startDate = biddingStrategySimulationName.startDate; this.endDate = biddingStrategySimulationName.endDate; } public BiddingStrategySimulationName build() { return new BiddingStrategySimulationName(this); } } }
googleads/google-ads-java
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/resources/BiddingStrategySimulationName.java
Java
apache-2.0
10,111
/* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.core.persistence; import org.apache.axis2.AxisFault; import org.apache.axis2.description.AxisModule; import org.apache.axis2.description.AxisOperation; import org.apache.axis2.description.Parameter; import org.apache.axis2.engine.AxisConfiguration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @Deprecated public class OperationPersistenceManager extends AbstractPersistenceManager { private static final Log log = LogFactory.getLog(OperationPersistenceManager.class); /** * Constructor gets the axis config and calls the super constructor. * * @param axisConfig - AxisConfiguration * @param pf * @throws AxisFault - if the config registry is not found */ public OperationPersistenceManager(AxisConfiguration axisConfig, PersistenceFactory pf) throws AxisFault { super(axisConfig, pf.getServiceGroupFilePM(), pf); } /** * Constructor gets the axis config and calls the super constructor. * * @param axisConfig - AxisConfiguration * @throws AxisFault - if the config registry is not found */ public OperationPersistenceManager(AxisConfiguration axisConfig) throws AxisFault { super(axisConfig); try { if (this.pf == null) { this.pf = PersistenceFactory.getInstance(axisConfig); } this.fpm = this.pf.getServiceGroupFilePM(); } catch (Exception e) { log.error("Error getting PersistenceFactory instance", e); } } /** * Handle the engagement of the module to operation at the registry level * * @param module - AxisModule instance * @param operation - AxisOperation instance * @throws Exception - on error */ public void engageModuleForOperation(AxisModule module, AxisOperation operation) throws Exception { try { handleModuleForAxisDescription(operation.getAxisService().getAxisServiceGroup().getServiceGroupName(), module, PersistenceUtils.getResourcePath(operation), true); if (log.isDebugEnabled()) { log.debug("Successfully engaged " + module.getName() + " module for " + operation.getName() + " operation"); } } catch (Throwable e) { handleExceptionWithRollback(module.getName(), "Unable to engage " + module.getName() + " module to " + module.getOperations() + " operation ", e); } } /** * Handle the dis-engagement of the module to operation at the registry level * * @param module - AxisModule instance * @param operation - AxisOperation instance * @throws Exception - on error */ public void disengageModuleForOperation(AxisModule module, AxisOperation operation) throws Exception { try { handleModuleForAxisDescription(operation.getAxisService().getAxisServiceGroup().getServiceGroupName(), module, PersistenceUtils.getResourcePath(operation), false); if (log.isDebugEnabled()) { log.debug("Successfully disengaged " + module.getName() + " module from " + operation.getName() + " operation"); } } catch (Throwable e) { handleExceptionWithRollback(module.getName(), "Unable to disengage " + module.getName() + " module from " + module.getOperations() + " operation ", e); } } /** * Remove the specified parameter from the given operation * * @param operation - AxisOperation instance * @param parameter - parameter to remove * @throws Exception - on error */ public void removeOperationParameter(AxisOperation operation, Parameter parameter) throws Exception { removeParameter(operation.getAxisService().getAxisServiceGroup().getServiceGroupName(), parameter.getName(), PersistenceUtils.getResourcePath(operation)); } /** * Persist the given operation parameter. If the parameter already exists in registry, update * it. Otherwise, create a new parameter. * * @param operation - AxisOperation instance * @param parameter - parameter to persist * @throws Exception - on registry call errors */ public void updateOperationParameter(AxisOperation operation, Parameter parameter) throws Exception { try { updateParameter(operation.getAxisService().getAxisServiceGroup().getServiceGroupName(), parameter, PersistenceUtils.getResourcePath(operation)); } catch (Throwable e) { handleExceptionWithRollback(operation.getAxisService().getAxisServiceGroup().getServiceGroupName(), "Unable to update the operation parameter " + parameter.getName() + " of operation " + operation.getName(), e); } } }
maheshika/carbon4-kernel
core/org.wso2.carbon.core/src/main/java/org/wso2/carbon/core/persistence/OperationPersistenceManager.java
Java
apache-2.0
5,853
/* * Copyright 2016 Drunken Dev. * * 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.drunkendev.menu; import java.io.OutputStream; import java.nio.file.Files; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Brett Ryan */ public class MenuBuilderTest { /** * Test of builder method, of class MenuBuilder. */ @Test public void testBuilder() { System.out.println("builder"); MenuItem menu = MenuBuilder.builder() .child("Product") .child("Knowledge Base", "/kb") .withChild("Support") .child("Help Me", "/") .child("Tickets") .end() .child("Blog", "/blog") .build(); assertEquals("Root menu length.", 4, menu.getChildren().size()); assertEquals("Menu item", "Product", menu.getChildren().get(0).getText()); assertEquals("Menu item", "Knowledge Base", menu.getChildren().get(1).getText()); assertEquals("Menu item", "Support", menu.getChildren().get(2).getText()); assertEquals("Menu item", "Help Me", menu.getChildren().get(2).getChildren().get(0).getText()); } /** * Test of write method, of class MenuBuilder. */ @Test public void testWrite() throws Exception { MenuItem build = MenuBuilder.builder() .child("Product") .child("Knowledge Base", "/kb") .withChild("Support") .child("Help Me", "/") .child("Tickets") .end() .child("Blog", "/blog") .build(); try (OutputStream os = Files.newOutputStream(Files.createTempFile("menu-test", ".xml"))) { MenuBuilder.write(build, os); } } /** * Test of load method, of class MenuBuilder. */ @Test public void testLoad() throws Exception { MenuItem menu = MenuBuilder.load(MenuBuilderTest.class.getResourceAsStream("menu1.xml")); assertEquals("Root menu length.", 4, menu.getChildren().size()); assertEquals("Menu item", "Product", menu.getChildren().get(0).getText()); assertEquals("Menu item", "Knowledge Base", menu.getChildren().get(1).getText()); assertEquals("Menu item", "Support", menu.getChildren().get(2).getText()); assertEquals("Menu item", "Help Me", menu.getChildren().get(2).getChildren().get(0).getText()); } }
brettryan/spring-app-base
src/test/java/com/drunkendev/menu/MenuBuilderTest.java
Java
apache-2.0
3,004
import React, { useContext } from 'react'; import { css, cx } from 'emotion'; import { CompletionItem, selectThemeVariant, ThemeContext } from '../..'; import { GrafanaTheme, renderMarkdown, textUtil } from '@savantly/sprout-api'; const getStyles = (theme: GrafanaTheme, height: number, visible: boolean) => { return { typeaheadItem: css` label: type-ahead-item; z-index: 11; padding: ${theme.spacing.sm} ${theme.spacing.sm} ${theme.spacing.sm} ${theme.spacing.md}; border-radius: ${theme.border.radius.md}; border: ${selectThemeVariant( { light: `solid 1px ${theme.palette.gray5}`, dark: `solid 1px ${theme.palette.dark1}` }, theme.type )}; overflow-y: scroll; overflow-x: hidden; outline: none; background: ${selectThemeVariant({ light: theme.palette.white, dark: theme.palette.dark4 }, theme.type)}; color: ${theme.colors.text}; box-shadow: ${selectThemeVariant( { light: `0 5px 10px 0 ${theme.palette.gray5}`, dark: `0 5px 10px 0 ${theme.palette.black}` }, theme.type )}; visibility: ${visible === true ? 'visible' : 'hidden'}; width: 250px; height: ${height + parseInt(theme.spacing.xxs, 10)}px; position: relative; word-break: break-word; `, }; }; interface Props { item: CompletionItem; height: number; } export const TypeaheadInfo: React.FC<Props> = ({ item, height }) => { const visible = item && !!item.documentation; const label = item ? item.label : ''; const documentation = textUtil.sanitize(renderMarkdown(item?.documentation)); const theme = useContext(ThemeContext); const styles = getStyles(theme, height, visible); return ( <div className={cx([styles.typeaheadItem])}> <b>{label}</b> <hr /> <div dangerouslySetInnerHTML={{ __html: documentation }} /> </div> ); };
savantly-net/sprout-platform
frontend/libs/sprout-ui/src/components/Typeahead/TypeaheadInfo.tsx
TypeScript
apache-2.0
1,884
/** * Copyright (C) 2011 Xavier Jodoin (xavier@jodoin.me) * * 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. * * @author xjodoin * @version $Id: $Id */ package org.torpedoquery.jpa; import static org.torpedoquery.jpa.internal.TorpedoMagic.getTorpedoMethodHandler; import static org.torpedoquery.jpa.internal.TorpedoMagic.setQuery; import org.torpedoquery.core.QueryBuilder; import org.torpedoquery.jpa.internal.Selector; import org.torpedoquery.jpa.internal.TorpedoProxy; import org.torpedoquery.jpa.internal.functions.CoalesceFunction; import org.torpedoquery.jpa.internal.functions.DynamicInstantiationFunction; import org.torpedoquery.jpa.internal.handlers.ArrayCallHandler; import org.torpedoquery.jpa.internal.handlers.AscFunctionHandler; import org.torpedoquery.jpa.internal.handlers.AvgFunctionHandler; import org.torpedoquery.jpa.internal.handlers.ComparableConstantFunctionHandler; import org.torpedoquery.jpa.internal.handlers.ConstantFunctionHandler; import org.torpedoquery.jpa.internal.handlers.CustomFunctionHandler; import org.torpedoquery.jpa.internal.handlers.DescFunctionHandler; import org.torpedoquery.jpa.internal.handlers.DistinctFunctionHandler; import org.torpedoquery.jpa.internal.handlers.IndexFunctionHandler; import org.torpedoquery.jpa.internal.handlers.MathOperationHandler; import org.torpedoquery.jpa.internal.handlers.MaxFunctionHandler; import org.torpedoquery.jpa.internal.handlers.MinFunctionHandler; import org.torpedoquery.jpa.internal.handlers.SubstringFunctionHandler; import org.torpedoquery.jpa.internal.handlers.SumFunctionHandler; import org.torpedoquery.jpa.internal.handlers.ValueHandler; import org.torpedoquery.jpa.internal.utils.TorpedoMethodHandler; public class TorpedoFunction { // JPA Functions /** * <p>count.</p> * * @param object a {@link java.lang.Object} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<Long> count(Object object) { return function("count", Long.class, object); } /** * <p>sum.</p> * * @param number a T object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> sum( T number) { return getTorpedoMethodHandler().handle( new SumFunctionHandler<V>(number)); } /** * <p>sum.</p> * * @param number a {@link org.torpedoquery.jpa.Function} object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> sum( Function<T> number) { return getTorpedoMethodHandler().handle( new SumFunctionHandler<V>(number)); } /** * <p>min.</p> * * @param number a T object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> min( T number) { return getTorpedoMethodHandler().handle( new MinFunctionHandler<V>(number)); } /** * <p>min.</p> * * @param number a {@link org.torpedoquery.jpa.Function} object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> min( Function<T> number) { return getTorpedoMethodHandler().handle( new MinFunctionHandler<V>(number)); } /** * <p>max.</p> * * @param number a T object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> max( T number) { return getTorpedoMethodHandler().handle( new MaxFunctionHandler<V>(number)); } /** * <p>max.</p> * * @param number a {@link org.torpedoquery.jpa.Function} object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> max( Function<T> number) { return getTorpedoMethodHandler().handle( new MaxFunctionHandler<V>(number)); } /** * <p>avg.</p> * * @param number a T object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> avg( T number) { return getTorpedoMethodHandler().handle( new AvgFunctionHandler<V>(number)); } /** * <p>avg.</p> * * @param number a {@link org.torpedoquery.jpa.Function} object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> avg( Function<T> number) { return getTorpedoMethodHandler().handle( new AvgFunctionHandler<V>(number)); } /** * <p>coalesce.</p> * * @param values a E object. * @param <T> a T object. * @return a E object. * @param <E> a E object. */ public static <T, E extends Function<T>> E coalesce(E... values) { CoalesceFunction<E> coalesceFunction = getCoalesceFunction(values); return (E) coalesceFunction; } /** * <p>coalesce.</p> * * @param values a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static <T> Function<T> coalesce(T... values) { return getCoalesceFunction(values); } private static <T> CoalesceFunction<T> getCoalesceFunction(T... values) { final CoalesceFunction coalesceFunction = new CoalesceFunction(); getTorpedoMethodHandler().handle( new ArrayCallHandler(new ValueHandler<Void>() { @Override public Void handle(TorpedoProxy proxy, QueryBuilder queryBuilder, Selector selector) { coalesceFunction.setQuery(proxy); coalesceFunction.addSelector(selector); return null; } }, values)); return coalesceFunction; } private static <T> DynamicInstantiationFunction<T> getDynamicInstantiationFunction(T val) { final DynamicInstantiationFunction<T> dynFunction = new DynamicInstantiationFunction<>(val); TorpedoMethodHandler torpedoMethodHandler = getTorpedoMethodHandler(); Object[] params = torpedoMethodHandler.params(); torpedoMethodHandler.handle( new ArrayCallHandler(new ValueHandler<Void>() { @Override public Void handle(TorpedoProxy proxy, QueryBuilder queryBuilder, Selector selector) { dynFunction.setQuery(proxy); dynFunction.addSelector(selector); return null; } }, params)); return dynFunction; } /** * * Hibernate calls this "dynamic instantiation". JPQL supports some of this feature and calls it a "constructor expression". * * dyn(new ProjectionEntity( * param(entity.getCode()), param(entity.getIntegerField()) * * Important: you need to wrap each constructor parameter with a param() call * * @param object a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static <T> Function<T> dyn(T object) { return getDynamicInstantiationFunction(object); } /** * <p>distinct.</p> * * @param object a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static <T> Function<T> distinct(T object) { if (object instanceof TorpedoProxy) { setQuery((TorpedoProxy) object); } return getTorpedoMethodHandler().handle( new DistinctFunctionHandler<T>(object)); } /** * <p>constant.</p> * * @param constant a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static <T> Function<T> constant(T constant) { return getTorpedoMethodHandler().handle( new ConstantFunctionHandler<T>(constant)); } /** * <p>constant.</p> * * @param constant a T object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<T> constant( T constant) { return getTorpedoMethodHandler().handle( new ComparableConstantFunctionHandler<T>(constant)); } /** * <p>index.</p> * * @param object a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. */ public static <T> ComparableFunction<Integer> index(T object) { if (object instanceof TorpedoProxy) { setQuery((TorpedoProxy) object); } return getTorpedoMethodHandler().handle( new IndexFunctionHandler(object)); } /** * Use this method to call functions witch are not supported natively by * Torpedo * * @return your custom function * @param name a {@link java.lang.String} object. * @param returnType a {@link java.lang.Class} object. * @param value a {@link java.lang.Object} object. * @param <T> a T object. */ public static <T> Function<T> function(String name, Class<T> returnType, Object value) { return getTorpedoMethodHandler().handle( new CustomFunctionHandler<T>(name, value)); } /** * <p>comparableFunction.</p> * * @param name a {@link java.lang.String} object. * @param returnType a {@link java.lang.Class} object. * @param value a {@link java.lang.Object} object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> comparableFunction( String name, Class<V> returnType, Object value) { return getTorpedoMethodHandler().handle( new CustomFunctionHandler<V>(name, value)); } // orderBy function /** * <p>asc.</p> * * @param object a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static <T> Function<T> asc(T object) { return getTorpedoMethodHandler().handle(new AscFunctionHandler<T>()); } /** * <p>desc.</p> * * @param object a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static <T> Function<T> desc(T object) { return getTorpedoMethodHandler().handle(new DescFunctionHandler<T>()); } // math operation /** * <p>operation.</p> * * @param left a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.OnGoingMathOperation} object. */ public static <T> OnGoingMathOperation<T> operation(T left) { return getTorpedoMethodHandler().handle( new MathOperationHandler<T>(null)); } /** * <p>operation.</p> * * @param left a {@link org.torpedoquery.jpa.Function} object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.OnGoingMathOperation} object. */ public static <T> OnGoingMathOperation<T> operation(Function<T> left) { return getTorpedoMethodHandler().handle( new MathOperationHandler<T>(left)); } // string functions // substring(), trim(), lower(), upper(), length() /** * <p>trim.</p> * * @param field a {@link java.lang.String} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> trim(String field) { return function("trim", String.class, field); } /** * <p>trim.</p> * * @param function a {@link org.torpedoquery.jpa.Function} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> trim(Function<String> function) { return function("trim", String.class, function); } /** * <p>lower.</p> * * @param field a {@link java.lang.String} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> lower(String field) { return function("lower", String.class, field); } /** * <p>lower.</p> * * @param function a {@link org.torpedoquery.jpa.Function} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> lower(Function<String> function) { return function("lower", String.class, function); } /** * <p>upper.</p> * * @param field a {@link java.lang.String} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> upper(String field) { return function("upper", String.class, field); } /** * <p>upper.</p> * * @param function a {@link org.torpedoquery.jpa.Function} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> upper(Function<String> function) { return function("upper", String.class, function); } /** * <p>length.</p> * * @param field a {@link java.lang.String} object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. */ public static ComparableFunction<Integer> length(String field) { return comparableFunction("length", Integer.class, field); } /** * <p>length.</p> * * @param function a {@link org.torpedoquery.jpa.Function} object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. */ public static ComparableFunction<Integer> length(Function<String> function) { return comparableFunction("length", Integer.class, function); } /** * <p>substring.</p> * * @param param a {@link java.lang.String} object. * @param beginIndex a int. * @param endIndex a int. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> substring(String param, int beginIndex, int endIndex) { return getTorpedoMethodHandler().handle( new SubstringFunctionHandler(param, beginIndex, endIndex)); } /** * <p>substring.</p> * * @param param a {@link org.torpedoquery.jpa.Function} object. * @param beginIndex a int. * @param endIndex a int. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> substring(Function<String> param, int beginIndex, int endIndex) { return getTorpedoMethodHandler().handle( new SubstringFunctionHandler(param, beginIndex, endIndex)); } }
xjodoin/torpedoquery
src/main/java/org/torpedoquery/jpa/TorpedoFunction.java
Java
apache-2.0
14,719
# pylint: skip-file # flake8: noqa # pylint: disable=too-many-lines # noqa: E301,E302,E303,T001 class OpenShiftCLIError(Exception): '''Exception class for openshiftcli''' pass ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')] def locate_oc_binary(): ''' Find and return oc binary file ''' # https://github.com/openshift/openshift-ansible/issues/3410 # oc can be in /usr/local/bin in some cases, but that may not # be in $PATH due to ansible/sudo paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS oc_binary = 'oc' # Use shutil.which if it is available, otherwise fallback to a naive path search try: which_result = shutil.which(oc_binary, path=os.pathsep.join(paths)) if which_result is not None: oc_binary = which_result except AttributeError: for path in paths: if os.path.exists(os.path.join(path, oc_binary)): oc_binary = os.path.join(path, oc_binary) break return oc_binary # pylint: disable=too-few-public-methods class OpenShiftCLI(object): ''' Class to wrap the command line tools ''' def __init__(self, namespace, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False, all_namespaces=False): ''' Constructor for OpenshiftCLI ''' self.namespace = namespace self.verbose = verbose self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig) self.all_namespaces = all_namespaces self.oc_binary = locate_oc_binary() # Pylint allows only 5 arguments to be passed. # pylint: disable=too-many-arguments def _replace_content(self, resource, rname, content, force=False, sep='.'): ''' replace the current object with the content ''' res = self._get(resource, rname) if not res['results']: return res fname = Utils.create_tmpfile(rname + '-') yed = Yedit(fname, res['results'][0], separator=sep) changes = [] for key, value in content.items(): changes.append(yed.put(key, value)) if any([change[0] for change in changes]): yed.write() atexit.register(Utils.cleanup, [fname]) return self._replace(fname, force) return {'returncode': 0, 'updated': False} def _replace(self, fname, force=False): '''replace the current object with oc replace''' # We are removing the 'resourceVersion' to handle # a race condition when modifying oc objects yed = Yedit(fname) results = yed.delete('metadata.resourceVersion') if results[0]: yed.write() cmd = ['replace', '-f', fname] if force: cmd.append('--force') return self.openshift_cmd(cmd) def _create_from_content(self, rname, content): '''create a temporary file and then call oc create on it''' fname = Utils.create_tmpfile(rname + '-') yed = Yedit(fname, content=content) yed.write() atexit.register(Utils.cleanup, [fname]) return self._create(fname) def _create(self, fname): '''call oc create on a filename''' return self.openshift_cmd(['create', '-f', fname]) def _delete(self, resource, name=None, selector=None): '''call oc delete on a resource''' cmd = ['delete', resource] if selector is not None: cmd.append('--selector={}'.format(selector)) elif name is not None: cmd.append(name) else: raise OpenShiftCLIError('Either name or selector is required when calling delete.') return self.openshift_cmd(cmd) def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501 '''process a template template_name: the name of the template to process create: whether to send to oc create after processing params: the parameters for the template template_data: the incoming template's data; instead of a file ''' cmd = ['process'] if template_data: cmd.extend(['-f', '-']) else: cmd.append(template_name) if params: param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()] cmd.append('-v') cmd.extend(param_str) results = self.openshift_cmd(cmd, output=True, input_data=template_data) if results['returncode'] != 0 or not create: return results fname = Utils.create_tmpfile(template_name + '-') yed = Yedit(fname, results['results']) yed.write() atexit.register(Utils.cleanup, [fname]) return self.openshift_cmd(['create', '-f', fname]) def _get(self, resource, name=None, selector=None): '''return a resource by name ''' cmd = ['get', resource] if selector is not None: cmd.append('--selector={}'.format(selector)) elif name is not None: cmd.append(name) cmd.extend(['-o', 'json']) rval = self.openshift_cmd(cmd, output=True) # Ensure results are retuned in an array if 'items' in rval: rval['results'] = rval['items'] elif not isinstance(rval['results'], list): rval['results'] = [rval['results']] return rval def _schedulable(self, node=None, selector=None, schedulable=True): ''' perform oadm manage-node scheduable ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) cmd.append('--schedulable={}'.format(schedulable)) return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501 def _list_pods(self, node=None, selector=None, pod_selector=None): ''' perform oadm list pods node: the node in which to list pods selector: the label selector filter if provided pod_selector: the pod selector filter if provided ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) if pod_selector: cmd.append('--pod-selector={}'.format(pod_selector)) cmd.extend(['--list-pods', '-o', 'json']) return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # pylint: disable=too-many-arguments def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False): ''' perform oadm manage-node evacuate ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) if dry_run: cmd.append('--dry-run') if pod_selector: cmd.append('--pod-selector={}'.format(pod_selector)) if grace_period: cmd.append('--grace-period={}'.format(int(grace_period))) if force: cmd.append('--force') cmd.append('--evacuate') return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') def _version(self): ''' return the openshift version''' return self.openshift_cmd(['version'], output=True, output_type='raw') def _import_image(self, url=None, name=None, tag=None): ''' perform image import ''' cmd = ['import-image'] image = '{0}'.format(name) if tag: image += ':{0}'.format(tag) cmd.append(image) if url: cmd.append('--from={0}/{1}'.format(url, image)) cmd.append('-n{0}'.format(self.namespace)) cmd.append('--confirm') return self.openshift_cmd(cmd) def _run(self, cmds, input_data): ''' Actually executes the command. This makes mocking easier. ''' curr_env = os.environ.copy() curr_env.update({'KUBECONFIG': self.kubeconfig}) proc = subprocess.Popen(cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=curr_env) stdout, stderr = proc.communicate(input_data) return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8') # pylint: disable=too-many-arguments,too-many-branches def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None): '''Base command for oc ''' cmds = [self.oc_binary] if oadm: cmds.append('adm') cmds.extend(cmd) if self.all_namespaces: cmds.extend(['--all-namespaces']) elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501 cmds.extend(['-n', self.namespace]) if self.verbose: print(' '.join(cmds)) try: returncode, stdout, stderr = self._run(cmds, input_data) except OSError as ex: returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex) rval = {"returncode": returncode, "cmd": ' '.join(cmds)} if output_type == 'json': rval['results'] = {} if output and stdout: try: rval['results'] = json.loads(stdout) except ValueError as verr: if "No JSON object could be decoded" in verr.args: rval['err'] = verr.args elif output_type == 'raw': rval['results'] = stdout if output else '' if self.verbose: print("STDOUT: {0}".format(stdout)) print("STDERR: {0}".format(stderr)) if 'err' in rval or returncode != 0: rval.update({"stderr": stderr, "stdout": stdout}) return rval class Utils(object): ''' utilities for openshiftcli modules ''' @staticmethod def _write(filename, contents): ''' Actually write the file contents to disk. This helps with mocking. ''' with open(filename, 'w') as sfd: sfd.write(str(contents)) @staticmethod def create_tmp_file_from_contents(rname, data, ftype='yaml'): ''' create a file in tmp with name and contents''' tmp = Utils.create_tmpfile(prefix=rname) if ftype == 'yaml': # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage # pylint: disable=no-member if hasattr(yaml, 'RoundTripDumper'): Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper)) else: Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False)) elif ftype == 'json': Utils._write(tmp, json.dumps(data)) else: Utils._write(tmp, data) # Register cleanup when module is done atexit.register(Utils.cleanup, [tmp]) return tmp @staticmethod def create_tmpfile_copy(inc_file): '''create a temporary copy of a file''' tmpfile = Utils.create_tmpfile('lib_openshift-') Utils._write(tmpfile, open(inc_file).read()) # Cleanup the tmpfile atexit.register(Utils.cleanup, [tmpfile]) return tmpfile @staticmethod def create_tmpfile(prefix='tmp'): ''' Generates and returns a temporary file name ''' with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp: return tmp.name @staticmethod def create_tmp_files_from_contents(content, content_type=None): '''Turn an array of dict: filename, content into a files array''' if not isinstance(content, list): content = [content] files = [] for item in content: path = Utils.create_tmp_file_from_contents(item['path'] + '-', item['data'], ftype=content_type) files.append({'name': os.path.basename(item['path']), 'path': path}) return files @staticmethod def cleanup(files): '''Clean up on exit ''' for sfile in files: if os.path.exists(sfile): if os.path.isdir(sfile): shutil.rmtree(sfile) elif os.path.isfile(sfile): os.remove(sfile) @staticmethod def exists(results, _name): ''' Check to see if the results include the name ''' if not results: return False if Utils.find_result(results, _name): return True return False @staticmethod def find_result(results, _name): ''' Find the specified result by name''' rval = None for result in results: if 'metadata' in result and result['metadata']['name'] == _name: rval = result break return rval @staticmethod def get_resource_file(sfile, sfile_type='yaml'): ''' return the service file ''' contents = None with open(sfile) as sfd: contents = sfd.read() if sfile_type == 'yaml': # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage # pylint: disable=no-member if hasattr(yaml, 'RoundTripLoader'): contents = yaml.load(contents, yaml.RoundTripLoader) else: contents = yaml.safe_load(contents) elif sfile_type == 'json': contents = json.loads(contents) return contents @staticmethod def filter_versions(stdout): ''' filter the oc version output ''' version_dict = {} version_search = ['oc', 'openshift', 'kubernetes'] for line in stdout.strip().split('\n'): for term in version_search: if not line: continue if line.startswith(term): version_dict[term] = line.split()[-1] # horrible hack to get openshift version in Openshift 3.2 # By default "oc version in 3.2 does not return an "openshift" version if "openshift" not in version_dict: version_dict["openshift"] = version_dict["oc"] return version_dict @staticmethod def add_custom_versions(versions): ''' create custom versions strings ''' versions_dict = {} for tech, version in versions.items(): # clean up "-" from version if "-" in version: version = version.split("-")[0] if version.startswith('v'): versions_dict[tech + '_numeric'] = version[1:].split('+')[0] # "v3.3.0.33" is what we have, we want "3.3" versions_dict[tech + '_short'] = version[1:4] return versions_dict @staticmethod def openshift_installed(): ''' check if openshift is installed ''' import rpm transaction_set = rpm.TransactionSet() rpmquery = transaction_set.dbMatch("name", "atomic-openshift") return rpmquery.count() > 0 # Disabling too-many-branches. This is a yaml dictionary comparison function # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements @staticmethod def check_def_equal(user_def, result_def, skip_keys=None, debug=False): ''' Given a user defined definition, compare it with the results given back by our query. ''' # Currently these values are autogenerated and we do not need to check them skip = ['metadata', 'status'] if skip_keys: skip.extend(skip_keys) for key, value in result_def.items(): if key in skip: continue # Both are lists if isinstance(value, list): if key not in user_def: if debug: print('User data does not have key [%s]' % key) print('User data: %s' % user_def) return False if not isinstance(user_def[key], list): if debug: print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key])) return False if len(user_def[key]) != len(value): if debug: print("List lengths are not equal.") print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value))) print("user_def: %s" % user_def[key]) print("value: %s" % value) return False for values in zip(user_def[key], value): if isinstance(values[0], dict) and isinstance(values[1], dict): if debug: print('sending list - list') print(type(values[0])) print(type(values[1])) result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug) if not result: print('list compare returned false') return False elif value != user_def[key]: if debug: print('value should be identical') print(user_def[key]) print(value) return False # recurse on a dictionary elif isinstance(value, dict): if key not in user_def: if debug: print("user_def does not have key [%s]" % key) return False if not isinstance(user_def[key], dict): if debug: print("dict returned false: not instance of dict") return False # before passing ensure keys match api_values = set(value.keys()) - set(skip) user_values = set(user_def[key].keys()) - set(skip) if api_values != user_values: if debug: print("keys are not equal in dict") print(user_values) print(api_values) return False result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug) if not result: if debug: print("dict returned false") print(result) return False # Verify each key, value pair is the same else: if key not in user_def or value != user_def[key]: if debug: print("value not equal; user_def does not have key") print(key) print(value) if key in user_def: print(user_def[key]) return False if debug: print('returning true') return True class OpenShiftCLIConfig(object): '''Generic Config''' def __init__(self, rname, namespace, kubeconfig, options): self.kubeconfig = kubeconfig self.name = rname self.namespace = namespace self._options = options @property def config_options(self): ''' return config options ''' return self._options def to_option_list(self, ascommalist=''): '''return all options as a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs''' return self.stringify(ascommalist) def stringify(self, ascommalist=''): ''' return the options hash as cli params in a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs ''' rval = [] for key in sorted(self.config_options.keys()): data = self.config_options[key] if data['include'] \ and (data['value'] is not None or isinstance(data['value'], int)): if key == ascommalist: val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())]) else: val = data['value'] rval.append('--{}={}'.format(key.replace('_', '-'), val)) return rval
akubicharm/openshift-ansible
roles/lib_openshift/src/lib/base.py
Python
apache-2.0
21,165
package ru.job4j.testtask; /** * Class Account. */ public class Account { public double value; public String requisites; /** * Constructor. * @param value amount of the money. * @param requisites user's account. */ public Account(double value, String requisites) { this.value = value; this.requisites = requisites; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Account account = (Account) o; if (value != account.value) { return false; } return requisites.equals(account.requisites); } @Override public int hashCode() { int result = (int) value; result = 31 * result + requisites.hashCode(); return result; } }
TatyanaAlex/tfukova
chapter_003/src/main/java/ru/job4j/testtask/Account.java
Java
apache-2.0
919
/** * Orignal work: Copyright 2015 www.seleniumtests.com * Modified work: Copyright 2016 www.infotel.com * Copyright 2017-2019 B.Hecquet * * 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.seleniumtests.uipage; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.NoSuchWindowException; import org.openqa.selenium.PageLoadStrategy; import org.openqa.selenium.Point; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.UnhandledAlertException; import org.openqa.selenium.UnsupportedCommandException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.remote.UnreachableBrowserException; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import com.seleniumtests.core.SeleniumTestsContext; import com.seleniumtests.core.SeleniumTestsContextManager; import com.seleniumtests.core.TestTasks; import com.seleniumtests.customexception.ConfigurationException; import com.seleniumtests.customexception.CustomSeleniumTestsException; import com.seleniumtests.customexception.NotCurrentPageException; import com.seleniumtests.customexception.ScenarioException; import com.seleniumtests.driver.BrowserType; import com.seleniumtests.driver.CustomEventFiringWebDriver; import com.seleniumtests.driver.TestType; import com.seleniumtests.driver.WebUIDriver; import com.seleniumtests.driver.screenshots.ScreenShot; import com.seleniumtests.driver.screenshots.ScreenshotUtil; import com.seleniumtests.driver.screenshots.SnapshotCheckType; import com.seleniumtests.driver.screenshots.SnapshotCheckType.Control; import com.seleniumtests.driver.screenshots.SnapshotTarget; import com.seleniumtests.uipage.htmlelements.CheckBoxElement; import com.seleniumtests.uipage.htmlelements.Element; import com.seleniumtests.uipage.htmlelements.GenericPictureElement; import com.seleniumtests.uipage.htmlelements.HtmlElement; import com.seleniumtests.uipage.htmlelements.LinkElement; import com.seleniumtests.uipage.htmlelements.RadioButtonElement; import com.seleniumtests.uipage.htmlelements.SelectList; import com.seleniumtests.uipage.htmlelements.Table; import com.seleniumtests.uipage.htmlelements.UiLibraryRegistry; import com.seleniumtests.util.helper.WaitHelper; public class PageObject extends BasePage implements IPage { private static final String ERROR_ELEMENT_S_IS_NOT_AN_TABLE_ELEMENT = "Element %s is not an Table element"; private static final String ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS = "Element %s is not an HtmlElement subclass"; private static final String ERROR_ELEMENT_IS_PRESENT = "Element %s is present"; private boolean frameFlag = false; private String windowHandle = null; // store the window / tab on which this page is loaded private String url = null; private String suiteName = null; private String outputDirectory = null; private String htmlFilePath = null; private String imageFilePath = null; private boolean captureSnapshot = true; private static Map<String, List<String>> uiLibraries = Collections.synchronizedMap(new HashMap<>()); // the UI libraries used for searching elements. Allows to speed up search when several UI libs are declared (e.g for SelectList) private ScreenshotUtil screenshotUtil; private Clock systemClock; private PageLoadStrategy pageLoadStrategy; public static final String HTML_UI_LIBRARY = "html"; private static final String ERROR_ELEMENT_NOT_PRESENT = "Element %s is not present"; /** * Constructor for non-entry point page. The control is supposed to have reached the page from other API call. * * @throws Exception */ public PageObject() { this(null, (String)null); } public PageObject(List<String> uiLibs) { this(null, null, uiLibs); } /** * Constructor for non-entry point page. The control is supposed to have reached the page from other API call. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement) { this(pageIdentifierElement, (String)null); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, List<String> uiLibs) { this(pageIdentifierElement, null, uiLibs); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, final String url) { this(pageIdentifierElement, url, new ArrayList<>()); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, final String url, List<String> uiLibs) { this(pageIdentifierElement, url, SeleniumTestsContextManager.getThreadContext().getBrowser(), WebUIDriver.getCurrentWebUiDriverName(), null, uiLibs); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param pageLoadStrategy whether to wait for the page to load or not (this is complementary to Selenium driver strategy. If not null, it will override selenium * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, final String url, PageLoadStrategy pageLoadStrategy) { this(pageIdentifierElement, url, SeleniumTestsContextManager.getThreadContext().getBrowser(), WebUIDriver.getCurrentWebUiDriverName(), null, pageLoadStrategy, true); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param pageLoadStrategy whether to wait for the page to load or not (this is complementary to Selenium driver strategy. If not null, it will override selenium * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, final String url, PageLoadStrategy pageLoadStrategy, List<String> uiLibs) { this(pageIdentifierElement, url, SeleniumTestsContextManager.getThreadContext().getBrowser(), WebUIDriver.getCurrentWebUiDriverName(), null, pageLoadStrategy, true, uiLibs); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param pageLoadStrategy whether to wait for the page to load or not (this is complementary to Selenium driver strategy. If not null, it will override selenium * @param captureSnapshot if true, snapshot will be captured after page loading. 'false' should only be used when capturing snapshot interfere with a popup alert * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, final String url, PageLoadStrategy pageLoadStrategy, boolean captureSnapshot) { this(pageIdentifierElement, url, SeleniumTestsContextManager.getThreadContext().getBrowser(), WebUIDriver.getCurrentWebUiDriverName(), null, pageLoadStrategy, captureSnapshot); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param pageLoadStrategy whether to wait for the page to load or not (this is complementary to Selenium driver strategy. If not null, it will override selenium * @param captureSnapshot if true, snapshot will be captured after page loading. 'false' should only be used when capturing snapshot interfere with a popup alert * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, final String url, PageLoadStrategy pageLoadStrategy, boolean captureSnapshot, List<String> uiLibs) { this(pageIdentifierElement, url, SeleniumTestsContextManager.getThreadContext().getBrowser(), WebUIDriver.getCurrentWebUiDriverName(), null, pageLoadStrategy, captureSnapshot, uiLibs); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param browserType the new browser type to create * @param driverName a logical name to give to the created driver * @param attachExistingDriverPort if we need to attach to an existing browser instead of creating one, then specify the port here * @throws IOException * * @throws Exception */ public PageObject(HtmlElement pageIdentifierElement, String url, BrowserType browserType, String driverName, Integer attachExistingDriverPort) { this(pageIdentifierElement, url, browserType, driverName, attachExistingDriverPort, null, true); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param browserType the new browser type to create * @param driverName a logical name to give to the created driver * @param attachExistingDriverPort if we need to attach to an existing browser instead of creating one, then specify the port here * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(HtmlElement pageIdentifierElement, String url, BrowserType browserType, String driverName, Integer attachExistingDriverPort, List<String> uiLibs) { this(pageIdentifierElement, url, browserType, driverName, attachExistingDriverPort, null, true, uiLibs); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param browserType the new browser type to create * @param driverName a logical name to give to the created driver * @param attachExistingDriverPort if we need to attach to an existing browser instead of creating one, then specify the port here * @param captureSnapshot if true, snapshot will be captured after page loading. 'false' should only be used when capturing snapshot interfere with a popup alert * @throws IOException * * @throws Exception */ public PageObject(HtmlElement pageIdentifierElement, String url, BrowserType browserType, String driverName, Integer attachExistingDriverPort, boolean captureSnapshot) { this(pageIdentifierElement, url, browserType, driverName, attachExistingDriverPort, null, captureSnapshot); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param browserType the new browser type to create * @param driverName a logical name to give to the created driver * @param attachExistingDriverPort if we need to attach to an existing browser instead of creating one, then specify the port here * @param captureSnapshot if true, snapshot will be captured after page loading. 'false' should only be used when capturing snapshot interfere with a popup alert * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(HtmlElement pageIdentifierElement, String url, BrowserType browserType, String driverName, Integer attachExistingDriverPort, boolean captureSnapshot, List<String> uiLibs) { this(pageIdentifierElement, url, browserType, driverName, attachExistingDriverPort, null, captureSnapshot, uiLibs); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param browserType the new browser type to create * @param driverName a logical name to give to the created driver * @param attachExistingDriverPort if we need to attach to an existing browser instead of creating one, then specify the port here * @param pageLoadStrategy whether to wait for the page to load or not (this is complementary to Selenium driver strategy. If not null, it will override selenium * @param captureSnapshot if true, snapshot will be captured after page loading. 'false' should only be used when capturing snapshot interfere with a popup alert * @throws IOException * * @throws Exception */ public PageObject(HtmlElement pageIdentifierElement, String url, BrowserType browserType, String driverName, Integer attachExistingDriverPort, PageLoadStrategy pageLoadStrategy, boolean captureSnapshot) { this(pageIdentifierElement, url, browserType, driverName, attachExistingDriverPort, pageLoadStrategy, captureSnapshot, new ArrayList<>()); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param browserType the new browser type to create * @param driverName a logical name to give to the created driver * @param attachExistingDriverPort if we need to attach to an existing browser instead of creating one, then specify the port here * @param pageLoadStrategy whether to wait for the page to load or not (this is complementary to Selenium driver strategy. If not null, it will override selenium * @param captureSnapshot if true, snapshot will be captured after page loading. 'false' should only be used when capturing snapshot interfere with a popup alert * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(HtmlElement pageIdentifierElement, String url, BrowserType browserType, String driverName, Integer attachExistingDriverPort, PageLoadStrategy pageLoadStrategy, boolean captureSnapshot, List<String> uiLibs) { for (String uiLib: uiLibs) { addUiLibrary(uiLib); } systemClock = Clock.systemUTC(); this.captureSnapshot = captureSnapshot; if (pageLoadStrategy == null) { this.pageLoadStrategy = robotConfig().getPageLoadStrategy(); } else { this.pageLoadStrategy = pageLoadStrategy; } Calendar start = Calendar.getInstance(); start.setTime(new Date()); if (SeleniumTestsContextManager.getGlobalContext() != null && SeleniumTestsContextManager.getGlobalContext().getTestNGContext() != null) { suiteName = SeleniumTestsContextManager.getGlobalContext().getTestNGContext().getSuite().getName(); outputDirectory = SeleniumTestsContextManager.getGlobalContext().getTestNGContext().getOutputDirectory(); } // set the URL to context if it has been provided. This will then be used on Edge(IE-mode) creation to avoid cross zone boundaries if (SeleniumTestsContextManager.getThreadContext() != null && url != null) { SeleniumTestsContextManager.getThreadContext().setInitialUrl(url); } // creates the driver and switch to it. It may be done twice as when the driver is created, we automatically switch to it, but in case driver // is already created, driver = WebUIDriver.getWebDriver(true, browserType, driverName, attachExistingDriverPort); if (driver == null && url != null) { throw new ConfigurationException("driver is null, 'browser' configuration may be empty"); } screenshotUtil = new ScreenshotUtil(driver); // open page openPage(url); // in case browser has been created outside of selenium and we attach to it, get initial window handles if (driver != null && attachExistingDriverPort != null && url == null) { ((CustomEventFiringWebDriver)driver).updateWindowsHandles(); } assertCurrentPage(false, pageIdentifierElement); Calendar end = Calendar.getInstance(); start.setTime(new Date()); long startTime = start.getTimeInMillis(); long endTime = end.getTimeInMillis(); if ((endTime - startTime) / 1000 > 0) { logger.log("Open web page in :" + (endTime - startTime) / 1000 + "seconds"); } } /** * Set the uiLibrary to use as a preferred library. * For example, by default, for SelectList, all UILibraries are tested before searching the element. With this setting, it's possible to make one of them preferred for this page * @param uiLibrary */ private synchronized void addUiLibrary(String uiLibrary) { String className = getClass().getCanonicalName(); uiLibraries.computeIfAbsent(className, k -> new ArrayList<>()); if (UiLibraryRegistry.getUiLibraries().contains(uiLibrary) && !uiLibraries.get(className).contains(uiLibrary)) { uiLibraries.get(className).add(uiLibrary); } else { throw new ScenarioException(String.format("uiLibrary '%s' has not been registered for any element. Available uiLibraries are: %s", uiLibrary, StringUtils.join(UiLibraryRegistry.getUiLibraries()))); } } protected void setUrl(final String openUrl) { this.url = openUrl; } public String getHtmlFilePath() { return htmlFilePath; } @Override public String getHtmlSource() { return driver.getPageSource(); } public String getImageFilePath() { return imageFilePath; } @Override public String getLocation() { return driver.getCurrentUrl(); } /** * Open page * Wait for page loading * @param url * @throws IOException */ private void openPage(String url) { if (url != null) { open(url); ((CustomEventFiringWebDriver)driver).updateWindowsHandles(); } // Wait for page load is applicable only for web test // When running tests on an iframe embedded site then test will fail if this command is not used // in case of mobile application, only capture screenshot if (SeleniumTestsContextManager.isWebTest()) { waitForPageToLoad(); } else if (SeleniumTestsContextManager.isAppTest() && captureSnapshot) { capturePageSnapshot(); } } @Override protected void assertCurrentPage(boolean log) { // not used } @Override protected void assertCurrentPage(boolean log, HtmlElement pageIdentifierElement) { if (pageIdentifierElement != null && !pageIdentifierElement.isElementPresent()) { throw new NotCurrentPageException(getClass().getCanonicalName() + " is not the current page.\nPageIdentifierElement " + pageIdentifierElement.toString() + " is not found."); } } /** * Get parameter from configuration * * @param key * * @return String */ public static String param(String key) { return TestTasks.param(key); } /** * Get parameter from configuration using pattern * If multiple variables match the pattern, only one is returned * @param keyPattern Pattern for searching key. If null, no filtering will be done on key * @return */ public static String param(Pattern keyPattern) { return TestTasks.param(keyPattern); } /** * Get parameter from configuration using pattern * If multiple variables match the pattern, only one is returned * @param keyPattern Pattern for searching key. If null, no filtering will be done on key * @param valuePattern Pattern for searching value. If null, no filtering will be done on value * @return */ public static String param(Pattern keyPattern, Pattern valuePattern) { return TestTasks.param(keyPattern, valuePattern); } /** * returns the robot configuration * @return */ public SeleniumTestsContext robotConfig() { return SeleniumTestsContextManager.getThreadContext(); } /** * Add step inside a page * @param stepName * @param passwordsToMask array of strings that must be replaced by '*****' in reports */ public void addStep(String stepName) { TestTasks.addStep(stepName); } public void addStep(String stepName, String ... passwordToMask) { TestTasks.addStep(stepName, passwordToMask); } /** * Method for creating or updating a variable on the seleniumRobot server (or locally if server is not used) * Moreover, created custom variable is specific to tuple (application, version, test environment) * Variable will be stored as a variable of the current tested application * @param key name of the param * @param value value of the parameter (or new value if we update it) */ public void createOrUpdateParam(String key, String value) { TestTasks.createOrUpdateParam(key, value); } /** * Method for creating or updating a variable locally. If selenium server is not used, there is no difference with 'createOrUpdateParam'. * If seleniumRobot server is used, then, this method will only change variable value locally, not updating the remote one * @param key * @param newValue */ public void createOrUpdateLocalParam(String key, String newValue) { TestTasks.createOrUpdateLocalParam(key, newValue); } /** * Method for creating or updating a variable on the seleniumRobot server ONLY. This will raise a ScenarioException if variables are get from * env.ini file * Moreover, created custom variable is specific to tuple (application, version, test environment) * @param key name of the param * @param newValue value of the parameter (or new value if we update it) * @param specificToVersion if true, this param will be stored on server with a reference to the application version. This will have no effect if changing a * current variable. */ public void createOrUpdateParam(String key, String value, boolean specificToVersion) { TestTasks.createOrUpdateParam(key, value, specificToVersion); } /** * Method for creating or updating a variable. If variables are get from seleniumRobot server, this method will update the value on the server * Moreover, created custom variable is specific to tuple (application, version, test environment) * @param key name of the param * @param newValue value of the parameter (or new value if we update it) * @param specificToVersion if true, this param will be stored on server with a reference to the application version. This will have no effect if changing a * current variable. * @param timeToLive if > 0, this variable will be destroyed after some days (defined by variable). A positive value is mandatory if reservable is set to true * because multiple variable can be created * @param reservable if true, this variable will be set as reservable in variable server. This means it can be used by only one test at the same time * True value also means that multiple variables of the same name can be created and a timeToLive > 0 MUST be provided so that server database is regularly purged */ public void createOrUpdateParam(String key, String value, boolean specificToVersion, int timeToLive, boolean reservable) { TestTasks.createOrUpdateParam(key, value, specificToVersion, timeToLive, reservable); } /** * In case the scenario uses several drivers, switch to one or another using this method, so that any new calls will go through this driver * @param driverName */ public WebDriver switchToDriver(String driverName) { driver = TestTasks.switchToDriver(driverName); return driver; } /** * Capture the whole page, scrolling if necessary * @param <T> * @return */ public <T extends PageObject> T capturePageSnapshot() { capturePageSnapshot(null); return (T)this; } /** * Capture only the visible part of the page, no scrolling will be done * @param <T> * @return */ public <T extends PageObject> T captureViewportSnapshot() { captureViewportSnapshot(null); return (T)this; } /** * Capture the desktop * @param <T> * @return */ public <T extends PageObject> T captureDesktopSnapshot() { captureDesktopSnapshot(null); return (T)this; } /** * Capture a page snapshot for storing in test step * @param snapshotName the snapshot name */ public void capturePageSnapshot(String snapshotName) { capturePageSnapshot(snapshotName, SnapshotCheckType.FALSE); } /** * Capture a viewport snapshot for storing in test step * @param snapshotName the snapshot name */ public void captureViewportSnapshot(String snapshotName) { captureViewportSnapshot(snapshotName, SnapshotCheckType.FALSE); } /** * Capture a viewport snapshot for storing in test step * @param snapshotName the snapshot name */ public void captureDesktopSnapshot(String snapshotName) { captureDesktopSnapshot(snapshotName, SnapshotCheckType.FALSE); } /** * Capture a page snapshot for storing in test step * @param snapshotName the snapshot name * @param checkSnapshot if true, will send snapshot to server (when seleniumRobot is configured for this) for comparison */ public void capturePageSnapshot(String snapshotName, SnapshotCheckType checkSnapshot) { ScreenShot screenShot = screenshotUtil.capture(SnapshotTarget.PAGE, ScreenShot.class, computeScrollDelay(checkSnapshot)); // check SnapshotCheckType configuration is compatible with the snapshot checkSnapshot.check(SnapshotTarget.PAGE); storeSnapshot(snapshotName, screenShot, checkSnapshot); } /** * Capture a page snapshot for storing in test step * @param snapshotName the snapshot name * @param checkSnapshot if true, will send snapshot to server (when seleniumRobot is configured for this) for comparison */ public void captureViewportSnapshot(String snapshotName, SnapshotCheckType checkSnapshot) { ScreenShot screenShot = screenshotUtil.capture(SnapshotTarget.VIEWPORT, ScreenShot.class); // check SnapshotCheckType configuration is compatible with the snapshot checkSnapshot.check(SnapshotTarget.VIEWPORT); storeSnapshot(snapshotName, screenShot, checkSnapshot); } /** * Capture a desktop snapshot (only the main screen in multiple screen environment) for storing in test step * @param snapshotName the snapshot name * @param checkSnapshot if true, will send snapshot to server (when seleniumRobot is configured for this) for comparison */ public void captureDesktopSnapshot(String snapshotName, SnapshotCheckType checkSnapshot) { ScreenShot screenShot = screenshotUtil.capture(SnapshotTarget.MAIN_SCREEN, ScreenShot.class); storeSnapshot(snapshotName, screenShot, checkSnapshot); } /** * Returns 0 if snapshot is only taken for test report. Else, returns the defined scrollDelay from params * @param checkSnapshot */ private int computeScrollDelay(SnapshotCheckType checkSnapshot) { if (checkSnapshot.getControl() != Control.NONE) { return robotConfig().getSnapshotScrollDelay().intValue(); } else { return 0; } } /** * Capture a portion of the page by giving the element to capture * @param element the element to capture */ public void captureElementSnapshot(WebElement element) { captureElementSnapshot(null, element); } /** * Capture a portion of the page by giving the element to capture * @param snapshotName the snapshot name * @param element the element to capture */ public void captureElementSnapshot(String snapshotName, WebElement element) { captureElementSnapshot(snapshotName, element, SnapshotCheckType.FALSE); } /** * Capture a portion of the page by giving the element to capture * @param snapshotName the snapshot name * @param element the element to capture * @param checkSnapshot if true, will send snapshot to server (when seleniumRobot is configured for this) for comparison */ public void captureElementSnapshot(String snapshotName, WebElement element, SnapshotCheckType checkSnapshot) { SnapshotTarget snapshotTarget = new SnapshotTarget(element); ScreenShot screenShot = screenshotUtil.capture(snapshotTarget, ScreenShot.class, computeScrollDelay(checkSnapshot)); // check SnapshotCheckType configuration is compatible with the snapshot checkSnapshot.check(snapshotTarget); storeSnapshot(snapshotName, screenShot, checkSnapshot); } /** * Store the snapshot to test step * Check if name is provided, in case we need to compare it to a baseline on server * @param snapshotName * @param screenShot * @param checkSnapshot */ private void storeSnapshot(String snapshotName, ScreenShot screenShot, SnapshotCheckType checkSnapshot) { if ((snapshotName == null || snapshotName.isEmpty()) && !checkSnapshot.equals(SnapshotCheckType.FALSE)) { throw new ScenarioException("Cannot check snapshot if no name is provided"); } if (screenShot != null) { // may be null if user request not to take snapshots if (screenShot.getHtmlSourcePath() != null) { htmlFilePath = screenShot.getHtmlSourcePath().replace(suiteName, outputDirectory); } if (screenShot.getImagePath() != null) { imageFilePath = screenShot.getImagePath().replace(suiteName, outputDirectory); } if (snapshotName != null) { screenShot.setTitle(snapshotName); } logger.logScreenshot(screenShot, snapshotName, checkSnapshot); } // store the window / tab on which this page is loaded windowHandle = driver.getWindowHandle(); } /** * Get focus on this page, using the handle we stored when creating it * When called, you should write {@code myPage.<MyPageClassName>getFocus().someMethodOfMyPage();} * @return */ @SuppressWarnings("unchecked") public <T extends PageObject> T getFocus() { selectWindow(windowHandle); return (T)this; } /** * Close a PageObject. This method can be called when a web session opens several pages and one of them has to be closed * In case there are multiple windows opened, switch back to the previous window in the list * * @throws NotCurrentPageException */ public final void close() { if (WebUIDriver.getWebDriver(false) == null) { return; } boolean isMultipleWindow = false; List<String> handles = new ArrayList<>(driver.getWindowHandles()); if (handles.size() > 1) { isMultipleWindow = true; } internalLogger.debug("Current handles: " + handles); try { logger.info("close web page: " + getTitle()); driver.close(); } catch (WebDriverException ignore) { internalLogger.info("Error closing driver: " + ignore.getMessage()); } // wait a bit before going back to main window WaitHelper.waitForSeconds(2); try { if (isMultipleWindow) { selectPreviousOrMainWindow(handles); } else { WebUIDriver.setWebDriver(null); } } catch (UnreachableBrowserException ex) { WebUIDriver.setWebDriver(null); } } private void selectPreviousOrMainWindow(List<String> handles) { try { selectWindow(handles.get(handles.indexOf(windowHandle) - 1)); } catch (IndexOutOfBoundsException | NoSuchWindowException e) { selectMainWindow(); } } /** * Close the current tab / window which leads to the previous window / tab in the list. * This uses the default constructor which MUST be available * @param previousPage the page we go back to, so that we can check we are on the right page * @return */ public <T extends PageObject> T close(Class<T> previousPage) { close(); try { return previousPage.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new ScenarioException("Cannot check for previous page: " + e.getMessage(), e); } } /** * Drags an element a certain distance and then drops it. * * @param element to dragAndDrop * @param offsetX in pixels from the current location to which the element should be moved, e.g., 70 * @param offsetY in pixels from the current location to which the element should be moved, e.g., -300 */ public void dragAndDrop(final HtmlElement element, final int offsetX, final int offsetY) { new Actions(driver).dragAndDropBy( element.getElement(), offsetX, offsetY).perform(); } /** * Get the number of elements in page * @param element * @return */ public final int getElementCount(final HtmlElement element) { return element.findElements().size(); } public int getTimeout() { return SeleniumTestsContextManager.getThreadContext().getWebSessionTimeout(); } @Override public String getTitle() { return driver.getTitle(); } public String getUrl() { return url; } public String getCanonicalURL() { return new LinkElement("Canonical URL", By.cssSelector("link[rel=canonical]")).getAttribute("href"); } /** * Returns the value of the named cookie * @param name name of the cookie * @return */ public final String getCookieByName(final String name) { if (driver.manage().getCookieNamed(name) == null) { return null; } return driver.manage().getCookieNamed(name).getValue(); } /** * Check if named cookie is present * @param name name of the cookie * @return */ public boolean isCookiePresent(final String name) { return getCookieByName(name) != null; } private void open(final String url) { setUrl(url); try { // Navigate to app URL for browser test if (SeleniumTestsContextManager.isWebTest()) { setWindowToRequestedSize(); driver.navigate().to(url); } } catch (UnreachableBrowserException e) { // recreate the driver without recreating the enclosing WebUiDriver driver = WebUIDriver.getWebUIDriver(false).createWebDriver(); if (SeleniumTestsContextManager.isWebTest()) { setWindowToRequestedSize(); driver.navigate().to(url); } } catch (UnsupportedCommandException e) { logger.error("get UnsupportedCommandException, retry"); // recreate the driver without recreating the enclosing WebUiDriver driver = WebUIDriver.getWebUIDriver(false).createWebDriver(); if (SeleniumTestsContextManager.isWebTest()) { setWindowToRequestedSize(); driver.navigate().to(url); } } catch (org.openqa.selenium.TimeoutException ex) { logger.error("got time out when loading " + url + ", ignored"); } catch (org.openqa.selenium.UnhandledAlertException ex) { logger.error("got UnhandledAlertException, retry"); driver.navigate().to(url); } catch (WebDriverException e) { internalLogger.error(e); throw new CustomSeleniumTestsException(e); } } public final void maximizeWindow() { try { // app test are not compatible with window if (SeleniumTestsContextManager.getThreadContext().getTestType().family() == TestType.APP || SeleniumTestsContextManager.getThreadContext().getBrowser() == BrowserType.BROWSER) { return; } driver.manage().window().maximize(); } catch (Exception ex) { try { ((JavascriptExecutor) driver).executeScript( "if (window.screen){window.moveTo(0, 0);window.resizeTo(window.screen.availWidth,window.screen.availHeight);}"); } catch (Exception ignore) { logger.log("Unable to maximize browser window. Exception occured: " + ignore.getMessage()); } } } /** * On init set window to size requested by user. Window is maximized if no size is set */ public final void setWindowToRequestedSize() { if (!SeleniumTestsContextManager.isWebTest()) { return; } Integer width = SeleniumTestsContextManager.getThreadContext().getViewPortWidth(); Integer height = SeleniumTestsContextManager.getThreadContext().getViewPortHeight(); if (width == null || height == null) { maximizeWindow(); } else { resizeTo(width, height); } } /** * Resize window to given dimensions. * * @param width * @param height */ public final void resizeTo(final int width, final int height) { // app test are not compatible with window if (SeleniumTestsContextManager.isAppTest()) { return; } try { Dimension setSize = new Dimension(width, height); driver.manage().window().setPosition(new Point(0, 0)); int retries = 5; for (int i=0; i < retries; i++) { driver.manage().window().setSize(setSize); Dimension viewPortSize = ((CustomEventFiringWebDriver)driver).getViewPortDimensionWithoutScrollbar(); if (viewPortSize.height == height && viewPortSize.width == width) { break; } else { setSize = new Dimension(2 * width - viewPortSize.width, 2 * height - viewPortSize.height); } } } catch (Exception ex) { internalLogger.error(ex); } } /** * @deprecated useless * @return */ @Deprecated public boolean isFrame() { return frameFlag; } /** * @deprecated useless * @return */ @Deprecated public final void selectFrame(final Integer index) { driver.switchTo().frame(index); frameFlag = true; } /** * @deprecated useless * @return */ @Deprecated public final void selectFrame(final By by) { WebElement element = driver.findElement(by); driver.switchTo().frame(element); frameFlag = true; } /** * @deprecated useless * @return */ @Deprecated public final void selectFrame(final String locator) { driver.switchTo().frame(locator); frameFlag = true; } /** * @deprecated useless * @return */ @Deprecated public final void exitFrame() { driver.switchTo().defaultContent(); frameFlag = false; } /** * Switch to first window in the list */ public final void selectMainWindow() { selectWindow(0); } /** * Switch to nth window in the list * It may not reflect the order of tabs in browser if some windows have been closed before * @param index index of the window */ public final void selectWindow(final int index) { // app test are not compatible with window if (SeleniumTestsContextManager.isAppTest()) { throw new ScenarioException("Application are not compatible with Windows"); } driver.switchTo().window((String) driver.getWindowHandles().toArray()[index]); WaitHelper.waitForSeconds(1); } /** * Selects the first unknown window. To use we an action creates a new window or tab * @return */ public final String selectNewWindow() { return selectNewWindow(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout() * 1000); } /** * Selects the first unknown window. To use immediately after an action creates a new window or tab * Each time we do a click, but just before it (selenium click, JS click or action click), we record the list of windows. * I a new window or tab is displayed, we select it. * @param waitMs wait for N milliseconds before raising error * @return */ public final String selectNewWindow(int waitMs) { // app test are not compatible with window if (SeleniumTestsContextManager.getThreadContext().getTestType().family() == TestType.APP) { throw new ScenarioException("Application are not compatible with Windows"); } // Keep the name of the current window handle before switching // sometimes, our action made window disappear String mainWindowHandle; try { mainWindowHandle = driver.getWindowHandle(); } catch (Exception e) { mainWindowHandle = ""; } internalLogger.debug("Current handle: " + mainWindowHandle); // wait for window to be displayed Instant end = systemClock.instant().plusMillis(waitMs + 250L); Set<String> handles = new TreeSet<>(); boolean found = false; while (end.isAfter(systemClock.instant()) && !found) { handles = driver.getWindowHandles(); internalLogger.debug("All handles: " + handles.toString()); for (String handle: handles) { // we already know this handle if (getCurrentHandles().contains(handle)) { continue; } selectWindow(handle); // wait for a valid address String address = ""; Instant endLoad = systemClock.instant().plusMillis(5000); while (address.isEmpty() && endLoad.isAfter(systemClock.instant())) { address = driver.getCurrentUrl(); } // make window display in foreground // TODO: reactivate feature try { // Point windowPosition = driver.manage().window().getPosition(); // org.openqa.selenium.interactions.Mouse mouse = ((HasInputDevices) driver).getMouse(); // mouse.click(); // Mouse mouse = new DesktopMouse(); // mouse.click(new DesktopScreenRegion(Math.max(0, windowPosition.x) + driver.manage().window().getSize().width / 2, Math.max(0, windowPosition.y) + 5, 2, 2).getCenter()); } catch (Exception e) { internalLogger.warn("error while giving focus to window"); } found = true; break; } WaitHelper.waitForMilliSeconds(300); } // check window has changed if (waitMs > 0 && mainWindowHandle.equals(driver.getWindowHandle())) { throw new CustomSeleniumTestsException("new window has not been found. Handles: " + handles); } return mainWindowHandle; } /** * Switch to the default content */ public void switchToDefaultContent() { try { driver.switchTo().defaultContent(); } catch (UnhandledAlertException e) { logger.warn("Alert found, you should handle it"); } } private void waitForPageToLoad() { try { if (pageLoadStrategy == PageLoadStrategy.NORMAL) { new WebDriverWait(driver, 5).until(ExpectedConditions.jsReturnsValue("if (document.readyState === \"complete\") { return \"ok\"; }")); } else if (pageLoadStrategy == PageLoadStrategy.EAGER) { new WebDriverWait(driver, 5).until(ExpectedConditions.jsReturnsValue("if (document.readyState === \"interactive\") { return \"ok\"; }")); } } catch (TimeoutException e) { // nothing } // populate page info if (captureSnapshot) { try { capturePageSnapshot(); } catch (Exception ex) { internalLogger.error(ex); throw ex; } } } public Alert waitForAlert(int waitInSeconds) { Instant end = systemClock.instant().plusSeconds(waitInSeconds); while (end.isAfter(systemClock.instant())) { try { return driver.switchTo().alert(); } catch (NoAlertPresentException e) { WaitHelper.waitForSeconds(1); } catch (NoSuchWindowException e) { return null; } } return null; } /** * get the name of the PageObject that made the call * * @param stack : the stacktrace of the caller */ public static String getCallingPage(StackTraceElement[] stack) { String page = null; Class<?> stackClass = null; //find the PageObject Loader for(int i=0; i<stack.length;i++){ try{ stackClass = Class.forName(stack[i].getClassName()); } catch (ClassNotFoundException e){ continue; } if (PageObject.class.isAssignableFrom(stackClass)){ page = stack[i].getClassName(); } } return page; } public String cancelConfirmation() { Alert alert = getAlert(); String seenText = alert.getText(); alert.dismiss(); driver.switchTo().defaultContent(); return seenText; } /** * Returns an Element object based on field name * @return */ private Element getElement(String fieldName) { try { Field field = getClass().getDeclaredField(fieldName); field.setAccessible(true); return (Element)field.get(this); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { throw new ScenarioException(String.format("Field %s does not exist in class %s", fieldName, getClass().getSimpleName())); } } // --------------------- Actions -------------------------- @GenericStep public <T extends PageObject> T goBack() { driver.navigate().back(); return (T)this; } @GenericStep public <T extends PageObject> T goForward() { driver.navigate().forward(); return (T)this; } @GenericStep public <T extends PageObject> T sendKeysToField(String fieldName, String value) { Element element = getElement(fieldName); element.sendKeys(value); return (T)this; } @GenericStep public <T extends PageObject> T sendRandomKeysToField(Integer charNumber, String fieldName) { Element element = getElement(fieldName); element.sendKeys(RandomStringUtils.random(charNumber, true, false)); return (T)this; } @SuppressWarnings("unchecked") @GenericStep public <T extends PageObject> T clear(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).clear(); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @SuppressWarnings("unchecked") @GenericStep public <T extends PageObject> T selectOption(String fieldName, String value) { Element element = getElement(fieldName); if (element instanceof SelectList) { ((SelectList)element).selectByText(value); } else { throw new ScenarioException(String.format("Element %s is not an SelectList", fieldName)); } return (T)this; } @SuppressWarnings("unchecked") @GenericStep public <T extends PageObject> T click(String fieldName) { Element element = getElement(fieldName); element.click(); return (T)this; } /** * Click on element and creates a new PageObject of the type of following page * @param fieldName * @param nextPage Class of the next page * @return * @throws SecurityException * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InstantiationException */ @GenericStep public <T extends PageObject> T clickAndChangeToPage(String fieldName, Class<T> nextPage) { Element element = getElement(fieldName); element.click(); try { return nextPage.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new ScenarioException(String.format("Cannot switch to next page %s, maybe default constructor does not exist", nextPage.getSimpleName()), e); } } /** * Return the next page * @param <T> * @param nextPage * @return */ @GenericStep public <T extends PageObject> T changeToPage(Class<T> nextPage) { try { return nextPage.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new ScenarioException(String.format("Cannot switch to next page %s, maybe default constructor does not exist", nextPage.getSimpleName()), e); } } @GenericStep public <T extends PageObject> T doubleClick(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).doubleClickAction(); } else { ((GenericPictureElement)element).doubleClick(); } return (T)this; } @GenericStep public <T extends PageObject> T wait(Integer waitMs) { WaitHelper.waitForMilliSeconds(waitMs); return (T)this; } @GenericStep public <T extends PageObject> T clickTableCell(Integer row, Integer column, String fieldName) { Element element = getElement(fieldName); if (element instanceof Table) { ((Table)element).getCell(row, column).click(); } else { throw new ScenarioException(String.format(ERROR_ELEMENT_S_IS_NOT_AN_TABLE_ELEMENT, fieldName)); } return (T)this; } /** * Switch to the newly created window * @return */ @GenericStep public <T extends PageObject> T switchToNewWindow() { selectNewWindow(); return (T)this; } /** * Switch to the newly created window with wait * @return */ @GenericStep public <T extends PageObject> T switchToNewWindow(int waitMs) { selectNewWindow(waitMs); return (T)this; } /** * Select first window in the list * @return */ @GenericStep public <T extends PageObject> T switchToMainWindow() { selectMainWindow(); return (T)this; } /** * Selects the nth window in list * @param index * @return */ @GenericStep public <T extends PageObject> T switchToWindow(int index) { selectWindow(index); return (T)this; } /** * Refresh browser window * @return */ @GenericStep public <T extends PageObject> T refresh() { if (SeleniumTestsContextManager.isWebTest()) { try { driver.navigate().refresh(); } catch (org.openqa.selenium.TimeoutException ex) { logger.error("got time out customexception, ignore"); } } return (T)this; } @GenericStep public <T extends PageObject> T acceptAlert() { Alert alert = getAlert(); if (alert != null) { alert.accept(); } driver.switchTo().defaultContent(); return (T)this; } @GenericStep public <T extends PageObject> T cancelAlert() { cancelConfirmation(); return (T)this; } /** * Method to handle file upload through robot class * /!\ This should only be used as the last option when uploading file cannot be done an other way as explained below * https://saucelabs.com/resources/articles/best-practices-tips-selenium-file-upload * <code> * driver.setFileDetector(new LocalFileDetector()); * driver.get("http://sso.dev.saucelabs.com/test/guinea-file-upload"); * WebElement upload = driver.findElement(By.id("myfile")); * upload.sendKeys("/Users/sso/the/local/path/to/darkbulb.jpg"); * </code> * * * To use this method, first click on the upload file button / link, then call this method. * * /!\ on firefox, clicking MUST be done through 'clickAction'. 'click()' is not supported by browser. * /!\ on firefox, using the uploadFile method several times without other actions between usage may lead to error. Firefox will never click to the button the second time, probably due to focus problems * * @param filePath */ @GenericStep public <T extends PageObject> T uploadFile(String filePath) { try { byte[] encoded = Base64.encodeBase64(FileUtils.readFileToByteArray(new File(filePath))); CustomEventFiringWebDriver.uploadFile(new File(filePath).getName(), new String(encoded), SeleniumTestsContextManager.getThreadContext().getRunMode(), SeleniumTestsContextManager.getThreadContext().getSeleniumGridConnector()); Alert alert = waitForAlert(5); if (alert != null) { alert.accept(); } } catch (IOException e) { throw new ScenarioException(String.format("could not read file to upload %s: %s", filePath, e.getMessage())); } return (T)this; } // --------------------- Waits -------------------------- @GenericStep public <T extends PageObject> T waitForPresent(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).waitForPresent(); } else { boolean present = ((GenericPictureElement)element).isElementPresent(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout() * 1000); if (!present) { throw new TimeoutException(String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); } } return (T)this; } @GenericStep public <T extends PageObject> T waitForVisible(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).waitForVisibility(); } else { boolean present = ((GenericPictureElement)element).isElementPresent(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout() * 1000); if (!present) { throw new TimeoutException(String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); } } return (T)this; } @GenericStep public <T extends PageObject> T waitForNotPresent(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).waitForNotPresent(); } else { boolean present = ((GenericPictureElement)element).isElementPresent(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout() * 1000); if (present) { throw new TimeoutException(String.format(ERROR_ELEMENT_IS_PRESENT, fieldName)); } } return (T)this; } @GenericStep public <T extends PageObject> T waitForInvisible(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).waitForInvisibility(); } else { boolean present = ((GenericPictureElement)element).isElementPresent(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout() * 1000); if (present) { throw new TimeoutException(String.format(ERROR_ELEMENT_IS_PRESENT, fieldName)); } } return (T)this; } @GenericStep public <T extends PageObject> T waitForValue(String fieldName, String value) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).waitFor(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout(), ExpectedConditions.or( ExpectedConditions.attributeToBe((HtmlElement)element, "value", value), ExpectedConditions.textToBePresentInElement((HtmlElement)element, value) )); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T waitTableCellValue(Integer row, Integer column, String fieldName, String value) { Element element = getElement(fieldName); if (element instanceof Table) { ((HtmlElement) element).waitFor(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout(), ExpectedConditions.textToBePresentInElement(((Table)element).getCell(row, column), value)); } else { throw new ScenarioException(String.format(ERROR_ELEMENT_S_IS_NOT_AN_TABLE_ELEMENT, fieldName)); } return (T)this; } // --------------------- Assertions -------------------------- @GenericStep public <T extends PageObject> T assertForInvisible(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertFalse(((HtmlElement) element).isElementPresent(0) && ((HtmlElement) element).isDisplayed(), String.format("Element %s is visible", fieldName)); } else { Assert.assertFalse(((GenericPictureElement)element).isElementPresent(), String.format("Element %s is visible", fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForVisible(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertTrue(((HtmlElement) element).isDisplayed(), String.format("Element %s is not visible", fieldName)); } else { Assert.assertTrue(((GenericPictureElement)element).isElementPresent(), String.format("Element %s is not visible", fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForDisabled(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertFalse(((HtmlElement) element).isEnabled(), String.format("Element %s is enabled", fieldName)); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForEnabled(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertTrue(((HtmlElement) element).isEnabled(), String.format("Element %s is disabled", fieldName)); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForValue(String fieldName, String value) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertTrue(((HtmlElement) element).getText().equals(value) || ((HtmlElement) element).getValue().equals(value), String.format("Value of element %s is not %s", fieldName, value)); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForEmptyValue(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertTrue(((HtmlElement) element).getValue().isEmpty(), String.format("Value or Element %s is not empty", fieldName)); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForNonEmptyValue(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertFalse(((HtmlElement) element).getValue().isEmpty(), String.format("Element %s is empty", fieldName)); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForMatchingValue(String fieldName, String regex) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertTrue(Pattern.compile(regex).matcher(((HtmlElement) element).getText()).find() || Pattern.compile(regex).matcher(((HtmlElement) element).getValue()).find(), String.format("Value of Element %s does not match %s ", fieldName, regex)); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertSelectedOption(String fieldName, String value) { Element element = getElement(fieldName); if (element instanceof SelectList) { try { WebElement selectedOption = ((SelectList)element).getFirstSelectedOption(); Assert.assertNotNull(selectedOption, "No selected option found"); Assert.assertEquals(selectedOption.getText(), value, "Selected option is not the expected one"); } catch (WebDriverException e) { Assert.assertTrue(false, String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); } } else { throw new ScenarioException(String.format("Element %s is not an SelectList subclass", fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertChecked(String fieldName) { Element element = getElement(fieldName); if (element instanceof CheckBoxElement || element instanceof RadioButtonElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertTrue(((HtmlElement)element).isSelected(), String.format("Element %s is unchecked", fieldName)); } else { throw new ScenarioException(String.format("Element %s is not an CheckBoxElement/RadioButtonElement", fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertNotChecked(String fieldName) { Element element = getElement(fieldName); if (element instanceof CheckBoxElement || element instanceof RadioButtonElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertFalse(((HtmlElement)element).isSelected(), String.format("Element %s is checked", fieldName)); } else { throw new ScenarioException(String.format("Element %s is not an CheckBoxElement/RadioButtonElement", fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertTableCellValue(Integer row, Integer column, String fieldName, String value) { Element element = getElement(fieldName); if (element instanceof Table) { try { Assert.assertEquals(((Table)element).getCell(row, column).getText(), value, String.format("Value of cell [%d,%d] in table %s is not %s", row, column, fieldName, value)); } catch (WebDriverException e) { Assert.assertTrue(false, "Table or cell not found"); } } else { throw new ScenarioException(String.format(ERROR_ELEMENT_S_IS_NOT_AN_TABLE_ELEMENT, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertTextPresentInPage(String text) { Assert.assertTrue(isTextPresent(text)); return (T)this; } @GenericStep public <T extends PageObject> T assertTextNotPresentInPage(String text) { Assert.assertFalse(isTextPresent(text)); return (T)this; } @GenericStep public <T extends PageObject> T assertCookiePresent(String name) { Assert.assertTrue(isCookiePresent(name), "Cookie: {" + name + "} not found."); return (T)this; } @GenericStep public <T extends PageObject> T assertElementCount(String fieldName, int elementCount) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertEquals(((HtmlElement)element).findElements().size(), elementCount); } else { throw new ScenarioException(String.format("Element %s is not an HtmlElement", fieldName)); } return (T)this; } /** * Check page title matches parameter * @param regexTitle * @return */ @GenericStep public <T extends PageObject> T assertPageTitleMatches(String regexTitle) { Assert.assertTrue(getTitle().matches(regexTitle)); return (T)this; } @GenericStep public void assertHtmlSource(String text) { Assert.assertTrue(getHtmlSource().contains(text), String.format("Text: {%s} not found on page source.", text)); } /** * @deprecated useless * @param text */ @Deprecated public void assertKeywordNotPresent(String text) { Assert.assertFalse(getHtmlSource().contains(text), String.format("Text: {%s} not found on page source.", text)); } @GenericStep public void assertLocation(String urlPattern) { Assert.assertTrue(getLocation().contains(urlPattern), "Pattern: {" + urlPattern + "} not found on page location."); } /** * @deprecated useless * @param text */ @Deprecated public void assertTitle(final String text) { Assert.assertTrue(getTitle().contains(text), String.format("Text: {%s} not found on page title.", text)); } public ScreenshotUtil getScreenshotUtil() { return screenshotUtil; } public void setScreenshotUtil(ScreenshotUtil screenshotUtil) { this.screenshotUtil = screenshotUtil; } /** * Returns the list of uiLibraries associated to this page or an empty list if none found * @param cannonicalClassName * @return */ public static List<String> getUiLibraries(String cannonicalClassName) { return uiLibraries.getOrDefault(cannonicalClassName, new ArrayList<>()); } }
bhecquet/seleniumRobot
core/src/main/java/com/seleniumtests/uipage/PageObject.java
Java
apache-2.0
75,240
// Copyright 2014 The Serviced 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. // +build unit package api import ( "testing" ) func TestListTemplates(t *testing.T) { } func BenchmarkListTemplates(b *testing.B) { } func TestAddTemplate(t *testing.T) { } func BenchmarkAddTemplate(b *testing.B) { } func TestRemoveTemplate(t *testing.T) { } func BenchmarkRemoveTemplate(b *testing.B) { } func TestCompileTemplate(t *testing.T) { } func BenchmarkCompileTemplate(b *testing.B) { } func TestDeployTemplate(t *testing.T) { } func BenchmarkDeployTemplate(b *testing.B) { }
spindance/serviced-precomp
cli/api/template_test.go
GO
apache-2.0
1,096
# Copyright (c) 2013 Mirantis Inc. # # 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 eventlet eventlet.monkey_patch() import uuid import mock from oslo.config import cfg from mistral.tests import base from mistral.openstack.common import log as logging from mistral.openstack.common import importutils from mistral.engine import states from mistral.db import api as db_api from mistral.actions import std_actions from mistral import engine from mistral.engine import executor # We need to make sure that all configuration properties are registered. importutils.import_module("mistral.config") LOG = logging.getLogger(__name__) # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') WORKBOOK_NAME = 'my_workbook' TASK_NAME = 'create-vms' SAMPLE_WORKBOOK = { 'id': str(uuid.uuid4()), 'name': WORKBOOK_NAME, 'description': 'my description', 'definition': base.get_resource("test_rest.yaml"), 'tags': [], 'scope': 'public', 'updated_at': None, 'project_id': '123', 'trust_id': '1234' } SAMPLE_EXECUTION = { 'id': str(uuid.uuid4()), 'workbook_name': WORKBOOK_NAME, 'task': TASK_NAME, 'state': states.RUNNING, 'updated_at': None, 'context': None } SAMPLE_TASK = { 'name': TASK_NAME, 'workbook_name': WORKBOOK_NAME, 'action_spec': { 'name': 'my-action', 'class': 'std.http', 'base-parameters': { 'url': 'http://localhost:8989/v1/workbooks', 'method': 'GET' }, 'namespace': 'MyRest' }, 'task_spec': { 'action': 'MyRest.my-action', 'name': TASK_NAME}, 'requires': {}, 'state': states.IDLE} SAMPLE_CONTEXT = { 'user': 'admin', 'tenant': 'mistral' } class TestExecutor(base.DbTestCase): def __init__(self, *args, **kwargs): super(TestExecutor, self).__init__(*args, **kwargs) self.transport = base.get_fake_transport() @mock.patch.object( executor.ExecutorClient, 'handle_task', mock.MagicMock(side_effect=base.EngineTestCase.mock_handle_task)) @mock.patch.object( std_actions.HTTPAction, 'run', mock.MagicMock(return_value={})) @mock.patch.object( engine.EngineClient, 'convey_task_result', mock.MagicMock(side_effect=base.EngineTestCase.mock_task_result)) def test_handle_task(self): # Create a new workbook. workbook = db_api.workbook_create(SAMPLE_WORKBOOK) self.assertIsInstance(workbook, dict) # Create a new execution. execution = db_api.execution_create(SAMPLE_EXECUTION['workbook_name'], SAMPLE_EXECUTION) self.assertIsInstance(execution, dict) # Create a new task. SAMPLE_TASK['execution_id'] = execution['id'] task = db_api.task_create(SAMPLE_TASK['workbook_name'], SAMPLE_TASK['execution_id'], SAMPLE_TASK) self.assertIsInstance(task, dict) self.assertIn('id', task) # Send the task request to the Executor. ex_client = executor.ExecutorClient(self.transport) ex_client.handle_task(SAMPLE_CONTEXT, task=task) # Check task execution state. db_task = db_api.task_get(task['workbook_name'], task['execution_id'], task['id']) self.assertEqual(db_task['state'], states.SUCCESS)
dmitryilyin/mistral
mistral/tests/unit/engine/default/test_executor.py
Python
apache-2.0
4,084
package com.osiris.component.bootstrap.menu.render; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.render.FacesRenderer; import org.primefaces.renderkit.CoreRenderer; import com.osiris.component.bootstrap.menu.UIMenuItem; import com.osiris.component.util.HTML; import com.osiris.component.util.HtmlConstants; /** * * Classe que renderiza um item do menu. * * @author Cristian Urbainski<cristianurbainskips@gmail.com> * @since 13/07/2013 * @version 1.0 * */ @FacesRenderer(componentFamily = UIMenuItem.COMPONENT_FAMILY, rendererType = MenuItemRender.RENDERER_TYPE) public class MenuItemRender extends CoreRenderer { /** * Tipo do renderizador do componente. */ public static final String RENDERER_TYPE = "com.osiris.component.bootstrap.MenuItemRenderer"; @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { UIMenuItem menuItem = (UIMenuItem) component; encodeMarkup(context, menuItem); } /** * Método responsável por fazer a construção do html para o componente. * * @param context do jsf * @param menuItem componente a ser transcrito para html * @throws IOException excecao que pode ocorrer */ protected void encodeMarkup(FacesContext context, UIMenuItem menuItem) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = menuItem.getClientId(context); String style = menuItem.getStyle(); String styleClass = ""; if (menuItem.isActive()) { styleClass = "active"; } if (menuItem.getStyleClass() != null) { styleClass += " " + menuItem.getStyleClass(); } writer.startElement(HTML.LI_ELEM, null); writer.writeAttribute(HtmlConstants.ID_ATTRIBUTE, clientId, null); if (styleClass.length() > 0) { writer.writeAttribute(HtmlConstants.CLASS_ATTR, styleClass, null); } if (style != null) { writer.writeAttribute(HtmlConstants.STYLE_ATTRIBUTE, style, null); } writer.startElement(HTML.A_ELEM, null); writer.writeAttribute(HtmlConstants.HREF_ATTR, menuItem.getLocation(), null); writer.writeText(menuItem.getLabel(), null); writer.endElement(HTML.A_ELEM); writer.endElement(HTML.LI_ELEM); } }
CristianUrbainski/osiris-faces
osiris-faces/src/main/java/com/osiris/component/bootstrap/menu/render/MenuItemRender.java
Java
apache-2.0
2,535
import codecs from pandas import read_csv import argparse import numpy as np import codecs import os FIELD_NAMES = ["context_id","target","target_pos","target_position","gold_sense_ids","predict_sense_ids", "golden_related","predict_related","context"] FIELD_TYPES = {"context_id":np.dtype(str),"target":np.dtype(str),"target_pos":np.dtype(str),"target_position":np.dtype(str),"gold_sense_ids":np.dtype(str),"predict_sense_ids":np.dtype(str), "golden_related":np.dtype(str),"predict_related":np.dtype(str),"context":np.dtype(str)} def cut_9_first(dataset_fpath, dataset_9_fpath): """ Cuts first 9 columns of the dataset file to make it openable with read_csv. """ with codecs.open(dataset_fpath, "r", "utf-8") as in_dataset, codecs.open(dataset_9_fpath, "w", "utf-8") as out_dataset: for line in in_dataset: print >> out_dataset, "\t".join(line.split("\t")[:9]) def convert_dataset2semevalkey(dataset_fpath, output_fpath, no_header=False): with codecs.open(output_fpath, "w", encoding="utf-8") as output: if no_header: df = read_csv(dataset_fpath, sep='\t', encoding='utf8', header=None, names=FIELD_NAMES, dtype=FIELD_TYPES, doublequote=False, quotechar='\0') df.target = df.target.astype(str) else: df = read_csv(dataset_fpath, encoding='utf-8', delimiter="\t", error_bad_lines=False, doublequote=False, quotechar='\0') for i, row in df.iterrows(): predicted_senses = " ".join(unicode(row.predict_sense_ids).split(",")) print >> output, "%s %s %s" % (row.target + "." + row.target_pos, row.context_id, predicted_senses) print "Key file:", output_fpath def main(): parser = argparse.ArgumentParser(description='Convert lexical sample dataset to SemEval 2013 key format.') parser.add_argument('input', help='Path to a file with input file.') parser.add_argument('output', help='Output file.') parser.add_argument('--no_header', action='store_true', help='No headers. Default -- false.') args = parser.parse_args() print "Input: ", args.input print "Output: ", args.output print "No header:", args.no_header tmp_fpath = args.input + "-9-columns.csv" cut_9_first(args.input, tmp_fpath) convert_dataset2semevalkey(tmp_fpath, args.output, args.no_header) #os.remove(tmp_fpath) if __name__ == '__main__': main()
mpelevina/context-eval
semeval_2013_13/dataset2key.py
Python
apache-2.0
2,427
/* * $Id: HtmlTag.java 54929 2004-10-16 16:38:42Z germuska $ * * Copyright 1999-2004 The Apache Software Foundation. * * 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.apache.struts.taglib.html; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.TagSupport; import org.apache.struts.Globals; import org.apache.struts.taglib.TagUtils; import org.apache.struts.util.MessageResources; /** * Renders an HTML <html> element with appropriate language attributes if * there is a current Locale available in the user's session. * * @version $Rev: 54929 $ $Date: 2004-10-17 01:38:42 +0900 (日, 17 10月 2004) $ */ public class HtmlTag extends TagSupport { // ------------------------------------------------------------- Properties /** * The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources(Constants.Package + ".LocalStrings"); /** * Should we set the current Locale for this user if needed? * @deprecated This will be removed after Struts 1.2. */ protected boolean locale = false; /** * @deprecated This will be removed after Struts 1.2. */ public boolean getLocale() { return (locale); } /** * @deprecated This will be removed after Struts 1.2. */ public void setLocale(boolean locale) { this.locale = locale; } /** * Are we rendering an xhtml page? */ protected boolean xhtml = false; /** * Are we rendering a lang attribute? * @since Struts 1.2 */ protected boolean lang = false; public boolean getXhtml() { return this.xhtml; } public void setXhtml(boolean xhtml) { this.xhtml = xhtml; } /** * Returns true if the tag should render a lang attribute. * @since Struts 1.2 */ public boolean getLang() { return this.lang; } /** * Sets whether the tag should render a lang attribute. * @since Struts 1.2 */ public void setLang(boolean lang) { this.lang = lang; } /** * Process the start of this tag. * * @exception JspException if a JSP exception has occurred */ public int doStartTag() throws JspException { TagUtils.getInstance().write(this.pageContext, this.renderHtmlStartElement()); return EVAL_BODY_INCLUDE; } /** * Renders an &lt;html&gt; element with appropriate language attributes. * @since Struts 1.2 */ protected String renderHtmlStartElement() { StringBuffer sb = new StringBuffer("<html"); String language = null; String country = ""; if (this.locale) { // provided for 1.1 backward compatibility, remove after 1.2 language = this.getCurrentLocale().getLanguage(); } else { Locale currentLocale = TagUtils.getInstance().getUserLocale(pageContext, Globals.LOCALE_KEY); language = currentLocale.getLanguage(); country = currentLocale.getCountry(); } boolean validLanguage = ((language != null) && (language.length() > 0)); boolean validCountry = country.length() > 0; if (this.xhtml) { this.pageContext.setAttribute( Globals.XHTML_KEY, "true", PageContext.PAGE_SCOPE); sb.append(" xmlns=\"http://www.w3.org/1999/xhtml\""); } if ((this.lang || this.locale || this.xhtml) && validLanguage) { sb.append(" lang=\""); sb.append(language); if (validCountry) { sb.append("-"); sb.append(country); } sb.append("\""); } if (this.xhtml && validLanguage) { sb.append(" xml:lang=\""); sb.append(language); if (validCountry) { sb.append("-"); sb.append(country); } sb.append("\""); } sb.append(">"); return sb.toString(); } /** * Process the end of this tag. * * @exception JspException if a JSP exception has occurred */ public int doEndTag() throws JspException { TagUtils.getInstance().write(pageContext, "</html>"); // Evaluate the remainder of this page return (EVAL_PAGE); } /** * Release any acquired resources. */ public void release() { this.locale = false; this.xhtml = false; this.lang=false; } // ------------------------------------------------------ Protected Methods /** * Return the current Locale for this request. If there is no locale in the session and * the locale attribute is set to "true", this method will create a Locale based on the * client's Accept-Language header or the server's default locale and store it in the * session. This will always return a Locale and never null. * @since Struts 1.1 * @deprecated This will be removed after Struts 1.2. */ protected Locale getCurrentLocale() { Locale userLocale = TagUtils.getInstance().getUserLocale(pageContext, Globals.LOCALE_KEY); // Store a new current Locale, if requested if (this.locale) { HttpSession session = ((HttpServletRequest) this.pageContext.getRequest()).getSession(); session.setAttribute(Globals.LOCALE_KEY, userLocale); } return userLocale; } }
codelibs/cl-struts
src/share/org/apache/struts/taglib/html/HtmlTag.java
Java
apache-2.0
6,309
package liquibase.snapshot.jvm; import java.util.stream.Collectors; import liquibase.Scope; import liquibase.database.Database; import liquibase.database.core.*; import liquibase.exception.DatabaseException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.executor.ExecutorService; import liquibase.snapshot.CachedRow; import liquibase.snapshot.DatabaseSnapshot; import liquibase.snapshot.JdbcDatabaseSnapshot; import liquibase.statement.core.RawSqlStatement; import liquibase.structure.DatabaseObject; import liquibase.structure.core.Catalog; import liquibase.structure.core.Column; import liquibase.structure.core.Index; import liquibase.structure.core.Relation; import liquibase.structure.core.Schema; import liquibase.structure.core.Table; import liquibase.structure.core.UniqueConstraint; import liquibase.util.StringUtil; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class UniqueConstraintSnapshotGenerator extends JdbcSnapshotGenerator { public UniqueConstraintSnapshotGenerator() { super(UniqueConstraint.class, new Class[]{Table.class}); } @Override public int getPriority(Class<? extends DatabaseObject> objectType, Database database) { if (database instanceof SQLiteDatabase) { return PRIORITY_NONE; } return super.getPriority(objectType, database); } @Override protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException { Database database = snapshot.getDatabase(); UniqueConstraint exampleConstraint = (UniqueConstraint) example; Relation table = exampleConstraint.getRelation(); List<Map<String, ?>> metadata = listColumns(exampleConstraint, database, snapshot); if (metadata.isEmpty()) { return null; } UniqueConstraint constraint = new UniqueConstraint(); constraint.setRelation(table); constraint.setName(example.getName()); constraint.setBackingIndex(exampleConstraint.getBackingIndex()); constraint.setInitiallyDeferred(((UniqueConstraint) example).isInitiallyDeferred()); constraint.setDeferrable(((UniqueConstraint) example).isDeferrable()); constraint.setClustered(((UniqueConstraint) example).isClustered()); for (Map<String, ?> col : metadata) { String ascOrDesc = (String) col.get("ASC_OR_DESC"); Boolean descending = "D".equals(ascOrDesc) ? Boolean.TRUE : ("A".equals(ascOrDesc) ? Boolean.FALSE : null); if (database instanceof H2Database) { for (String columnName : StringUtil.splitAndTrim((String) col.get("COLUMN_NAME"), ",")) { constraint.getColumns().add(new Column(columnName).setDescending(descending).setRelation(table)); } } else { constraint.getColumns().add(new Column((String) col.get("COLUMN_NAME")).setDescending(descending).setRelation(table)); } setValidateOptionIfAvailable(database, constraint, col); } return constraint; } /** * Method to map 'validate' option for UC. This thing works only for ORACLE * * @param database - DB where UC will be created * @param uniqueConstraint - UC object to persist validate option * @param columnsMetadata - it's a cache-map to get metadata about UC */ private void setValidateOptionIfAvailable(Database database, UniqueConstraint uniqueConstraint, Map<String, ?> columnsMetadata) { if (!(database instanceof OracleDatabase)) { return; } final Object constraintValidate = columnsMetadata.get("CONSTRAINT_VALIDATE"); final String VALIDATE = "VALIDATED"; if (constraintValidate != null && !constraintValidate.toString().trim().isEmpty()) { uniqueConstraint.setShouldValidate(VALIDATE.equals(cleanNameFromDatabase(constraintValidate.toString().trim(), database))); } } @Override protected void addTo(DatabaseObject foundObject, DatabaseSnapshot snapshot) throws DatabaseException { if (!snapshot.getSnapshotControl().shouldInclude(UniqueConstraint.class)) { return; } if (foundObject instanceof Table) { Table table = (Table) foundObject; Database database = snapshot.getDatabase(); Schema schema; schema = table.getSchema(); List<CachedRow> metadata; try { metadata = listConstraints(table, snapshot, schema); } catch (SQLException e) { throw new DatabaseException(e); } Set<String> seenConstraints = new HashSet<>(); for (CachedRow constraint : metadata) { UniqueConstraint uq = new UniqueConstraint() .setName(cleanNameFromDatabase((String) constraint.get("CONSTRAINT_NAME"), database)).setRelation(table); if (constraint.containsColumn("INDEX_NAME")) { uq.setBackingIndex(new Index((String) constraint.get("INDEX_NAME"), (String) constraint.get("INDEX_CATALOG"), (String) constraint.get("INDEX_SCHEMA"), table.getName())); } if ("CLUSTERED".equals(constraint.get("TYPE_DESC"))) { uq.setClustered(true); } if (seenConstraints.add(uq.getName())) { table.getUniqueConstraints().add(uq); } } } } protected List<CachedRow> listConstraints(Table table, DatabaseSnapshot snapshot, Schema schema) throws DatabaseException, SQLException { return ((JdbcDatabaseSnapshot) snapshot).getMetaDataFromCache().getUniqueConstraints(schema.getCatalogName(), schema.getName(), table.getName()); } protected List<Map<String, ?>> listColumns(UniqueConstraint example, Database database, DatabaseSnapshot snapshot) throws DatabaseException { Relation table = example.getRelation(); Schema schema = example.getSchema(); String name = example.getName(); boolean bulkQuery; String sql; String cacheKey = "uniqueConstraints-" + example.getClass().getSimpleName() + "-" + example.getSchema().toCatalogAndSchema().customize(database).toString(); String queryCountKey = "uniqueConstraints-" + example.getClass().getSimpleName() + "-queryCount"; Map<String, List<Map<String, ?>>> columnCache = (Map<String, List<Map<String, ?>>>) snapshot.getScratchData(cacheKey); Integer columnQueryCount = (Integer) snapshot.getScratchData(queryCountKey); if (columnQueryCount == null) { columnQueryCount = 0; } if (columnCache == null) { bulkQuery = false; if (columnQueryCount > 3) { bulkQuery = supportsBulkQuery(database); } snapshot.setScratchData(queryCountKey, columnQueryCount + 1); if ((database instanceof MySQLDatabase) || (database instanceof HsqlDatabase)) { sql = "select const.CONSTRAINT_NAME, const.TABLE_NAME, COLUMN_NAME, const.constraint_schema as CONSTRAINT_CONTAINER " + "from " + database.getSystemSchema() + ".table_constraints const " + "join " + database.getSystemSchema() + ".key_column_usage col " + "on const.constraint_schema=col.constraint_schema " + "and const.table_name=col.table_name " + "and const.constraint_name=col.constraint_name " + "where const.constraint_schema='" + database.correctObjectName(schema.getCatalogName(), Catalog.class) + "' "; if (!bulkQuery) { sql += "and const.table_name='" + database.correctObjectName(example.getRelation().getName(), Table.class) + "' " + "and const.constraint_name='" + database.correctObjectName(name, UniqueConstraint.class) + "'"; } sql += "order by ordinal_position"; } else if (database instanceof PostgresDatabase) { List<String> conditions = new ArrayList<>(); sql = "select const.CONSTRAINT_NAME, COLUMN_NAME, const.constraint_schema as CONSTRAINT_CONTAINER " + "from " + database.getSystemSchema() + ".table_constraints const " + "join " + database.getSystemSchema() + ".key_column_usage col " + "on const.constraint_schema=col.constraint_schema " + "and const.table_name=col.table_name " + "and const.constraint_name=col.constraint_name "; if (schema.getCatalogName() != null) { conditions.add("const.constraint_catalog='" + database.correctObjectName(schema.getCatalogName(), Catalog.class) + "'"); } if (database instanceof CockroachDatabase) { conditions.add("(select count(*) from (select indexdef from pg_indexes where schemaname='\" + database.correctObjectName(schema.getSchema().getName(), Schema.class) + \"' AND indexname='\" + database.correctObjectName(name, UniqueConstraint.class) + \"' AND (position('DESC,' in indexdef) > 0 OR position('DESC)' in indexdef) > 0))) = 0"); conditions.add("const.constraint_name != 'primary'"); } if (schema.getSchema().getName() != null) { conditions.add("const.constraint_schema='" + database.correctObjectName(schema.getSchema().getName(), Schema.class) + "'"); } if (!bulkQuery) { conditions.add("const.table_name='" + database.correctObjectName(example.getRelation().getName(), Table.class) + "'"); if (name != null) { conditions.add("const.constraint_name='" + database.correctObjectName(name, UniqueConstraint.class) + "' "); } } if (!conditions.isEmpty()) { sql += " WHERE "; sql += conditions.stream().collect(Collectors.joining(" AND ")); } sql += " order by ordinal_position"; } else if (database.getClass().getName().contains("MaxDB")) { //have to check classname as this is currently an extension sql = "select CONSTRAINTNAME as constraint_name, COLUMNNAME as column_name from CONSTRAINTCOLUMNS WHERE CONSTRAINTTYPE = 'UNIQUE_CONST' AND tablename = '" + database.correctObjectName(example.getRelation().getName(), Table.class) + "' AND constraintname = '" + database.correctObjectName(name, UniqueConstraint.class) + "'"; } else if (database instanceof MSSQLDatabase) { sql = "SELECT " + "[kc].[name] AS [CONSTRAINT_NAME], " + "s.name AS constraint_container, " + "[c].[name] AS [COLUMN_NAME], " + "CASE [ic].[is_descending_key] WHEN 0 THEN N'A' WHEN 1 THEN N'D' END AS [ASC_OR_DESC] " + "FROM [sys].[schemas] AS [s] " + "INNER JOIN [sys].[tables] AS [t] " + "ON [t].[schema_id] = [s].[schema_id] " + "INNER JOIN [sys].[key_constraints] AS [kc] " + "ON [kc].[parent_object_id] = [t].[object_id] " + "INNER JOIN [sys].[indexes] AS [i] " + "ON [i].[object_id] = [kc].[parent_object_id] " + "AND [i].[index_id] = [kc].[unique_index_id] " + "INNER JOIN [sys].[index_columns] AS [ic] " + "ON [ic].[object_id] = [i].[object_id] " + "AND [ic].[index_id] = [i].[index_id] " + "INNER JOIN [sys].[columns] AS [c] " + "ON [c].[object_id] = [ic].[object_id] " + "AND [c].[column_id] = [ic].[column_id] " + "WHERE [s].[name] = N'" + database.escapeStringForDatabase(database.correctObjectName(schema.getName(), Schema.class)) + "' "; if (!bulkQuery) { sql += "AND [t].[name] = N'" + database.escapeStringForDatabase(database.correctObjectName(example.getRelation().getName(), Table.class)) + "' " + "AND [kc].[name] = N'" + database.escapeStringForDatabase(database.correctObjectName(name, UniqueConstraint.class)) + "' "; } sql += "ORDER BY " + "[ic].[key_ordinal]"; } else if (database instanceof OracleDatabase) { sql = "select ucc.owner as constraint_container, ucc.constraint_name as constraint_name, ucc.column_name, f.validated as constraint_validate, ucc.table_name " + "from all_cons_columns ucc " + "INNER JOIN all_constraints f " + "ON ucc.owner = f.owner " + "AND ucc.constraint_name = f.constraint_name " + "where " + (bulkQuery ? "" : "ucc.constraint_name='" + database.correctObjectName(name, UniqueConstraint.class) + "' and ") + "ucc.owner='" + database.correctObjectName(schema.getCatalogName(), Catalog.class) + "' " + "and ucc.table_name not like 'BIN$%' " + "order by ucc.position"; } else if (database instanceof DB2Database) { if (database.getDatabaseProductName().startsWith("DB2 UDB for AS/400")) { sql = "select T1.constraint_name as CONSTRAINT_NAME, T2.COLUMN_NAME as COLUMN_NAME, T1.CONSTRAINT_SCHEMA as CONSTRAINT_CONTAINER from QSYS2.TABLE_CONSTRAINTS T1, QSYS2.SYSCSTCOL T2\n" + "where T1.CONSTRAINT_TYPE='UNIQUE' and T1.CONSTRAINT_NAME=T2.CONSTRAINT_NAME\n" + "and T1.CONSTRAINT_SCHEMA='" + database.correctObjectName(schema.getName(), Schema.class) + "'\n" + "and T2.CONSTRAINT_SCHEMA='" + database.correctObjectName(schema.getName(), Schema.class) + "'\n" //+ "T2.TABLE_NAME='"+ database.correctObjectName(example.getTable().getName(), Table.class) + "'\n" //+ "\n" + "order by T2.COLUMN_NAME\n"; } else { sql = "select k.constname as constraint_name, k.colname as column_name from syscat.keycoluse k, syscat.tabconst t " + "where k.constname = t.constname " + "and k.tabschema = t.tabschema " + "and t.type='U' " + (bulkQuery? "" : "and k.constname='" + database.correctObjectName(name, UniqueConstraint.class) + "' ") + "and t.tabschema = '" + database.correctObjectName(schema.getName(), Schema.class) + "' " + "order by colseq"; } } else if (database instanceof Db2zDatabase) { sql = "select k.colname as column_name from SYSIBM.SYSKEYCOLUSE k, SYSIBM.SYSTABCONST t " + "where k.constname = t.constname " + "and k.TBCREATOR = t.TBCREATOR " + "and t.type = 'U'" + "and k.constname='" + database.correctObjectName(name, UniqueConstraint.class) + "' " + "and t.TBCREATOR = '" + database.correctObjectName(schema.getName(), Schema.class) + "' " + "order by colseq"; } else if (database instanceof DerbyDatabase) { //does not support bulkQuery, supportsBulkQuery should return false() sql = "SELECT cg.descriptor as descriptor, t.tablename " + "FROM sys.sysconglomerates cg " + "JOIN sys.syskeys k ON cg.conglomerateid = k.conglomerateid " + "JOIN sys.sysconstraints c ON c.constraintid = k.constraintid " + "JOIN sys.systables t ON c.tableid = t.tableid " + "WHERE c.constraintname='" + database.correctObjectName(name, UniqueConstraint.class) + "'"; List<Map<String, ?>> rows = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).queryForList(new RawSqlStatement(sql)); List<Map<String, ?>> returnList = new ArrayList<>(); if (rows.isEmpty()) { return returnList; } else if (rows.size() > 1) { throw new UnexpectedLiquibaseException("Got multiple rows back querying unique constraints"); } else { Map rowData = rows.get(0); String descriptor = rowData.get("DESCRIPTOR").toString(); descriptor = descriptor.replaceFirst(".*\\(", "").replaceFirst("\\).*", ""); for (String columnNumber : StringUtil.splitAndTrim(descriptor, ",")) { String columnName = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).queryForObject(new RawSqlStatement( "select c.columnname from sys.syscolumns c " + "join sys.systables t on t.tableid=c.referenceid " + "where t.tablename='" + rowData.get("TABLENAME") + "' and c.columnnumber=" + columnNumber), String.class); Map<String, String> row = new HashMap<>(); row.put("COLUMN_NAME", columnName); returnList.add(row); } return returnList; } } else if (database instanceof FirebirdDatabase) { //does not support bulkQuery, supportsBulkQuery should return false() // Careful! FIELD_NAME and INDEX_NAME in RDB$INDEX_SEGMENTS are CHAR, not VARCHAR columns. sql = "SELECT TRIM(RDB$INDEX_SEGMENTS.RDB$FIELD_NAME) AS column_name " + "FROM RDB$INDEX_SEGMENTS " + "LEFT JOIN RDB$INDICES ON RDB$INDICES.RDB$INDEX_NAME = RDB$INDEX_SEGMENTS.RDB$INDEX_NAME " + "WHERE UPPER(TRIM(RDB$INDICES.RDB$INDEX_NAME))='" + database.correctObjectName(name, UniqueConstraint.class) + "' " + "ORDER BY RDB$INDEX_SEGMENTS.RDB$FIELD_POSITION"; } else if (database instanceof SybaseASADatabase) { //does not support bulkQuery, supportsBulkQuery should return false() sql = "select sysconstraint.constraint_name, syscolumn.column_name " + "from sysconstraint, syscolumn, systable " + "where sysconstraint.ref_object_id = syscolumn.object_id " + "and sysconstraint.table_object_id = systable.object_id " + "and sysconstraint.constraint_name = '" + database.correctObjectName(name, UniqueConstraint.class) + "' " + "and systable.table_name = '" + database.correctObjectName(example.getRelation().getName(), Table.class) + "'"; } else if(database instanceof Ingres9Database) { //does not support bulkQuery, supportsBulkQuery should return false() sql = "select constraint_name, column_name " + "from iikeys " + "where constraint_name = '" + database.correctObjectName(name, UniqueConstraint.class) + "' " + "and table_name = '" + database.correctObjectName(example.getTable().getName(), Table.class) + "'"; } else if (database instanceof InformixDatabase) { //does not support bulkQuery, supportsBulkQuery should return false() sql = getUniqueConstraintsSqlInformix((InformixDatabase) database, schema, name); } else if (database instanceof Db2zDatabase) { sql = "select KC.TBCREATOR as CONSTRAINT_CONTAINER, KC.CONSTNAME as CONSTRAINT_NAME, KC.COLNAME as COLUMN_NAME from SYSIBM.SYSKEYCOLUSE KC, SYSIBM.SYSTABCONST TC " + "where KC.CONSTNAME = TC.CONSTNAME " + "and KC.TBCREATOR = TC.TBCREATOR " + "and TC.TYPE='U' " + (bulkQuery ? "" : "and KC.CONSTNAME='" + database.correctObjectName(name, UniqueConstraint.class) + "' ") + "and TC.TBCREATOR = '" + database.correctObjectName(schema.getName(), Schema.class) + "' " + "order by KC.COLSEQ"; } else if (database instanceof H2Database && database.getDatabaseMajorVersion() >= 2) { String catalogName = database.correctObjectName(schema.getCatalogName(), Catalog.class); String schemaName = database.correctObjectName(schema.getName(), Schema.class); String constraintName = database.correctObjectName(name, UniqueConstraint.class); String tableName = database.correctObjectName(table.getName(), Table.class); sql = "select table_constraints.CONSTRAINT_NAME, index_columns.COLUMN_NAME, table_constraints.constraint_schema as CONSTRAINT_CONTAINER " + "from information_schema.table_constraints " + "join information_schema.index_columns on index_columns.index_name=table_constraints.index_name " + "where constraint_type='UNIQUE' "; if (catalogName != null) { sql += "and constraint_catalog='" + catalogName + "' "; } if (schemaName != null) { sql += "and constraint_schema='" + schemaName + "' "; } if (!bulkQuery) { if (tableName != null) { sql += "and table_constraints.table_name='" + tableName + "' "; } if (constraintName != null) { sql += "and constraint_name='" + constraintName + "'"; } } } else { // If we do not have a specific handler for the RDBMS, we assume that the database has an // INFORMATION_SCHEMA we can use. This is a last-resort measure and might fail. String catalogName = database.correctObjectName(schema.getCatalogName(), Catalog.class); String schemaName = database.correctObjectName(schema.getName(), Schema.class); String constraintName = database.correctObjectName(name, UniqueConstraint.class); String tableName = database.correctObjectName(table.getName(), Table.class); sql = "select CONSTRAINT_NAME, COLUMN_LIST as COLUMN_NAME, constraint_schema as CONSTRAINT_CONTAINER " + "from " + database.getSystemSchema() + ".constraints " + "where constraint_type='UNIQUE' "; if (catalogName != null) { sql += "and constraint_catalog='" + catalogName + "' "; } if (schemaName != null) { sql += "and constraint_schema='" + schemaName + "' "; } if (!bulkQuery) { if (tableName != null) { sql += "and table_name='" + tableName + "' "; } if (constraintName != null) { sql += "and constraint_name='" + constraintName + "'"; } } } List<Map<String, ?>> rows = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).queryForList(new RawSqlStatement(sql)); if (bulkQuery) { columnCache = new HashMap<>(); snapshot.setScratchData(cacheKey, columnCache); for (Map<String, ?> row : rows) { String key = getCacheKey(row, database); List<Map<String, ?>> constraintRows = columnCache.get(key); if (constraintRows == null) { constraintRows = new ArrayList<>(); columnCache.put(key, constraintRows); } constraintRows.add(row); } return listColumns(example, database, snapshot); } else { return rows; } } else { String lookupKey = getCacheKey(example, database); List<Map<String, ?>> rows = columnCache.get(lookupKey); if (rows == null) { rows = new ArrayList<>(); } return rows; } } /** * Should the given database include the table name in the key? * Databases that need to include the table names are ones where unique constraint names do not have to be unique * within the schema. * * Currently only mysql is known to have non-unique constraint names. * * If this returns true, the database-specific query in {@link #listColumns(UniqueConstraint, Database, DatabaseSnapshot)} must include * a TABLE_NAME column in the results for {@link #getCacheKey(Map, Database)} to use. */ protected boolean includeTableNameInCacheKey(Database database) { return database instanceof MySQLDatabase; } /** * Return the cache key for the given UniqueConstraint. Must return the same result as {@link #getCacheKey(Map, Database)}. * Default implementation uses {@link #includeTableNameInCacheKey(Database)} to determine if the table name should be included in the key or not. */ protected String getCacheKey(UniqueConstraint example, Database database) { if (includeTableNameInCacheKey(database)) { return example.getSchema().getName() + "_" + example.getRelation() + "_" + example.getName(); } else { return example.getSchema().getName() + "_" + example.getName(); } } /** * Return the cache key for the given query row. Must return the same result as {@link #getCacheKey(UniqueConstraint, Database)} * Default implementation uses {@link #includeTableNameInCacheKey(Database)} to determine if the table name should be included in the key or not. */ protected String getCacheKey(Map<String, ?> row, Database database) { if (includeTableNameInCacheKey(database)) { return row.get("CONSTRAINT_CONTAINER") + "_" + row.get("TABLE_NAME") + "_" + row.get("CONSTRAINT_NAME"); } else { return row.get("CONSTRAINT_CONTAINER") + "_" + row.get("CONSTRAINT_NAME"); } } /** * To support bulk query, the resultSet must include a CONSTRAINT_CONTAINER column for caching purposes */ protected boolean supportsBulkQuery(Database database) { return !(database instanceof DerbyDatabase) && !(database instanceof FirebirdDatabase) && !(database instanceof SybaseASADatabase) && !(database instanceof Ingres9Database) && !(database instanceof InformixDatabase); } /** * Gets an SQL query that returns the constraint names and columns for all UNIQUE constraints. * * @param database A database object of the InformixDatabase type * @param schema Name of the schema to examine (or null for all) * @param name Name of the constraint to examine (or null for all) * @return A lengthy SQL statement that fetches the constraint names and columns */ private String getUniqueConstraintsSqlInformix(InformixDatabase database, Schema schema, String name) { StringBuilder sqlBuf = new StringBuilder(); sqlBuf.append("SELECT * FROM (\n"); // Yes, I am serious about this. It appears there are neither CTE/WITH clauses nor PIVOT/UNPIVOT operators // in Informix SQL. for (int i = 1; i <= 16; i++) { if (i > 1) sqlBuf.append("UNION ALL\n"); sqlBuf.append( String.format(" SELECT\n" + " CONS.owner,\n" + " CONS.constrname AS constraint_name,\n" + " COL.colname AS column_name,\n" + " CONS.constrtype,\n" + " %d AS column_index\n" + " FROM informix.sysconstraints CONS\n" + " JOIN informix.sysindexes IDX ON CONS.idxname = IDX.idxname\n" + " JOIN informix.syscolumns COL ON COL.tabid = CONS.tabid AND COL.colno = IDX.part%d\n", i, i ) ); } // Finish the subquery and filter on the U(NIQUE) constraint type sqlBuf.append( " ) SUBQ\n" + "WHERE constrtype='U' \n"); String catalogName = database.correctObjectName(schema.getCatalogName(), Catalog.class); String constraintName = database.correctObjectName(name, UniqueConstraint.class); // If possible, filter for catalog name and/or constraint name if (catalogName != null) { sqlBuf.append("AND owner='").append(catalogName).append("'\n"); } if (constraintName != null) { sqlBuf.append("AND constraint_name='").append(constraintName).append("'"); } // For correct processing, it is important that we get all columns in order. sqlBuf.append("ORDER BY owner, constraint_name, column_index"); // Return the query return sqlBuf.toString(); } }
liquibase/liquibase
liquibase-core/src/main/java/liquibase/snapshot/jvm/UniqueConstraintSnapshotGenerator.java
Java
apache-2.0
30,661
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.module('Blockly.test.connectionChecker'); const {ConnectionType} = goog.require('Blockly.ConnectionType'); const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); suite('Connection checker', function() { setup(function() { sharedTestSetup.call(this); }); teardown(function() { sharedTestTeardown.call(this); }); suiteSetup(function() { this.checker = new Blockly.ConnectionChecker(); }); suite('Safety checks', function() { function assertReasonHelper(checker, one, two, reason) { chai.assert.equal(checker.canConnectWithReason(one, two), reason); // Order should not matter. chai.assert.equal(checker.canConnectWithReason(two, one), reason); } test('Target Null', function() { const connection = new Blockly.Connection({}, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, connection, null, Blockly.Connection.REASON_TARGET_NULL); }); test('Target Self', function() { const block = {workspace: 1}; const connection1 = new Blockly.Connection(block, ConnectionType.INPUT_VALUE); const connection2 = new Blockly.Connection(block, ConnectionType.OUTPUT_VALUE); assertReasonHelper( this.checker, connection1, connection2, Blockly.Connection.REASON_SELF_CONNECTION); }); test('Different Workspaces', function() { const connection1 = new Blockly.Connection( {workspace: 1}, ConnectionType.INPUT_VALUE); const connection2 = new Blockly.Connection( {workspace: 2}, ConnectionType.OUTPUT_VALUE); assertReasonHelper( this.checker, connection1, connection2, Blockly.Connection.REASON_DIFFERENT_WORKSPACES); }); suite('Types', function() { setup(function() { // We have to declare each separately so that the connections belong // on different blocks. const prevBlock = {isShadow: function() {}}; const nextBlock = {isShadow: function() {}}; const outBlock = {isShadow: function() {}}; const inBlock = {isShadow: function() {}}; this.previous = new Blockly.Connection( prevBlock, ConnectionType.PREVIOUS_STATEMENT); this.next = new Blockly.Connection( nextBlock, ConnectionType.NEXT_STATEMENT); this.output = new Blockly.Connection( outBlock, ConnectionType.OUTPUT_VALUE); this.input = new Blockly.Connection( inBlock, ConnectionType.INPUT_VALUE); }); test('Previous, Next', function() { assertReasonHelper( this.checker, this.previous, this.next, Blockly.Connection.CAN_CONNECT); }); test('Previous, Output', function() { assertReasonHelper( this.checker, this.previous, this.output, Blockly.Connection.REASON_WRONG_TYPE); }); test('Previous, Input', function() { assertReasonHelper( this.checker, this.previous, this.input, Blockly.Connection.REASON_WRONG_TYPE); }); test('Next, Previous', function() { assertReasonHelper( this.checker, this.next, this.previous, Blockly.Connection.CAN_CONNECT); }); test('Next, Output', function() { assertReasonHelper( this.checker, this.next, this.output, Blockly.Connection.REASON_WRONG_TYPE); }); test('Next, Input', function() { assertReasonHelper( this.checker, this.next, this.input, Blockly.Connection.REASON_WRONG_TYPE); }); test('Output, Previous', function() { assertReasonHelper( this.checker, this.previous, this.output, Blockly.Connection.REASON_WRONG_TYPE); }); test('Output, Next', function() { assertReasonHelper( this.checker, this.output, this.next, Blockly.Connection.REASON_WRONG_TYPE); }); test('Output, Input', function() { assertReasonHelper( this.checker, this.output, this.input, Blockly.Connection.CAN_CONNECT); }); test('Input, Previous', function() { assertReasonHelper( this.checker, this.previous, this.input, Blockly.Connection.REASON_WRONG_TYPE); }); test('Input, Next', function() { assertReasonHelper( this.checker, this.input, this.next, Blockly.Connection.REASON_WRONG_TYPE); }); test('Input, Output', function() { assertReasonHelper( this.checker, this.input, this.output, Blockly.Connection.CAN_CONNECT); }); }); suite('Shadows', function() { test('Previous Shadow', function() { const prevBlock = {isShadow: function() {return true;}}; const nextBlock = {isShadow: function() {return false;}}; const prev = new Blockly.Connection(prevBlock, ConnectionType.PREVIOUS_STATEMENT); const next = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); assertReasonHelper( this.checker, prev, next, Blockly.Connection.CAN_CONNECT); }); test('Next Shadow', function() { const prevBlock = {isShadow: function() {return false;}}; const nextBlock = {isShadow: function() {return true;}}; const prev = new Blockly.Connection(prevBlock, ConnectionType.PREVIOUS_STATEMENT); const next = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); assertReasonHelper( this.checker, prev, next, Blockly.Connection.REASON_SHADOW_PARENT); }); test('Prev and Next Shadow', function() { const prevBlock = {isShadow: function() {return true;}}; const nextBlock = {isShadow: function() {return true;}}; const prev = new Blockly.Connection(prevBlock, ConnectionType.PREVIOUS_STATEMENT); const next = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); assertReasonHelper( this.checker, prev, next, Blockly.Connection.CAN_CONNECT); }); test('Output Shadow', function() { const outBlock = {isShadow: function() {return true;}}; const inBlock = {isShadow: function() {return false;}}; const outCon = new Blockly.Connection(outBlock, ConnectionType.OUTPUT_VALUE); const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, outCon, inCon, Blockly.Connection.CAN_CONNECT); }); test('Input Shadow', function() { const outBlock = {isShadow: function() {return false;}}; const inBlock = {isShadow: function() {return true;}}; const outCon = new Blockly.Connection(outBlock, ConnectionType.OUTPUT_VALUE); const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, outCon, inCon, Blockly.Connection.REASON_SHADOW_PARENT); }); test('Output and Input Shadow', function() { const outBlock = {isShadow: function() {return true;}}; const inBlock = {isShadow: function() {return true;}}; const outCon = new Blockly.Connection(outBlock, ConnectionType.OUTPUT_VALUE); const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, outCon, inCon, Blockly.Connection.CAN_CONNECT); }); }); suite('Output and Previous', function() { /** * Update two connections to target each other. * @param {Connection} first The first connection to update. * @param {Connection} second The second connection to update. */ const connectReciprocally = function(first, second) { if (!first || !second) { throw Error('Cannot connect null connections.'); } first.targetConnection = second; second.targetConnection = first; }; test('Output connected, adding previous', function() { const outBlock = { isShadow: function() { }, }; const inBlock = { isShadow: function() { }, }; const outCon = new Blockly.Connection(outBlock, ConnectionType.OUTPUT_VALUE); const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); outBlock.outputConnection = outCon; inBlock.inputConnection = inCon; connectReciprocally(inCon, outCon); const prevCon = new Blockly.Connection(outBlock, ConnectionType.PREVIOUS_STATEMENT); const nextBlock = { isShadow: function() { }, }; const nextCon = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); assertReasonHelper( this.checker, prevCon, nextCon, Blockly.Connection.REASON_PREVIOUS_AND_OUTPUT); }); test('Previous connected, adding output', function() { const prevBlock = { isShadow: function() { }, }; const nextBlock = { isShadow: function() { }, }; const prevCon = new Blockly.Connection(prevBlock, ConnectionType.PREVIOUS_STATEMENT); const nextCon = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); prevBlock.previousConnection = prevCon; nextBlock.nextConnection = nextCon; connectReciprocally(prevCon, nextCon); const outCon = new Blockly.Connection(prevBlock, ConnectionType.OUTPUT_VALUE); const inBlock = { isShadow: function() { }, }; const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, outCon, inCon, Blockly.Connection.REASON_PREVIOUS_AND_OUTPUT); }); }); }); suite('Check Types', function() { setup(function() { this.con1 = new Blockly.Connection({}, ConnectionType.PREVIOUS_STATEMENT); this.con2 = new Blockly.Connection({}, ConnectionType.NEXT_STATEMENT); }); function assertCheckTypes(checker, one, two) { chai.assert.isTrue(checker.doTypeChecks(one, two)); // Order should not matter. chai.assert.isTrue(checker.doTypeChecks(one, two)); } test('No Types', function() { assertCheckTypes(this.checker, this.con1, this.con2); }); test('Same Type', function() { this.con1.setCheck('type1'); this.con2.setCheck('type1'); assertCheckTypes(this.checker, this.con1, this.con2); }); test('Same Types', function() { this.con1.setCheck(['type1', 'type2']); this.con2.setCheck(['type1', 'type2']); assertCheckTypes(this.checker, this.con1, this.con2); }); test('Single Same Type', function() { this.con1.setCheck(['type1', 'type2']); this.con2.setCheck(['type1', 'type3']); assertCheckTypes(this.checker, this.con1, this.con2); }); test('One Typed, One Promiscuous', function() { this.con1.setCheck('type1'); assertCheckTypes(this.checker, this.con1, this.con2); }); test('No Compatible Types', function() { this.con1.setCheck('type1'); this.con2.setCheck('type2'); chai.assert.isFalse(this.checker.doTypeChecks(this.con1, this.con2)); }); }); });
google/blockly
tests/mocha/connection_checker_test.js
JavaScript
apache-2.0
12,098
/* * Copyright (c) 2015 Complexible Inc. <http://complexible.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 com.complexible.basecrm; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; /** * <p></p> * * @author Michael Grove * @since 0.1 * @version 0.1 */ public class Deal extends BaseObject { private String mName; private String mStageName; private boolean mHot; private boolean mIsNew; private Contact mMainContact; private Contact mCompany; public Contact getCompany() { return mCompany; } public void setCompany(final Contact theCompany) { mCompany = theCompany; } public boolean isHot() { return mHot; } public void setHot(final boolean theHot) { mHot = theHot; } public boolean isNew() { return mIsNew; } public void setNew(final boolean theIsNew) { mIsNew = theIsNew; } public Contact getMainContact() { return mMainContact; } public void setMainContact(final Contact theMainContact) { mMainContact = theMainContact; } public String getName() { return mName; } public void setName(final String theName) { mName = theName; } public String getStageName() { return mStageName; } public void setStageName(final String theStageName) { mStageName = theStageName; } /** * @{inheritDoc} */ @Override public int hashCode() { return Objects.hashCode(mId, mName); } /** * @{inheritDoc} */ @Override public boolean equals(final Object theObj) { if (theObj == this) { return true; } else if (theObj instanceof Deal) { Deal aDeal = (Deal) theObj; return Objects.equal(mName, aDeal.mName) && Objects.equal(mId, aDeal.mId); } else { return false; } } /** * @{inheritDoc} */ @Override public String toString() { return MoreObjects.toStringHelper("Deal") .add("name", mName) .add("stage", mStageName) .add("company", mCompany) .toString(); } }
Complexible/basecrm
main/src/com/complexible/basecrm/Deal.java
Java
apache-2.0
2,438
package com.resource; public abstract class RscValidator { public ValidatorConfiguration config; public RscValidator(){} public RscValidator(ValidatorConfiguration config){ this.config = config; } public void set_config(ValidatorConfiguration config){ this.config = config; } public abstract void init(); public abstract void head(); public abstract void options(); public abstract void get(); public abstract void post(); public abstract void put(); public abstract void delete(); }
wanglilong007/rest_assured_framework
src/main/java/com/resource/RscValidator.java
Java
apache-2.0
504
<?php /** * 2013-11-25 上午12:08:30 * @author x.li * @abstract */ class Product_Model_Series extends Application_Model_Db { /** * 表名、主键 */ protected $_name = 'product_catalog_series'; protected $_primary = 'id'; public function getData() { $sql = $this->select() ->setIntegrityCheck(false) ->from(array('t1' => $this->_name)) ->joinLeft(array('t2' => $this->_dbprefix.'user'), "t2.id = t1.create_user", array()) ->joinLeft(array('t3' => $this->_dbprefix.'employee'), "t3.id = t2.employee_id", array('creater' => 'cname')) ->joinLeft(array('t4' => $this->_dbprefix.'user'), "t4.id = t1.update_user", array()) ->joinLeft(array('t5' => $this->_dbprefix.'employee'), "t5.id = t4.employee_id", array('updater' => 'cname')) ->order(array('t1.name')); $data = $this->fetchAll($sql)->toArray(); for($i = 0; $i < count($data); $i++){ $data[$i]['create_time'] = strtotime($data[$i]['create_time']); $data[$i]['update_time'] = strtotime($data[$i]['update_time']); $data[$i]['active'] = $data[$i]['active'] == 1 ? true : false; } return $data; } }
eoasoft/evolve
application/modules/product/models/Series.php
PHP
apache-2.0
1,314
/* * Copyright (C) 2015 Orange * * 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.orange.ngsi.model; /** * Created by pborscia on 05/06/2015. */ public enum UpdateAction { UPDATE("UPDATE"),APPEND("APPEND"),DELETE("DELETE"); private String label; UpdateAction(String label) { this.label=label; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public Boolean isDelete() { return label.equals("DELETE"); } public Boolean isUpdate() { return label.equals("UPDATE"); } public Boolean isAppend() { return label.equals("APPEND"); } }
Orange-OpenSource/fiware-ngsi-api
ngsi-client/src/main/java/com/orange/ngsi/model/UpdateAction.java
Java
apache-2.0
1,228
/* * 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. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.error; import static java.lang.String.format; import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ShouldBeSame.shouldBeSame; import org.assertj.core.description.TextDescription; import org.assertj.core.presentation.StandardRepresentation; import org.junit.jupiter.api.Test; /** * Tests for <code>{@link ShouldBeSame#create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation)}</code>. * * @author Alex Ruiz */ class ShouldBeSame_create_Test { @Test void should_create_error_message() { // GIVEN ErrorMessageFactory factory = shouldBeSame("Yoda", "Luke"); // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Luke\"%nand actual:%n \"Yoda\"%nto refer to the same object")); } }
hazendaz/assertj-core
src/test/java/org/assertj/core/error/ShouldBeSame_create_Test.java
Java
apache-2.0
1,541
package com.github.florent37.camerafragment.internal.timer; import com.github.florent37.camerafragment.internal.utils.DateTimeUtils; /* * Created by florentchampigny on 13/01/2017. */ public class TimerTask extends TimerTaskBase implements Runnable { public TimerTask(TimerTaskBase.Callback callback) { super(callback); } @Override public void run() { recordingTimeSeconds++; if (recordingTimeSeconds == 60) { recordingTimeSeconds = 0; recordingTimeMinutes++; } if(callback != null) { callback.setText( String.format("%02d:%02d", recordingTimeMinutes, recordingTimeSeconds)); } if (alive) handler.postDelayed(this, DateTimeUtils.SECOND); } public void start() { alive = true; recordingTimeMinutes = 0; recordingTimeSeconds = 0; if(callback != null) { callback.setText( String.format("%02d:%02d", recordingTimeMinutes, recordingTimeSeconds)); callback.setTextVisible(true); } handler.postDelayed(this, DateTimeUtils.SECOND); } public void stop() { if(callback != null){ callback.setTextVisible(false); } alive = false; } }
mkrtchyanmnatsakan/DemoAppHelloWord
camerafragment/src/main/java/com/github/florent37/camerafragment/internal/timer/TimerTask.java
Java
apache-2.0
1,308
package fr.openwide.core.commons.util.registry; import java.io.Closeable; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Sets; import de.schlichtherle.truezip.file.TFile; import de.schlichtherle.truezip.file.TVFS; import de.schlichtherle.truezip.fs.FsSyncException; import de.schlichtherle.truezip.fs.FsSyncOptions; /** * A registry responsible for keeping track of open {@link TFile TFiles} and for cleaning them up upon closing it. * <p>This should generally be used as a factory for creating TFiles (see the <code>create</code> methods), and the * calling of {@link #open()} and {@link #close()} should be done in some generic code (such as a servlet filter). * <p>Please note that this registry is using a {@link ThreadLocal}. Opening and closing the registry must therefore * be done in the same thread, and each TFile-creating thread should use its own registry. */ public final class TFileRegistry { private static final Logger LOGGER = LoggerFactory.getLogger(TFileRegistry.class); private static final ThreadLocal<TFileRegistryImpl> THREAD_LOCAL = new ThreadLocal<TFileRegistryImpl>(); private TFileRegistry() { } /** * Enables the (thread-local) TFileRegistry, so that every call to the createXX() or register() static methods * will result in the relevant TFile to be stored for further cleaning of TrueZip internal resources. * <p>The actual cleaning must be performed by calling the {@link #close()} static method on TFileRegistry. */ public static void open() { TFileRegistryImpl registry = THREAD_LOCAL.get(); if (registry == null) { THREAD_LOCAL.set(new TFileRegistryImpl()); } else { throw new IllegalStateException("TFileRegistry.open() should not be called twice without calling close() in-between."); } } /** * {@link TVFS#sync(de.schlichtherle.truezip.fs.FsMountPoint, de.schlichtherle.truezip.util.BitField) Synchronize} * the TrueZip virtual filesystem for every registered file, and clears the registry. * <p><strong>WARNING :</strong> If some {@link InputStream InputStreams} or {@link OutputStream OutputStreams} * managed by the current thread have not been closed yet, they will be ignored. */ public static void close() { try { TFileRegistryImpl registry = THREAD_LOCAL.get(); if (registry != null) { registry.close(); } else { throw new IllegalStateException("TFileRegistry.close() should not be called if TFileRegistry.open() has not been called before."); } } finally { THREAD_LOCAL.remove(); } } public static TFile create(String path) { TFile tFile = new TFile(path); register(tFile); return tFile; } public static TFile create(File file) { TFile tFile = new TFile(file); register(tFile); return tFile; } public static TFile create(String parent, String member) { TFile tFile = new TFile(parent, member); register(tFile); return tFile; } public static TFile create(File parent, String member) { TFile tFile = new TFile(parent, member); register(tFile); return tFile; } public static TFile create(URI uri) { TFile tFile = new TFile(uri); register(tFile); return tFile; } public static void register(File file) { Objects.requireNonNull(file, "file must not be null"); TFileRegistryImpl registry = THREAD_LOCAL.get(); if (registry != null) { registry.register(file); } else { LOGGER.info("Trying to register file '{}', but the TFileRegistry has not been open (see TFileRegistry.open()). Ignoring registration.", file); THREAD_LOCAL.remove(); } } public static void register(Iterable<? extends File> files) { Objects.requireNonNull(files, "files must not be null"); TFileRegistryImpl registry = THREAD_LOCAL.get(); if (registry != null) { registry.register(files); } else { LOGGER.info("Trying to register files '{}', but the TFileRegistry has not been open (see TFileRegistry.open()). Ignoring registration.", files); THREAD_LOCAL.remove(); } } private static final class TFileRegistryImpl implements Closeable { private final Set<TFile> registeredFiles = Sets.newHashSet(); private TFileRegistryImpl() { } public void register(File file) { if (file instanceof TFile) { TFile topLevelArchive = ((TFile)file).getTopLevelArchive(); if (topLevelArchive != null) { registeredFiles.add(topLevelArchive); } } } public void register(Iterable<? extends File> files) { for (File file : files) { register(file); } } @Override public void close() { for (TFile tFile : registeredFiles) { try { TVFS.sync(tFile, FsSyncOptions.SYNC); } catch (RuntimeException | FsSyncException e) { LOGGER.error("Error while trying to sync the truezip filesystem on '" + tFile + "'", e); } } } } }
openwide-java/owsi-core-parent
owsi-core/owsi-core-components/owsi-core-component-commons/src/main/java/fr/openwide/core/commons/util/registry/TFileRegistry.java
Java
apache-2.0
4,967
/* Copyright 2014 base2Services 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.base2.kagura.core.report.configmodel; import com.base2.kagura.core.report.connectors.JDBCDataReportConnector; import com.base2.kagura.core.report.connectors.ReportConnector; /** * JDBC backend for @see #FreeMarkerSQLReport * User: aubels * Date: 24/07/13 * Time: 4:46 PM * */ public class JDBCReportConfig extends FreeMarkerSQLReportConfig { String jdbc; String username; String password; private String classLoaderPath; /** * {@inheritDoc} * @return */ @Override public ReportConnector getReportConnector() { return new JDBCDataReportConnector(this); } /** * JDBC connection string * @return */ public String getJdbc() { return jdbc; } /** * @see #getJdbc() */ public void setJdbc(String jdbc) { this.jdbc = jdbc; } /** * JDBC Password if necessary * @return */ public String getPassword() { return password; } /** * @see #getPassword() */ public void setPassword(String password) { this.password = password; } /** * JDBC username * @return */ public String getUsername() { return username; } /** * @see #getUsername() * @param username */ public void setUsername(String username) { this.username = username; } /** * Class path loader for the Database driver, for instance: com.mysql.jdbc.Driver * @return */ public String getClassLoaderPath() { return classLoaderPath; } /** * @see #getClassLoaderPath() */ public void setClassLoaderPath(String classLoaderPath) { this.classLoaderPath = classLoaderPath; } }
base2Services/kagura
shared/reporting-core/src/main/java/com/base2/kagura/core/report/configmodel/JDBCReportConfig.java
Java
apache-2.0
2,350
<?php final class ManiphestTaskResultListView extends ManiphestView { private $tasks; private $savedQuery; private $canEditPriority; private $canBatchEdit; private $showBatchControls; public function setSavedQuery(PhabricatorSavedQuery $query) { $this->savedQuery = $query; return $this; } public function setTasks(array $tasks) { $this->tasks = $tasks; return $this; } public function setCanEditPriority($can_edit_priority) { $this->canEditPriority = $can_edit_priority; return $this; } public function setCanBatchEdit($can_batch_edit) { $this->canBatchEdit = $can_batch_edit; return $this; } public function setShowBatchControls($show_batch_controls) { $this->showBatchControls = $show_batch_controls; return $this; } public function render() { $viewer = $this->getUser(); $tasks = $this->tasks; $query = $this->savedQuery; // If we didn't match anything, just pick up the default empty state. if (!$tasks) { return id(new PHUIObjectItemListView()) ->setUser($viewer); } $group_parameter = nonempty($query->getParameter('group'), 'priority'); $order_parameter = nonempty($query->getParameter('order'), 'priority'); $handles = ManiphestTaskListView::loadTaskHandles($viewer, $tasks); $groups = $this->groupTasks( $tasks, $group_parameter, $handles); $can_edit_priority = $this->canEditPriority; $can_drag = ($order_parameter == 'priority') && ($can_edit_priority) && ($group_parameter == 'none' || $group_parameter == 'priority'); if (!$viewer->isLoggedIn()) { // TODO: (T603) Eventually, we conceivably need to make each task // draggable individually, since the user may be able to edit some but // not others. $can_drag = false; } $result = array(); $lists = array(); foreach ($groups as $group => $list) { $task_list = new ManiphestTaskListView(); $task_list->setShowBatchControls($this->showBatchControls); if ($can_drag) { $task_list->setShowSubpriorityControls(true); } $task_list->setUser($viewer); $task_list->setTasks($list); $task_list->setHandles($handles); $header = javelin_tag( 'h1', array( 'class' => 'maniphest-task-group-header', 'sigil' => 'task-group', 'meta' => array( 'priority' => head($list)->getPriority(), ), ), pht('%s (%s)', $group, new PhutilNumber(count($list)))); $lists[] = phutil_tag( 'div', array( 'class' => 'maniphest-task-group' ), array( $header, $task_list, )); } if ($can_drag) { Javelin::initBehavior( 'maniphest-subpriority-editor', array( 'uri' => '/maniphest/subpriority/', )); } return phutil_tag( 'div', array( 'class' => 'maniphest-list-container', ), array( $lists, $this->showBatchControls ? $this->renderBatchEditor($query) : null, )); } private function groupTasks(array $tasks, $group, array $handles) { assert_instances_of($tasks, 'ManiphestTask'); assert_instances_of($handles, 'PhabricatorObjectHandle'); $groups = $this->getTaskGrouping($tasks, $group); $results = array(); foreach ($groups as $label_key => $tasks) { $label = $this->getTaskLabelName($group, $label_key, $handles); $results[$label][] = $tasks; } foreach ($results as $label => $task_groups) { $results[$label] = array_mergev($task_groups); } return $results; } private function getTaskGrouping(array $tasks, $group) { switch ($group) { case 'priority': return mgroup($tasks, 'getPriority'); case 'status': return mgroup($tasks, 'getStatus'); case 'assigned': return mgroup($tasks, 'getOwnerPHID'); case 'project': return mgroup($tasks, 'getGroupByProjectPHID'); default: return array(pht('Tasks') => $tasks); } } private function getTaskLabelName($group, $label_key, array $handles) { switch ($group) { case 'priority': return ManiphestTaskPriority::getTaskPriorityName($label_key); case 'status': return ManiphestTaskStatus::getTaskStatusFullName($label_key); case 'assigned': if ($label_key) { return $handles[$label_key]->getFullName(); } else { return pht('(Not Assigned)'); } case 'project': if ($label_key) { return $handles[$label_key]->getFullName(); } else { // This may mean "No Projects", or it may mean the query has project // constraints but the task is only in constrained projects (in this // case, we don't show the group because it would always have all // of the tasks). Since distinguishing between these two cases is // messy and the UI is reasonably clear, label generically. return pht('(Ungrouped)'); } default: return pht('Tasks'); } } private function renderBatchEditor(PhabricatorSavedQuery $saved_query) { $user = $this->getUser(); if (!$this->canBatchEdit) { return null; } if (!$user->isLoggedIn()) { // Don't show the batch editor or excel export for logged-out users. // Technically we //could// let them export, but ehh. return null; } Javelin::initBehavior( 'maniphest-batch-selector', array( 'selectAll' => 'batch-select-all', 'selectNone' => 'batch-select-none', 'submit' => 'batch-select-submit', 'status' => 'batch-select-status-cell', 'idContainer' => 'batch-select-id-container', 'formID' => 'batch-select-form', )); $select_all = javelin_tag( 'a', array( 'href' => '#', 'mustcapture' => true, 'class' => 'grey button', 'id' => 'batch-select-all', ), pht('Select All')); $select_none = javelin_tag( 'a', array( 'href' => '#', 'mustcapture' => true, 'class' => 'grey button', 'id' => 'batch-select-none', ), pht('Clear Selection')); $submit = phutil_tag( 'button', array( 'id' => 'batch-select-submit', 'disabled' => 'disabled', 'class' => 'disabled', ), pht("Batch Edit Selected \xC2\xBB")); $export = javelin_tag( 'a', array( 'href' => '/maniphest/export/'.$saved_query->getQueryKey().'/', 'class' => 'grey button', ), pht('Export to Excel')); $hidden = phutil_tag( 'div', array( 'id' => 'batch-select-id-container', ), ''); $editor = hsprintf( '<div class="maniphest-batch-editor">'. '<div class="batch-editor-header">%s</div>'. '<table class="maniphest-batch-editor-layout">'. '<tr>'. '<td>%s%s</td>'. '<td>%s</td>'. '<td id="batch-select-status-cell">%s</td>'. '<td class="batch-select-submit-cell">%s%s</td>'. '</tr>'. '</table>'. '</div>', pht('Batch Task Editor'), $select_all, $select_none, $export, '', $submit, $hidden); $editor = phabricator_form( $user, array( 'method' => 'POST', 'action' => '/maniphest/batch/', 'id' => 'batch-select-form', ), $editor); return $editor; } }
akkakks/phabricator
src/applications/maniphest/view/ManiphestTaskResultListView.php
PHP
apache-2.0
7,755
#region license // Copyright 2014 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. #endregion using JetBrains.ReSharper.Plugins.AngularJS.Psi.Html; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.JavaScript.Tree; using JetBrains.ReSharper.Psi.Resolve; using JetBrains.ReSharper.Psi.Tree; using JetBrains.ReSharper.Psi.Util; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.AngularJS.Psi.AngularJs.References { [ReferenceProviderFactory] public class AngularJsIncludeFileReferenceProvider : AngularJsReferenceFactoryBase { private readonly IAngularJsHtmlDeclaredElementTypes elementTypes; public AngularJsIncludeFileReferenceProvider(IAngularJsHtmlDeclaredElementTypes elementTypes) { this.elementTypes = elementTypes; } protected override IReference[] GetReferences(ITreeNode element, IReference[] oldReferences) { if (!HasReference(element, null)) return EmptyArray<IReference>.Instance; var stringLiteral = (IJavaScriptLiteralExpression)element; var references = PathReferenceUtil.CreatePathReferences(stringLiteral, stringLiteral, null, GetFolderPathReference, GetFileReference, node => node.GetStringValue(), node => node.GetUnquotedTreeTextRange('"', '\'').StartOffset.Offset); return references; } private static IPathReference GetFileReference(IJavaScriptLiteralExpression literal, IQualifier qualifier, IJavaScriptLiteralExpression token, TreeTextRange range) { return new AngularJsFileLateBoundReference<IJavaScriptLiteralExpression, IJavaScriptLiteralExpression>(literal, qualifier, token, range); } private static IPathReference GetFolderPathReference(IJavaScriptLiteralExpression literal, IQualifier qualifier, IJavaScriptLiteralExpression token, TreeTextRange range) { return new AngularJsFolderLateBoundReference<IJavaScriptLiteralExpression, IJavaScriptLiteralExpression>(literal, qualifier, token, range); } protected override bool HasReference(ITreeNode element, IReferenceNameContainer names) { var stringLiteral = element as IJavaScriptLiteralExpression; if (stringLiteral == null) return false; var file = element.GetContainingFile(); if (file == null) return false; // TODO: We can't use this, due to losing data when we reparse for code completion // When we start code completion, the tree node is reparsed with new text inserted, // so that references have something to attach to. Reparsing works with IChameleon // blocks that allow for resync-ing in-place. Our AngularJs nodes don't have any // chameleon blocks (for JS, it's the Block class - anything with braces) so we end // up re-parsing the file. This creates a new IFile, (in a sandbox that allows access // to the original file's reference provider) but it doesn't copy the user data. We // could theoretically look for a containing sandbox, get the context node and try // and get the user data there, but that just makes it feel like this is the wrong // solution. I think maybe this should be a reference provider for HTML, not AngularJs. // It would have the context of the attribute name, but should really work with the // injected AngularJs language, if only to see that it's a string literal //var originalAttributeType = file.UserData.GetData(AngularJsFileData.OriginalAttributeType); //if (originalAttributeType != elementTypes.AngularJsUrlType.Name) // return false; return true; } } }
JetBrains/resharper-angularjs
src/resharper-angularjs/Psi/AngularJs/References/AngularJsIncludeFileReferenceProvider.cs
C#
apache-2.0
4,390
package com.github.windchopper.common.fx.behavior; import javafx.geometry.*; import javafx.scene.Cursor; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Region; import javafx.stage.Stage; import javafx.stage.Window; import java.util.stream.Stream; import static java.util.Arrays.stream; public class WindowMoveResizeBehavior implements Behavior<Region> { private static class AngleRange { private final double minAngle; private final double maxAngle; public AngleRange(double minAngle, double maxAngle) { this.minAngle = minAngle; this.maxAngle = maxAngle; } public boolean matches(double angle) { return angle >= minAngle && angle <= maxAngle; } } private abstract class DragMode { protected double savedSceneX; protected double savedSceneY; protected double savedScreenX; protected double savedScreenY; protected double savedWidth; protected double savedHeight; public abstract void apply(MouseEvent event); public void store(MouseEvent event) { savedSceneX = event.getSceneX(); savedSceneY = event.getSceneY(); savedScreenX = event.getScreenX(); savedScreenY = event.getScreenY(); Window window = region.getScene().getWindow(); savedWidth = window.getWidth(); savedHeight = window.getHeight(); } } private class MoveMode extends DragMode { private final Cursor normalCursor; private final Cursor dragCursor; public MoveMode(Cursor normalCursor, Cursor dragCursor) { this.normalCursor = normalCursor; this.dragCursor = dragCursor; } @Override public void apply(MouseEvent event) { if (event.getEventType() != MouseEvent.MOUSE_DRAGGED) { region.setCursor(normalCursor); } else { region.setCursor(dragCursor); Window window = region.getScene().getWindow(); window.setX(event.getScreenX() - savedSceneX); window.setY(event.getScreenY() - savedSceneY); } } } private abstract class ResizeMode extends DragMode { private final Cursor cursor; private final AngleRange []angleRanges; public abstract Bounds calculateBounds(MouseEvent dragEvent, Window window); public ResizeMode(Cursor cursor, AngleRange... angleRanges) { this.cursor = cursor; this.angleRanges = angleRanges; } public boolean matches(double angle) { return stream(angleRanges).anyMatch(range -> range.matches(angle)); } @Override public void apply(MouseEvent event) { region.setCursor(cursor); if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) { var window = region.getScene().getWindow(); var bounds = calculateBounds(event, window); var width = bounds.getWidth(); var height = bounds.getHeight(); if (window instanceof Stage) { var stage = (Stage) window; if (stage.isResizable()) { width = Math.min(Math.max(width, stage.getMinWidth()), stage.getMaxWidth()); height = Math.min(Math.max(height, stage.getMinHeight()), stage.getMaxHeight()); } else { width = window.getWidth(); height = window.getHeight(); } } window.setX(bounds.getMinX()); window.setY(bounds.getMinY()); window.setWidth(width); window.setHeight(height); } } } private class ResizeEastMode extends ResizeMode { public ResizeEastMode(AngleRange... angleRanges) { super(Cursor.E_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( window.getX(), window.getY(), savedWidth + dragEvent.getScreenX() - savedScreenX, window.getHeight()); } } private class ResizeNorthEastMode extends ResizeMode { public ResizeNorthEastMode(AngleRange... angleRanges) { super(Cursor.NE_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( window.getX(), dragEvent.getScreenY() - savedSceneY, savedWidth + dragEvent.getScreenX() - savedScreenX, savedHeight - dragEvent.getScreenY() + savedScreenY); } } private class ResizeNorthMode extends ResizeMode { public ResizeNorthMode(AngleRange... angleRanges) { super(Cursor.N_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( window.getX(), dragEvent.getScreenY() - savedSceneY, window.getWidth(), savedHeight - dragEvent.getScreenY() + savedScreenY); } } private class ResizeNorthWestMode extends ResizeMode { public ResizeNorthWestMode(AngleRange... angleRanges) { super(Cursor.NW_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( dragEvent.getScreenX() - savedSceneX, dragEvent.getScreenY() - savedSceneY, savedWidth - dragEvent.getScreenX() + savedScreenX, savedHeight - dragEvent.getScreenY() + savedScreenY); } } private class ResizeWestMode extends ResizeMode { public ResizeWestMode(AngleRange... angleRanges) { super(Cursor.W_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( dragEvent.getScreenX() - savedSceneX, window.getY(), savedWidth - dragEvent.getScreenX() + savedScreenX, window.getHeight()); } } private class ResizeSouthWestMode extends ResizeMode { public ResizeSouthWestMode(AngleRange... angleRanges) { super(Cursor.SW_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( dragEvent.getScreenX() - savedSceneX, window.getY(), savedWidth - dragEvent.getScreenX() + savedScreenX, savedHeight + dragEvent.getScreenY() - savedScreenY); } } private class ResizeSouthMode extends ResizeMode { public ResizeSouthMode(AngleRange... angleRanges) { super(Cursor.S_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( window.getX(), window.getY(), window.getWidth(), savedHeight + dragEvent.getScreenY() - savedScreenY); } } private class ResizeSouthEastMode extends ResizeMode { public ResizeSouthEastMode(AngleRange... angleRanges) { super(Cursor.SE_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( window.getX(), window.getY(), savedWidth + dragEvent.getScreenX() - savedScreenX, savedHeight + dragEvent.getScreenY() - savedScreenY); } } private final Region region; private final double resizeBorderSize; private final MoveMode move; private final ResizeMode resizeEast; private final ResizeMode resizeNorthEast; private final ResizeMode resizeNorth; private final ResizeMode resizeNorthWest; private final ResizeMode resizeWest; private final ResizeMode resizeSouthWest; private final ResizeMode resizeSouth; private final ResizeMode resizeSouthEast; private DragMode dragMode; public WindowMoveResizeBehavior(Region region) { this(region, 2, 2); } public WindowMoveResizeBehavior(Region region, double resizeBorderSize, double diagonalResizeSpotAngularSize) { this.region = region; this.resizeBorderSize = resizeBorderSize; dragMode = move = new MoveMode(Cursor.DEFAULT, Cursor.MOVE); resizeEast = new ResizeEastMode(new AngleRange(0, 45 - diagonalResizeSpotAngularSize), new AngleRange(315 + diagonalResizeSpotAngularSize, 360)); resizeNorthEast = new ResizeNorthEastMode(new AngleRange(45 - diagonalResizeSpotAngularSize, 45 + diagonalResizeSpotAngularSize)); resizeNorth = new ResizeNorthMode(new AngleRange(45 + diagonalResizeSpotAngularSize, 135 - diagonalResizeSpotAngularSize)); resizeNorthWest = new ResizeNorthWestMode(new AngleRange(135 - diagonalResizeSpotAngularSize, 135 + diagonalResizeSpotAngularSize)); resizeWest = new ResizeWestMode(new AngleRange(135 + diagonalResizeSpotAngularSize, 225 - diagonalResizeSpotAngularSize)); resizeSouthWest = new ResizeSouthWestMode(new AngleRange(225 - diagonalResizeSpotAngularSize, 225 + diagonalResizeSpotAngularSize)); resizeSouth = new ResizeSouthMode(new AngleRange(225 + diagonalResizeSpotAngularSize, 315 - diagonalResizeSpotAngularSize)); resizeSouthEast = new ResizeSouthEastMode(new AngleRange(315 - diagonalResizeSpotAngularSize, 315 + diagonalResizeSpotAngularSize)); } private double calculateAngle(double x, double y) { double angle = Math.toDegrees( Math.atan2(y, x)); if (angle < 0) { angle = 360 + angle; } if (angle > 360) { angle = 360; } return angle; } private DragMode detect(MouseEvent event) { Bounds bounds = region.getLayoutBounds(); Bounds outerBounds = new BoundingBox(bounds.getMinX() - resizeBorderSize, bounds.getMinY() - resizeBorderSize, bounds.getWidth() + resizeBorderSize * 2, bounds.getHeight() + resizeBorderSize * 2); Bounds innerBounds = new BoundingBox(bounds.getMinX() + resizeBorderSize, bounds.getMinY() + resizeBorderSize, bounds.getWidth() - resizeBorderSize * 2, bounds.getHeight() - resizeBorderSize * 2); Point2D center = new Point2D(innerBounds.getWidth() / 2, innerBounds.getHeight() / 2); Point2D ptr = new Point2D( event.getX(), event.getY()); if (outerBounds.contains(ptr) && !innerBounds.contains(ptr)) { double angle = calculateAngle(ptr.getX() - center.getX(), (ptr.getY() - center.getY()) * (outerBounds.getWidth() / outerBounds.getHeight()) * -1); return Stream.of(resizeEast, resizeNorthEast, resizeNorth, resizeNorthWest, resizeWest, resizeSouthWest, resizeSouth, resizeSouthEast) .filter(mode -> mode.matches(angle)) .findFirst().orElseThrow(AssertionError::new); } return move; } private void mouseAny(MouseEvent event) { dragMode.apply(event); } private void mousePress(MouseEvent event) { dragMode.store(event); mouseAny(event); } private void mouseRelease(MouseEvent event) { mouseAny(event); } private void mouseMove(MouseEvent event) { dragMode = detect(event); mouseAny(event); } private void mouseDrag(MouseEvent event) { mouseAny(event); } /* * */ @Override public void apply(Region region) { region.setOnMousePressed(this::mousePress); region.setOnMouseReleased(this::mouseRelease); region.setOnMouseMoved(this::mouseMove); region.setOnMouseDragged(this::mouseDrag); } }
windchopper/common
common-fx/src/main/java/com/github/windchopper/common/fx/behavior/WindowMoveResizeBehavior.java
Java
apache-2.0
12,341
/* * Copyright 2016 Johann Reyes * * 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.vaporwarecorp.mirror.feature.artik; import android.content.Intent; import com.fasterxml.jackson.databind.JsonNode; import com.robopupu.api.dependency.Provides; import com.robopupu.api.dependency.Scope; import com.robopupu.api.plugin.Plug; import com.robopupu.api.plugin.Plugin; import com.robopupu.api.plugin.PluginBus; import com.vaporwarecorp.mirror.app.MirrorAppScope; import com.vaporwarecorp.mirror.component.AppManager; import com.vaporwarecorp.mirror.component.ConfigurationManager; import com.vaporwarecorp.mirror.component.EventManager; import com.vaporwarecorp.mirror.component.PluginFeatureManager; import com.vaporwarecorp.mirror.event.ApplicationEvent; import com.vaporwarecorp.mirror.feature.common.AbstractMirrorManager; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import timber.log.Timber; import java.util.Map; import static com.vaporwarecorp.mirror.event.ApplicationEvent.TRY_TO_START; import static com.vaporwarecorp.mirror.util.JsonUtil.createTextNode; import static org.apache.commons.lang3.StringUtils.isNotEmpty; @Plugin @Scope(MirrorAppScope.class) @Provides(ArtikManager.class) public class ArtikManagerImpl extends AbstractMirrorManager implements ArtikManager { // ------------------------------ FIELDS ------------------------------ private static final String PREF = ArtikManager.class.getName(); private static final String PREF_APPLICATION_ID = PREF + ".PREF_APPLICATION_ID"; private static final String PREF_CONTROL_DEVICE_ID = PREF + ".PREF_CONTROL_DEVICE_ID"; private static final String PREF_SIDEKICK_DEVICE_ID = PREF + ".PREF_SIDEKICK_DEVICE_ID"; @Plug AppManager mAppManager; @Plug ConfigurationManager mConfigurationManager; @Plug EventManager mEventManager; @Plug PluginFeatureManager mFeatureManager; private String mAccessToken; private String mApplicationId; private ArtikCloudManager mArtikCloudManager; private ArtikOAuthManager mArtikOAuthManager; private String mControlDeviceId; private boolean mEnabled; private String mSidekickDeviceId; // ------------------------ INTERFACE METHODS ------------------------ // --------------------- Interface ArtikManager --------------------- @Override public void share(Map<String, Object> content) { if (mArtikCloudManager == null) { return; } subscribe(mArtikCloudManager.sendAction(content) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { Timber.d("onCompleted"); } @Override public void onError(Throwable e) { Timber.e(e, "Error trying to send action"); } @Override public void onNext(String s) { } })); } // --------------------- Interface Configuration --------------------- @Override public String getJsonConfiguration() { return "configuration/json/artik.json"; } @Override public String getJsonValues() { return createTextNode("applicationId", mApplicationId) .put("controlDeviceId", mControlDeviceId) .put("sidekickDeviceId", mSidekickDeviceId) .toString(); } @Override public void updateConfiguration(JsonNode jsonNode) { mConfigurationManager.updateString(PREF_APPLICATION_ID, jsonNode, "applicationId"); mConfigurationManager.updateString(PREF_CONTROL_DEVICE_ID, jsonNode, "controlDeviceId"); mConfigurationManager.updateString(PREF_SIDEKICK_DEVICE_ID, jsonNode, "sidekickDeviceId"); loadConfiguration(); onFeatureResume(); } // --------------------- Interface MirrorManager --------------------- @Override public void onFeaturePause() { if (mArtikCloudManager != null) { mArtikCloudManager.stopMessaging(); mArtikCloudManager = null; } } @Override public void onFeatureResume() { if (mEnabled) { mArtikCloudManager = new ArtikCloudManager(mEventManager, mApplicationId, mSidekickDeviceId, mControlDeviceId, mAccessToken); mArtikCloudManager.startMessaging(); } } // --------------------- Interface PluginComponent --------------------- @Override public void onPlugged(PluginBus bus) { super.onPlugged(bus); loadConfiguration(); } @Override public void onUnplugged(PluginBus bus) { mArtikCloudManager = null; mArtikOAuthManager = null; super.onUnplugged(bus); } // --------------------- Interface WebAuthentication --------------------- @Override public void doAuthentication() { if(!mEnabled) { mEventManager.post(new ApplicationEvent(TRY_TO_START)); return; } // get authorization subscribe(mArtikOAuthManager.authorizeImplicitly() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { Timber.d("onCompleted"); mEventManager.post(new ApplicationEvent(TRY_TO_START)); } @Override public void onError(Throwable e) { Timber.e(e, "Error trying to authenticate"); } @Override public void onNext(String s) { mAccessToken = s; } })); } @Override public void isAuthenticated(IsAuthenticatedCallback callback) { callback.onResult(false); } @Override public void onAuthenticationResult(int requestCode, int resultCode, Intent data) { } private void loadConfiguration() { mApplicationId = mConfigurationManager.getString(PREF_APPLICATION_ID, ""); mControlDeviceId = mConfigurationManager.getString(PREF_CONTROL_DEVICE_ID, ""); mSidekickDeviceId = mConfigurationManager.getString(PREF_SIDEKICK_DEVICE_ID, ""); mEnabled = isNotEmpty(mApplicationId) && (isNotEmpty(mControlDeviceId) || isNotEmpty(mSidekickDeviceId)); startArtikManagers(); } private void startArtikManagers() { if (!mEnabled) { return; } mArtikOAuthManager = ArtikOAuthManager.newInstance(mFeatureManager.getForegroundActivity(), mApplicationId); } }
jreyes/mirror
app/src/main/java/com/vaporwarecorp/mirror/feature/artik/ArtikManagerImpl.java
Java
apache-2.0
7,495
package com.vaadin.book.applications; import com.vaadin.Application; import com.vaadin.data.Property; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.ui.*; import com.vaadin.ui.UriFragmentUtility.FragmentChangedEvent; import com.vaadin.ui.UriFragmentUtility.FragmentChangedListener; // BEGIN-EXAMPLE: advanced.urifragmentutility.uriexample public class UriFragmentApplication extends Application { private static final long serialVersionUID = -128617724108192945L; @Override public void init() { Window main = new Window("URI Fragment Example"); setMainWindow(main); setTheme("book-examples"); // Create the URI fragment utility final UriFragmentUtility urifu = new UriFragmentUtility(); main.addComponent(urifu); // Application state menu final ListSelect menu = new ListSelect("Select a URI Fragment"); menu.addItem("mercury"); menu.addItem("venus"); menu.addItem("earth"); menu.addItem("mars"); menu.setRows(4); menu.setNullSelectionAllowed(false); menu.setImmediate(true); main.addComponent(menu); // Set the URI Fragment when menu selection changes menu.addListener(new Property.ValueChangeListener() { private static final long serialVersionUID = 6380648224897936536L; public void valueChange(ValueChangeEvent event) { String itemid = (String) event.getProperty().getValue(); urifu.setFragment(itemid); } }); // When the URI fragment is given, use it to set menu selection urifu.addListener(new FragmentChangedListener() { private static final long serialVersionUID = -6588416218607827834L; public void fragmentChanged(FragmentChangedEvent source) { String fragment = source.getUriFragmentUtility().getFragment(); if (fragment != null) menu.setValue(fragment); } }); } } // END-EXAMPLE: advanced.urifragmentutility.uriexample
BillHan/book-examples-v6
src/main/java/com/vaadin/book/applications/UriFragmentApplication.java
Java
apache-2.0
2,141
package resource import ( "fmt" "net/url" "strings" "github.com/rs/rest-layer/schema" ) // Index is an interface defining a type able to bind and retrieve resources // from a resource graph. type Index interface { // Bind a new resource at the "name" endpoint Bind(name string, s schema.Schema, h Storer, c Conf) *Resource // GetResource retrives a given resource by it's path. // For instance if a resource user has a sub-resource posts, // a users.posts path can be use to retrieve the posts resource. // // If a parent is given and the path starts with a dot, the lookup is started at the // parent's location instead of root's. GetResource(path string, parent *Resource) (*Resource, bool) // GetResources returns first level resources GetResources() []*Resource } // index is the root of the resource graph type index struct { resources subResources } // NewIndex creates a new resource index func NewIndex() Index { return &index{ resources: subResources{}, } } // Bind a resource at the specified endpoint name func (r *index) Bind(name string, s schema.Schema, h Storer, c Conf) *Resource { assertNotBound(name, r.resources, nil) sr := new(name, s, h, c) r.resources.add(sr) return sr } // Compile the resource graph and report any error func (r *index) Compile() error { return compileResourceGraph(r.resources) } // GetResource retrives a given resource by it's path. // For instance if a resource user has a sub-resource posts, // a users.posts path can be use to retrieve the posts resource. // // If a parent is given and the path starts with a dot, the lookup is started at the // parent's location instead of root's. func (r *index) GetResource(path string, parent *Resource) (*Resource, bool) { resources := r.resources if len(path) > 0 && path[0] == '.' { if parent == nil { // If field starts with a dot and no parent is given, fail the lookup return nil, false } path = path[1:] resources = parent.resources } var sr *Resource if strings.IndexByte(path, '.') == -1 { if sr = resources.get(path); sr != nil { resources = sr.resources } else { return nil, false } } else { for _, comp := range strings.Split(path, ".") { if sr = resources.get(comp); sr != nil { resources = sr.resources } else { return nil, false } } } return sr, true } // GetResources returns first level resources func (r *index) GetResources() []*Resource { return r.resources } func compileResourceGraph(resources subResources) error { for _, r := range resources { if err := r.Compile(); err != nil { sep := "." if err.Error()[0] == ':' { sep = "" } return fmt.Errorf("%s%s%s", r.name, sep, err) } } return nil } // assertNotBound asserts a given resource name is not already bound func assertNotBound(name string, resources subResources, aliases map[string]url.Values) { for _, r := range resources { if r.name == name { logPanicf(nil, "Cannot bind `%s': already bound as resource'", name) } } if _, found := aliases[name]; found { logPanicf(nil, "Cannot bind `%s': already bound as alias'", name) } }
elmgone/coligui
vendor/github.com/rs/rest-layer/resource/index.go
GO
apache-2.0
3,120
from django.test import TestCase from django.utils.timezone import utc from datetime import datetime import json import logging import mock from dbkeeper.models import Organization, Team, Setting from piservice.models import PiStation, PiEvent import scoreboard.views as target def _mocked_utcNow(): return datetime(2001, 1, 1, 0, 0, 0).replace(tzinfo=utc) class ScoreboardStatusDockTestCase(TestCase): def _setUpStations(self): self.launchStation = PiStation.objects.create( station_type = PiStation.LAUNCH_STATION_TYPE, serial_num = self._serialNum ) self._serialNum += 1 self.dockStation = PiStation.objects.create( station_type = PiStation.DOCK_STATION_TYPE, serial_num = self._serialNum ) self._serialNum += 1 self.secureStation = PiStation.objects.create( station_type = PiStation.SECURE_STATION_TYPE, serial_num = self._serialNum ) self._serialNum += 1 self.returnStation = PiStation.objects.create( station_type = PiStation.RETURN_STATION_TYPE, serial_num = self._serialNum ) self._serialNum += 1 self.station = self.dockStation def _setUpTeams(self): org = Organization.objects.create( name = "School 1", type = Organization.SCHOOL_TYPE ) self.team1Name = "Team 1" self.team1 = Team.objects.create( name = self.team1Name, organization = org ) def _setUpEvents(self): # Some tests don't need these events. If not needed for a particular # test, use PiEvent.objects.all().delete() e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 0, 0).replace(tzinfo=utc), type = PiEvent.EVENT_STARTED_MSG_TYPE ) def _verify(self, expectedScore, expectedDuration_s): actual = target._recomputeTeamScore(self.team1Name) actualScore = actual['dock_score'] actualDuration_s = actual['dock_duration_s'] self.assertEqual(expectedScore, actualScore) self.assertEqual(expectedDuration_s, actualDuration_s) def setUp(self): PiEvent._meta.get_field("time").auto_now_add = False self._serialNum = 1 self._setUpStations() self._setUpTeams() self._setUpEvents() self._watchingTime_s = 45.0 Setting.objects.create(name = 'DNF_TIME_PENALTY_FACTOR', value = str(2.0)) Setting.objects.create(name = 'DOCK_SIM_PLAYBACK_TIME_S', value = str(self._watchingTime_s)) def test_recomputeDockScore_noEvents(self): PiEvent.objects.all().delete() expectedScore = 0 expectedDuration_s = 0 self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_noEventStartedEvent(self, side_effect=_mocked_utcNow): PiEvent.objects.all().delete() e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": 0, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) expectedScore = 0 expectedDuration_s = 0 self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_eventsBeforeEventStartedEvent(self, side_effect=_mocked_utcNow): PiEvent.objects.all().delete() e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, pi = self.station, team = self.team1, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": 0, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 59).replace(tzinfo=utc), type = PiEvent.EVENT_STARTED_MSG_TYPE ) expectedScore = 0 expectedDuration_s = 0 self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_noStartChallengeEvents(self, side_effect=_mocked_utcNow): e = PiEvent.objects.create( time = datetime(2001, 1, 1, 0, 0, 0).replace(tzinfo=utc), type = PiEvent.REGISTER_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS ) expectedScore = 0 expectedDuration_s = 0 self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventSameTimestampNoSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2001, 1, 1, 0, 0, 0).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 0 self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampNoSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 10 self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampSuccessNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 100 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampSuccessWithConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 68 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.EVENT_CONCLUDED_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampFailOutcomeDnf2xPenaltyNoConclude(self, mock_utcNow): dnfPenalty = 2.0 Setting.objects.all().delete() Setting.objects.create(name = 'DNF_TIME_PENALTY_FACTOR', value = str(dnfPenalty)) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 213 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_DNF"}, separators=(',',':')) ) expectedScore = 1 expectedDuration_s = 10 - self._watchingTime_s + (actualTime_s * dnfPenalty) self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampFailOutcomeDnf3xPenaltyNoConclude(self, mock_utcNow): dnfPenalty = 3.0 Setting.objects.all().delete() Setting.objects.create(name = 'DNF_TIME_PENALTY_FACTOR', value = str(dnfPenalty)) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 47 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_DNF"}, separators=(',',':')) ) expectedScore = 1 expectedDuration_s = 10 - self._watchingTime_s + (actualTime_s * dnfPenalty) self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampFailOutcomeDnf8xPenaltyNoConclude(self, mock_utcNow): dnfPenalty = 8.0 Setting.objects.all().delete() Setting.objects.create(name = 'DNF_TIME_PENALTY_FACTOR', value = str(dnfPenalty)) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 33 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_DNF"}, separators=(',',':')) ) expectedScore = 1 expectedDuration_s = 10 - self._watchingTime_s + (actualTime_s * dnfPenalty) self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampFailNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 1684 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) expectedScore = 1 expectedDuration_s = 10 - self._watchingTime_s + actualTime_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampFailWithConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 2000 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.EVENT_CONCLUDED_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 8 - self._watchingTime_s + actualTime_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampSuccessNoSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 3000 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 57).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 319 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 57).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 4897 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime1_s # ignore actualTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampSuccessSuccess(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 3213 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 57).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 228 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime1_s # ignore acutalTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampFailNoSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 283 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 14 - self._watchingTime_s + actualTime_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampFailSuccessNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 9385 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 332 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampFailSuccessWithConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 123 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 456 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.EVENT_CONCLUDED_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampFailFailNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 345 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 678 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 14 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampFailFailWithConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 4567 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 678 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.EVENT_CONCLUDED_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 12 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_threeStartChallengeEventsEarlierTimestampFailFailNoSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 567 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 890 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 14 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_threeStartChallengeEventsEarlierTimestampFailFailSuccessNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 678 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 789 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 7654 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) expectedScore = 9 expectedDuration_s = 10 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_threeStartChallengeEventsEarlierTimestampFailFailSuccessWithConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 321 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 654 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 987 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.EVENT_CONCLUDED_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 9 expectedDuration_s = 10 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_threeStartChallengeEventsEarlierTimestampFailFailFailNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 37 # this is less than 45 sec, so watchingTime will be used instead e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 54 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 76 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) expectedScore = 5 expectedDuration_s = 10 - self._watchingTime_s + self._watchingTime_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_threeStartChallengeEventsEarlierTimestampFailFailFailWithConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 23 # use watchTime_s instead since this is less than 45 sec e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 45 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 67 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.EVENT_CONCLUDED_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 5 expectedDuration_s = 10 - self._watchingTime_s + self._watchingTime_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_fourStartChallengeEventsEarlierTimestampFailFailFailNoSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 123 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 45 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 6789 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 57).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 5 expectedDuration_s = 10 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_fourStartChallengeEventsEarlierTimestampFailFailFailFailNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 122 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 233 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 344 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 57).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime4_s = 455 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime4_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) expectedScore = 5 expectedDuration_s = 10 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s # ignore actualTime4_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_fourStartChallengeEventsEarlierTimestampFailFailFailSuccessNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 1223 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 2334 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 3445 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 57).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime4_s = 4556 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime4_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) expectedScore = 5 expectedDuration_s = 10 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s # ignore actualTime4_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventLaterTimestamp(self, mock_utcNow): pass # Don't worry about later timestamps #TODO - Remaining items... # # Scoreboard # [x] 1. absent/present Registered indicator # [x] 2. make title larger and change to "Leaderboard" # [x] 3. fill width 100% # [x] 4. make 30 teams fit on the same page with roughly 20-30 chars # [x] 5. header row multiple lines--all text doesn't show up # [x] 6. don't need to show page footer; find another place for the attribution # [ ] 7. put "Harris Design Challenge 2016" along the left-hand side # [x] 8. ranking # [x] 11. remove team logo if not implementing this time # [ ] 12. Page has two jquery <script> tags--one looks WRONG_ARGUMENTS # # # Enhancements # [ ] 9. Change color (darker) for the ones that are zero (not started) # [ ] 10. Set color brighter to stand out for the ones that are done
brata-hsdc/brata.masterserver
workspace/ms/scoreboard/tests/test_dock.py
Python
apache-2.0
49,951
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var stylus = require('stylus'); var nib = require('nib'); var passport = require('passport'); var HttpStrategy = require('passport-http'); var LocalStrategy = require('passport-local').Strategy; var expressSession = require('express-session'); var md5 = require('md5'); var sql = require('mssql') var flash = require('connect-flash'); var routes = require('./routes/index'); var templates = require('./routes/templates'); var publicApisRoutes = require('./routes/publicApis'); var authedApisRoutes = require('./routes/authedApis'); var app = express(); var db = require('mongoskin').db('mongodb://192.168.0.56/TestDB', { native_parser: true }) // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); //-------------------------------------------------------------------------------------------------------------- app.use(expressSession({ secret: 'mySecretKey' })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); function compile(str, path) { return stylus(str) .set('filename', path) .use(nib()); } app.use(stylus.middleware({ src: __dirname + '/public/', compile: compile })); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'bower_components'))); var sqlconfig = { user: 'Nodejs', password: 'Nodejs', server: 'frosh', database: 'UM', } app.use(function (req, res, next) { req.db = db req.sqlconfig = sqlconfig; next(); }); passport.serializeUser(function (user, done) { done(null, user.UserId); }); passport.deserializeUser(function (id, done) { var sqlconnection = new sql.Connection(sqlconfig, function (err) { var request = new sql.Request(sqlconnection); request.query('SELECT TOP 1 * FROM dbo.Users WHERE UserId = ' + id, function (err, recordset) { if (recordset) return done(err, recordset[0]); }); }); }); passport.use('local', new LocalStrategy({ passReqToCallback: true }, function (req, username, password, done) { var sqlconnection = new sql.Connection(sqlconfig, function (err) { var request = new sql.Request(sqlconnection); request.query('SELECT TOP 1 * FROM dbo.Users WHERE UserId = ' + username, function (err, recordset) { if (recordset.length == 1) { var userRec = recordset[0]; var hashPass = md5(password); if (userRec.PasswordText.toLowerCase() == hashPass.toLowerCase()) { //success var request2 = new sql.Request(sqlconnection); request2.input('ID', sql.NVarChar(50), username) request2.execute('dbo.spTest', function (err, records) { req.session.user = recordset[0]; req.session.employee = records[0][0]; return done(null, recordset[0]); }) } else return done(null, false, req.flash('loginMessage', 'کلمه عبور صحیح نیست.')); } else return done(err, false, req.flash('loginMessage', 'کد پرسنلی صحیح نیست یا در مرکز سعیدآباد مشغول نیست.')); }); }); })); //-------------------------------------------------------------------------------------------------------------- app.use('/tmpl', templates); app.use('/papi', publicApisRoutes); app.use('/api', authedApisRoutes(passport)); app.all('/*', routes(passport)); passport.authenticate('local', function (req, res, next) { }) // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
Hamcker/PersonalExit
app.js
JavaScript
apache-2.0
4,622
/* * Copyright (C) 2016 Google Inc. * * 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.googlecode.android_scripting.future; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * FutureResult represents an eventual execution result for asynchronous operations. * * @author Damon Kohler (damonkohler@gmail.com) */ public class FutureResult<T> implements Future<T> { private final CountDownLatch mLatch = new CountDownLatch(1); private volatile T mResult = null; public void set(T result) { mResult = result; mLatch.countDown(); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public T get() throws InterruptedException { mLatch.await(); return mResult; } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException { mLatch.await(timeout, unit); return mResult; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return mResult != null; } }
kuri65536/sl4a
android/Utils/src/com/googlecode/android_scripting/future/FutureResult.java
Java
apache-2.0
1,701
package com.datalint.open.server.io; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import com.datalint.open.shared.general.ILineReader; public class LineReader implements ILineReader { private final BufferedReader reader; public LineReader(Reader reader) { this.reader = new BufferedReader(reader); } public LineReader(InputStream inputStream) { this(new InputStreamReader(inputStream)); } @Override public String readLine() throws IOException { return reader.readLine(); } @Override public void close() throws IOException { reader.close(); } }
datalint/open
Open/src/main/java/com/datalint/open/server/io/LineReader.java
Java
apache-2.0
669
<?php declare(strict_types=1); /* * +----------------------------------------------------------------------+ * | ThinkSNS Plus | * +----------------------------------------------------------------------+ * | Copyright (c) 2016-Present ZhiYiChuangXiang Technology Co., Ltd. | * +----------------------------------------------------------------------+ * | This source file is subject to enterprise private license, that is | * | bundled with this package in the file LICENSE, and is available | * | through the world-wide-web at the following url: | * | https://github.com/slimkit/plus/blob/master/LICENSE | * +----------------------------------------------------------------------+ * | Author: Slim Kit Group <master@zhiyicx.com> | * | Homepage: www.thinksns.com | * +----------------------------------------------------------------------+ */ namespace Zhiyi\Plus\Http\Controllers\APIs\V2; use Illuminate\Http\Request; use Illuminate\Support\Arr; use Zhiyi\Plus\Models\WalletCharge as WalletChargeModel; use Zhiyi\Plus\Services\Wallet\Charge as ChargeService; use function Zhiyi\Plus\setting; class PingPlusPlusChargeWebHooks { public function webhook(Request $request, ChargeService $chargeService) { if ($request->json('type') !== 'charge.succeeded') { return response('不是支持的事件', 422); } $settings = setting('wallet', 'ping++', []); $signature = $request->headers->get('x-pingplusplus-signature'); $pingPlusPlusPublicCertificate = $settings['public_key'] ?? null; $signed = openssl_verify($request->getContent(), base64_decode($signature), $pingPlusPlusPublicCertificate, OPENSSL_ALGO_SHA256); if (! $signed) { return response('加密验证失败', 422); } $pingPlusPlusCharge = $request->json('data.object'); $charge = WalletChargeModel::find($chargeService->unformatChargeId($pingPlusPlusCharge['order_no'])); if (! $charge) { return response('凭据不存在', 404); } elseif ($charge->status === 1) { return response('订单已提前完成'); } $user = $charge->user; $charge->status = 1; $charge->transaction_no = $pingPlusPlusCharge['transaction_no']; $charge->account = $this->resolveChargeAccount($pingPlusPlusCharge, $charge->account); $user->getConnection()->transaction(function () use ($user, $charge) { $user->wallet()->increment('balance', $charge->amount); $charge->save(); }); return response('通知成功'); } /** * 解决付款订单来源. * * @param array $charge * @param string|null $default * @return string|null * @author Seven Du <shiweidu@outlook.com> */ protected function resolveChargeAccount($charge, $default = null) { $channel = Arr::get($charge, 'channel'); // 支付宝渠道 if (in_array($channel, ['alipay', 'alipay_wap', 'alipay_pc_direct', 'alipay_qr'])) { return Arr::get($charge, 'extra.buyer_account', $default); // 支付宝付款账号 // 微信渠道 } elseif (in_array($channel, ['wx', 'wx_pub', 'wx_pub_qr', 'wx_wap', 'wx_lite'])) { return Arr::get($charge, 'extra.open_id', $default); // 用户唯一 open_id } return $default; } }
slimkit/thinksns-plus
app/Http/Controllers/APIs/V2/PingPlusPlusChargeWebHooks.php
PHP
apache-2.0
3,568
<!DOCTYPE html> <html> <head> <title>Ferramenta X</title> </head> <body> <?php require("template.php"); ?> <div class="container" align="center"> <h2>Login</h2> <p>Realize o login para acessar a plataforma NERD POWER</p><br> <form name="form1" action="proc/proc_login.php" method="POST" id="IdForm1"> <div class="col-md-4 col-md-offset-4"> <label for="usr">E-mail:</label> <input type="text" class="form-control" id="IdEmail" name="NEmail" required placeholder="Digite seu email..." /> </div> <br><br><br><br> <div class="col-md-4 col-md-offset-4"> <label for="pwd">Senha:</label> <input type="password" class="form-control" id="IdSenha" name="NSenha" required placeholder="Sua senha..." /> </div> <br><br><br><br> <div class="col-md-4 col-md-offset-4"> <button type="submit" class="btn btn-primary" name="Enviar">Login</button> </div> </form> </div> <br /> </body> </html>
IsaacR2/FerramentaX
login.php
PHP
apache-2.0
957
// Copyright 2020 the Exposure Notifications Verification Server 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 issueapi import ( "context" "crypto" "fmt" "net/http" "strings" "time" "github.com/google/exposure-notifications-server/pkg/logging" enobs "github.com/google/exposure-notifications-server/pkg/observability" "github.com/google/exposure-notifications-verification-server/pkg/api" "github.com/google/exposure-notifications-verification-server/pkg/database" "github.com/google/exposure-notifications-verification-server/pkg/signatures" "github.com/google/exposure-notifications-verification-server/pkg/sms" ) // scrubbers is a list of known Twilio error messages that contain the send to phone number. var scrubbers = []struct { prefix string suffix string }{ { prefix: "phone number: ", suffix: ", ", }, { prefix: "'To' number ", suffix: " is not", }, } // ScrubPhoneNumbers checks for phone numbers in known Twilio error strings that contains // user phone numbers. func ScrubPhoneNumbers(s string) string { noScrubs := s for _, scrub := range scrubbers { pi := strings.Index(noScrubs, scrub.prefix) si := strings.Index(noScrubs, scrub.suffix) // if prefix is in the string and suffix is in the sting after the prefix if pi >= 0 && si > pi+len(scrub.prefix) { noScrubs = strings.Join([]string{ noScrubs[0 : pi+len(scrub.prefix)], noScrubs[si:], }, "REDACTED") } } return noScrubs } // SendSMS sends the sms mesage with the given provider and wraps any seen errors into the IssueResult func (c *Controller) SendSMS(ctx context.Context, realm *database.Realm, smsProvider sms.Provider, signer crypto.Signer, keyID string, request *api.IssueCodeRequest, result *IssueResult) { if request.Phone == "" { return } if err := c.doSend(ctx, realm, smsProvider, signer, keyID, request, result); err != nil { result.HTTPCode = http.StatusBadRequest if sms.IsSMSQueueFull(err) { result.ErrorReturn = api.Errorf("failed to send sms: queue is full: %s", err).WithCode(api.ErrSMSQueueFull) } else { result.ErrorReturn = api.Errorf("failed to send sms: %s", err).WithCode(api.ErrSMSFailure) } } } // BuildSMS builds and signs (if configured) the SMS message. It returns the // complete and compiled message. func (c *Controller) BuildSMS(ctx context.Context, realm *database.Realm, signer crypto.Signer, keyID string, request *api.IssueCodeRequest, vercode *database.VerificationCode) (string, error) { now := time.Now() logger := logging.FromContext(ctx).Named("issueapi.BuildSMS") redirectDomain := c.config.IssueConfig().ENExpressRedirectDomain message, err := realm.BuildSMSText(vercode.Code, vercode.LongCode, redirectDomain, request.SMSTemplateLabel) if err != nil { logger.Errorw("failed to build sms text for realm", "template", request.SMSTemplateLabel, "error", err) return "", fmt.Errorf("failed to build sms message: %w", err) } // A signer will only be provided if the realm has configured and enabled // SMS signing. if signer == nil { return message, nil } purpose := signatures.SMSPurposeENReport if request.TestType == api.TestTypeUserReport { purpose = signatures.SMSPurposeUserReport } message, err = signatures.SignSMS(signer, keyID, now, purpose, request.Phone, message) if err != nil { logger.Errorw("failed to sign sms", "error", err) if c.config.GetAuthenticatedSMSFailClosed() { return "", fmt.Errorf("failed to sign sms: %w", err) } } return message, nil } func (c *Controller) doSend(ctx context.Context, realm *database.Realm, smsProvider sms.Provider, signer crypto.Signer, keyID string, request *api.IssueCodeRequest, result *IssueResult) error { defer enobs.RecordLatency(ctx, time.Now(), mSMSLatencyMs, &result.obsResult) logger := logging.FromContext(ctx).Named("issueapi.sendSMS") // Build the message message, err := c.BuildSMS(ctx, realm, signer, keyID, request, result.VerCode) if err != nil { logger.Errorw("failed to build sms", "error", err) result.obsResult = enobs.ResultError("FAILED_TO_BUILD_SMS") return err } // Send the message if err := smsProvider.SendSMS(ctx, request.Phone, message); err != nil { // Delete the user report record. if result.VerCode.UserReportID != nil { // No audit record since this is a recall of an action that can't happen inside the transaction. if err := c.db.DeleteUserReport(request.Phone, database.NullActor); err != nil { logger.Errorw("failed to delete the user report record", "error", err) } } // Delete the verification code. if err := realm.DeleteVerificationCode(c.db, result.VerCode.ID); err != nil { logger.Errorw("failed to delete verification code", "error", err) // fallthrough to the error } logger.Infow("failed to send sms", "error", ScrubPhoneNumbers(err.Error())) result.obsResult = enobs.ResultError("FAILED_TO_SEND_SMS") return err } return nil }
google/exposure-notifications-verification-server
pkg/controller/issueapi/send_sms.go
GO
apache-2.0
5,453
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.InputListItem. sap.ui.define(['jquery.sap.global', './ListItemBase', './library'], function(jQuery, ListItemBase, library) { "use strict"; /** * Constructor for a new InputListItem. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * List item should be used for a label and an input field. * @extends sap.m.ListItemBase * * @author SAP SE * @version 1.38.7 * * @constructor * @public * @alias sap.m.InputListItem * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var InputListItem = ListItemBase.extend("sap.m.InputListItem", /** @lends sap.m.InputListItem.prototype */ { metadata : { library : "sap.m", properties : { /** * Label of the list item */ label : {type : "string", group : "Misc", defaultValue : null}, /** * This property specifies the label text directionality with enumerated options. By default, the label inherits text direction from the DOM. * @since 1.30.0 */ labelTextDirection : {type : "sap.ui.core.TextDirection", group : "Appearance", defaultValue : sap.ui.core.TextDirection.Inherit} }, defaultAggregation : "content", aggregations : { /** * Content controls can be added */ content : {type : "sap.ui.core.Control", multiple : true, singularName : "content", bindable : "bindable"} }, designtime : true }}); return InputListItem; }, /* bExport= */ true);
SuicidePreventionSquad/SeniorProject
resources/sap/m/InputListItem-dbg.js
JavaScript
apache-2.0
1,780
/** * Created by Janeluo on 2016/8/13 0013. */ package com.janeluo.jfinalplus;
yangyining/JFinal-plus
src/main/java/com/janeluo/jfinalplus/package-info.java
Java
apache-2.0
80
package com.likya.tlossw.utils; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import org.apache.commons.collections.iterators.ArrayIterator; import org.apache.log4j.Logger; import com.likya.tlos.model.xmlbeans.data.JobListDocument.JobList; import com.likya.tlos.model.xmlbeans.data.JobPropertiesDocument.JobProperties; import com.likya.tlos.model.xmlbeans.data.ScenarioDocument.Scenario; import com.likya.tlos.model.xmlbeans.data.TlosProcessDataDocument.TlosProcessData; import com.likya.tlos.model.xmlbeans.state.LiveStateInfoDocument.LiveStateInfo; import com.likya.tlos.model.xmlbeans.state.StateNameDocument.StateName; import com.likya.tlos.model.xmlbeans.state.StatusNameDocument.StatusName; import com.likya.tlos.model.xmlbeans.state.SubstateNameDocument.SubstateName; import com.likya.tlossw.TlosSpaceWide; import com.likya.tlossw.core.cpc.CpcBase; import com.likya.tlossw.core.cpc.model.SpcInfoType; import com.likya.tlossw.core.spc.Spc; import com.likya.tlossw.core.spc.helpers.JobQueueOperations; import com.likya.tlossw.core.spc.model.JobRuntimeProperties; import com.likya.tlossw.exceptions.TlosFatalException; import com.likya.tlossw.model.SpcLookupTable; import com.likya.tlossw.model.engine.EngineeConstants; import com.likya.tlossw.model.path.BasePathType; import com.likya.tlossw.model.path.TlosSWPathType; import com.likya.tlossw.utils.validation.XMLValidations; public class CpcUtils { public static Scenario getScenario(TlosProcessData tlosProcessData) { Scenario scenario = Scenario.Factory.newInstance(); scenario.setJobList(tlosProcessData.getJobList()); scenario.setScenarioArray(tlosProcessData.getScenarioArray()); scenario.setBaseScenarioInfos(tlosProcessData.getBaseScenarioInfos()); scenario.setDependencyList(tlosProcessData.getDependencyList()); scenario.setScenarioStatusList(tlosProcessData.getScenarioStatusList()); scenario.setAlarmPreference(tlosProcessData.getAlarmPreference()); scenario.setManagement(tlosProcessData.getManagement()); scenario.setAdvancedScenarioInfos(tlosProcessData.getAdvancedScenarioInfos()); scenario.setLocalParameters(tlosProcessData.getLocalParameters()); return scenario; } public static Scenario getScenario(TlosProcessData tlosProcessData, String runId) { Scenario scenario = CpcUtils.getScenario(tlosProcessData); scenario.getManagement().getConcurrencyManagement().setRunningId(runId); return scenario; } // public static Scenario getScenarioOrj(TlosProcessData tlosProcessData, String planId) { // // Scenario scenario = Scenario.Factory.newInstance(); // scenario.setJobList(tlosProcessData.getJobList()); // // scenario.setScenarioArray(tlosProcessData.getScenarioArray()); // // tlosProcessData.getConcurrencyManagement().setPlanId(planId); // // scenario.setBaseScenarioInfos(tlosProcessData.getBaseScenarioInfos()); // scenario.setDependencyList(tlosProcessData.getDependencyList()); // scenario.setScenarioStatusList(tlosProcessData.getScenarioStatusList()); // scenario.setAlarmPreference(tlosProcessData.getAlarmPreference()); // scenario.setTimeManagement(tlosProcessData.getTimeManagement()); // scenario.setAdvancedScenarioInfos(tlosProcessData.getAdvancedScenarioInfos()); // scenario.setConcurrencyManagement(tlosProcessData.getConcurrencyManagement()); // scenario.setLocalParameters(tlosProcessData.getLocalParameters()); // // return scenario; // } public static Scenario getScenario(Spc spc) { Scenario scenario = Scenario.Factory.newInstance(); scenario.setBaseScenarioInfos(spc.getBaseScenarioInfos()); scenario.setDependencyList(spc.getDependencyList()); scenario.setScenarioStatusList(spc.getScenarioStatusList()); scenario.setAlarmPreference(spc.getAlarmPreference()); scenario.setManagement(spc.getManagement()); scenario.setAdvancedScenarioInfos(spc.getAdvancedScenarioInfos()); scenario.setLocalParameters(spc.getLocalParameters()); return scenario; } public static Scenario getScenario(Scenario tmpScenario) { Scenario scenario = Scenario.Factory.newInstance(); scenario.setBaseScenarioInfos(tmpScenario.getBaseScenarioInfos()); scenario.setDependencyList(tmpScenario.getDependencyList()); scenario.setScenarioStatusList(tmpScenario.getScenarioStatusList()); scenario.setAlarmPreference(tmpScenario.getAlarmPreference()); scenario.setManagement(tmpScenario.getManagement()); scenario.setAdvancedScenarioInfos(tmpScenario.getAdvancedScenarioInfos()); scenario.setLocalParameters(tmpScenario.getLocalParameters()); return scenario; } public static SpcInfoType getSpcInfo(Spc spc, String userId, String runId, Scenario tmpScenario) { LiveStateInfo myLiveStateInfo = LiveStateInfo.Factory.newInstance(); myLiveStateInfo.setStateName(StateName.PENDING); myLiveStateInfo.setSubstateName(SubstateName.IDLED); myLiveStateInfo.setStatusName(StatusName.BYTIME); spc.setLiveStateInfo(myLiveStateInfo); Thread thread = new Thread(spc); spc.setExecuterThread(thread); spc.setJsName(tmpScenario.getBaseScenarioInfos().getJsName()); spc.setConcurrent(tmpScenario.getManagement().getConcurrencyManagement().getConcurrent()); spc.setComment(tmpScenario.getBaseScenarioInfos().getComment()); spc.setUserId(userId); tmpScenario.getManagement().getConcurrencyManagement().setRunningId(runId); spc.setBaseScenarioInfos(tmpScenario.getBaseScenarioInfos()); spc.setDependencyList(tmpScenario.getDependencyList()); spc.setScenarioStatusList(tmpScenario.getScenarioStatusList()); spc.setAlarmPreference(tmpScenario.getAlarmPreference()); spc.setManagement(tmpScenario.getManagement()); spc.setAdvancedScenarioInfos(tmpScenario.getAdvancedScenarioInfos()); spc.setLocalParameters(tmpScenario.getLocalParameters()); SpcInfoType spcInfoType = new SpcInfoType(); spcInfoType.setJsName(spc.getBaseScenarioInfos().getJsName()); spcInfoType.setConcurrent(spc.getManagement().getConcurrencyManagement().getConcurrent()); spcInfoType.setComment(spc.getBaseScenarioInfos().getComment()); spcInfoType.setUserId(userId); Scenario scenario = CpcUtils.getScenario(spc); spcInfoType.setScenario(scenario); spcInfoType.setSpcReferance(spc); return spcInfoType; } public static SpcInfoType getSpcInfo(String userId, String runId, Scenario tmpScenario) { SpcInfoType spcInfoType = new SpcInfoType(); spcInfoType.setJsName(tmpScenario.getBaseScenarioInfos().getJsName()); spcInfoType.setConcurrent(tmpScenario.getManagement().getConcurrencyManagement().getConcurrent()); spcInfoType.setComment(tmpScenario.getBaseScenarioInfos().getComment()); spcInfoType.setUserId(userId); Scenario scenario = CpcUtils.getScenario(tmpScenario); spcInfoType.setScenario(scenario); spcInfoType.setSpcReferance(null); return spcInfoType; } public static ArrayList<JobRuntimeProperties> transformJobList(JobList jobList, Logger myLogger) { myLogger.debug("start:transformJobList"); ArrayList<JobRuntimeProperties> transformTable = new ArrayList<JobRuntimeProperties>(); ArrayIterator jobListIterator = new ArrayIterator(jobList.getJobPropertiesArray()); while (jobListIterator.hasNext()) { JobProperties jobProperties = (JobProperties) (jobListIterator.next()); JobRuntimeProperties jobRuntimeProperties = new JobRuntimeProperties(); /* IDLED state i ekle */ LiveStateInfoUtils.insertNewLiveStateInfo(jobProperties, StateName.INT_PENDING, SubstateName.INT_IDLED, StatusName.INT_BYTIME); jobRuntimeProperties.setJobProperties(jobProperties); // TODO infoBusInfo Manager i bilgilendir. transformTable.add(jobRuntimeProperties); } myLogger.debug("end:transformJobList"); return transformTable; } public static boolean validateJobList(JobList jobList, Logger myLogger) { XMLValidations.validateWithCode(jobList, myLogger); return true; } public static SpcInfoType prepareScenario(String runId, TlosSWPathType tlosSWPathType, Scenario myScenario, Logger myLogger) throws TlosFatalException { myLogger.info(""); myLogger.info(" > Senaryo ismi : " + tlosSWPathType.getFullPath()); JobList jobList = myScenario.getJobList(); if (!validateJobList(jobList, myLogger)) { // TODO WAITING e nasil alacagiz? myLogger.info(" > is listesi validasyonunda problem oldugundan WAITING e alinarak problemin giderilmesi beklenmektedir."); myLogger.error("Cpc Scenario jobs validation failed, process state changed to WAITING !"); return null; // 08.07.2013 Serkan // throw new TlosException("Cpc Job List validation failed, process state changed to WAITING !"); } if (jobList.getJobPropertiesArray().length == 0 && myScenario.getScenarioArray().length == 0) { myLogger.error(tlosSWPathType.getFullPath() + " isimli senaryo bilgileri yüklenemedi ya da iş listesi bos geldi !"); myLogger.error(tlosSWPathType.getFullPath() + " isimli senaryo için spc başlatılmıyor !"); return null; } SpcInfoType spcInfoType = null; // TODO Henüz ayarlanmadı ! String userId = null; if (jobList.getJobPropertiesArray().length == 0) { spcInfoType = CpcUtils.getSpcInfo(userId, runId, myScenario); spcInfoType.setSpcId(tlosSWPathType); } else { Spc spc = new Spc(tlosSWPathType.getRunId(), tlosSWPathType.getAbsolutePath(), TlosSpaceWide.getSpaceWideRegistry(), transformJobList(jobList, myLogger)); spcInfoType = CpcUtils.getSpcInfo(spc, userId, runId, myScenario); spcInfoType.setSpcId(tlosSWPathType); if (!TlosSpaceWide.getSpaceWideRegistry().getServerConfig().getServerParams().getIsPersistent().getUse() || !JobQueueOperations.recoverJobQueue(spcInfoType.getSpcReferance().getSpcAbsolutePath(), spc.getJobQueue(), spc.getJobQueueIndex())) { if (!spc.initScenarioInfo()) { myLogger.warn(tlosSWPathType.getFullPath() + " isimli senaryo bilgileri yüklenemedi ya da iş listesi boş geldi !"); Logger.getLogger(CpcBase.class).warn(" WARNING : " + tlosSWPathType.getFullPath() + " isimli senaryo bilgileri yüklenemedi ya da iş listesi boş geldi !"); System.exit(-1); } } } return spcInfoType; } public static String getRunId(TlosProcessData tlosProcessData, boolean isTest, Logger myLogger) { String runId = null; if (isTest) { String userId = "" + tlosProcessData.getBaseScenarioInfos().getUserId(); if (userId == null || userId.equals("")) { userId = "" + Calendar.getInstance().getTimeInMillis(); } myLogger.info(" > InstanceID = " + userId + " olarak belirlenmistir."); runId = userId; } else { runId = tlosProcessData.getRunId(); if (runId == null) { runId = "" + Calendar.getInstance().getTimeInMillis(); } myLogger.info(" > InstanceID = " + runId + " olarak belirlenmiştir."); } return runId; } public static void startSpc(TlosSWPathType tlosSWPathType, Logger myLogger) { SpcLookupTable spcLookupTable = TlosSpaceWide.getSpaceWideRegistry().getRunLookupTable().get(tlosSWPathType.getRunId()).getSpcLookupTable(); HashMap<String, SpcInfoType> table = spcLookupTable.getTable(); SpcInfoType spcInfoType = table.get(tlosSWPathType.getFullPath()); startSpc(spcInfoType, myLogger); } public static void startSpc(SpcInfoType spcInfoType, Logger myLogger) { /** * Bu thread daha once calistirildi mi? Degilse thread i * baslatabiliriz !! **/ Spc mySpc = spcInfoType.getSpcReferance(); if (spcInfoType.isVirgin() && !mySpc.getExecuterThread().isAlive()) { spcInfoType.setVirgin(false); /* Artik baslattik */ /** Statuleri set edelim **/ mySpc.getLiveStateInfo().setStateName(StateName.RUNNING); mySpc.getLiveStateInfo().setSubstateName(SubstateName.STAGE_IN); myLogger.info(" > Senaryo " + mySpc.getSpcFullPath() + " aktive edildi !"); mySpc.getExecuterThread().setName(mySpc.getCommonName()); /** Senaryonun thread lerle calistirildigi yer !! **/ mySpc.getExecuterThread().start(); myLogger.info(" > OK"); } } public static String getRootScenarioPath(String runId) { return getInstancePath(runId) + "." + EngineeConstants.LONELY_JOBS; } public static String getInstancePath(String runId) { return BasePathType.getRootPath() + "." + runId; } }
likyateknoloji/TlosSWGroup
TlosSW_V1.0/src/com/likya/tlossw/utils/CpcUtils.java
Java
apache-2.0
12,211
package org.ovirt.engine.core.common.businessentities; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.Size; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.INotifyPropertyChanged; /** * Quota business entity which reflects the <code>Quota</code> limitations for storage pool. <BR/> * The limitation are separated to two different types * <ul> * <li>General Limitation - Indicates the general limitation of the quota cross all the storage pool</li> * <li>Specific Limitation - Indicates specific limitation of the quota for specific storage or vds group</li> * </ul> * <BR/> * Quota entity encapsulate the specific limitations of the storage pool with lists, general limitations are configured * in the field members.<BR/> * <BR/> * Take in notice there can not be general limitation and specific limitation on the same resource type. */ public class Quota extends IVdcQueryable implements INotifyPropertyChanged, Serializable, QuotaVdsGroupProperties, QuotaStorageProperties { /** * Automatic generated serial version ID. */ private static final long serialVersionUID = 6637198348072059199L; /** * The quota id. */ private Guid id = new Guid(); /** * The storage pool id the quota is enforced on. */ private Guid storagePoolId; /** * The storage pool name the quota is enforced on, for GUI use. */ private transient String storagePoolName; /** * The quota name. */ @Size(min = 1, max = BusinessEntitiesDefinitions.QUOTA_NAME_SIZE) private String quotaName; /** * The quota description. */ @Size(min = 1, max = BusinessEntitiesDefinitions.QUOTA_DESCRIPTION_SIZE) private String description; /** * The threshold of vds group in percentages. */ @Min(0) @Max(100) private int thresholdVdsGroupPercentage; /** * The threshold of storage in percentages. */ @Min(0) @Max(100) private int thresholdStoragePercentage; /** * The grace of vds group in percentages. */ @Min(0) @Max(100) private int graceVdsGroupPercentage; /** * The grace of storage in percentages. */ @Min(0) @Max(100) private int graceStoragePercentage; /** * The global storage limit in Giga bytes. */ @Min(-1) private Long storageSizeGB; /** * The global storage usage in Giga bytes for Quota. */ private transient Double storageSizeGBUsage; /** * The global virtual CPU limitations. */ @Min(-1) private Integer virtualCpu; /** * The global virtual CPU usage for Quota. */ private transient Integer virtualCpuUsage; /** * The global virtual memory limitations for Quota. */ @Min(-1) private Long memSizeMB; /** * The global virtual memory usage for Quota. */ private transient Long memSizeMBUsage; /** * List of all the specific VdsGroups limitations. */ private List<QuotaVdsGroup> quotaVdsGroupList; /** * List of all the specific storage limitations. */ private List<QuotaStorage> quotaStorageList; /** * Default constructor of Quota, which initialize empty lists for specific limitations, and no user assigned. */ public Quota() { setQuotaStorages(new ArrayList<QuotaStorage>()); setQuotaVdsGroups(new ArrayList<QuotaVdsGroup>()); } /** * @return the quota id. */ public Guid getId() { return id; } /** * @param id * the quota Id to set. */ public void setId(Guid id) { this.id = id; } /** * @return the thresholdVdsGroupPercentage */ public int getThresholdVdsGroupPercentage() { return thresholdVdsGroupPercentage; } /** * @param thresholdVdsGroupPercentage * the thresholdVdsGroupPercentage to set */ public void setThresholdVdsGroupPercentage(int thresholdVdsGroupPercentage) { this.thresholdVdsGroupPercentage = thresholdVdsGroupPercentage; } /** * @return the thresholdStoragePercentage */ public int getThresholdStoragePercentage() { return thresholdStoragePercentage; } /** * @param thresholdStoragePercentage * the thresholdStoragePercentage to set */ public void setThresholdStoragePercentage(int thresholdStoragePercentage) { this.thresholdStoragePercentage = thresholdStoragePercentage; } /** * @return the graceVdsGroupPercentage */ public int getGraceVdsGroupPercentage() { return graceVdsGroupPercentage; } /** * @param graceVdsGroupPercentage * the graceVdsGroupPercentage to set */ public void setGraceVdsGroupPercentage(int graceVdsGroupPercentage) { this.graceVdsGroupPercentage = graceVdsGroupPercentage; } /** * @return the graceStoragePercentage */ public int getGraceStoragePercentage() { return graceStoragePercentage; } /** * @param graceStoragePercentage * the graceStoragePercentage to set */ public void setGraceStoragePercentage(int graceStoragePercentage) { this.graceStoragePercentage = graceStoragePercentage; } /** * @return the description */ public String getDescription() { return description; } /** * @param description * the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the quotaName */ public String getQuotaName() { return quotaName; } /** * @param quotaName * the quotaName to set */ public void setQuotaName(String quotaName) { this.quotaName = quotaName; } /** * @return the storagePoolId */ public Guid getStoragePoolId() { return storagePoolId; } /** * @param storagePoolId * the storagePoolId to set */ public void setStoragePoolId(Guid storagePoolId) { this.storagePoolId = storagePoolId; } /** * @return the storagePoolName */ public String getStoragePoolName() { return storagePoolName; } /** * @param storagePoolName * the storagePoolName to set */ public void setStoragePoolName(String storagePoolName) { this.storagePoolName = storagePoolName; } /** * @return the quotaStorageList */ public List<QuotaStorage> getQuotaStorages() { return quotaStorageList; } /** * @param quotaStorages * the quotaStorages to set */ public void setQuotaStorages(List<QuotaStorage> quotaStorages) { this.quotaStorageList = quotaStorages; } /** * @return the quotaVdsGroups */ public List<QuotaVdsGroup> getQuotaVdsGroups() { return quotaVdsGroupList; } /** * @param quotaVdsGroups * the quotaVdsGroups to set */ public void setQuotaVdsGroups(List<QuotaVdsGroup> quotaVdsGroups) { this.quotaVdsGroupList = quotaVdsGroups; } /** * @return the memSizeMBUsage */ public Long getMemSizeMBUsage() { return memSizeMBUsage; } /** * @param memSizeMBUsage * the memSizeMBUsage to set */ public void setMemSizeMBUsage(Long memSizeMBUsage) { this.memSizeMBUsage = memSizeMBUsage; } /** * @return the memSizeMB */ public Long getMemSizeMB() { return memSizeMB; } /** * @param memSizeMB * the memSizeMB to set */ public void setMemSizeMB(Long memSizeMB) { this.memSizeMB = memSizeMB; } /** * @return the virtualCpuUsage */ public Integer getVirtualCpuUsage() { return virtualCpuUsage; } /** * @param virtualCpuUsage * the virtualCpuUsage to set */ public void setVirtualCpuUsage(Integer virtualCpuUsage) { this.virtualCpuUsage = virtualCpuUsage; } /** * @return the virtualCpu */ public Integer getVirtualCpu() { return virtualCpu; } /** * @param virtualCpu * the virtualCpu to set */ public void setVirtualCpu(Integer virtualCpu) { this.virtualCpu = virtualCpu; } /** * @return the storageSizeGBUsage */ public Double getStorageSizeGBUsage() { return storageSizeGBUsage; } /** * @param storageSizeGBUsage * the storageSizeGBUsage to set */ public void setStorageSizeGBUsage(Double storageSizeGBUsage) { this.storageSizeGBUsage = storageSizeGBUsage; } /** * @return the storageSizeGB */ public Long getStorageSizeGB() { return storageSizeGB; } /** * @param storageSizeGB * the storageSizeGB to set */ public void setStorageSizeGB(Long storageSizeGB) { this.storageSizeGB = storageSizeGB; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + graceStoragePercentage; result = prime * result + graceVdsGroupPercentage; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((quotaName == null) ? 0 : quotaName.hashCode()); result = prime * result + ((quotaStorageList == null) ? 0 : quotaStorageList.hashCode()); result = prime * result + ((quotaVdsGroupList == null) ? 0 : quotaVdsGroupList.hashCode()); result = prime * result + ((storageSizeGB == null) ? 0 : storageSizeGB.hashCode()); result = prime * result + ((storagePoolId == null) ? 0 : storagePoolId.hashCode()); result = prime * result + thresholdStoragePercentage; result = prime * result + thresholdVdsGroupPercentage; result = prime * result + ((virtualCpu == null) ? 0 : virtualCpu.hashCode()); result = prime * result + ((memSizeMB == null) ? 0 : memSizeMB.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Quota other = (Quota) obj; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (graceStoragePercentage != other.graceStoragePercentage) return false; if (graceVdsGroupPercentage != other.graceVdsGroupPercentage) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (quotaName == null) { if (other.quotaName != null) return false; } else if (!quotaName.equals(other.quotaName)) return false; if (quotaStorageList == null) { if (other.quotaStorageList != null) return false; } else if (!quotaStorageList.equals(other.quotaStorageList)) return false; if (quotaVdsGroupList == null) { if (other.quotaVdsGroupList != null) return false; } else if (!quotaVdsGroupList.equals(other.quotaVdsGroupList)) return false; if (storageSizeGB == null) { if (other.storageSizeGB != null) return false; } else if (!storageSizeGB.equals(other.storageSizeGB)) return false; if (storagePoolId == null) { if (other.storagePoolId != null) return false; } else if (!storagePoolId.equals(other.storagePoolId)) return false; if (thresholdStoragePercentage != other.thresholdStoragePercentage) return false; if (thresholdVdsGroupPercentage != other.thresholdVdsGroupPercentage) return false; if (virtualCpu == null) { if (other.virtualCpu != null) return false; } else if (!virtualCpu.equals(other.virtualCpu)) return false; if (memSizeMB == null) { if (other.memSizeMB != null) return false; } else if (!memSizeMB.equals(other.memSizeMB)) return false; return true; } }
raksha-rao/gluster-ovirt
backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/businessentities/Quota.java
Java
apache-2.0
12,992
/** * 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.pulsar.broker.resources; import com.fasterxml.jackson.core.type.TypeReference; import java.util.Map; import java.util.Optional; import lombok.Getter; import org.apache.pulsar.common.partition.PartitionedTopicMetadata; import org.apache.pulsar.common.policies.data.NamespaceIsolationData; import org.apache.pulsar.common.policies.data.Policies; import org.apache.pulsar.common.policies.impl.NamespaceIsolationPolicies; import org.apache.pulsar.metadata.api.MetadataStoreException; import org.apache.pulsar.metadata.api.extended.MetadataStoreExtended; @Getter public class NamespaceResources extends BaseResources<Policies> { private IsolationPolicyResources isolationPolicies; private PartitionedTopicResources partitionedTopicResources; private MetadataStoreExtended configurationStore; public NamespaceResources(MetadataStoreExtended configurationStore, int operationTimeoutSec) { super(configurationStore, Policies.class, operationTimeoutSec); this.configurationStore = configurationStore; isolationPolicies = new IsolationPolicyResources(configurationStore, operationTimeoutSec); partitionedTopicResources = new PartitionedTopicResources(configurationStore, operationTimeoutSec); } public static class IsolationPolicyResources extends BaseResources<Map<String, NamespaceIsolationData>> { public IsolationPolicyResources(MetadataStoreExtended store, int operationTimeoutSec) { super(store, new TypeReference<Map<String, NamespaceIsolationData>>() { }, operationTimeoutSec); } public Optional<NamespaceIsolationPolicies> getPolicies(String path) throws MetadataStoreException { Optional<Map<String, NamespaceIsolationData>> data = super.get(path); return data.isPresent() ? Optional.of(new NamespaceIsolationPolicies(data.get())) : Optional.empty(); } } public static class PartitionedTopicResources extends BaseResources<PartitionedTopicMetadata> { public PartitionedTopicResources(MetadataStoreExtended configurationStore, int operationTimeoutSec) { super(configurationStore, PartitionedTopicMetadata.class, operationTimeoutSec); } } }
yahoo/pulsar
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/NamespaceResources.java
Java
apache-2.0
3,049
/* * Created on Nov 29, 2007 * * Copyright (c), 2007 Don Branson. 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.moneybender.proxy.channels.decorators; import com.moneybender.proxy.channels.IReadBytes; public class ThrottleDecorator extends ReadDelayDecorator { private final int microsecondsPerByte; public ThrottleDecorator(IReadBytes decoratedWriter, int bandwidthLimit) { super(decoratedWriter); double bytesPerSecond = bandwidthLimit * 1000; this.microsecondsPerByte = (int)((1 / bytesPerSecond) * 1000 * 1000); saveEarliestNextIO(0); } @Override protected void saveEarliestNextIO(int bytesRead) { setEarliestNextIO(System.currentTimeMillis() + ((bytesRead * microsecondsPerByte) / 1000)); } }
DonBranson/DonsProxy
src/main/com/moneybender/proxy/channels/decorators/ThrottleDecorator.java
Java
apache-2.0
1,299
/** * 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.hadoop.hbase.regionserver.wal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.SmallTests; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Test that we can create, load, setup our own custom codec */ @Category(SmallTests.class) public class TestCustomWALCellCodec { public static class CustomWALCellCodec extends WALCellCodec { public Configuration conf; public CompressionContext context; public CustomWALCellCodec(Configuration conf, CompressionContext compression) { super(conf, compression); this.conf = conf; this.context = compression; } } /** * Test that a custom {@link WALCellCodec} will be completely setup when it is instantiated via * {@link WALCellCodec} * @throws Exception on failure */ @Test public void testCreatePreparesCodec() throws Exception { Configuration conf = new Configuration(false); conf.setClass(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, CustomWALCellCodec.class, WALCellCodec.class); CustomWALCellCodec codec = (CustomWALCellCodec) WALCellCodec.create(conf, null, null); assertEquals("Custom codec didn't get initialized with the right configuration!", conf, codec.conf); assertEquals("Custom codec didn't get initialized with the right compression context!", null, codec.context); } }
Jackygq1982/hbase_src
hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/wal/TestCustomWALCellCodec.java
Java
apache-2.0
2,335
# frozen_string_literal: true # Copyright 2015 Australian National Botanic Gardens # # This file is part of the NSL Editor. # # 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. # require "test_helper" require "models/reference/update/if_changed/test_helper" # Single Reference model test. class ForAnUnchangedRefVolumeTest < ActiveSupport::TestCase test "unchanged volume" do test_reference_text_field_lack_of_change_is_detected("volume") end end
bio-org-au/nsl-editor
test/models/reference/update/if_changed/for_an_unchanged_volume_test.rb
Ruby
apache-2.0
968
<?php echo e(Form::open(['url' => route('lotes.store'), 'class'=>'form-horizontal', 'role'=>"form"])); ?> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title">Criar Lote</h4> </div> <div class="modal-body"> <div class="form-group"> <label for="inputDescricao" class="col-sm-2 control-label">Nome:</label> <div class="col-sm-10"> <input type="text" name="descricao" id="inputDescricao" class="form-control" value="" required="required" tabindex="1" autofocus> </div> </div> <div class="form-group"> <label for="inputDataPCP" class="col-sm-2 control-label">PCP:</label> <div class="col-sm-4"> <input type="date" name="dataprev_pcp" id="inputDataPCP" class="form-control" value="<?php echo e(date('Y-m-d')); ?>" tabindex="2" required="required"> </div> <label for="inputDataPintura" class="col-sm-2 control-label">Pintura:</label> <div class="col-sm-4"> <input type="date" name="dataprev_pintura" id="inputDataPintura" class="form-control" value="" tabindex="6"> </div> </div> <div class="form-group"> <label for="inputDataPreparacao" class="col-sm-2 control-label">Preparacao:</label> <div class="col-sm-4"> <input type="date" name="dataprev_preparacao" id="inputDataPreparacao" class="form-control" value="" tabindex="3"> </div> <label for="inputDataExpedicao" class="col-sm-2 control-label">Expedição:</label> <div class="col-sm-4"> <input type="date" name="dataprev_expedicao" id="inputDataExpedicao" class="form-control" value="" tabindex="7"> </div> </div> <div class="form-group"> <label for="inputDataGabarito" class="col-sm-2 control-label">Gabarito:</label> <div class="col-sm-4"> <input type="date" name="dataprev_gabarito" id="inputDataGabarito" class="form-control" value="" tabindex="4"> </div> <label for="inputDataMontagem" class="col-sm-2 control-label">Montagem:</label> <div class="col-sm-4"> <input type="date" name="dataprev_montagem" id="inputDataMontagem" class="form-control" value="" tabindex="8"> </div> </div> <div class="form-group"> <label for="inputDataSolda" class="col-sm-2 control-label">Solda:</label> <div class="col-sm-4"> <input type="date" name="dataprev_solda" id="inputDataSolda" class="form-control" value="" tabindex="5"> </div> <label for="inputDataEntregaFinal" class="col-sm-2 control-label">Entrega Final:</label> <div class="col-sm-4"> <input type="date" name="dataprev_entrega" id="inputDataEntregaFinal" class="form-control" value="null" tabindex="9"> </div> </div> <!-- HIDDEN IDs --> <input type="hidden" name="obra_id" value="<?php echo e($obra_id); ?>"> <input type="hidden" name="etapa_id" value="<?php echo e($etapa_id); ?>"> <input type="hidden" name="grouped" value="<?php echo e($grouped); ?>"> <?php foreach($handles_ids as $handle_id): ?> <input type="hidden" name="handles_ids[]" id="inputHandleIds" class="form-control" value="<?php echo e($handle_id); ?>"> <?php endforeach; ?> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button> <button type="submit" class="btn btn-primary">Salvar</button> </div> <?php echo e(Form::close()); ?>
System3D/gestor-de-lotes
storage/framework/views/96fd683b3799ea6bb61223346be7d37255bde268.php
PHP
apache-2.0
3,354
// Copyright 2010-2014, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package org.mozc.android.inputmethod.japanese.testing; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCandidates.CandidateWord; import org.mozc.android.inputmethod.japanese.ui.CandidateLayout; import org.mozc.android.inputmethod.japanese.ui.CandidateLayout.Row; import org.mozc.android.inputmethod.japanese.ui.CandidateLayout.Span; import com.google.common.base.Optional; import org.easymock.EasyMockSupport; import org.easymock.IMockBuilder; import java.util.Collections; import java.util.List; /** * Methods commonly used for MechaMozc's testing. * */ public class MozcLayoutUtil { // Disallow instantiation. private MozcLayoutUtil() { } public static Row createRow(int top, int height, int width, Span... spans) { Row result = new Row(); result.setTop(top); result.setHeight(height); result.setWidth(width); for (Span span : spans) { result.addSpan(span); } return result; } public static Span createSpan(int id, int left, int right) { Span span = new Span( Optional.of(CandidateWord.newBuilder().setId(id).build()), 0, 0, Collections.<String>emptyList()); span.setLeft(left); span.setRight(right); return span; } public static Span createEmptySpan() { return new Span( Optional.of(CandidateWord.getDefaultInstance()), 0, 0, Collections.<String>emptyList()); } public static CandidateLayout createCandidateLayoutMock(EasyMockSupport easyMockSupport) { return createCandidateLayoutMockBuilder(easyMockSupport).createMock(); } public static CandidateLayout createNiceCandidateLayoutMock(EasyMockSupport easyMockSupport) { return createCandidateLayoutMockBuilder(easyMockSupport).createNiceMock(); } public static IMockBuilder<CandidateLayout> createCandidateLayoutMockBuilder( EasyMockSupport easyMockSupport) { return easyMockSupport.createMockBuilder(CandidateLayout.class) .withConstructor(List.class, float.class, float.class) .withArgs(Collections.emptyList(), 0f, 0f); } }
kishikawakatsumi/Mozc-for-iOS
src/android/tests/src/com/google/android/inputmethod/japanese/testing/MozcLayoutUtil.java
Java
apache-2.0
3,609
/* * Copyright 2021 ThoughtWorks, Inc. * * 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.thoughtworks.go.spark; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import static java.lang.String.valueOf; public abstract class HtmlErrorPage { public static String errorPage(int code, String message) { return Holder.INSTANCE.replaceAll(buildRegex("status_code"), valueOf(code)) .replaceAll(buildRegex("error_message"), message); } private static String buildRegex(final String value) { return "\\{\\{" + value + "\\}\\}"; } private static class Holder { private static final String INSTANCE = fileContents(); private static String fileContents() { try (InputStream in = Holder.class.getResourceAsStream("/error.html")) { return IOUtils.toString(in, StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } } }
marques-work/gocd
spark/spark-base/src/main/java/com/thoughtworks/go/spark/HtmlErrorPage.java
Java
apache-2.0
1,606
<?php /** * THE CODE IN THIS FILE WAS GENERATED FROM THE EBAY WSDL USING THE PROJECT: * * https://github.com/davidtsadler/ebay-api-sdk-php * * Copyright 2014 David T. Sadler * * 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. */ namespace DTS\eBaySDK\Trading\Types; /** * * @property boolean $BestOfferEnabled * @property boolean $AutoPayEnabled * @property boolean $B2BVATEnabled * @property boolean $CatalogEnabled * @property string $CategoryID * @property integer $CategoryLevel * @property string $CategoryName * @property string[] $CategoryParentID * @property string[] $CategoryParentName * @property boolean $Expired * @property boolean $IntlAutosFixedCat * @property boolean $LeafCategory * @property boolean $Virtual * @property boolean $ORPA * @property boolean $ORRA * @property boolean $LSD */ class CategoryType extends \DTS\eBaySDK\Types\BaseType { /** * @var array Properties belonging to objects of this class. */ private static $propertyTypes = array( 'BestOfferEnabled' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'BestOfferEnabled' ), 'AutoPayEnabled' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'AutoPayEnabled' ), 'B2BVATEnabled' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'B2BVATEnabled' ), 'CatalogEnabled' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'CatalogEnabled' ), 'CategoryID' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'CategoryID' ), 'CategoryLevel' => array( 'type' => 'integer', 'unbound' => false, 'attribute' => false, 'elementName' => 'CategoryLevel' ), 'CategoryName' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'CategoryName' ), 'CategoryParentID' => array( 'type' => 'string', 'unbound' => true, 'attribute' => false, 'elementName' => 'CategoryParentID' ), 'CategoryParentName' => array( 'type' => 'string', 'unbound' => true, 'attribute' => false, 'elementName' => 'CategoryParentName' ), 'Expired' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'Expired' ), 'IntlAutosFixedCat' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'IntlAutosFixedCat' ), 'LeafCategory' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'LeafCategory' ), 'Virtual' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'Virtual' ), 'ORPA' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'ORPA' ), 'ORRA' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'ORRA' ), 'LSD' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'LSD' ) ); /** * @param array $values Optional properties and values to assign to the object. */ public function __construct(array $values = array()) { list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values); parent::__construct($parentValues); if (!array_key_exists(__CLASS__, self::$properties)) { self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes); } if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) { self::$xmlNamespaces[__CLASS__] = 'urn:ebay:apis:eBLBaseComponents'; } $this->setValues(__CLASS__, $childValues); } }
emullaraj/ebay-sdk-php
src/DTS/eBaySDK/Trading/Types/CategoryType.php
PHP
apache-2.0
5,200
export interface CommentJson { body: string; color?: string; size?: number; duration?: number; easing?: string; } export interface StampJson { path?: string; url?: string; duration?: number; easing?: string; } export interface Setting { key: string; value: string; } export interface Stamp { id: number; label: string; path: string; contentType: string; }
chimerast/niconico-speenya
messages/index.ts
TypeScript
apache-2.0
389
/* * Copyright 2012 - 2015 Manuel Laggner * * 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.tinymediamanager.core.movie; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import org.jdesktop.observablecollections.ObservableCollections; import org.tinymediamanager.core.AbstractModelObject; import org.tinymediamanager.core.movie.connector.MovieConnectors; import org.tinymediamanager.scraper.CountryCode; import org.tinymediamanager.scraper.MediaArtwork.FanartSizes; import org.tinymediamanager.scraper.MediaArtwork.PosterSizes; import org.tinymediamanager.scraper.MediaLanguages; /** * The Class MovieSettings. */ @XmlRootElement(name = "MovieSettings") public class MovieSettings extends AbstractModelObject { private final static String PATH = "path"; private final static String FILENAME = "filename"; private final static String MOVIE_DATA_SOURCE = "movieDataSource"; private final static String IMAGE_POSTER_SIZE = "imagePosterSize"; private final static String IMAGE_FANART_SIZE = "imageFanartSize"; private final static String IMAGE_EXTRATHUMBS = "imageExtraThumbs"; private final static String IMAGE_EXTRATHUMBS_RESIZE = "imageExtraThumbsResize"; private final static String IMAGE_EXTRATHUMBS_SIZE = "imageExtraThumbsSize"; private final static String IMAGE_EXTRATHUMBS_COUNT = "imageExtraThumbsCount"; private final static String IMAGE_EXTRAFANART = "imageExtraFanart"; private final static String IMAGE_EXTRAFANART_COUNT = "imageExtraFanartCount"; private final static String ENABLE_MOVIESET_ARTWORK_MOVIE_FOLDER = "enableMovieSetArtworkMovieFolder"; private final static String ENABLE_MOVIESET_ARTWORK_FOLDER = "enableMovieSetArtworkFolder"; private final static String MOVIESET_ARTWORK_FOLDER = "movieSetArtworkFolder"; private final static String MOVIE_CONNECTOR = "movieConnector"; private final static String MOVIE_NFO_FILENAME = "movieNfoFilename"; private final static String MOVIE_POSTER_FILENAME = "moviePosterFilename"; private final static String MOVIE_FANART_FILENAME = "movieFanartFilename"; private final static String MOVIE_RENAMER_PATHNAME = "movieRenamerPathname"; private final static String MOVIE_RENAMER_FILENAME = "movieRenamerFilename"; private final static String MOVIE_RENAMER_SPACE_SUBSTITUTION = "movieRenamerSpaceSubstitution"; private final static String MOVIE_RENAMER_SPACE_REPLACEMENT = "movieRenamerSpaceReplacement"; private final static String MOVIE_RENAMER_NFO_CLEANUP = "movieRenamerNfoCleanup"; private final static String MOVIE_RENAMER_MOVIESET_SINGLE_MOVIE = "movieRenamerMoviesetSingleMovie"; private final static String MOVIE_SCRAPER = "movieScraper"; private final static String SCRAPE_BEST_IMAGE = "scrapeBestImage"; private final static String IMAGE_SCRAPER_TMDB = "imageScraperTmdb"; private final static String IMAGE_SCRAPER_FANART_TV = "imageScraperFanartTv"; private final static String TRAILER_SCRAPER_TMDB = "trailerScraperTmdb"; private final static String TRAILER_SCRAPER_HD_TRAILERS = "trailerScraperHdTrailers"; private final static String TRAILER_SCRAPER_OFDB = "trailerScraperOfdb"; private final static String WRITE_ACTOR_IMAGES = "writeActorImages"; private final static String IMDB_SCRAPE_FOREIGN_LANGU = "imdbScrapeForeignLanguage"; private final static String SCRAPER_LANGU = "scraperLanguage"; private final static String CERTIFICATION_COUNTRY = "certificationCountry"; private final static String SCRAPER_THRESHOLD = "scraperThreshold"; private final static String DETECT_MOVIE_MULTI_DIR = "detectMovieMultiDir"; private final static String BUILD_IMAGE_CACHE_ON_IMPORT = "buildImageCacheOnImport"; private final static String BAD_WORDS = "badWords"; private final static String ENTRY = "entry"; private final static String RUNTIME_FROM_MI = "runtimeFromMediaInfo"; private final static String ASCII_REPLACEMENT = "asciiReplacement"; private final static String YEAR_COLUMN_VISIBLE = "yearColumnVisible"; private final static String NFO_COLUMN_VISIBLE = "nfoColumnVisible"; private final static String IMAGE_COLUMN_VISIBLE = "imageColumnVisible"; private final static String TRAILER_COLUMN_VISIBLE = "trailerColumnVisible"; private final static String SUBTITLE_COLUMN_VISIBLE = "subtitleColumnVisible"; private final static String WATCHED_COLUMN_VISIBLE = "watchedColumnVisible"; private final static String SCRAPER_FALLBACK = "scraperFallback"; @XmlElementWrapper(name = MOVIE_DATA_SOURCE) @XmlElement(name = PATH) private final List<String> movieDataSources = ObservableCollections.observableList(new ArrayList<String>()); @XmlElementWrapper(name = MOVIE_NFO_FILENAME) @XmlElement(name = FILENAME) private final List<MovieNfoNaming> movieNfoFilenames = new ArrayList<MovieNfoNaming>(); @XmlElementWrapper(name = MOVIE_POSTER_FILENAME) @XmlElement(name = FILENAME) private final List<MoviePosterNaming> moviePosterFilenames = new ArrayList<MoviePosterNaming>(); @XmlElementWrapper(name = MOVIE_FANART_FILENAME) @XmlElement(name = FILENAME) private final List<MovieFanartNaming> movieFanartFilenames = new ArrayList<MovieFanartNaming>(); @XmlElementWrapper(name = BAD_WORDS) @XmlElement(name = ENTRY) private final List<String> badWords = ObservableCollections.observableList(new ArrayList<String>()); private MovieConnectors movieConnector = MovieConnectors.XBMC; private String movieRenamerPathname = "$T ($Y)"; private String movieRenamerFilename = "$T ($Y) $V $A"; private boolean movieRenamerSpaceSubstitution = false; private String movieRenamerSpaceReplacement = "_"; private boolean movieRenamerNfoCleanup = false; private boolean imdbScrapeForeignLanguage = false; private MovieScrapers movieScraper = MovieScrapers.TMDB; private PosterSizes imagePosterSize = PosterSizes.BIG; private boolean imageScraperTmdb = true; private boolean imageScraperFanartTv = true; private FanartSizes imageFanartSize = FanartSizes.LARGE; private boolean imageExtraThumbs = false; private boolean imageExtraThumbsResize = true; private int imageExtraThumbsSize = 300; private int imageExtraThumbsCount = 5; private boolean imageExtraFanart = false; private int imageExtraFanartCount = 5; private boolean enableMovieSetArtworkMovieFolder = true; private boolean enableMovieSetArtworkFolder = false; private String movieSetArtworkFolder = "MoviesetArtwork"; private boolean scrapeBestImage = true; private boolean imageLanguagePriority = true; private boolean imageLogo = false; private boolean imageBanner = false; private boolean imageClearart = false; private boolean imageDiscart = false; private boolean imageThumb = false; private boolean trailerScraperTmdb = true; private boolean trailerScraperHdTrailers = true; private boolean trailerScraperOfdb = true; private boolean writeActorImages = false; private MediaLanguages scraperLanguage = MediaLanguages.en; private CountryCode certificationCountry = CountryCode.US; private double scraperThreshold = 0.75; private boolean detectMovieMultiDir = false; private boolean buildImageCacheOnImport = false; private boolean movieRenamerCreateMoviesetForSingleMovie = false; private boolean runtimeFromMediaInfo = false; private boolean asciiReplacement = false; private boolean yearColumnVisible = true; private boolean ratingColumnVisible = true; private boolean nfoColumnVisible = true; private boolean imageColumnVisible = true; private boolean trailerColumnVisible = true; private boolean subtitleColumnVisible = true; private boolean watchedColumnVisible = true; private boolean scraperFallback = false; private boolean useTrailerPreference = false; private MovieTrailerQuality trailerQuality = MovieTrailerQuality.HD_720; private MovieTrailerSources trailerSource = MovieTrailerSources.YOUTUBE; private boolean syncTrakt = false; public MovieSettings() { } public void addMovieDataSources(String path) { if (!movieDataSources.contains(path)) { movieDataSources.add(path); firePropertyChange(MOVIE_DATA_SOURCE, null, movieDataSources); } } public void removeMovieDataSources(String path) { MovieList movieList = MovieList.getInstance(); movieList.removeDatasource(path); movieDataSources.remove(path); firePropertyChange(MOVIE_DATA_SOURCE, null, movieDataSources); } public List<String> getMovieDataSource() { return movieDataSources; } public void addMovieNfoFilename(MovieNfoNaming filename) { if (!movieNfoFilenames.contains(filename)) { movieNfoFilenames.add(filename); firePropertyChange(MOVIE_NFO_FILENAME, null, movieNfoFilenames); } } public void removeMovieNfoFilename(MovieNfoNaming filename) { if (movieNfoFilenames.contains(filename)) { movieNfoFilenames.remove(filename); firePropertyChange(MOVIE_NFO_FILENAME, null, movieNfoFilenames); } } public void clearMovieNfoFilenames() { movieNfoFilenames.clear(); firePropertyChange(MOVIE_NFO_FILENAME, null, movieNfoFilenames); } public List<MovieNfoNaming> getMovieNfoFilenames() { return new ArrayList<MovieNfoNaming>(this.movieNfoFilenames); } public void addMoviePosterFilename(MoviePosterNaming filename) { if (!moviePosterFilenames.contains(filename)) { moviePosterFilenames.add(filename); firePropertyChange(MOVIE_POSTER_FILENAME, null, moviePosterFilenames); } } public void removeMoviePosterFilename(MoviePosterNaming filename) { if (moviePosterFilenames.contains(filename)) { moviePosterFilenames.remove(filename); firePropertyChange(MOVIE_POSTER_FILENAME, null, moviePosterFilenames); } } public void clearMoviePosterFilenames() { moviePosterFilenames.clear(); firePropertyChange(MOVIE_POSTER_FILENAME, null, moviePosterFilenames); } public List<MoviePosterNaming> getMoviePosterFilenames() { return new ArrayList<MoviePosterNaming>(this.moviePosterFilenames); } public void addMovieFanartFilename(MovieFanartNaming filename) { if (!movieFanartFilenames.contains(filename)) { movieFanartFilenames.add(filename); firePropertyChange(MOVIE_FANART_FILENAME, null, movieFanartFilenames); } } public void removeMovieFanartFilename(MovieFanartNaming filename) { if (movieFanartFilenames.contains(filename)) { movieFanartFilenames.remove(filename); firePropertyChange(MOVIE_FANART_FILENAME, null, movieFanartFilenames); } } public void clearMovieFanartFilenames() { movieFanartFilenames.clear(); firePropertyChange(MOVIE_FANART_FILENAME, null, movieFanartFilenames); } public List<MovieFanartNaming> getMovieFanartFilenames() { return new ArrayList<MovieFanartNaming>(this.movieFanartFilenames); } @XmlElement(name = IMAGE_POSTER_SIZE) public PosterSizes getImagePosterSize() { return imagePosterSize; } public void setImagePosterSize(PosterSizes newValue) { PosterSizes oldValue = this.imagePosterSize; this.imagePosterSize = newValue; firePropertyChange(IMAGE_POSTER_SIZE, oldValue, newValue); } @XmlElement(name = IMAGE_FANART_SIZE) public FanartSizes getImageFanartSize() { return imageFanartSize; } public void setImageFanartSize(FanartSizes newValue) { FanartSizes oldValue = this.imageFanartSize; this.imageFanartSize = newValue; firePropertyChange(IMAGE_FANART_SIZE, oldValue, newValue); } public boolean isImageExtraThumbs() { return imageExtraThumbs; } public boolean isImageExtraThumbsResize() { return imageExtraThumbsResize; } public int getImageExtraThumbsSize() { return imageExtraThumbsSize; } public void setImageExtraThumbsResize(boolean newValue) { boolean oldValue = this.imageExtraThumbsResize; this.imageExtraThumbsResize = newValue; firePropertyChange(IMAGE_EXTRATHUMBS_RESIZE, oldValue, newValue); } public void setImageExtraThumbsSize(int newValue) { int oldValue = this.imageExtraThumbsSize; this.imageExtraThumbsSize = newValue; firePropertyChange(IMAGE_EXTRATHUMBS_SIZE, oldValue, newValue); } public int getImageExtraThumbsCount() { return imageExtraThumbsCount; } public void setImageExtraThumbsCount(int newValue) { int oldValue = this.imageExtraThumbsCount; this.imageExtraThumbsCount = newValue; firePropertyChange(IMAGE_EXTRATHUMBS_COUNT, oldValue, newValue); } public int getImageExtraFanartCount() { return imageExtraFanartCount; } public void setImageExtraFanartCount(int newValue) { int oldValue = this.imageExtraFanartCount; this.imageExtraFanartCount = newValue; firePropertyChange(IMAGE_EXTRAFANART_COUNT, oldValue, newValue); } public boolean isImageExtraFanart() { return imageExtraFanart; } public void setImageExtraThumbs(boolean newValue) { boolean oldValue = this.imageExtraThumbs; this.imageExtraThumbs = newValue; firePropertyChange(IMAGE_EXTRATHUMBS, oldValue, newValue); } public void setImageExtraFanart(boolean newValue) { boolean oldValue = this.imageExtraFanart; this.imageExtraFanart = newValue; firePropertyChange(IMAGE_EXTRAFANART, oldValue, newValue); } public boolean isEnableMovieSetArtworkMovieFolder() { return enableMovieSetArtworkMovieFolder; } public void setEnableMovieSetArtworkMovieFolder(boolean newValue) { boolean oldValue = this.enableMovieSetArtworkMovieFolder; this.enableMovieSetArtworkMovieFolder = newValue; firePropertyChange(ENABLE_MOVIESET_ARTWORK_MOVIE_FOLDER, oldValue, newValue); } public boolean isEnableMovieSetArtworkFolder() { return enableMovieSetArtworkFolder; } public void setEnableMovieSetArtworkFolder(boolean newValue) { boolean oldValue = this.enableMovieSetArtworkFolder; this.enableMovieSetArtworkFolder = newValue; firePropertyChange(ENABLE_MOVIESET_ARTWORK_FOLDER, oldValue, newValue); } public String getMovieSetArtworkFolder() { return movieSetArtworkFolder; } public void setMovieSetArtworkFolder(String newValue) { String oldValue = this.movieSetArtworkFolder; this.movieSetArtworkFolder = newValue; firePropertyChange(MOVIESET_ARTWORK_FOLDER, oldValue, newValue); } @XmlElement(name = MOVIE_CONNECTOR) public MovieConnectors getMovieConnector() { return movieConnector; } public void setMovieConnector(MovieConnectors newValue) { MovieConnectors oldValue = this.movieConnector; this.movieConnector = newValue; firePropertyChange(MOVIE_CONNECTOR, oldValue, newValue); } @XmlElement(name = MOVIE_RENAMER_PATHNAME) public String getMovieRenamerPathname() { return movieRenamerPathname; } public void setMovieRenamerPathname(String newValue) { String oldValue = this.movieRenamerPathname; this.movieRenamerPathname = newValue; firePropertyChange(MOVIE_RENAMER_PATHNAME, oldValue, newValue); } @XmlElement(name = MOVIE_RENAMER_FILENAME) public String getMovieRenamerFilename() { return movieRenamerFilename; } public void setMovieRenamerFilename(String newValue) { String oldValue = this.movieRenamerFilename; this.movieRenamerFilename = newValue; firePropertyChange(MOVIE_RENAMER_FILENAME, oldValue, newValue); } @XmlElement(name = MOVIE_RENAMER_SPACE_SUBSTITUTION) public boolean isMovieRenamerSpaceSubstitution() { return movieRenamerSpaceSubstitution; } public void setMovieRenamerSpaceSubstitution(boolean movieRenamerSpaceSubstitution) { this.movieRenamerSpaceSubstitution = movieRenamerSpaceSubstitution; } @XmlElement(name = MOVIE_RENAMER_SPACE_REPLACEMENT) public String getMovieRenamerSpaceReplacement() { return movieRenamerSpaceReplacement; } public void setMovieRenamerSpaceReplacement(String movieRenamerSpaceReplacement) { this.movieRenamerSpaceReplacement = movieRenamerSpaceReplacement; } public MovieScrapers getMovieScraper() { if (movieScraper == null) { return MovieScrapers.TMDB; } return movieScraper; } public void setMovieScraper(MovieScrapers newValue) { MovieScrapers oldValue = this.movieScraper; this.movieScraper = newValue; firePropertyChange(MOVIE_SCRAPER, oldValue, newValue); } public boolean isImdbScrapeForeignLanguage() { return imdbScrapeForeignLanguage; } public void setImdbScrapeForeignLanguage(boolean newValue) { boolean oldValue = this.imdbScrapeForeignLanguage; this.imdbScrapeForeignLanguage = newValue; firePropertyChange(IMDB_SCRAPE_FOREIGN_LANGU, oldValue, newValue); } public boolean isImageScraperTmdb() { return imageScraperTmdb; } public boolean isImageScraperFanartTv() { return imageScraperFanartTv; } public void setImageScraperTmdb(boolean newValue) { boolean oldValue = this.imageScraperTmdb; this.imageScraperTmdb = newValue; firePropertyChange(IMAGE_SCRAPER_TMDB, oldValue, newValue); } public void setImageScraperFanartTv(boolean newValue) { boolean oldValue = this.imageScraperFanartTv; this.imageScraperFanartTv = newValue; firePropertyChange(IMAGE_SCRAPER_FANART_TV, oldValue, newValue); } public boolean isScrapeBestImage() { return scrapeBestImage; } public void setScrapeBestImage(boolean newValue) { boolean oldValue = this.scrapeBestImage; this.scrapeBestImage = newValue; firePropertyChange(SCRAPE_BEST_IMAGE, oldValue, newValue); } public boolean isTrailerScraperTmdb() { return trailerScraperTmdb; } public boolean isTrailerScraperHdTrailers() { return trailerScraperHdTrailers; } public void setTrailerScraperTmdb(boolean newValue) { boolean oldValue = this.trailerScraperTmdb; this.trailerScraperTmdb = newValue; firePropertyChange(TRAILER_SCRAPER_TMDB, oldValue, newValue); } public void setTrailerScraperHdTrailers(boolean newValue) { boolean oldValue = this.trailerScraperHdTrailers; this.trailerScraperHdTrailers = newValue; firePropertyChange(TRAILER_SCRAPER_HD_TRAILERS, oldValue, newValue); } public boolean isTrailerScraperOfdb() { return trailerScraperOfdb; } public void setTrailerScraperOfdb(boolean newValue) { boolean oldValue = this.trailerScraperOfdb; this.trailerScraperOfdb = newValue; firePropertyChange(TRAILER_SCRAPER_OFDB, oldValue, newValue); } public boolean isWriteActorImages() { return writeActorImages; } public void setWriteActorImages(boolean newValue) { boolean oldValue = this.writeActorImages; this.writeActorImages = newValue; firePropertyChange(WRITE_ACTOR_IMAGES, oldValue, newValue); } @XmlElement(name = SCRAPER_LANGU) public MediaLanguages getScraperLanguage() { return scraperLanguage; } public void setScraperLanguage(MediaLanguages newValue) { MediaLanguages oldValue = this.scraperLanguage; this.scraperLanguage = newValue; firePropertyChange(SCRAPER_LANGU, oldValue, newValue); } @XmlElement(name = CERTIFICATION_COUNTRY) public CountryCode getCertificationCountry() { return certificationCountry; } public void setCertificationCountry(CountryCode newValue) { CountryCode oldValue = this.certificationCountry; certificationCountry = newValue; firePropertyChange(CERTIFICATION_COUNTRY, oldValue, newValue); } @XmlElement(name = SCRAPER_THRESHOLD) public double getScraperThreshold() { return scraperThreshold; } public void setScraperThreshold(double newValue) { double oldValue = this.scraperThreshold; scraperThreshold = newValue; firePropertyChange(SCRAPER_THRESHOLD, oldValue, newValue); } @XmlElement(name = MOVIE_RENAMER_NFO_CLEANUP) public boolean isMovieRenamerNfoCleanup() { return movieRenamerNfoCleanup; } public void setMovieRenamerNfoCleanup(boolean movieRenamerNfoCleanup) { this.movieRenamerNfoCleanup = movieRenamerNfoCleanup; } /** * Should we detect (and create) movies from directories containing more than one movie? * * @return true/false */ public boolean isDetectMovieMultiDir() { return detectMovieMultiDir; } /** * Should we detect (and create) movies from directories containing more than one movie? * * @param newValue * true/false */ public void setDetectMovieMultiDir(boolean newValue) { boolean oldValue = this.detectMovieMultiDir; this.detectMovieMultiDir = newValue; firePropertyChange(DETECT_MOVIE_MULTI_DIR, oldValue, newValue); } public boolean isBuildImageCacheOnImport() { return buildImageCacheOnImport; } public void setBuildImageCacheOnImport(boolean newValue) { boolean oldValue = this.buildImageCacheOnImport; this.buildImageCacheOnImport = newValue; firePropertyChange(BUILD_IMAGE_CACHE_ON_IMPORT, oldValue, newValue); } public boolean isMovieRenamerCreateMoviesetForSingleMovie() { return movieRenamerCreateMoviesetForSingleMovie; } public void setMovieRenamerCreateMoviesetForSingleMovie(boolean newValue) { boolean oldValue = this.movieRenamerCreateMoviesetForSingleMovie; this.movieRenamerCreateMoviesetForSingleMovie = newValue; firePropertyChange(MOVIE_RENAMER_MOVIESET_SINGLE_MOVIE, oldValue, newValue); } public boolean isRuntimeFromMediaInfo() { return runtimeFromMediaInfo; } public void setRuntimeFromMediaInfo(boolean newValue) { boolean oldValue = this.runtimeFromMediaInfo; this.runtimeFromMediaInfo = newValue; firePropertyChange(RUNTIME_FROM_MI, oldValue, newValue); } public boolean isAsciiReplacement() { return asciiReplacement; } public void setAsciiReplacement(boolean newValue) { boolean oldValue = this.asciiReplacement; this.asciiReplacement = newValue; firePropertyChange(ASCII_REPLACEMENT, oldValue, newValue); } public void addBadWord(String badWord) { if (!badWords.contains(badWord.toLowerCase())) { badWords.add(badWord.toLowerCase()); firePropertyChange(BAD_WORDS, null, badWords); } } public void removeBadWord(String badWord) { badWords.remove(badWord.toLowerCase()); firePropertyChange(BAD_WORDS, null, badWords); } public List<String> getBadWords() { // convert to lowercase for easy contains checking ListIterator<String> iterator = badWords.listIterator(); while (iterator.hasNext()) { iterator.set(iterator.next().toLowerCase()); } return badWords; } public boolean isYearColumnVisible() { return yearColumnVisible; } public void setYearColumnVisible(boolean newValue) { boolean oldValue = this.yearColumnVisible; this.yearColumnVisible = newValue; firePropertyChange(YEAR_COLUMN_VISIBLE, oldValue, newValue); } public boolean isRatingColumnVisible() { return ratingColumnVisible; } public void setRatingColumnVisible(boolean newValue) { boolean oldValue = this.ratingColumnVisible; this.ratingColumnVisible = newValue; firePropertyChange("ratingColumnVisible", oldValue, newValue); } public boolean isNfoColumnVisible() { return nfoColumnVisible; } public void setNfoColumnVisible(boolean newValue) { boolean oldValue = this.nfoColumnVisible; this.nfoColumnVisible = newValue; firePropertyChange(NFO_COLUMN_VISIBLE, oldValue, newValue); } public boolean isImageColumnVisible() { return imageColumnVisible; } public void setImageColumnVisible(boolean newValue) { boolean oldValue = this.imageColumnVisible; this.imageColumnVisible = newValue; firePropertyChange(IMAGE_COLUMN_VISIBLE, oldValue, newValue); } public boolean isTrailerColumnVisible() { return trailerColumnVisible; } public void setTrailerColumnVisible(boolean newValue) { boolean oldValue = this.trailerColumnVisible; this.trailerColumnVisible = newValue; firePropertyChange(TRAILER_COLUMN_VISIBLE, oldValue, newValue); } public boolean isSubtitleColumnVisible() { return subtitleColumnVisible; } public void setSubtitleColumnVisible(boolean newValue) { boolean oldValue = this.subtitleColumnVisible; this.subtitleColumnVisible = newValue; firePropertyChange(SUBTITLE_COLUMN_VISIBLE, oldValue, newValue); } public boolean isWatchedColumnVisible() { return watchedColumnVisible; } public void setWatchedColumnVisible(boolean newValue) { boolean oldValue = this.watchedColumnVisible; this.watchedColumnVisible = newValue; firePropertyChange(WATCHED_COLUMN_VISIBLE, oldValue, newValue); } public boolean isScraperFallback() { return scraperFallback; } public void setScraperFallback(boolean newValue) { boolean oldValue = this.scraperFallback; this.scraperFallback = newValue; firePropertyChange(SCRAPER_FALLBACK, oldValue, newValue); } public boolean isImageLogo() { return imageLogo; } public boolean isImageBanner() { return imageBanner; } public boolean isImageClearart() { return imageClearart; } public boolean isImageDiscart() { return imageDiscart; } public boolean isImageThumb() { return imageThumb; } public void setImageLogo(boolean newValue) { boolean oldValue = this.imageLogo; this.imageLogo = newValue; firePropertyChange("imageLogo", oldValue, newValue); } public void setImageBanner(boolean newValue) { boolean oldValue = this.imageBanner; this.imageBanner = newValue; firePropertyChange("imageBanner", oldValue, newValue); } public void setImageClearart(boolean newValue) { boolean oldValue = this.imageClearart; this.imageClearart = newValue; firePropertyChange("imageClearart", oldValue, newValue); } public void setImageDiscart(boolean newValue) { boolean oldValue = this.imageDiscart; this.imageDiscart = newValue; firePropertyChange("imageDiscart", oldValue, newValue); } public void setImageThumb(boolean newValue) { boolean oldValue = this.imageThumb; this.imageThumb = newValue; firePropertyChange("imageThumb", oldValue, newValue); } public boolean isUseTrailerPreference() { return useTrailerPreference; } public void setUseTrailerPreference(boolean newValue) { boolean oldValue = this.useTrailerPreference; this.useTrailerPreference = newValue; firePropertyChange("useTrailerPreference", oldValue, newValue); } public MovieTrailerQuality getTrailerQuality() { return trailerQuality; } public void setTrailerQuality(MovieTrailerQuality newValue) { MovieTrailerQuality oldValue = this.trailerQuality; this.trailerQuality = newValue; firePropertyChange("trailerQuality", oldValue, newValue); } public MovieTrailerSources getTrailerSource() { return trailerSource; } public void setTrailerSource(MovieTrailerSources newValue) { MovieTrailerSources oldValue = this.trailerSource; this.trailerSource = newValue; firePropertyChange("trailerSource", oldValue, newValue); } public void setSyncTrakt(boolean newValue) { boolean oldValue = this.syncTrakt; this.syncTrakt = newValue; firePropertyChange("syncTrakt", oldValue, newValue); } public boolean getSyncTrakt() { return syncTrakt; } public boolean isImageLanguagePriority() { return imageLanguagePriority; } public void setImageLanguagePriority(boolean newValue) { boolean oldValue = this.imageLanguagePriority; this.imageLanguagePriority = newValue; firePropertyChange("imageLanguagePriority", oldValue, newValue); } }
mlaggner/tinyMediaManager
src/org/tinymediamanager/core/movie/MovieSettings.java
Java
apache-2.0
32,049
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib 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. */ 'use strict'; // MODULES // var factory = require( './factory.js' ); // MAIN // /** * Tests whether a collection contains at least `n` elements which pass a test implemented by a predicate function. * * ## Notes * * - If a predicate function calls the provided callback with a truthy error argument, the function suspends execution and immediately calls the `done` callback for subsequent error handling. * - This function does **not** guarantee that execution is asynchronous. To do so, wrap the `done` callback in a function which either executes at the end of the current stack (e.g., `nextTick`) or during a subsequent turn of the event loop (e.g., `setImmediate`, `setTimeout`). * * * @param {Collection} collection - input collection * @param {PositiveInteger} n - number of elements * @param {Options} [options] - function options * @param {*} [options.thisArg] - execution context * @param {PositiveInteger} [options.limit] - maximum number of pending invocations at any one time * @param {boolean} [options.series=false] - boolean indicating whether to wait for a previous invocation to complete before invoking a provided function for the next element in a collection * @param {Function} predicate - predicate function to invoke for each element in a collection * @param {Callback} done - function to invoke upon completion * @throws {TypeError} first argument must be a collection * @throws {TypeError} second argument must be a positive integer * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} second-to-last argument must be a function * @throws {TypeError} last argument must be a function * @returns {void} * * @example * var readFile = require( '@stdlib/fs/read-file' ); * * function done( error, bool ) { * if ( error ) { * throw error; * } * if ( bool ) { * console.log( 'Successfully read some files.' ); * } else { * console.log( 'Unable to read some files.' ); * } * } * * function predicate( file, next ) { * var opts = { * 'encoding': 'utf8' * }; * readFile( file, opts, onFile ); * * function onFile( error ) { * if ( error ) { * return next( null, false ); * } * next( null, true ); * } * } * * var files = [ * './beep.js', * './boop.js' * ]; * * someByAsync( files, 2, predicate, done ); */ function someByAsync( collection, n, options, predicate, done ) { if ( arguments.length < 5 ) { return factory( options )( collection, n, predicate ); } factory( options, predicate )( collection, n, done ); } // EXPORTS // module.exports = someByAsync;
stdlib-js/stdlib
lib/node_modules/@stdlib/utils/async/some-by/lib/some_by.js
JavaScript
apache-2.0
3,300
/* * Copyright 2014 Josselin Pujo * * 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 fr.assoba.open.sel.jetbrains; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class SelElementType extends IElementType { public SelElementType(@NotNull @NonNls String debugName) { super(debugName, SelLanguage.INSTANCE); } }
neuneu2k/SEL
JetbrainsPlugin/src/fr/assoba/open/sel/jetbrains/SelElementType.java
Java
apache-2.0
923
package com.hxtech.offer.fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hxtech.offer.R; public class CanonFragment extends BaseFragment { public static CanonFragment newInstance() { CanonFragment fragment = new CanonFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } public CanonFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_canon, container, false); } }
offerHere/offer
app/src/main/java/com/hxtech/offer/fragments/CanonFragment.java
Java
apache-2.0
877
/* Copyright (c) 2015, Google Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <CNIOBoringSSL_ssl.h> #include <assert.h> #include <limits.h> #include <stdlib.h> #include <string.h> #include <CNIOBoringSSL_bio.h> #include <CNIOBoringSSL_err.h> #include <CNIOBoringSSL_mem.h> #include "../crypto/internal.h" #include "internal.h" BSSL_NAMESPACE_BEGIN // BIO uses int instead of size_t. No lengths will exceed uint16_t, so this will // not overflow. static_assert(0xffff <= INT_MAX, "uint16_t does not fit in int"); static_assert((SSL3_ALIGN_PAYLOAD & (SSL3_ALIGN_PAYLOAD - 1)) == 0, "SSL3_ALIGN_PAYLOAD must be a power of 2"); void SSLBuffer::Clear() { if (buf_allocated_) { free(buf_); // Allocated with malloc(). } buf_ = nullptr; buf_allocated_ = false; offset_ = 0; size_ = 0; cap_ = 0; } bool SSLBuffer::EnsureCap(size_t header_len, size_t new_cap) { if (new_cap > 0xffff) { OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR); return false; } if (cap_ >= new_cap) { return true; } uint8_t *new_buf; bool new_buf_allocated; size_t new_offset; if (new_cap <= sizeof(inline_buf_)) { // This function is called twice per TLS record, first for the five-byte // header. To avoid allocating twice, use an inline buffer for short inputs. new_buf = inline_buf_; new_buf_allocated = false; new_offset = 0; } else { // Add up to |SSL3_ALIGN_PAYLOAD| - 1 bytes of slack for alignment. // // Since this buffer gets allocated quite frequently and doesn't contain any // sensitive data, we allocate with malloc rather than |OPENSSL_malloc| and // avoid zeroing on free. new_buf = (uint8_t *)malloc(new_cap + SSL3_ALIGN_PAYLOAD - 1); if (new_buf == NULL) { OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE); return false; } new_buf_allocated = true; // Offset the buffer such that the record body is aligned. new_offset = (0 - header_len - (uintptr_t)new_buf) & (SSL3_ALIGN_PAYLOAD - 1); } // Note if the both old and new buffer are inline, the source and destination // may alias. OPENSSL_memmove(new_buf + new_offset, buf_ + offset_, size_); if (buf_allocated_) { free(buf_); // Allocated with malloc(). } buf_ = new_buf; buf_allocated_ = new_buf_allocated; offset_ = new_offset; cap_ = new_cap; return true; } void SSLBuffer::DidWrite(size_t new_size) { if (new_size > cap() - size()) { abort(); } size_ += new_size; } void SSLBuffer::Consume(size_t len) { if (len > size_) { abort(); } offset_ += (uint16_t)len; size_ -= (uint16_t)len; cap_ -= (uint16_t)len; } void SSLBuffer::DiscardConsumed() { if (size_ == 0) { Clear(); } } static int dtls_read_buffer_next_packet(SSL *ssl) { SSLBuffer *buf = &ssl->s3->read_buffer; if (!buf->empty()) { // It is an error to call |dtls_read_buffer_extend| when the read buffer is // not empty. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR); return -1; } // Read a single packet from |ssl->rbio|. |buf->cap()| must fit in an int. int ret = BIO_read(ssl->rbio.get(), buf->data(), static_cast<int>(buf->cap())); if (ret <= 0) { ssl->s3->rwstate = SSL_ERROR_WANT_READ; return ret; } buf->DidWrite(static_cast<size_t>(ret)); return 1; } static int tls_read_buffer_extend_to(SSL *ssl, size_t len) { SSLBuffer *buf = &ssl->s3->read_buffer; if (len > buf->cap()) { OPENSSL_PUT_ERROR(SSL, SSL_R_BUFFER_TOO_SMALL); return -1; } // Read until the target length is reached. while (buf->size() < len) { // The amount of data to read is bounded by |buf->cap|, which must fit in an // int. int ret = BIO_read(ssl->rbio.get(), buf->data() + buf->size(), static_cast<int>(len - buf->size())); if (ret <= 0) { ssl->s3->rwstate = SSL_ERROR_WANT_READ; return ret; } buf->DidWrite(static_cast<size_t>(ret)); } return 1; } int ssl_read_buffer_extend_to(SSL *ssl, size_t len) { // |ssl_read_buffer_extend_to| implicitly discards any consumed data. ssl->s3->read_buffer.DiscardConsumed(); if (SSL_is_dtls(ssl)) { static_assert( DTLS1_RT_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH <= 0xffff, "DTLS read buffer is too large"); // The |len| parameter is ignored in DTLS. len = DTLS1_RT_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH; } if (!ssl->s3->read_buffer.EnsureCap(ssl_record_prefix_len(ssl), len)) { return -1; } if (ssl->rbio == nullptr) { OPENSSL_PUT_ERROR(SSL, SSL_R_BIO_NOT_SET); return -1; } int ret; if (SSL_is_dtls(ssl)) { // |len| is ignored for a datagram transport. ret = dtls_read_buffer_next_packet(ssl); } else { ret = tls_read_buffer_extend_to(ssl, len); } if (ret <= 0) { // If the buffer was empty originally and remained empty after attempting to // extend it, release the buffer until the next attempt. ssl->s3->read_buffer.DiscardConsumed(); } return ret; } int ssl_handle_open_record(SSL *ssl, bool *out_retry, ssl_open_record_t ret, size_t consumed, uint8_t alert) { *out_retry = false; if (ret != ssl_open_record_partial) { ssl->s3->read_buffer.Consume(consumed); } if (ret != ssl_open_record_success) { // Nothing was returned to the caller, so discard anything marked consumed. ssl->s3->read_buffer.DiscardConsumed(); } switch (ret) { case ssl_open_record_success: return 1; case ssl_open_record_partial: { int read_ret = ssl_read_buffer_extend_to(ssl, consumed); if (read_ret <= 0) { return read_ret; } *out_retry = true; return 1; } case ssl_open_record_discard: *out_retry = true; return 1; case ssl_open_record_close_notify: return 0; case ssl_open_record_error: if (alert != 0) { ssl_send_alert(ssl, SSL3_AL_FATAL, alert); } return -1; } assert(0); return -1; } static_assert(SSL3_RT_HEADER_LENGTH * 2 + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD * 2 + SSL3_RT_MAX_PLAIN_LENGTH <= 0xffff, "maximum TLS write buffer is too large"); static_assert(DTLS1_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD + SSL3_RT_MAX_PLAIN_LENGTH <= 0xffff, "maximum DTLS write buffer is too large"); static int tls_write_buffer_flush(SSL *ssl) { SSLBuffer *buf = &ssl->s3->write_buffer; while (!buf->empty()) { int ret = BIO_write(ssl->wbio.get(), buf->data(), buf->size()); if (ret <= 0) { ssl->s3->rwstate = SSL_ERROR_WANT_WRITE; return ret; } buf->Consume(static_cast<size_t>(ret)); } buf->Clear(); return 1; } static int dtls_write_buffer_flush(SSL *ssl) { SSLBuffer *buf = &ssl->s3->write_buffer; if (buf->empty()) { return 1; } int ret = BIO_write(ssl->wbio.get(), buf->data(), buf->size()); if (ret <= 0) { ssl->s3->rwstate = SSL_ERROR_WANT_WRITE; // If the write failed, drop the write buffer anyway. Datagram transports // can't write half a packet, so the caller is expected to retry from the // top. buf->Clear(); return ret; } buf->Clear(); return 1; } int ssl_write_buffer_flush(SSL *ssl) { if (ssl->wbio == nullptr) { OPENSSL_PUT_ERROR(SSL, SSL_R_BIO_NOT_SET); return -1; } if (SSL_is_dtls(ssl)) { return dtls_write_buffer_flush(ssl); } else { return tls_write_buffer_flush(ssl); } } BSSL_NAMESPACE_END
apple/swift-nio-ssl
Sources/CNIOBoringSSL/ssl/ssl_buffer.cc
C++
apache-2.0
8,307
package de.kevinschie.SimulatorListener; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import java.net.URLConnection; public class SimulationListener { ObjectInputStream ois; Socket socket; public void listenToSimulator() { try{ new Thread("Device Listener") { public void run() { try ( Socket echoSocket = new Socket("0.0.0.0", 50001); BufferedReader in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); ) { System.out.println("TEST"); String line; while ((line = in.readLine()) != null) { System.out.println("echo: " + line); } } catch(Exception ex) { ex.printStackTrace(); } }; }.start(); } catch (Exception ex) { ex.printStackTrace(); } /*try{ System.out.println("Listener läuft........."); URL oracle = new URL("http://0.0.0.0:50001/"); URLConnection yc = oracle.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } catch(Exception ex) { ex.printStackTrace(); }*/ /*try { final ServerSocket serverSocket = new ServerSocket(50001); new Thread("Device Listener") { public void run() { try ( ServerSocket serverSocket = new ServerSocket(50001); Socket clientSocket = serverSocket.accept(); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); ) { System.out.println(in.readLine()); } catch (Exception e) { e.printStackTrace(); } }; }.start(); } catch (Exception ex) { ex.printStackTrace(); }*/ } }
kevinschie/carGateway
src/de/kevinschie/SimulatorListener/SimulationListener.java
Java
apache-2.0
2,431
/* ### * IP: GHIDRA * * 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 ghidra.feature.vt.api.db; import static ghidra.feature.vt.api.db.VTMatchMarkupItemTableDBAdapter.MarkupTableDescriptor.ADDRESS_SOURCE_COL; import static ghidra.feature.vt.api.db.VTMatchMarkupItemTableDBAdapter.MarkupTableDescriptor.ASSOCIATION_KEY_COL; import static ghidra.feature.vt.api.db.VTMatchMarkupItemTableDBAdapter.MarkupTableDescriptor.DESTINATION_ADDRESS_COL; import static ghidra.feature.vt.api.db.VTMatchMarkupItemTableDBAdapter.MarkupTableDescriptor.MARKUP_TYPE_COL; import static ghidra.feature.vt.api.db.VTMatchMarkupItemTableDBAdapter.MarkupTableDescriptor.ORIGINAL_DESTINATION_VALUE_COL; import static ghidra.feature.vt.api.db.VTMatchMarkupItemTableDBAdapter.MarkupTableDescriptor.SOURCE_ADDRESS_COL; import static ghidra.feature.vt.api.db.VTMatchMarkupItemTableDBAdapter.MarkupTableDescriptor.SOURCE_VALUE_COL; import static ghidra.feature.vt.api.db.VTMatchMarkupItemTableDBAdapter.MarkupTableDescriptor.STATUS_COL; import ghidra.feature.vt.api.impl.MarkupItemStorage; import ghidra.feature.vt.api.main.VTSession; import ghidra.feature.vt.api.markuptype.VTMarkupTypeFactory; import ghidra.feature.vt.api.util.Stringable; import ghidra.program.database.map.AddressMap; import ghidra.program.model.address.Address; import ghidra.program.model.listing.Program; import ghidra.util.exception.VersionException; import ghidra.util.task.TaskMonitor; import java.io.IOException; import db.*; public class VTMatchMarkupItemTableDBAdapterV0 extends VTMatchMarkupItemTableDBAdapter { private Table table; public VTMatchMarkupItemTableDBAdapterV0(DBHandle dbHandle) throws IOException { table = dbHandle.createTable(TABLE_NAME, TABLE_SCHEMA, INDEXED_COLUMNS); } public VTMatchMarkupItemTableDBAdapterV0(DBHandle dbHandle, OpenMode openMode, TaskMonitor monitor) throws VersionException { table = dbHandle.getTable(TABLE_NAME); if (table == null) { throw new VersionException("Missing Table: " + TABLE_NAME); } else if (table.getSchema().getVersion() != 0) { throw new VersionException("Expected version 0 for table " + TABLE_NAME + " but got " + table.getSchema().getVersion()); } } @Override public DBRecord createMarkupItemRecord(MarkupItemStorage markupItem) throws IOException { DBRecord record = TABLE_SCHEMA.createRecord(table.getKey()); VTAssociationDB association = (VTAssociationDB) markupItem.getAssociation(); VTSession manager = association.getSession(); Program sourceProgram = manager.getSourceProgram(); Program destinationProgram = manager.getDestinationProgram(); record.setLongValue(ASSOCIATION_KEY_COL.column(), association.getKey()); record.setString(ADDRESS_SOURCE_COL.column(), markupItem.getDestinationAddressSource()); record.setLongValue(SOURCE_ADDRESS_COL.column(), getAddressID(sourceProgram, markupItem.getSourceAddress())); Address destinationAddress = markupItem.getDestinationAddress(); if (destinationAddress != null) { record.setLongValue(DESTINATION_ADDRESS_COL.column(), getAddressID(destinationProgram, markupItem.getDestinationAddress())); } record.setShortValue(MARKUP_TYPE_COL.column(), (short) VTMarkupTypeFactory.getID(markupItem.getMarkupType())); record.setString(SOURCE_VALUE_COL.column(), Stringable.getString( markupItem.getSourceValue(), sourceProgram)); record.setString(ORIGINAL_DESTINATION_VALUE_COL.column(), Stringable.getString( markupItem.getDestinationValue(), destinationProgram)); record.setByteValue(STATUS_COL.column(), (byte) markupItem.getStatus().ordinal()); table.putRecord(record); return record; } private long getAddressID(Program program, Address address) { AddressMap addressMap = program.getAddressMap(); return addressMap.getKey(address, false); } @Override public void removeMatchMarkupItemRecord(long key) throws IOException { table.deleteRecord(key); } @Override public RecordIterator getRecords() throws IOException { return table.iterator(); } @Override public RecordIterator getRecords(long associationKey) throws IOException { LongField longField = new LongField(associationKey); return table.indexIterator(ASSOCIATION_KEY_COL.column(), longField, longField, true); } @Override public DBRecord getRecord(long key) throws IOException { return table.getRecord(key); } @Override void updateRecord(DBRecord record) throws IOException { table.putRecord(record); } @Override public int getRecordCount() { return table.getRecordCount(); } }
NationalSecurityAgency/ghidra
Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/db/VTMatchMarkupItemTableDBAdapterV0.java
Java
apache-2.0
5,056
package liquibase.datatype.core; import liquibase.database.Database; import liquibase.database.core.DB2Database; import liquibase.database.core.DerbyDatabase; import liquibase.database.core.FirebirdDatabase; import liquibase.database.core.HsqlDatabase; import liquibase.database.core.InformixDatabase; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.MySQLDatabase; import liquibase.database.core.OracleDatabase; import liquibase.database.core.SQLiteDatabase; import liquibase.database.core.SybaseASADatabase; import liquibase.database.core.SybaseDatabase; import liquibase.datatype.DataTypeInfo; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.LiquibaseDataType; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.statement.DatabaseFunction; @DataTypeInfo(name = "boolean", aliases = {"java.sql.Types.BOOLEAN", "java.lang.Boolean", "bit"}, minParameters = 0, maxParameters = 0, priority = LiquibaseDataType.PRIORITY_DEFAULT) public class BooleanType extends LiquibaseDataType { @Override public DatabaseDataType toDatabaseDataType(Database database) { if (database instanceof DB2Database || database instanceof FirebirdDatabase) { return new DatabaseDataType("SMALLINT"); } else if (database instanceof MSSQLDatabase) { return new DatabaseDataType("BIT"); } else if (database instanceof MySQLDatabase) { if (getRawDefinition().toLowerCase().startsWith("bit")) { return new DatabaseDataType("BIT", getParameters()); } return new DatabaseDataType("BIT", 1); } else if (database instanceof OracleDatabase) { return new DatabaseDataType("NUMBER", 1); } else if (database instanceof SybaseASADatabase || database instanceof SybaseDatabase) { return new DatabaseDataType("BIT"); } else if (database instanceof DerbyDatabase) { if (((DerbyDatabase) database).supportsBooleanDataType()) { return new DatabaseDataType("BOOLEAN"); } else { return new DatabaseDataType("SMALLINT"); } } else if (database instanceof HsqlDatabase) { return new DatabaseDataType("BOOLEAN"); } return super.toDatabaseDataType(database); } @Override public String objectToSql(Object value, Database database) { if (value == null || value.toString().equalsIgnoreCase("null")) { return null; } String returnValue; if (value instanceof String) { if (((String) value).equalsIgnoreCase("true") || value.equals("1") || value.equals("t") || ((String) value).equalsIgnoreCase(this.getTrueBooleanValue(database))) { returnValue = this.getTrueBooleanValue(database); } else if (((String) value).equalsIgnoreCase("false") || value.equals("0") || value.equals("f") || ((String) value).equalsIgnoreCase(this.getFalseBooleanValue(database))) { returnValue = this.getFalseBooleanValue(database); } else { throw new UnexpectedLiquibaseException("Unknown boolean value: " + value); } } else if (value instanceof Long) { if (Long.valueOf(1).equals(value)) { returnValue = this.getTrueBooleanValue(database); } else { returnValue = this.getFalseBooleanValue(database); } } else if (value instanceof Number) { if (value.equals(1)) { returnValue = this.getTrueBooleanValue(database); } else { returnValue = this.getFalseBooleanValue(database); } } else if (value instanceof DatabaseFunction) { return value.toString(); } else if (value instanceof Boolean) { if (((Boolean) value)) { returnValue = this.getTrueBooleanValue(database); } else { returnValue = this.getFalseBooleanValue(database); } } else { throw new UnexpectedLiquibaseException("Cannot convert type "+value.getClass()+" to a boolean value"); } return returnValue; } protected boolean isNumericBoolean(Database database) { if (database instanceof DerbyDatabase) { return !((DerbyDatabase) database).supportsBooleanDataType(); } return database instanceof DB2Database || database instanceof FirebirdDatabase || database instanceof MSSQLDatabase || database instanceof MySQLDatabase || database instanceof OracleDatabase || database instanceof SQLiteDatabase || database instanceof SybaseASADatabase || database instanceof SybaseDatabase; } /** * The database-specific value to use for "false" "boolean" columns. */ public String getFalseBooleanValue(Database database) { if (isNumericBoolean(database)) { return "0"; } if (database instanceof InformixDatabase) { return "'f'"; } return "FALSE"; } /** * The database-specific value to use for "true" "boolean" columns. */ public String getTrueBooleanValue(Database database) { if (isNumericBoolean(database)) { return "1"; } if (database instanceof InformixDatabase) { return "'t'"; } return "TRUE"; } //sqllite // } else if (columnTypeString.toLowerCase(Locale.ENGLISH).contains("boolean") || // columnTypeString.toLowerCase(Locale.ENGLISH).contains("binary")) { // type = new BooleanType("BOOLEAN"); }
adriens/liquibase
liquibase-core/src/main/java/liquibase/datatype/core/BooleanType.java
Java
apache-2.0
5,817
package client import ( "io" "time" "github.com/docker/engine-api/types" "github.com/docker/engine-api/types/container" "github.com/docker/engine-api/types/filters" "github.com/docker/engine-api/types/network" "github.com/docker/engine-api/types/registry" "github.com/docker/engine-api/types/swarm" "golang.org/x/net/context" ) // CommonAPIClient is the common methods between stable and experimental versions of APIClient. type CommonAPIClient interface { ContainerAPIClient ImageAPIClient NodeAPIClient NetworkAPIClient ServiceAPIClient SwarmAPIClient SystemAPIClient VolumeAPIClient ClientVersion() string ServerVersion(ctx context.Context) (types.Version, error) UpdateClientVersion(v string) } // ContainerAPIClient defines API client methods for the containers type ContainerAPIClient interface { ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.ContainerCommitResponse, error) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string) (types.ContainerCreateResponse, error) ContainerDiff(ctx context.Context, container string) ([]types.ContainerChange, error) ContainerExecAttach(ctx context.Context, execID string, config types.ExecConfig) (types.HijackedResponse, error) ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.ContainerExecCreateResponse, error) ContainerExecInspect(ctx context.Context, execID string) (types.ContainerExecInspect, error) ContainerExecResize(ctx context.Context, execID string, options types.ResizeOptions) error ContainerExecStart(ctx context.Context, execID string, config types.ExecStartCheck) error ContainerExport(ctx context.Context, container string) (io.ReadCloser, error) ContainerInspect(ctx context.Context, container string) (types.ContainerJSON, error) ContainerInspectWithRaw(ctx context.Context, container string, getSize bool) (types.ContainerJSON, []byte, error) ContainerKill(ctx context.Context, container, signal string) error ContainerList(ctx context.Context, options types.ContainerListOptions) ([]types.Container, error) ContainerLogs(ctx context.Context, container string, options types.ContainerLogsOptions) (io.ReadCloser, error) ContainerPause(ctx context.Context, container string) error ContainerRemove(ctx context.Context, container string, options types.ContainerRemoveOptions) error ContainerRename(ctx context.Context, container, newContainerName string) error ContainerResize(ctx context.Context, container string, options types.ResizeOptions) error ContainerRestart(ctx context.Context, container string, timeout *time.Duration) error ContainerStatPath(ctx context.Context, container, path string) (types.ContainerPathStat, error) ContainerStats(ctx context.Context, container string, stream bool) (io.ReadCloser, error) ContainerStart(ctx context.Context, container string, options types.ContainerStartOptions) error ContainerStop(ctx context.Context, container string, timeout *time.Duration) error ContainerTop(ctx context.Context, container string, arguments []string) (types.ContainerProcessList, error) ContainerUnpause(ctx context.Context, container string) error ContainerUpdate(ctx context.Context, container string, updateConfig container.UpdateConfig) error ContainerWait(ctx context.Context, container string) (int, error) CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) CopyToContainer(ctx context.Context, container, path string, content io.Reader, options types.CopyToContainerOptions) error } // ImageAPIClient defines API client methods for the images type ImageAPIClient interface { ImageBuild(ctx context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) ImageCreate(ctx context.Context, parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) ImageHistory(ctx context.Context, image string) ([]types.ImageHistory, error) ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) ImageInspectWithRaw(ctx context.Context, image string, getSize bool) (types.ImageInspect, []byte, error) ImageList(ctx context.Context, options types.ImageListOptions) ([]types.Image, error) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) ImagePull(ctx context.Context, ref string, options types.ImagePullOptions) (io.ReadCloser, error) ImagePush(ctx context.Context, ref string, options types.ImagePushOptions) (io.ReadCloser, error) ImageRemove(ctx context.Context, image string, options types.ImageRemoveOptions) ([]types.ImageDelete, error) ImageSearch(ctx context.Context, term string, options types.ImageSearchOptions) ([]registry.SearchResult, error) ImageSave(ctx context.Context, images []string) (io.ReadCloser, error) ImageTag(ctx context.Context, image, ref string) error } // NetworkAPIClient defines API client methods for the networks type NetworkAPIClient interface { NetworkConnect(ctx context.Context, networkID, container string, config *network.EndpointSettings) error NetworkCreate(ctx context.Context, name string, options types.NetworkCreate) (types.NetworkCreateResponse, error) NetworkDisconnect(ctx context.Context, networkID, container string, force bool) error NetworkInspect(ctx context.Context, networkID string) (types.NetworkResource, error) NetworkInspectWithRaw(ctx context.Context, networkID string) (types.NetworkResource, []byte, error) NetworkList(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) NetworkRemove(ctx context.Context, networkID string) error } // NodeAPIClient defines API client methods for the nodes type NodeAPIClient interface { NodeInspectWithRaw(ctx context.Context, nodeID string) (swarm.Node, []byte, error) NodeList(ctx context.Context, options types.NodeListOptions) ([]swarm.Node, error) NodeRemove(ctx context.Context, nodeID string, options types.NodeRemoveOptions) error NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error } // ServiceAPIClient defines API client methods for the services type ServiceAPIClient interface { ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) ServiceInspectWithRaw(ctx context.Context, serviceID string) (swarm.Service, []byte, error) ServiceList(ctx context.Context, options types.ServiceListOptions) ([]swarm.Service, error) ServiceRemove(ctx context.Context, serviceID string) error ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) error TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) TaskList(ctx context.Context, options types.TaskListOptions) ([]swarm.Task, error) } // SwarmAPIClient defines API client methods for the swarm type SwarmAPIClient interface { SwarmInit(ctx context.Context, req swarm.InitRequest) (string, error) SwarmJoin(ctx context.Context, req swarm.JoinRequest) error SwarmLeave(ctx context.Context, force bool) error SwarmInspect(ctx context.Context) (swarm.Swarm, error) SwarmUpdate(ctx context.Context, version swarm.Version, swarm swarm.Spec, flags swarm.UpdateFlags) error } // SystemAPIClient defines API client methods for the system type SystemAPIClient interface { Events(ctx context.Context, options types.EventsOptions) (io.ReadCloser, error) Info(ctx context.Context) (types.Info, error) RegistryLogin(ctx context.Context, auth types.AuthConfig) (types.AuthResponse, error) } // VolumeAPIClient defines API client methods for the volumes type VolumeAPIClient interface { VolumeCreate(ctx context.Context, options types.VolumeCreateRequest) (types.Volume, error) VolumeInspect(ctx context.Context, volumeID string) (types.Volume, error) VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) VolumeList(ctx context.Context, filter filters.Args) (types.VolumesListResponse, error) VolumeRemove(ctx context.Context, volumeID string, force bool) error }
thaJeztah/engine-api
client/interface.go
GO
apache-2.0
8,469
package esilatest /* 200 ok object */ type GetCorporationsCorporationIdKillmailsRecent200Ok struct { /* A hash of this killmail */ KillmailHash string `json:"killmail_hash,omitempty"` /* ID of this killmail */ KillmailId int32 `json:"killmail_id,omitempty"` }
antihax/mock-esi
latest/go/model_get_corporations_corporation_id_killmails_recent_200_ok.go
GO
apache-2.0
269
# Copyright 2021 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. """Utilities for generating BigQuery data querying scirpts.""" from google.cloud import aiplatform as vertex_ai def _get_source_query(bq_dataset_name, bq_table_name, ml_use, limit=None): query = f""" SELECT IF(trip_month IS NULL, -1, trip_month) trip_month, IF(trip_day IS NULL, -1, trip_day) trip_day, IF(trip_day_of_week IS NULL, -1, trip_day_of_week) trip_day_of_week, IF(trip_hour IS NULL, -1, trip_hour) trip_hour, IF(trip_seconds IS NULL, -1, trip_seconds) trip_seconds, IF(trip_miles IS NULL, -1, trip_miles) trip_miles, IF(payment_type IS NULL, 'NA', payment_type) payment_type, IF(pickup_grid IS NULL, 'NA', pickup_grid) pickup_grid, IF(dropoff_grid IS NULL, 'NA', dropoff_grid) dropoff_grid, IF(euclidean IS NULL, -1, euclidean) euclidean, IF(loc_cross IS NULL, 'NA', loc_cross) loc_cross""" if ml_use: query += f""", tip_bin FROM {bq_dataset_name}.{bq_table_name} WHERE ML_use = '{ml_use}' """ else: query += f""" FROM {bq_dataset_name}.{bq_table_name} """ if limit: query += f"LIMIT {limit}" return query def get_training_source_query( project, region, dataset_display_name, ml_use, limit=None ): vertex_ai.init(project=project, location=region) dataset = vertex_ai.TabularDataset.list( filter=f"display_name={dataset_display_name}", order_by="update_time" )[-1] bq_source_uri = dataset.gca_resource.metadata["inputConfig"]["bigquerySource"][ "uri" ] _, bq_dataset_name, bq_table_name = bq_source_uri.replace("g://", "").split(".") return _get_source_query(bq_dataset_name, bq_table_name, ml_use, limit) def get_serving_source_query(bq_dataset_name, bq_table_name, limit=None): return _get_source_query(bq_dataset_name, bq_table_name, ml_use=None, limit=limit)
GoogleCloudPlatform/mlops-with-vertex-ai
src/common/datasource_utils.py
Python
apache-2.0
2,483
<?php if(isset($_SESSION["bird"])) { $bird_info = $_SESSION["bird"]; $observers_list = $db->get_observers($bird_info["id_kentish_plover"]); $observers_array = array(); while($observers = $observers_list->fetch()) { array_push($observers_array, array( "date" => $observers["date"], "town" => $observers["town"], "name" => $observers["last_name"] . ' ' . $observers["first_name"] )); } $to_replace = array("\"", "'"); $replace_by = array("£dqot;", "£sqot;"); $bird_info_json = str_replace($to_replace, $replace_by, json_encode($bird_info)); $observers_list_json = str_replace($to_replace, $replace_by, json_encode($observers_array)); ?> <h2>Résultat de la requête</h2> <form method="post" action="core/pdf_creator.php"> <input type="hidden" name="bird_infos" value='<?php echo $bird_info_json ?>'> <input type="hidden" name="observers_list" value='<?php echo $observers_list_json ?>'> <button type="submit" class="btn btn-warning">Obtenir une version PDF</button> </form> <div class="row"> <div class="col-sm-4 padding-content"> <img src="statics/pictures/gonm_logo.jpg" class="img-responsive"> </div> <div class="col-sm-4"> <h2> Historique des observations d'un Gravelot à Collier interrompu bagué couleur <i>Charadrius alexandrinus</i> </h2> </div> <div class="col-sm-4 padding-content"> <img src="statics/pictures/plover_2.jpg" class="img-responsive"> </div> </div> <div class="row padding-content"> <div class="col-sm-5"> <div class="col-sm-12"> <table class="table"> <tbody> <tr> <td class="strong">Bague acier</td> <td><?php echo $bird_info["metal_ring"]; ?></td> </tr> <tr> <td class="strong">Numéro de la bague</td> <td><?php echo $bird_info["number"]; ?></td> </tr> <tr> <td class="strong">Couleur de la bague</td> <td><?php echo $bird_info["color"]; ?></td> </tr> <tr> <td class="strong">Date du baguage</td> <td><?php echo $bird_info["date"]; ?></td> </tr> <tr> <td class="strong">Age</td> <td><?php echo $bird_info["age"]; ?></td> </tr> <tr> <td class="strong">Sexe</td> <td><?php echo $bird_info["sex"]; ?></td> </tr> <tr> <td class="strong">Lieu de baguage</td> <td><?php echo $bird_info["town"]; ?></td> </tr> <tr> <td class="strong">Bagueur</td> <td><?php echo $bird_info["observer"]; ?></td> </tr> </tbody> </table> </div> <div class="col-sm-12"> <img src="statics/pictures/mnhn.jpg" class="img-responsive"> </div> <div class="col-sm-12"> <img src="statics/pictures/logo_warning.jpg" class="img-responsive"> </div> </div> <div class="col-sm-7"> <table class="table table-striped"> <thead> <tr> <th>Date</th> <th>Lieu d'observation</th> <th>Observateur</th> </tr> </thead> <tbody> <?php $observers_list = $db->get_observers($bird_info["id_kentish_plover"]); while($observers = $observers_list->fetch()) { ?> <tr> <td> <?php $mysql_date = strtotime($observers["date"]); echo date('d-m-Y', $mysql_date); ?> </td> <td><?php echo $observers["town"]; ?></td> <td><?php echo $observers["last_name"] . " " . $observers["first_name"]; ?></td> </tr> <?php } ?> </tbody> </table> </div> </div> <?php unset($_SESSION["bird"]); } else { header("Location: index.php?url=form"); } ?>
Carmain/Banding-tracking
content/obs_sheet.php
PHP
apache-2.0
3,621
"""Insteon base entity.""" import functools import logging from pyinsteon import devices from homeassistant.core import callback from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) from homeassistant.helpers.entity import DeviceInfo, Entity from .const import ( DOMAIN, SIGNAL_ADD_DEFAULT_LINKS, SIGNAL_LOAD_ALDB, SIGNAL_PRINT_ALDB, SIGNAL_REMOVE_ENTITY, SIGNAL_SAVE_DEVICES, STATE_NAME_LABEL_MAP, ) from .utils import print_aldb_to_log _LOGGER = logging.getLogger(__name__) class InsteonEntity(Entity): """INSTEON abstract base entity.""" def __init__(self, device, group): """Initialize the INSTEON binary sensor.""" self._insteon_device_group = device.groups[group] self._insteon_device = device def __hash__(self): """Return the hash of the Insteon Entity.""" return hash(self._insteon_device) @property def should_poll(self): """No polling needed.""" return False @property def address(self): """Return the address of the node.""" return str(self._insteon_device.address) @property def group(self): """Return the INSTEON group that the entity responds to.""" return self._insteon_device_group.group @property def unique_id(self) -> str: """Return a unique ID.""" if self._insteon_device_group.group == 0x01: uid = self._insteon_device.id else: uid = f"{self._insteon_device.id}_{self._insteon_device_group.group}" return uid @property def name(self): """Return the name of the node (used for Entity_ID).""" # Set a base description if (description := self._insteon_device.description) is None: description = "Unknown Device" # Get an extension label if there is one extension = self._get_label() if extension: extension = f" {extension}" return f"{description} {self._insteon_device.address}{extension}" @property def extra_state_attributes(self): """Provide attributes for display on device card.""" return {"insteon_address": self.address, "insteon_group": self.group} @property def device_info(self) -> DeviceInfo: """Return device information.""" return DeviceInfo( identifiers={(DOMAIN, str(self._insteon_device.address))}, manufacturer="Smart Home", model=f"{self._insteon_device.model} ({self._insteon_device.cat!r}, 0x{self._insteon_device.subcat:02x})", name=f"{self._insteon_device.description} {self._insteon_device.address}", sw_version=f"{self._insteon_device.firmware:02x} Engine Version: {self._insteon_device.engine_version}", via_device=(DOMAIN, str(devices.modem.address)), ) @callback def async_entity_update(self, name, address, value, group): """Receive notification from transport that new data exists.""" _LOGGER.debug( "Received update for device %s group %d value %s", address, group, value, ) self.async_write_ha_state() async def async_added_to_hass(self): """Register INSTEON update events.""" _LOGGER.debug( "Tracking updates for device %s group %d name %s", self.address, self.group, self._insteon_device_group.name, ) self._insteon_device_group.subscribe(self.async_entity_update) load_signal = f"{self.entity_id}_{SIGNAL_LOAD_ALDB}" self.async_on_remove( async_dispatcher_connect(self.hass, load_signal, self._async_read_aldb) ) print_signal = f"{self.entity_id}_{SIGNAL_PRINT_ALDB}" async_dispatcher_connect(self.hass, print_signal, self._print_aldb) default_links_signal = f"{self.entity_id}_{SIGNAL_ADD_DEFAULT_LINKS}" async_dispatcher_connect( self.hass, default_links_signal, self._async_add_default_links ) remove_signal = f"{self._insteon_device.address.id}_{SIGNAL_REMOVE_ENTITY}" self.async_on_remove( async_dispatcher_connect( self.hass, remove_signal, functools.partial(self.async_remove, force_remove=True), ) ) async def async_will_remove_from_hass(self): """Unsubscribe to INSTEON update events.""" _LOGGER.debug( "Remove tracking updates for device %s group %d name %s", self.address, self.group, self._insteon_device_group.name, ) self._insteon_device_group.unsubscribe(self.async_entity_update) async def _async_read_aldb(self, reload): """Call device load process and print to log.""" await self._insteon_device.aldb.async_load(refresh=reload) self._print_aldb() async_dispatcher_send(self.hass, SIGNAL_SAVE_DEVICES) def _print_aldb(self): """Print the device ALDB to the log file.""" print_aldb_to_log(self._insteon_device.aldb) def _get_label(self): """Get the device label for grouped devices.""" label = "" if len(self._insteon_device.groups) > 1: if self._insteon_device_group.name in STATE_NAME_LABEL_MAP: label = STATE_NAME_LABEL_MAP[self._insteon_device_group.name] else: label = f"Group {self.group:d}" return label async def _async_add_default_links(self): """Add default links between the device and the modem.""" await self._insteon_device.async_add_default_links()
aronsky/home-assistant
homeassistant/components/insteon/insteon_entity.py
Python
apache-2.0
5,749
package com.monkeyk.os.service.dto; import com.monkeyk.os.domain.oauth.ClientDetails; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * 2016/6/8 * * @author Shengzhao Li */ public class ClientDetailsListDto implements Serializable { private static final long serialVersionUID = -6327364441565670231L; private String clientId; private List<ClientDetailsDto> clientDetailsDtos = new ArrayList<>(); public ClientDetailsListDto() { } public ClientDetailsListDto(String clientId, List<ClientDetails> list) { this.clientId = clientId; this.clientDetailsDtos = ClientDetailsDto.toDtos(list); } public int getSize() { return clientDetailsDtos.size(); } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public List<ClientDetailsDto> getClientDetailsDtos() { return clientDetailsDtos; } public void setClientDetailsDtos(List<ClientDetailsDto> clientDetailsDtos) { this.clientDetailsDtos = clientDetailsDtos; } }
monkeyk/oauth2-shiro
authz/src/main/java/com/monkeyk/os/service/dto/ClientDetailsListDto.java
Java
apache-2.0
1,151
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.nd4j.api.loader; import java.io.Serializable; /** * A factory interface for getting {@link Source} objects given a String path * @author Alex Black */ public interface SourceFactory extends Serializable { Source getSource(String path); }
RobAltena/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/api/loader/SourceFactory.java
Java
apache-2.0
1,022
package ch.sourcepond.utils.fileobserver.impl; import static org.mockito.Mockito.mock; import ch.sourcepond.utils.fileobserver.impl.dispatcher.DefaultEventDispatcher; import ch.sourcepond.utils.fileobserver.impl.replay.DefaultEventReplayFactory; /** * @author rolandhauser * */ public class DefaultWorkspaceTest { private final WorkspaceDirectory dir = mock(WorkspaceDirectory.class); private final DefaultEventReplayFactory evenrplFactory = mock(DefaultEventReplayFactory.class); private final DefaultEventDispatcher dispatcher = mock(DefaultEventDispatcher.class); }
SourcePond/fileobserver-impl
src/test/java/ch/sourcepond/utils/fileobserver/impl/DefaultWorkspaceTest.java
Java
apache-2.0
578
//MongoDB script to Update the Wing Directors list. //The list includes Wing Directors and Assistants only. // //History: // 15Nov21 MEG Clean spaces from email addresses. // 07Mar21 MEG Exclude assistants // 27Jan21 MEG Created. var DEBUG = false; var db = db.getSiblingDB( 'NHWG'); // Google Group of interest var baseGroupName = 'nh-wing-directors'; var googleGroup = baseGroupName + '@nhwg.cap.gov'; // Mongo collection that holds all wing groups var groupsCollection = 'GoogleGroups'; // Aggregation pipeline find all wing staff members as var memberPipeline = [ // Stage 1 - find ALL directors and assistants { $match: { Duty:/director/i, Asst: 0, } }, // Stage 2 { $lookup: // join Google account record { from: "Google", localField: "CAPID", foreignField: "customSchemas.Member.CAPID", as: "member" } }, // Stage 3 { // flatten array $unwind: { path : "$member", preserveNullAndEmptyArrays : false // optional } }, // Stage 4 { $project: { CAPID:1, Duty:1, Asst:1, Director: "$member.name.fullName", Email: "$member.primaryEmail", } }, ]; // Aggregate a list of all emails for the Google group of interest // Exlcuding MANAGER & OWNER roles, no group aristocrats var groupMemberPipeline = [ { "$match" : { "group" : googleGroup, "role" : 'MEMBER', } }, { "$project" : { "email" : "$email" } } ]; // pipeline options var options = { "allowDiskUse" : false }; function isActiveMember( capid ) { // Check to see if member is active. // This function needs to be changed for each group depending // on what constitutes "active". var m = db.getCollection( "Member").findOne( { "CAPID": capid, "MbrStatus": "ACTIVE" } ); if ( m == null ) { return false; } return true; } function isGroupMember( group, email ) { // Check if email is already in the group var email = email.toLowerCase(); var rx = new RegExp( email, 'i' ); return db.getCollection( groupsCollection ).findOne( { 'group': group, 'email': rx } ); } function addMembers( collection, pipeline, options, group ) { // Scans looking for active members // if member is not currently on the mailing list generate gam command to add member. // returns a list of members qualified to be on the list regardless of inclusion. var list = []; // the set of possible group members // Get the list of all qualified potential members for the list var cursor = db.getCollection( collection ).aggregate( pipeline, options ); while ( cursor.hasNext() ) { var m = cursor.next(); var email = m.Email.toLowerCase().replace( / /g, "" ); if ( ! isActiveMember( m.CAPID ) ) { continue; } if ( ! list.includes( email ) ) { list.push( email ); } if ( isGroupMember( googleGroup, m.Email ) ) { continue; } // Print gam command to add new member print("gam update group", googleGroup, "add member", email ); } return list; } function removeMembers( collection, pipeline, options, group, authMembers ) { // compare each member of the group against the authList // check active status, if not generate a gam command to remove member. // collection - name of collection holding all Google Group info // pipeline - array containing the pipeline to extract members of the target group // options - options for aggregations pipeline var m = db.getCollection( collection ).aggregate( pipeline, options ); while ( m.hasNext() ) { var e = m.next().email.toLowerCase().replace( / /g, "" ); DEBUG && print("DEBUG::removeMembers::email",e); var rgx = new RegExp( e, "i" ); if ( authMembers.includes( e ) ) { continue; } var r = db.getCollection( 'MbrContact' ).findOne( { Type: 'EMAIL', Priority: 'PRIMARY', Contact: rgx } ); if ( r ) { var a = db.getCollection( 'Member' ).findOne( { CAPID: r.CAPID } ); DEBUG && print("DEBUG::removeMembers::Member.CAPID",a.CAPID,"NameLast:",a.NameLast,"NameFirst:",a.NameFirst); if ( a ) { print( '#INFO:', a.CAPID, a.NameLast, a.NameFirst, a.NameSuffix ); print( 'gam update group', googleGroup, 'delete member', e ); } } } } // Main here print("# Update group:", googleGroup ); print("# Add new members"); var theAuthList = addMembers( "DutyPosition", memberPipeline, options, googleGroup ); DEBUG == true && print("DEBUG::theAuthList:", theAuthList); print( "# Remove inactive members") ; removeMembers( "GoogleGroups", groupMemberPipeline, options, googleGroup, theAuthList );
ifrguy/NHWG-MIMS
src/Groups/wing_directors.js
JavaScript
apache-2.0
4,806
package ec.master.assignment1.selection.impl; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import ec.master.assignment1.model.Individual; import ec.master.assignment1.selection.Selector; /** * @ClassName: FPSelection * @Description: implementation of fitness proportional selection * @date 17/08/2015 11:15:33 pm * */ public class FPSelection implements Selector { /** * The method is do fitness proportional selection * @return selected list */ public List<Individual> doSelection(List<Individual> individuals, int groupSize, int resultSize) { Collections.shuffle(individuals); ArrayList<Individual> selectedIndividuals = new ArrayList<Individual>(resultSize); double sum = 0; //sum all the fitness of each individual for(int i=0;i<individuals.size();i++){ sum += individuals.get(i).getFitness(); } Random random = new Random(); double compare; //select populationSize individuals for (int p = 0; p < resultSize; p++) { compare = random.nextDouble()*sum; for(int i=0;i<individuals.size();i++){ compare -= individuals.get(i).getFitness(); //choose individual when compared value is >former fitness && <later fitness if(compare<=0){ selectedIndividuals.add(individuals.get(i)); break; } } } return selectedIndividuals; } }
nettree/EC
EC_Assignment1/src/ec/master/assignment1/selection/impl/FPSelection.java
Java
apache-2.0
1,373
/* * Copyright 2017 Nobuki HIRAMINE * * 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.hiramine.modelfileloader; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.StringTokenizer; import android.util.Log; public class StlFileLoader { public static MFLModel load( String strPath, OnProgressListener onProgressListener ) { File file = new File( strPath ); if( 0 == file.length() ) { return null; } // ファーストパース(要素数カウント) int[] aiCountTriangle = new int[1]; int[] aiCountLine = new int[1]; if( !parse_first( strPath, aiCountTriangle, aiCountLine ) ) { return null; } // 領域確保 if( 0 == aiCountTriangle[0] ) { return null; } float[] af3Vertex = new float[aiCountTriangle[0] * 3 * 3]; // af3Vertexは、3つのデータで一つの頂点、さらにそれが3つで一つの三角形 // セカンドパース(値詰め) if( !parse_second( strPath, af3Vertex, aiCountLine[0], onProgressListener ) ) { return null; } // 領域確保、データ構築 MFLModel model = new MFLModel(); model.iCountVertex = af3Vertex.length / 3; model.af3Vertex = af3Vertex; model.iCountTriangle = model.iCountVertex / 3; model.aIndexedTriangle = new MFLIndexedTriangle[model.iCountTriangle]; for( int iIndexTriangle = 0; iIndexTriangle < model.iCountTriangle; ++iIndexTriangle ) { model.aIndexedTriangle[iIndexTriangle] = new MFLIndexedTriangle(); model.aIndexedTriangle[iIndexTriangle].i3IndexVertex[0] = (short)( iIndexTriangle * 3 + 0 ); model.aIndexedTriangle[iIndexTriangle].i3IndexVertex[1] = (short)( iIndexTriangle * 3 + 1 ); model.aIndexedTriangle[iIndexTriangle].i3IndexVertex[2] = (short)( iIndexTriangle * 3 + 2 ); } model.iCountNormal = 0; model.af3Normal = null; model.aMaterial = null; model.groupRoot = new MFLGroup( "" ); model.groupRoot.iCountTriangle = model.iCountTriangle; model.groupRoot.aiIndexTriangle = new int[model.groupRoot.iCountTriangle]; for( int iIndexTriangle = 0; iIndexTriangle < model.groupRoot.iCountTriangle; ++iIndexTriangle ) { model.groupRoot.aiIndexTriangle[iIndexTriangle] = iIndexTriangle; } return model; } private static boolean parse_first( String strPath, int[] aiCountTriangle, int[] aiCountLine ) { // インプットのチェック if( null == aiCountTriangle || null == aiCountLine ) { return false; } // アウトプットの初期化 aiCountTriangle[0] = 0; aiCountLine[0] = 0; try { // 読み取り BufferedReader br = new BufferedReader( new FileReader( strPath ) ); int iIndexTriangle = 0; int iIndexLine = 0; while( true ) { ++iIndexLine; String strReadString = br.readLine(); if( null == strReadString ) { break; } StringTokenizer stReadString = new StringTokenizer( strReadString, ", \t\r\n" ); if( !stReadString.hasMoreTokens() ) { continue; } String token = stReadString.nextToken(); if( token.equalsIgnoreCase( "endfacet" ) ) { ++iIndexTriangle; continue; } } br.close(); aiCountTriangle[0] = iIndexTriangle; aiCountLine[0] = iIndexLine; return true; } catch( Exception e ) { Log.e( "StlFileLoader", "parse_first error : " + e ); return false; } } private static boolean parse_second( String strPath, float[] af3Vertex, int iCountLine, OnProgressListener onProgressListener ) { // インプットのチェック if( null == af3Vertex ) { return false; } try { // 読み取り BufferedReader br = new BufferedReader( new FileReader( strPath ) ); int iIndexTriangle = 0; int iIndexLine = 0; int iIndex3 = 0; while( true ) { if( null != onProgressListener && 0 == iIndexLine % 100 ) { if( !onProgressListener.updateProgress( iIndexLine, iCountLine ) ) { // ユーザー操作による処理中止 Log.d( "LoaderStlFile", "Cancelled" ); return false; } } ++iIndexLine; String strReadString = br.readLine(); if( null == strReadString ) { break; } StringTokenizer stReadString = new StringTokenizer( strReadString, ", \t\r\n" ); if( !stReadString.hasMoreTokens() ) { continue; } String token = stReadString.nextToken(); if( token.equalsIgnoreCase( "vertex" ) ) { if( 3 <= iIndex3 ) { continue; } af3Vertex[iIndexTriangle * 9 + iIndex3 * 3 + 0] = Float.valueOf( stReadString.nextToken() ); af3Vertex[iIndexTriangle * 9 + iIndex3 * 3 + 1] = Float.valueOf( stReadString.nextToken() ); af3Vertex[iIndexTriangle * 9 + iIndex3 * 3 + 2] = Float.valueOf( stReadString.nextToken() ); ++iIndex3; continue; } else if( token.equalsIgnoreCase( "facet" ) ) { // 面法線ベクトル iIndex3 = 0; continue; } else if( token.equalsIgnoreCase( "endfacet" ) ) { ++iIndexTriangle; continue; } else if( token.equalsIgnoreCase( "solid" ) ) { // ソリッド名 continue; } } br.close(); return true; } catch( Exception e ) { Log.e( "StlFileLoader", "parse_second error : " + e ); return false; } } }
nobukihiramine/ModelViewerTutorial
app/src/main/java/com/hiramine/modelfileloader/StlFileLoader.java
Java
apache-2.0
6,007
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace GovITHub.Auth.Common.Services.Impl { /// <summary> /// Base email sender /// </summary> public abstract class BaseEmailSender : IEmailSender { public EmailProviderSettings Settings { get; set; } protected ILogger<EmailService> Logger { get; set; } protected IHostingEnvironment Env { get; set; } public abstract Task SendEmailAsync(string email, string subject, string message); public BaseEmailSender(EmailProviderSettings settingsValue, ILogger<EmailService> logger, IHostingEnvironment env) { this.Logger = logger; this.Env = env; Settings = settingsValue; } /// <summary> /// Build settings /// </summary> /// <param name="settingsValue">settings</param> protected virtual void Build(string settingsValue) { if (string.IsNullOrEmpty(settingsValue)) { throw new ArgumentNullException("settings"); } Settings = JsonConvert.DeserializeObject<EmailProviderSettings>(settingsValue); if (string.IsNullOrEmpty(Settings.Address)) { throw new ArgumentNullException("settings.Address"); } } } }
gov-ithub/auth-sso
src/GovITHub.Auth.Common/Services/Impl/BaseEmailSender.cs
C#
apache-2.0
1,437
// 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. package com.google.api.ads.admanager.jaxws.v202202; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * An error that occurs while parsing {@link Statement} objects. * * * <p>Java class for StatementError complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="StatementError"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v202202}ApiError"> * &lt;sequence> * &lt;element name="reason" type="{https://www.google.com/apis/ads/publisher/v202202}StatementError.Reason" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "StatementError", propOrder = { "reason" }) public class StatementError extends ApiError { @XmlSchemaType(name = "string") protected StatementErrorReason reason; /** * Gets the value of the reason property. * * @return * possible object is * {@link StatementErrorReason } * */ public StatementErrorReason getReason() { return reason; } /** * Sets the value of the reason property. * * @param value * allowed object is * {@link StatementErrorReason } * */ public void setReason(StatementErrorReason value) { this.reason = value; } }
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202202/StatementError.java
Java
apache-2.0
2,266
using System; using NUnit.Framework; using PCLActivitySet.Domain.Recurrence; using PCLActivitySet.Dto.Recurrence; namespace PCLActivitySet.Test.Domain.Recurrence { [TestFixture] public class DateProjectionTest { [Test] public void TranslateProjectionType() { const int periodCount = 1; const EMonth month = EMonth.February; const int dayOfMonth = 3; const EDaysOfWeekExt dayOfWeekExt = EDaysOfWeekExt.Thursday; const EDaysOfWeekFlags dayOfWeekFlags = EDaysOfWeekFlags.Friday; const EWeeksInMonth weekInMonth = EWeeksInMonth.Last; DateProjection prj = new DateProjection(EDateProjectionType.Daily) { PeriodCount = periodCount, Month = month, DayOfMonth = dayOfMonth, DaysOfWeekExt = dayOfWeekExt, DaysOfWeekFlags = dayOfWeekFlags, WeeksInMonth = weekInMonth, }; prj.ProjectionType = EDateProjectionType.Weekly; Assert.That(DateProjection.ToShortDescription(prj), Is.EqualTo("Weekly")); prj.ProjectionType = EDateProjectionType.Monthly; Assert.That(DateProjection.ToShortDescription(prj), Is.EqualTo("Monthly")); prj.ProjectionType = EDateProjectionType.MonthlyRelative; Assert.That(DateProjection.ToShortDescription(prj), Is.EqualTo("Monthly Relative")); prj.ProjectionType = EDateProjectionType.Yearly; Assert.That(DateProjection.ToShortDescription(prj), Is.EqualTo("Yearly")); prj.ProjectionType = EDateProjectionType.YearlyRelative; Assert.That(DateProjection.ToShortDescription(prj), Is.EqualTo("Yearly Relative")); prj.ProjectionType = EDateProjectionType.Daily; Assert.That(DateProjection.ToShortDescription(prj), Is.EqualTo("Daily")); Assert.That(prj.PeriodCount, Is.EqualTo(periodCount)); Assert.That(prj.Month, Is.EqualTo(month)); Assert.That(prj.DayOfMonth, Is.EqualTo(dayOfMonth)); Assert.That(prj.DaysOfWeekExt, Is.EqualTo(dayOfWeekExt)); Assert.That(prj.DaysOfWeekFlags, Is.EqualTo(dayOfWeekFlags)); Assert.That(prj.WeeksInMonth, Is.EqualTo(weekInMonth)); Assert.That(DateProjection.ToShortDescription(null), Is.EqualTo("None")); } [Test] public void TranslateToInvalidProjectionType() { var prj = new DateProjection(); Assert.That(() => prj.ProjectionType = (EDateProjectionType) int.MaxValue, Throws.TypeOf<InvalidOperationException>()); } } }
Merlin9999/PCLActivitySet
src/PCLActivitySet/PCLActivitySet.Test/Domain/Recurrence/DateProjectionTest.cs
C#
apache-2.0
2,704
using System; using CJia.Net.Communication; using CJia.Net.Tcp; using CJia.Net.Communication.Messengers; using CJia.Net.Client; namespace CJia.Net.Server { /// <summary> /// Represents a client from a perspective of a server. /// </summary> public interface IServerClient : IMessenger { /// <summary> /// This event is raised when client disconnected from server. /// </summary> event EventHandler Disconnected; /// <summary> /// Unique identifier for this client in server. /// </summary> long ClientId { get; } ///<summary> /// Gets endpoint of remote application. ///</summary> CJiaEndPoint RemoteEndPoint { get; } /// <summary> /// Gets the current communication state. /// </summary> CommunicationStates CommunicationState { get; } /// <summary> /// Disconnects from server. /// </summary> void Disconnect(); } }
leborety/CJia
CJia.Framework/CJia.Net/Server/IServerClient.cs
C#
apache-2.0
1,018
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: sample-weight-meta.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='sample-weight-meta.proto', package='com.webank.ai.fate.common.mlmodel.buffer', syntax='proto3', serialized_options=_b('B\025SampleWeightMetaProto'), serialized_pb=_b('\n\x18sample-weight-meta.proto\x12(com.webank.ai.fate.common.mlmodel.buffer\"S\n\x10SampleWeightMeta\x12\x10\n\x08need_run\x18\x01 \x01(\x08\x12\x1a\n\x12sample_weight_name\x18\x02 \x01(\t\x12\x11\n\tnormalize\x18\x03 \x01(\x08\x42\x17\x42\x15SampleWeightMetaProtob\x06proto3') ) _SAMPLEWEIGHTMETA = _descriptor.Descriptor( name='SampleWeightMeta', full_name='com.webank.ai.fate.common.mlmodel.buffer.SampleWeightMeta', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='need_run', full_name='com.webank.ai.fate.common.mlmodel.buffer.SampleWeightMeta.need_run', index=0, number=1, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='sample_weight_name', full_name='com.webank.ai.fate.common.mlmodel.buffer.SampleWeightMeta.sample_weight_name', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='normalize', full_name='com.webank.ai.fate.common.mlmodel.buffer.SampleWeightMeta.normalize', index=2, number=3, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=70, serialized_end=153, ) DESCRIPTOR.message_types_by_name['SampleWeightMeta'] = _SAMPLEWEIGHTMETA _sym_db.RegisterFileDescriptor(DESCRIPTOR) SampleWeightMeta = _reflection.GeneratedProtocolMessageType('SampleWeightMeta', (_message.Message,), { 'DESCRIPTOR' : _SAMPLEWEIGHTMETA, '__module__' : 'sample_weight_meta_pb2' # @@protoc_insertion_point(class_scope:com.webank.ai.fate.common.mlmodel.buffer.SampleWeightMeta) }) _sym_db.RegisterMessage(SampleWeightMeta) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
FederatedAI/FATE
python/federatedml/protobuf/generated/sample_weight_meta_pb2.py
Python
apache-2.0
3,206
/* Copyright 2022 The Kubernetes 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 io.kubernetes.client.openapi.models; /** Generated */ public interface V1beta1CronJobSpecFluent< A extends io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent<A>> extends io.kubernetes.client.fluent.Fluent<A> { public java.lang.String getConcurrencyPolicy(); public A withConcurrencyPolicy(java.lang.String concurrencyPolicy); public java.lang.Boolean hasConcurrencyPolicy(); /** Method is deprecated. use withConcurrencyPolicy instead. */ @java.lang.Deprecated public A withNewConcurrencyPolicy(java.lang.String original); public java.lang.Integer getFailedJobsHistoryLimit(); public A withFailedJobsHistoryLimit(java.lang.Integer failedJobsHistoryLimit); public java.lang.Boolean hasFailedJobsHistoryLimit(); /** * This method has been deprecated, please use method buildJobTemplate instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V1beta1JobTemplateSpec getJobTemplate(); public io.kubernetes.client.openapi.models.V1beta1JobTemplateSpec buildJobTemplate(); public A withJobTemplate(io.kubernetes.client.openapi.models.V1beta1JobTemplateSpec jobTemplate); public java.lang.Boolean hasJobTemplate(); public io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent.JobTemplateNested<A> withNewJobTemplate(); public io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent.JobTemplateNested<A> withNewJobTemplateLike(io.kubernetes.client.openapi.models.V1beta1JobTemplateSpec item); public io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent.JobTemplateNested<A> editJobTemplate(); public io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent.JobTemplateNested<A> editOrNewJobTemplate(); public io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent.JobTemplateNested<A> editOrNewJobTemplateLike(io.kubernetes.client.openapi.models.V1beta1JobTemplateSpec item); public java.lang.String getSchedule(); public A withSchedule(java.lang.String schedule); public java.lang.Boolean hasSchedule(); /** Method is deprecated. use withSchedule instead. */ @java.lang.Deprecated public A withNewSchedule(java.lang.String original); public java.lang.Long getStartingDeadlineSeconds(); public A withStartingDeadlineSeconds(java.lang.Long startingDeadlineSeconds); public java.lang.Boolean hasStartingDeadlineSeconds(); public java.lang.Integer getSuccessfulJobsHistoryLimit(); public A withSuccessfulJobsHistoryLimit(java.lang.Integer successfulJobsHistoryLimit); public java.lang.Boolean hasSuccessfulJobsHistoryLimit(); public java.lang.Boolean getSuspend(); public A withSuspend(java.lang.Boolean suspend); public java.lang.Boolean hasSuspend(); public interface JobTemplateNested<N> extends io.kubernetes.client.fluent.Nested<N>, io.kubernetes.client.openapi.models.V1beta1JobTemplateSpecFluent< io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent.JobTemplateNested<N>> { public N and(); public N endJobTemplate(); } }
kubernetes-client/java
fluent/src/main/java/io/kubernetes/client/openapi/models/V1beta1CronJobSpecFluent.java
Java
apache-2.0
3,688
package com.github.hayataka.hibernatevalidatorsample.context; import java.io.Closeable; /** * tryでのresourceCloseを行うための仕組 * @author hayakawatakahiko */ interface AutoCloseable extends Closeable { /** * 開放すべきリソースを閉じる処理. */ void close(); }
hayataka/hibernateValidatorSample
src/main/java/com/github/hayataka/hibernatevalidatorsample/context/AutoCloseable.java
Java
apache-2.0
297
// +build windows package handlers import ( "syscall" "golang.org/x/crypto/ssh" ) var SyscallSignals = map[ssh.Signal]syscall.Signal{ ssh.SIGABRT: syscall.SIGABRT, ssh.SIGALRM: syscall.SIGALRM, ssh.SIGFPE: syscall.SIGFPE, ssh.SIGHUP: syscall.SIGHUP, ssh.SIGILL: syscall.SIGILL, ssh.SIGINT: syscall.SIGINT, ssh.SIGKILL: syscall.SIGKILL, ssh.SIGPIPE: syscall.SIGPIPE, ssh.SIGQUIT: syscall.SIGQUIT, ssh.SIGSEGV: syscall.SIGSEGV, ssh.SIGTERM: syscall.SIGTERM, } var SSHSignals = map[syscall.Signal]ssh.Signal{ syscall.SIGABRT: ssh.SIGABRT, syscall.SIGALRM: ssh.SIGALRM, syscall.SIGFPE: ssh.SIGFPE, syscall.SIGHUP: ssh.SIGHUP, syscall.SIGILL: ssh.SIGILL, syscall.SIGINT: ssh.SIGINT, syscall.SIGKILL: ssh.SIGKILL, syscall.SIGPIPE: ssh.SIGPIPE, syscall.SIGQUIT: ssh.SIGQUIT, syscall.SIGSEGV: ssh.SIGSEGV, syscall.SIGTERM: ssh.SIGTERM, }
cloudfoundry-incubator/diego-ssh-windows
handlers/signals_windows.go
GO
apache-2.0
867
/* * Copyright 2005-2017 Dozer 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.dozer.vo.interfacerecursion; /** * @author Christoph Goldner */ public interface UserPrime { String getFirstName(); void setFirstName(String aFirstName); String getLastName(); void setLastName(String aLastName); UserGroupPrime getUserGroup(); void setUserGroup(UserGroupPrime aUserGroup); }
STRiDGE/dozer
core/src/test/java/org/dozer/vo/interfacerecursion/UserPrime.java
Java
apache-2.0
973
// Copyright 2012 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <iostream> // NOLINT(readability/streams) #include "src/v8.h" #include "test/cctest/cctest.h" #include "src/arm/simulator-arm.h" #include "src/base/utils/random-number-generator.h" #include "src/disassembler.h" #include "src/factory.h" #include "src/macro-assembler.h" #include "src/ostreams.h" using namespace v8::base; using namespace v8::internal; // Define these function prototypes to match JSEntryFunction in execution.cc. typedef Object* (*F1)(int x, int p1, int p2, int p3, int p4); typedef Object* (*F2)(int x, int y, int p2, int p3, int p4); typedef Object* (*F3)(void* p0, int p1, int p2, int p3, int p4); typedef Object* (*F4)(void* p0, void* p1, int p2, int p3, int p4); typedef Object* (*F5)(uint32_t p0, void* p1, void* p2, int p3, int p4); #define __ assm. TEST(0) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); __ add(r0, r0, Operand(r1)); __ mov(pc, Operand(lr)); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F2 f = FUNCTION_CAST<F2>(code->entry()); int res = reinterpret_cast<int>(CALL_GENERATED_CODE(isolate, f, 3, 4, 0, 0, 0)); ::printf("f() = %d\n", res); CHECK_EQ(7, res); } TEST(1) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); Label L, C; __ mov(r1, Operand(r0)); __ mov(r0, Operand::Zero()); __ b(&C); __ bind(&L); __ add(r0, r0, Operand(r1)); __ sub(r1, r1, Operand(1)); __ bind(&C); __ teq(r1, Operand::Zero()); __ b(ne, &L); __ mov(pc, Operand(lr)); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F1 f = FUNCTION_CAST<F1>(code->entry()); int res = reinterpret_cast<int>(CALL_GENERATED_CODE(isolate, f, 100, 0, 0, 0, 0)); ::printf("f() = %d\n", res); CHECK_EQ(5050, res); } TEST(2) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); Label L, C; __ mov(r1, Operand(r0)); __ mov(r0, Operand(1)); __ b(&C); __ bind(&L); __ mul(r0, r1, r0); __ sub(r1, r1, Operand(1)); __ bind(&C); __ teq(r1, Operand::Zero()); __ b(ne, &L); __ mov(pc, Operand(lr)); // some relocated stuff here, not executed __ RecordComment("dead code, just testing relocations"); __ mov(r0, Operand(isolate->factory()->true_value())); __ RecordComment("dead code, just testing immediate operands"); __ mov(r0, Operand(-1)); __ mov(r0, Operand(0xFF000000)); __ mov(r0, Operand(0xF0F0F0F0)); __ mov(r0, Operand(0xFFF0FFFF)); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F1 f = FUNCTION_CAST<F1>(code->entry()); int res = reinterpret_cast<int>(CALL_GENERATED_CODE(isolate, f, 10, 0, 0, 0, 0)); ::printf("f() = %d\n", res); CHECK_EQ(3628800, res); } TEST(3) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); typedef struct { int i; char c; int16_t s; } T; T t; Assembler assm(isolate, NULL, 0); Label L, C; __ mov(ip, Operand(sp)); __ stm(db_w, sp, r4.bit() | fp.bit() | lr.bit()); __ sub(fp, ip, Operand(4)); __ mov(r4, Operand(r0)); __ ldr(r0, MemOperand(r4, offsetof(T, i))); __ mov(r2, Operand(r0, ASR, 1)); __ str(r2, MemOperand(r4, offsetof(T, i))); __ ldrsb(r2, MemOperand(r4, offsetof(T, c))); __ add(r0, r2, Operand(r0)); __ mov(r2, Operand(r2, LSL, 2)); __ strb(r2, MemOperand(r4, offsetof(T, c))); __ ldrsh(r2, MemOperand(r4, offsetof(T, s))); __ add(r0, r2, Operand(r0)); __ mov(r2, Operand(r2, ASR, 3)); __ strh(r2, MemOperand(r4, offsetof(T, s))); __ ldm(ia_w, sp, r4.bit() | fp.bit() | pc.bit()); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); t.i = 100000; t.c = 10; t.s = 1000; int res = reinterpret_cast<int>(CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0)); ::printf("f() = %d\n", res); CHECK_EQ(101010, res); CHECK_EQ(100000/2, t.i); CHECK_EQ(10*4, t.c); CHECK_EQ(1000/8, t.s); } TEST(4) { // Test the VFP floating point instructions. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); typedef struct { double a; double b; double c; double d; double e; double f; double g; double h; int i; double j; double m; double n; float o; float p; float x; float y; } T; T t; // Create a function that accepts &t, and loads, manipulates, and stores // the doubles and floats. Assembler assm(isolate, NULL, 0); Label L, C; if (CpuFeatures::IsSupported(VFPv3)) { CpuFeatureScope scope(&assm, VFPv3); __ mov(ip, Operand(sp)); __ stm(db_w, sp, r4.bit() | fp.bit() | lr.bit()); __ sub(fp, ip, Operand(4)); __ mov(r4, Operand(r0)); __ vldr(d6, r4, offsetof(T, a)); __ vldr(d7, r4, offsetof(T, b)); __ vadd(d5, d6, d7); __ vstr(d5, r4, offsetof(T, c)); __ vmla(d5, d6, d7); __ vmls(d5, d5, d6); __ vmov(r2, r3, d5); __ vmov(d4, r2, r3); __ vstr(d4, r4, offsetof(T, b)); // Load t.x and t.y, switch values, and store back to the struct. __ vldr(s0, r4, offsetof(T, x)); __ vldr(s1, r4, offsetof(T, y)); __ vmov(s2, s0); __ vmov(s0, s1); __ vmov(s1, s2); __ vstr(s0, r4, offsetof(T, x)); __ vstr(s1, r4, offsetof(T, y)); // Move a literal into a register that can be encoded in the instruction. __ vmov(d4, 1.0); __ vstr(d4, r4, offsetof(T, e)); // Move a literal into a register that requires 64 bits to encode. // 0x3ff0000010000000 = 1.000000059604644775390625 __ vmov(d4, 1.000000059604644775390625); __ vstr(d4, r4, offsetof(T, d)); // Convert from floating point to integer. __ vmov(d4, 2.0); __ vcvt_s32_f64(s1, d4); __ vstr(s1, r4, offsetof(T, i)); // Convert from integer to floating point. __ mov(lr, Operand(42)); __ vmov(s1, lr); __ vcvt_f64_s32(d4, s1); __ vstr(d4, r4, offsetof(T, f)); // Convert from fixed point to floating point. __ mov(lr, Operand(2468)); __ vmov(s8, lr); __ vcvt_f64_s32(d4, 2); __ vstr(d4, r4, offsetof(T, j)); // Test vabs. __ vldr(d1, r4, offsetof(T, g)); __ vabs(d0, d1); __ vstr(d0, r4, offsetof(T, g)); __ vldr(d2, r4, offsetof(T, h)); __ vabs(d0, d2); __ vstr(d0, r4, offsetof(T, h)); // Test vneg. __ vldr(d1, r4, offsetof(T, m)); __ vneg(d0, d1); __ vstr(d0, r4, offsetof(T, m)); __ vldr(d1, r4, offsetof(T, n)); __ vneg(d0, d1); __ vstr(d0, r4, offsetof(T, n)); // Test vmov for single-precision immediates. __ vmov(s0, 0.25f); __ vstr(s0, r4, offsetof(T, o)); __ vmov(s0, -16.0f); __ vstr(s0, r4, offsetof(T, p)); __ ldm(ia_w, sp, r4.bit() | fp.bit() | pc.bit()); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); t.a = 1.5; t.b = 2.75; t.c = 17.17; t.d = 0.0; t.e = 0.0; t.f = 0.0; t.g = -2718.2818; t.h = 31415926.5; t.i = 0; t.j = 0; t.m = -2718.2818; t.n = 123.456; t.x = 4.5; t.y = 9.0; Object* dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); USE(dummy); CHECK_EQ(-16.0f, t.p); CHECK_EQ(0.25f, t.o); CHECK_EQ(-123.456, t.n); CHECK_EQ(2718.2818, t.m); CHECK_EQ(2, t.i); CHECK_EQ(2718.2818, t.g); CHECK_EQ(31415926.5, t.h); CHECK_EQ(617.0, t.j); CHECK_EQ(42.0, t.f); CHECK_EQ(1.0, t.e); CHECK_EQ(1.000000059604644775390625, t.d); CHECK_EQ(4.25, t.c); CHECK_EQ(-4.1875, t.b); CHECK_EQ(1.5, t.a); CHECK_EQ(4.5f, t.y); CHECK_EQ(9.0f, t.x); } } TEST(5) { // Test the ARMv7 bitfield instructions. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); if (CpuFeatures::IsSupported(ARMv7)) { CpuFeatureScope scope(&assm, ARMv7); // On entry, r0 = 0xAAAAAAAA = 0b10..10101010. __ ubfx(r0, r0, 1, 12); // 0b00..010101010101 = 0x555 __ sbfx(r0, r0, 0, 5); // 0b11..111111110101 = -11 __ bfc(r0, 1, 3); // 0b11..111111110001 = -15 __ mov(r1, Operand(7)); __ bfi(r0, r1, 3, 3); // 0b11..111111111001 = -7 __ mov(pc, Operand(lr)); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F1 f = FUNCTION_CAST<F1>(code->entry()); int res = reinterpret_cast<int>( CALL_GENERATED_CODE(isolate, f, 0xAAAAAAAA, 0, 0, 0, 0)); ::printf("f() = %d\n", res); CHECK_EQ(-7, res); } } TEST(6) { // Test saturating instructions. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); __ usat(r1, 8, Operand(r0)); // Sat 0xFFFF to 0-255 = 0xFF. __ usat(r2, 12, Operand(r0, ASR, 9)); // Sat (0xFFFF>>9) to 0-4095 = 0x7F. __ usat(r3, 1, Operand(r0, LSL, 16)); // Sat (0xFFFF<<16) to 0-1 = 0x0. __ add(r0, r1, Operand(r2)); __ add(r0, r0, Operand(r3)); __ mov(pc, Operand(lr)); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F1 f = FUNCTION_CAST<F1>(code->entry()); int res = reinterpret_cast<int>( CALL_GENERATED_CODE(isolate, f, 0xFFFF, 0, 0, 0, 0)); ::printf("f() = %d\n", res); CHECK_EQ(382, res); } enum VCVTTypes { s32_f64, u32_f64 }; static void TestRoundingMode(VCVTTypes types, VFPRoundingMode mode, double value, int expected, bool expected_exception = false) { Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); Label wrong_exception; __ vmrs(r1); // Set custom FPSCR. __ bic(r2, r1, Operand(kVFPRoundingModeMask | kVFPExceptionMask)); __ orr(r2, r2, Operand(mode)); __ vmsr(r2); // Load value, convert, and move back result to r0 if everything went well. __ vmov(d1, value); switch (types) { case s32_f64: __ vcvt_s32_f64(s0, d1, kFPSCRRounding); break; case u32_f64: __ vcvt_u32_f64(s0, d1, kFPSCRRounding); break; default: UNREACHABLE(); break; } // Check for vfp exceptions __ vmrs(r2); __ tst(r2, Operand(kVFPExceptionMask)); // Check that we behaved as expected. __ b(&wrong_exception, expected_exception ? eq : ne); // There was no exception. Retrieve the result and return. __ vmov(r0, s0); __ mov(pc, Operand(lr)); // The exception behaviour is not what we expected. // Load a special value and return. __ bind(&wrong_exception); __ mov(r0, Operand(11223344)); __ mov(pc, Operand(lr)); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F1 f = FUNCTION_CAST<F1>(code->entry()); int res = reinterpret_cast<int>(CALL_GENERATED_CODE(isolate, f, 0, 0, 0, 0, 0)); ::printf("res = %d\n", res); CHECK_EQ(expected, res); } TEST(7) { CcTest::InitializeVM(); // Test vfp rounding modes. // s32_f64 (double to integer). TestRoundingMode(s32_f64, RN, 0, 0); TestRoundingMode(s32_f64, RN, 0.5, 0); TestRoundingMode(s32_f64, RN, -0.5, 0); TestRoundingMode(s32_f64, RN, 1.5, 2); TestRoundingMode(s32_f64, RN, -1.5, -2); TestRoundingMode(s32_f64, RN, 123.7, 124); TestRoundingMode(s32_f64, RN, -123.7, -124); TestRoundingMode(s32_f64, RN, 123456.2, 123456); TestRoundingMode(s32_f64, RN, -123456.2, -123456); TestRoundingMode(s32_f64, RN, static_cast<double>(kMaxInt), kMaxInt); TestRoundingMode(s32_f64, RN, (kMaxInt + 0.49), kMaxInt); TestRoundingMode(s32_f64, RN, (kMaxInt + 1.0), kMaxInt, true); TestRoundingMode(s32_f64, RN, (kMaxInt + 0.5), kMaxInt, true); TestRoundingMode(s32_f64, RN, static_cast<double>(kMinInt), kMinInt); TestRoundingMode(s32_f64, RN, (kMinInt - 0.5), kMinInt); TestRoundingMode(s32_f64, RN, (kMinInt - 1.0), kMinInt, true); TestRoundingMode(s32_f64, RN, (kMinInt - 0.51), kMinInt, true); TestRoundingMode(s32_f64, RM, 0, 0); TestRoundingMode(s32_f64, RM, 0.5, 0); TestRoundingMode(s32_f64, RM, -0.5, -1); TestRoundingMode(s32_f64, RM, 123.7, 123); TestRoundingMode(s32_f64, RM, -123.7, -124); TestRoundingMode(s32_f64, RM, 123456.2, 123456); TestRoundingMode(s32_f64, RM, -123456.2, -123457); TestRoundingMode(s32_f64, RM, static_cast<double>(kMaxInt), kMaxInt); TestRoundingMode(s32_f64, RM, (kMaxInt + 0.5), kMaxInt); TestRoundingMode(s32_f64, RM, (kMaxInt + 1.0), kMaxInt, true); TestRoundingMode(s32_f64, RM, static_cast<double>(kMinInt), kMinInt); TestRoundingMode(s32_f64, RM, (kMinInt - 0.5), kMinInt, true); TestRoundingMode(s32_f64, RM, (kMinInt + 0.5), kMinInt); TestRoundingMode(s32_f64, RZ, 0, 0); TestRoundingMode(s32_f64, RZ, 0.5, 0); TestRoundingMode(s32_f64, RZ, -0.5, 0); TestRoundingMode(s32_f64, RZ, 123.7, 123); TestRoundingMode(s32_f64, RZ, -123.7, -123); TestRoundingMode(s32_f64, RZ, 123456.2, 123456); TestRoundingMode(s32_f64, RZ, -123456.2, -123456); TestRoundingMode(s32_f64, RZ, static_cast<double>(kMaxInt), kMaxInt); TestRoundingMode(s32_f64, RZ, (kMaxInt + 0.5), kMaxInt); TestRoundingMode(s32_f64, RZ, (kMaxInt + 1.0), kMaxInt, true); TestRoundingMode(s32_f64, RZ, static_cast<double>(kMinInt), kMinInt); TestRoundingMode(s32_f64, RZ, (kMinInt - 0.5), kMinInt); TestRoundingMode(s32_f64, RZ, (kMinInt - 1.0), kMinInt, true); // u32_f64 (double to integer). // Negative values. TestRoundingMode(u32_f64, RN, -0.5, 0); TestRoundingMode(u32_f64, RN, -123456.7, 0, true); TestRoundingMode(u32_f64, RN, static_cast<double>(kMinInt), 0, true); TestRoundingMode(u32_f64, RN, kMinInt - 1.0, 0, true); TestRoundingMode(u32_f64, RM, -0.5, 0, true); TestRoundingMode(u32_f64, RM, -123456.7, 0, true); TestRoundingMode(u32_f64, RM, static_cast<double>(kMinInt), 0, true); TestRoundingMode(u32_f64, RM, kMinInt - 1.0, 0, true); TestRoundingMode(u32_f64, RZ, -0.5, 0); TestRoundingMode(u32_f64, RZ, -123456.7, 0, true); TestRoundingMode(u32_f64, RZ, static_cast<double>(kMinInt), 0, true); TestRoundingMode(u32_f64, RZ, kMinInt - 1.0, 0, true); // Positive values. // kMaxInt is the maximum *signed* integer: 0x7fffffff. static const uint32_t kMaxUInt = 0xffffffffu; TestRoundingMode(u32_f64, RZ, 0, 0); TestRoundingMode(u32_f64, RZ, 0.5, 0); TestRoundingMode(u32_f64, RZ, 123.7, 123); TestRoundingMode(u32_f64, RZ, 123456.2, 123456); TestRoundingMode(u32_f64, RZ, static_cast<double>(kMaxInt), kMaxInt); TestRoundingMode(u32_f64, RZ, (kMaxInt + 0.5), kMaxInt); TestRoundingMode(u32_f64, RZ, (kMaxInt + 1.0), static_cast<uint32_t>(kMaxInt) + 1); TestRoundingMode(u32_f64, RZ, (kMaxUInt + 0.5), kMaxUInt); TestRoundingMode(u32_f64, RZ, (kMaxUInt + 1.0), kMaxUInt, true); TestRoundingMode(u32_f64, RM, 0, 0); TestRoundingMode(u32_f64, RM, 0.5, 0); TestRoundingMode(u32_f64, RM, 123.7, 123); TestRoundingMode(u32_f64, RM, 123456.2, 123456); TestRoundingMode(u32_f64, RM, static_cast<double>(kMaxInt), kMaxInt); TestRoundingMode(u32_f64, RM, (kMaxInt + 0.5), kMaxInt); TestRoundingMode(u32_f64, RM, (kMaxInt + 1.0), static_cast<uint32_t>(kMaxInt) + 1); TestRoundingMode(u32_f64, RM, (kMaxUInt + 0.5), kMaxUInt); TestRoundingMode(u32_f64, RM, (kMaxUInt + 1.0), kMaxUInt, true); TestRoundingMode(u32_f64, RN, 0, 0); TestRoundingMode(u32_f64, RN, 0.5, 0); TestRoundingMode(u32_f64, RN, 1.5, 2); TestRoundingMode(u32_f64, RN, 123.7, 124); TestRoundingMode(u32_f64, RN, 123456.2, 123456); TestRoundingMode(u32_f64, RN, static_cast<double>(kMaxInt), kMaxInt); TestRoundingMode(u32_f64, RN, (kMaxInt + 0.49), kMaxInt); TestRoundingMode(u32_f64, RN, (kMaxInt + 0.5), static_cast<uint32_t>(kMaxInt) + 1); TestRoundingMode(u32_f64, RN, (kMaxUInt + 0.49), kMaxUInt); TestRoundingMode(u32_f64, RN, (kMaxUInt + 0.5), kMaxUInt, true); TestRoundingMode(u32_f64, RN, (kMaxUInt + 1.0), kMaxUInt, true); } TEST(8) { // Test VFP multi load/store with ia_w. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); typedef struct { double a; double b; double c; double d; double e; double f; double g; double h; } D; D d; typedef struct { float a; float b; float c; float d; float e; float f; float g; float h; } F; F f; // Create a function that uses vldm/vstm to move some double and // single precision values around in memory. Assembler assm(isolate, NULL, 0); __ mov(ip, Operand(sp)); __ stm(db_w, sp, r4.bit() | fp.bit() | lr.bit()); __ sub(fp, ip, Operand(4)); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(D, a)))); __ vldm(ia_w, r4, d0, d3); __ vldm(ia_w, r4, d4, d7); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(D, a)))); __ vstm(ia_w, r4, d6, d7); __ vstm(ia_w, r4, d0, d5); __ add(r4, r1, Operand(static_cast<int32_t>(offsetof(F, a)))); __ vldm(ia_w, r4, s0, s3); __ vldm(ia_w, r4, s4, s7); __ add(r4, r1, Operand(static_cast<int32_t>(offsetof(F, a)))); __ vstm(ia_w, r4, s6, s7); __ vstm(ia_w, r4, s0, s5); __ ldm(ia_w, sp, r4.bit() | fp.bit() | pc.bit()); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F4 fn = FUNCTION_CAST<F4>(code->entry()); d.a = 1.1; d.b = 2.2; d.c = 3.3; d.d = 4.4; d.e = 5.5; d.f = 6.6; d.g = 7.7; d.h = 8.8; f.a = 1.0; f.b = 2.0; f.c = 3.0; f.d = 4.0; f.e = 5.0; f.f = 6.0; f.g = 7.0; f.h = 8.0; Object* dummy = CALL_GENERATED_CODE(isolate, fn, &d, &f, 0, 0, 0); USE(dummy); CHECK_EQ(7.7, d.a); CHECK_EQ(8.8, d.b); CHECK_EQ(1.1, d.c); CHECK_EQ(2.2, d.d); CHECK_EQ(3.3, d.e); CHECK_EQ(4.4, d.f); CHECK_EQ(5.5, d.g); CHECK_EQ(6.6, d.h); CHECK_EQ(7.0f, f.a); CHECK_EQ(8.0f, f.b); CHECK_EQ(1.0f, f.c); CHECK_EQ(2.0f, f.d); CHECK_EQ(3.0f, f.e); CHECK_EQ(4.0f, f.f); CHECK_EQ(5.0f, f.g); CHECK_EQ(6.0f, f.h); } TEST(9) { // Test VFP multi load/store with ia. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); typedef struct { double a; double b; double c; double d; double e; double f; double g; double h; } D; D d; typedef struct { float a; float b; float c; float d; float e; float f; float g; float h; } F; F f; // Create a function that uses vldm/vstm to move some double and // single precision values around in memory. Assembler assm(isolate, NULL, 0); __ mov(ip, Operand(sp)); __ stm(db_w, sp, r4.bit() | fp.bit() | lr.bit()); __ sub(fp, ip, Operand(4)); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(D, a)))); __ vldm(ia, r4, d0, d3); __ add(r4, r4, Operand(4 * 8)); __ vldm(ia, r4, d4, d7); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(D, a)))); __ vstm(ia, r4, d6, d7); __ add(r4, r4, Operand(2 * 8)); __ vstm(ia, r4, d0, d5); __ add(r4, r1, Operand(static_cast<int32_t>(offsetof(F, a)))); __ vldm(ia, r4, s0, s3); __ add(r4, r4, Operand(4 * 4)); __ vldm(ia, r4, s4, s7); __ add(r4, r1, Operand(static_cast<int32_t>(offsetof(F, a)))); __ vstm(ia, r4, s6, s7); __ add(r4, r4, Operand(2 * 4)); __ vstm(ia, r4, s0, s5); __ ldm(ia_w, sp, r4.bit() | fp.bit() | pc.bit()); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F4 fn = FUNCTION_CAST<F4>(code->entry()); d.a = 1.1; d.b = 2.2; d.c = 3.3; d.d = 4.4; d.e = 5.5; d.f = 6.6; d.g = 7.7; d.h = 8.8; f.a = 1.0; f.b = 2.0; f.c = 3.0; f.d = 4.0; f.e = 5.0; f.f = 6.0; f.g = 7.0; f.h = 8.0; Object* dummy = CALL_GENERATED_CODE(isolate, fn, &d, &f, 0, 0, 0); USE(dummy); CHECK_EQ(7.7, d.a); CHECK_EQ(8.8, d.b); CHECK_EQ(1.1, d.c); CHECK_EQ(2.2, d.d); CHECK_EQ(3.3, d.e); CHECK_EQ(4.4, d.f); CHECK_EQ(5.5, d.g); CHECK_EQ(6.6, d.h); CHECK_EQ(7.0f, f.a); CHECK_EQ(8.0f, f.b); CHECK_EQ(1.0f, f.c); CHECK_EQ(2.0f, f.d); CHECK_EQ(3.0f, f.e); CHECK_EQ(4.0f, f.f); CHECK_EQ(5.0f, f.g); CHECK_EQ(6.0f, f.h); } TEST(10) { // Test VFP multi load/store with db_w. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); typedef struct { double a; double b; double c; double d; double e; double f; double g; double h; } D; D d; typedef struct { float a; float b; float c; float d; float e; float f; float g; float h; } F; F f; // Create a function that uses vldm/vstm to move some double and // single precision values around in memory. Assembler assm(isolate, NULL, 0); __ mov(ip, Operand(sp)); __ stm(db_w, sp, r4.bit() | fp.bit() | lr.bit()); __ sub(fp, ip, Operand(4)); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(D, h)) + 8)); __ vldm(db_w, r4, d4, d7); __ vldm(db_w, r4, d0, d3); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(D, h)) + 8)); __ vstm(db_w, r4, d0, d5); __ vstm(db_w, r4, d6, d7); __ add(r4, r1, Operand(static_cast<int32_t>(offsetof(F, h)) + 4)); __ vldm(db_w, r4, s4, s7); __ vldm(db_w, r4, s0, s3); __ add(r4, r1, Operand(static_cast<int32_t>(offsetof(F, h)) + 4)); __ vstm(db_w, r4, s0, s5); __ vstm(db_w, r4, s6, s7); __ ldm(ia_w, sp, r4.bit() | fp.bit() | pc.bit()); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F4 fn = FUNCTION_CAST<F4>(code->entry()); d.a = 1.1; d.b = 2.2; d.c = 3.3; d.d = 4.4; d.e = 5.5; d.f = 6.6; d.g = 7.7; d.h = 8.8; f.a = 1.0; f.b = 2.0; f.c = 3.0; f.d = 4.0; f.e = 5.0; f.f = 6.0; f.g = 7.0; f.h = 8.0; Object* dummy = CALL_GENERATED_CODE(isolate, fn, &d, &f, 0, 0, 0); USE(dummy); CHECK_EQ(7.7, d.a); CHECK_EQ(8.8, d.b); CHECK_EQ(1.1, d.c); CHECK_EQ(2.2, d.d); CHECK_EQ(3.3, d.e); CHECK_EQ(4.4, d.f); CHECK_EQ(5.5, d.g); CHECK_EQ(6.6, d.h); CHECK_EQ(7.0f, f.a); CHECK_EQ(8.0f, f.b); CHECK_EQ(1.0f, f.c); CHECK_EQ(2.0f, f.d); CHECK_EQ(3.0f, f.e); CHECK_EQ(4.0f, f.f); CHECK_EQ(5.0f, f.g); CHECK_EQ(6.0f, f.h); } TEST(11) { // Test instructions using the carry flag. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); typedef struct { int32_t a; int32_t b; int32_t c; int32_t d; } I; I i; i.a = 0xabcd0001; i.b = 0xabcd0000; Assembler assm(isolate, NULL, 0); // Test HeapObject untagging. __ ldr(r1, MemOperand(r0, offsetof(I, a))); __ mov(r1, Operand(r1, ASR, 1), SetCC); __ adc(r1, r1, Operand(r1), LeaveCC, cs); __ str(r1, MemOperand(r0, offsetof(I, a))); __ ldr(r2, MemOperand(r0, offsetof(I, b))); __ mov(r2, Operand(r2, ASR, 1), SetCC); __ adc(r2, r2, Operand(r2), LeaveCC, cs); __ str(r2, MemOperand(r0, offsetof(I, b))); // Test corner cases. __ mov(r1, Operand(0xffffffff)); __ mov(r2, Operand::Zero()); __ mov(r3, Operand(r1, ASR, 1), SetCC); // Set the carry. __ adc(r3, r1, Operand(r2)); __ str(r3, MemOperand(r0, offsetof(I, c))); __ mov(r1, Operand(0xffffffff)); __ mov(r2, Operand::Zero()); __ mov(r3, Operand(r2, ASR, 1), SetCC); // Unset the carry. __ adc(r3, r1, Operand(r2)); __ str(r3, MemOperand(r0, offsetof(I, d))); __ mov(pc, Operand(lr)); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); Object* dummy = CALL_GENERATED_CODE(isolate, f, &i, 0, 0, 0, 0); USE(dummy); CHECK_EQ(static_cast<int32_t>(0xabcd0001), i.a); CHECK_EQ(static_cast<int32_t>(0xabcd0000) >> 1, i.b); CHECK_EQ(0x00000000, i.c); CHECK_EQ(static_cast<int32_t>(0xffffffff), i.d); } TEST(12) { // Test chaining of label usages within instructions (issue 1644). CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); Label target; __ b(eq, &target); __ b(ne, &target); __ bind(&target); __ nop(); } TEST(13) { // Test VFP instructions using registers d16-d31. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); if (!CpuFeatures::IsSupported(VFP32DREGS)) { return; } typedef struct { double a; double b; double c; double x; double y; double z; double i; double j; double k; uint32_t low; uint32_t high; } T; T t; // Create a function that accepts &t, and loads, manipulates, and stores // the doubles and floats. Assembler assm(isolate, NULL, 0); Label L, C; if (CpuFeatures::IsSupported(VFPv3)) { CpuFeatureScope scope(&assm, VFPv3); __ stm(db_w, sp, r4.bit() | lr.bit()); // Load a, b, c into d16, d17, d18. __ mov(r4, Operand(r0)); __ vldr(d16, r4, offsetof(T, a)); __ vldr(d17, r4, offsetof(T, b)); __ vldr(d18, r4, offsetof(T, c)); __ vneg(d25, d16); __ vadd(d25, d25, d17); __ vsub(d25, d25, d18); __ vmul(d25, d25, d25); __ vdiv(d25, d25, d18); __ vmov(d16, d25); __ vsqrt(d17, d25); __ vneg(d17, d17); __ vabs(d17, d17); __ vmla(d18, d16, d17); // Store d16, d17, d18 into a, b, c. __ mov(r4, Operand(r0)); __ vstr(d16, r4, offsetof(T, a)); __ vstr(d17, r4, offsetof(T, b)); __ vstr(d18, r4, offsetof(T, c)); // Load x, y, z into d29-d31. __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, x)))); __ vldm(ia_w, r4, d29, d31); // Swap d29 and d30 via r registers. __ vmov(r1, r2, d29); __ vmov(d29, d30); __ vmov(d30, r1, r2); // Convert to and from integer. __ vcvt_s32_f64(s1, d31); __ vcvt_f64_u32(d31, s1); // Store d29-d31 into x, y, z. __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, x)))); __ vstm(ia_w, r4, d29, d31); // Move constants into d20, d21, d22 and store into i, j, k. __ vmov(d20, 14.7610017472335499); __ vmov(d21, 16.0); __ mov(r1, Operand(372106121)); __ mov(r2, Operand(1079146608)); __ vmov(d22, VmovIndexLo, r1); __ vmov(d22, VmovIndexHi, r2); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, i)))); __ vstm(ia_w, r4, d20, d22); // Move d22 into low and high. __ vmov(r4, VmovIndexLo, d22); __ str(r4, MemOperand(r0, offsetof(T, low))); __ vmov(r4, VmovIndexHi, d22); __ str(r4, MemOperand(r0, offsetof(T, high))); __ ldm(ia_w, sp, r4.bit() | pc.bit()); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); t.a = 1.5; t.b = 2.75; t.c = 17.17; t.x = 1.5; t.y = 2.75; t.z = 17.17; Object* dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); USE(dummy); CHECK_EQ(14.7610017472335499, t.a); CHECK_EQ(3.84200491244266251, t.b); CHECK_EQ(73.8818412254460241, t.c); CHECK_EQ(2.75, t.x); CHECK_EQ(1.5, t.y); CHECK_EQ(17.0, t.z); CHECK_EQ(14.7610017472335499, t.i); CHECK_EQ(16.0, t.j); CHECK_EQ(73.8818412254460241, t.k); CHECK_EQ(372106121u, t.low); CHECK_EQ(1079146608u, t.high); } } TEST(14) { // Test the VFP Canonicalized Nan mode. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); typedef struct { double left; double right; double add_result; double sub_result; double mul_result; double div_result; } T; T t; // Create a function that makes the four basic operations. Assembler assm(isolate, NULL, 0); // Ensure FPSCR state (as JSEntryStub does). Label fpscr_done; __ vmrs(r1); __ tst(r1, Operand(kVFPDefaultNaNModeControlBit)); __ b(ne, &fpscr_done); __ orr(r1, r1, Operand(kVFPDefaultNaNModeControlBit)); __ vmsr(r1); __ bind(&fpscr_done); __ vldr(d0, r0, offsetof(T, left)); __ vldr(d1, r0, offsetof(T, right)); __ vadd(d2, d0, d1); __ vstr(d2, r0, offsetof(T, add_result)); __ vsub(d2, d0, d1); __ vstr(d2, r0, offsetof(T, sub_result)); __ vmul(d2, d0, d1); __ vstr(d2, r0, offsetof(T, mul_result)); __ vdiv(d2, d0, d1); __ vstr(d2, r0, offsetof(T, div_result)); __ mov(pc, Operand(lr)); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); t.left = bit_cast<double>(kHoleNanInt64); t.right = 1; t.add_result = 0; t.sub_result = 0; t.mul_result = 0; t.div_result = 0; Object* dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); USE(dummy); const uint32_t kArmNanUpper32 = 0x7ff80000; const uint32_t kArmNanLower32 = 0x00000000; #ifdef DEBUG const uint64_t kArmNanInt64 = (static_cast<uint64_t>(kArmNanUpper32) << 32) | kArmNanLower32; CHECK(kArmNanInt64 != kHoleNanInt64); #endif // With VFP2 the sign of the canonicalized Nan is undefined. So // we remove the sign bit for the upper tests. CHECK_EQ(kArmNanUpper32, (bit_cast<int64_t>(t.add_result) >> 32) & 0x7fffffff); CHECK_EQ(kArmNanLower32, bit_cast<int64_t>(t.add_result) & 0xffffffffu); CHECK_EQ(kArmNanUpper32, (bit_cast<int64_t>(t.sub_result) >> 32) & 0x7fffffff); CHECK_EQ(kArmNanLower32, bit_cast<int64_t>(t.sub_result) & 0xffffffffu); CHECK_EQ(kArmNanUpper32, (bit_cast<int64_t>(t.mul_result) >> 32) & 0x7fffffff); CHECK_EQ(kArmNanLower32, bit_cast<int64_t>(t.mul_result) & 0xffffffffu); CHECK_EQ(kArmNanUpper32, (bit_cast<int64_t>(t.div_result) >> 32) & 0x7fffffff); CHECK_EQ(kArmNanLower32, bit_cast<int64_t>(t.div_result) & 0xffffffffu); } #define CHECK_EQ_SPLAT(field, ex) \ CHECK_EQ(ex, t.field[0]); \ CHECK_EQ(ex, t.field[1]); \ CHECK_EQ(ex, t.field[2]); \ CHECK_EQ(ex, t.field[3]); #define CHECK_EQ_32X4(field, ex0, ex1, ex2, ex3) \ CHECK_EQ(ex0, t.field[0]); \ CHECK_EQ(ex1, t.field[1]); \ CHECK_EQ(ex2, t.field[2]); \ CHECK_EQ(ex3, t.field[3]); #define CHECK_ESTIMATE(expected, tolerance, value) \ CHECK_LT((expected) - (tolerance), value); \ CHECK_GT((expected) + (tolerance), value); #define CHECK_ESTIMATE_SPLAT(field, ex, tol) \ CHECK_ESTIMATE(ex, tol, t.field[0]); \ CHECK_ESTIMATE(ex, tol, t.field[1]); \ CHECK_ESTIMATE(ex, tol, t.field[2]); \ CHECK_ESTIMATE(ex, tol, t.field[3]); #define INT32_TO_FLOAT(val) \ std::round(static_cast<float>(bit_cast<int32_t>(val))) #define UINT32_TO_FLOAT(val) \ std::round(static_cast<float>(bit_cast<uint32_t>(val))) TEST(15) { // Test the Neon instructions. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); typedef struct { uint32_t src0; uint32_t src1; uint32_t src2; uint32_t src3; uint32_t src4; uint32_t src5; uint32_t src6; uint32_t src7; uint32_t dst0; uint32_t dst1; uint32_t dst2; uint32_t dst3; uint32_t dst4; uint32_t dst5; uint32_t dst6; uint32_t dst7; uint32_t srcA0; uint32_t srcA1; uint32_t dstA0; uint32_t dstA1; uint32_t dstA2; uint32_t dstA3; uint32_t dstA4; uint32_t dstA5; uint32_t dstA6; uint32_t dstA7; uint32_t lane_test[4]; uint64_t vmov_to_scalar1, vmov_to_scalar2; uint32_t vmov_from_scalar_s8, vmov_from_scalar_u8; uint32_t vmov_from_scalar_s16, vmov_from_scalar_u16; uint32_t vmov_from_scalar_32; uint32_t vmov[4], vmvn[4]; int32_t vcvt_s32_f32[4]; uint32_t vcvt_u32_f32[4]; float vcvt_f32_s32[4], vcvt_f32_u32[4]; uint32_t vdup8[4], vdup16[4], vdup32[4]; float vabsf[4], vnegf[4]; uint32_t vabs_s8[4], vabs_s16[4], vabs_s32[4]; uint32_t vneg_s8[4], vneg_s16[4], vneg_s32[4]; uint32_t veor[4], vand[4], vorr[4]; float vdupf[4], vaddf[4], vsubf[4], vmulf[4]; uint32_t vmin_s8[4], vmin_u16[4], vmin_s32[4]; uint32_t vmax_s8[4], vmax_u16[4], vmax_s32[4]; uint32_t vadd8[4], vadd16[4], vadd32[4]; uint32_t vsub8[4], vsub16[4], vsub32[4]; uint32_t vmul8[4], vmul16[4], vmul32[4]; uint32_t vceq[4], vceqf[4], vcgef[4], vcgtf[4]; uint32_t vcge_s8[4], vcge_u16[4], vcge_s32[4]; uint32_t vcgt_s8[4], vcgt_u16[4], vcgt_s32[4]; float vrecpe[4], vrecps[4], vrsqrte[4], vrsqrts[4]; float vminf[4], vmaxf[4]; uint32_t vtst[4], vbsl[4]; uint32_t vext[4]; uint32_t vzip8a[4], vzip8b[4], vzip16a[4], vzip16b[4], vzip32a[4], vzip32b[4]; uint32_t vrev64_32[4], vrev64_16[4], vrev64_8[4]; uint32_t vrev32_16[4], vrev32_8[4]; uint32_t vrev16_8[4]; uint32_t vtbl[2], vtbx[2]; } T; T t; // Create a function that accepts &t, and loads, manipulates, and stores // the doubles, floats, and SIMD values. Assembler assm(isolate, NULL, 0); if (CpuFeatures::IsSupported(NEON)) { CpuFeatureScope scope(&assm, NEON); __ stm(db_w, sp, r4.bit() | r5.bit() | lr.bit()); // Move 32 bytes with neon. __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, src0)))); __ vld1(Neon8, NeonListOperand(d0, 4), NeonMemOperand(r4)); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, dst0)))); __ vst1(Neon8, NeonListOperand(d0, 4), NeonMemOperand(r4)); // Expand 8 bytes into 8 words(16 bits). __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, srcA0)))); __ vld1(Neon8, NeonListOperand(d0), NeonMemOperand(r4)); __ vmovl(NeonU8, q0, d0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, dstA0)))); __ vst1(Neon8, NeonListOperand(d0, 2), NeonMemOperand(r4)); // The same expansion, but with different source and destination registers. __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, srcA0)))); __ vld1(Neon8, NeonListOperand(d1), NeonMemOperand(r4)); __ vmovl(NeonU8, q1, d1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, dstA4)))); __ vst1(Neon8, NeonListOperand(d2, 2), NeonMemOperand(r4)); // ARM core register to scalar. __ mov(r4, Operand(0xfffffff8)); __ vmov(d0, 0); __ vmov(NeonS8, d0, 1, r4); __ vmov(NeonS16, d0, 1, r4); __ vmov(NeonS32, d0, 1, r4); __ vstr(d0, r0, offsetof(T, vmov_to_scalar1)); __ vmov(d0, 0); __ vmov(NeonS8, d0, 3, r4); __ vmov(NeonS16, d0, 3, r4); __ vstr(d0, r0, offsetof(T, vmov_to_scalar2)); // Scalar to ARM core register. __ mov(r4, Operand(0xffffff00)); __ mov(r5, Operand(0xffffffff)); __ vmov(d0, r4, r5); __ vmov(NeonS8, r4, d0, 1); __ str(r4, MemOperand(r0, offsetof(T, vmov_from_scalar_s8))); __ vmov(NeonU8, r4, d0, 1); __ str(r4, MemOperand(r0, offsetof(T, vmov_from_scalar_u8))); __ vmov(NeonS16, r4, d0, 1); __ str(r4, MemOperand(r0, offsetof(T, vmov_from_scalar_s16))); __ vmov(NeonU16, r4, d0, 1); __ str(r4, MemOperand(r0, offsetof(T, vmov_from_scalar_u16))); __ vmov(NeonS32, r4, d0, 1); __ str(r4, MemOperand(r0, offsetof(T, vmov_from_scalar_32))); // vmov for q-registers. __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, lane_test)))); __ vld1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); __ vmov(q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmov)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vmvn. __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, lane_test)))); __ vld1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); __ vmvn(q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmvn)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vcvt for q-registers. __ vmov(s0, -1.5); __ vmov(s1, -1); __ vmov(s2, 1); __ vmov(s3, 1.5); __ vcvt_s32_f32(q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vcvt_s32_f32)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ vcvt_u32_f32(q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vcvt_u32_f32)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ mov(r4, Operand(kMinInt)); __ mov(r5, Operand(kMaxInt)); __ vmov(d0, r4, r5); __ mov(r4, Operand(kMaxUInt32)); __ mov(r5, Operand(kMinInt + 1)); __ vmov(d1, r4, r5); // q0 = [kMinInt, kMaxInt, kMaxUInt32, kMinInt + 1] __ vcvt_f32_s32(q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vcvt_f32_s32)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ vcvt_f32_u32(q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vcvt_f32_u32)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vdup (integer). __ mov(r4, Operand(0xa)); __ vdup(Neon8, q0, r4); __ vdup(Neon16, q1, r4); __ vdup(Neon32, q2, r4); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vdup8)))); __ vst1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vdup16)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vdup32)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); // vdup (float). __ vmov(s0, -1.0); __ vdup(q0, s0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vdupf)))); __ vst1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); // vabs (float). __ vmov(s0, -1.0); __ vmov(s1, -0.0); __ vmov(s2, 0.0); __ vmov(s3, 1.0); __ vabs(q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vabsf)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vneg (float). __ vneg(q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vnegf)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vabs (integer). __ mov(r4, Operand(0x7f7f7f7f)); __ mov(r5, Operand(0x01010101)); __ vmov(d0, r4, r5); __ mov(r4, Operand(0xffffffff)); __ mov(r5, Operand(0x80808080)); __ vmov(d1, r4, r5); __ vabs(Neon8, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vabs_s8)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ vabs(Neon16, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vabs_s16)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ vabs(Neon32, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vabs_s32)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vneg (integer). __ vneg(Neon8, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vneg_s8)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ vneg(Neon16, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vneg_s16)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ vneg(Neon32, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vneg_s32)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // veor. __ mov(r4, Operand(0xaa)); __ vdup(Neon16, q0, r4); __ mov(r4, Operand(0x55)); __ vdup(Neon16, q1, r4); __ veor(q1, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, veor)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vand. __ mov(r4, Operand(0xff)); __ vdup(Neon16, q0, r4); __ mov(r4, Operand(0xfe)); __ vdup(Neon16, q1, r4); __ vand(q1, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vand)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vorr. __ mov(r4, Operand(0xaa)); __ vdup(Neon16, q0, r4); __ mov(r4, Operand(0x55)); __ vdup(Neon16, q1, r4); __ vorr(q1, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vorr)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vmin (float). __ vmov(s4, 2.0); __ vdup(q0, s4); __ vmov(s4, 1.0); __ vdup(q1, s4); __ vmin(q1, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vminf)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vmax (float). __ vmov(s4, 2.0); __ vdup(q0, s4); __ vmov(s4, 1.0); __ vdup(q1, s4); __ vmax(q1, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmaxf)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vadd (float). __ vmov(s4, 1.0); __ vdup(q0, s4); __ vdup(q1, s4); __ vadd(q1, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vaddf)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vsub (float). __ vmov(s4, 2.0); __ vdup(q0, s4); __ vmov(s4, 1.0); __ vdup(q1, s4); __ vsub(q1, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vsubf)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vmul (float). __ vmov(s4, 2.0); __ vdup(q0, s4); __ vdup(q1, s4); __ vmul(q1, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmulf)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vrecpe. __ vmov(s4, 2.0); __ vdup(q0, s4); __ vrecpe(q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vrecpe)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vrecps. __ vmov(s4, 2.0); __ vdup(q0, s4); __ vmov(s4, 1.5); __ vdup(q1, s4); __ vrecps(q1, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vrecps)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vrsqrte. __ vmov(s4, 4.0); __ vdup(q0, s4); __ vrsqrte(q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vrsqrte)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vrsqrts. __ vmov(s4, 2.0); __ vdup(q0, s4); __ vmov(s4, 2.5); __ vdup(q1, s4); __ vrsqrts(q1, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vrsqrts)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vceq (float). __ vmov(s4, 1.0); __ vdup(q0, s4); __ vdup(q1, s4); __ vceq(q1, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vceqf)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vcge (float). __ vmov(s0, 1.0); __ vmov(s1, -1.0); __ vmov(s2, -0.0); __ vmov(s3, 0.0); __ vdup(q1, s3); __ vcge(q2, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vcgef)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); __ vcgt(q2, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vcgtf)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); // vmin/vmax integer. __ mov(r4, Operand(0x03)); __ vdup(Neon16, q0, r4); __ vdup(Neon8, q1, r4); __ vmin(NeonS8, q2, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmin_s8)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); __ vmax(NeonS8, q2, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmax_s8)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); __ mov(r4, Operand(0xff)); __ vdup(Neon16, q0, r4); __ vdup(Neon8, q1, r4); __ vmin(NeonU16, q2, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmin_u16)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); __ vmax(NeonU16, q2, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmax_u16)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); __ mov(r4, Operand(0xff)); __ vdup(Neon32, q0, r4); __ vdup(Neon8, q1, r4); __ vmin(NeonS32, q2, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmin_s32)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); __ vmax(NeonS32, q2, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmax_s32)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); // vadd (integer). __ mov(r4, Operand(0x81)); __ vdup(Neon8, q0, r4); __ mov(r4, Operand(0x82)); __ vdup(Neon8, q1, r4); __ vadd(Neon8, q1, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vadd8)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ mov(r4, Operand(0x8001)); __ vdup(Neon16, q0, r4); __ mov(r4, Operand(0x8002)); __ vdup(Neon16, q1, r4); __ vadd(Neon16, q1, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vadd16)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ mov(r4, Operand(0x80000001)); __ vdup(Neon32, q0, r4); __ mov(r4, Operand(0x80000002)); __ vdup(Neon32, q1, r4); __ vadd(Neon32, q1, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vadd32)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vsub (integer). __ mov(r4, Operand(0x01)); __ vdup(Neon8, q0, r4); __ mov(r4, Operand(0x03)); __ vdup(Neon8, q1, r4); __ vsub(Neon8, q1, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vsub8)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ mov(r4, Operand(0x0001)); __ vdup(Neon16, q0, r4); __ mov(r4, Operand(0x0003)); __ vdup(Neon16, q1, r4); __ vsub(Neon16, q1, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vsub16)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ mov(r4, Operand(0x00000001)); __ vdup(Neon32, q0, r4); __ mov(r4, Operand(0x00000003)); __ vdup(Neon32, q1, r4); __ vsub(Neon32, q1, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vsub32)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vmul (integer). __ mov(r4, Operand(0x02)); __ vdup(Neon8, q0, r4); __ vmul(Neon8, q1, q0, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmul8)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ mov(r4, Operand(0x0002)); __ vdup(Neon16, q0, r4); __ vmul(Neon16, q1, q0, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmul16)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ mov(r4, Operand(0x00000002)); __ vdup(Neon32, q0, r4); __ vmul(Neon32, q1, q0, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vmul32)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vceq. __ mov(r4, Operand(0x03)); __ vdup(Neon8, q0, r4); __ vdup(Neon16, q1, r4); __ vceq(Neon8, q1, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vceq)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vcge/vcgt (integer). __ mov(r4, Operand(0x03)); __ vdup(Neon16, q0, r4); __ vdup(Neon8, q1, r4); __ vcge(NeonS8, q2, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vcge_s8)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); __ vcgt(NeonS8, q2, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vcgt_s8)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); __ mov(r4, Operand(0xff)); __ vdup(Neon16, q0, r4); __ vdup(Neon8, q1, r4); __ vcge(NeonU16, q2, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vcge_u16)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); __ vcgt(NeonU16, q2, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vcgt_u16)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); __ mov(r4, Operand(0xff)); __ vdup(Neon32, q0, r4); __ vdup(Neon8, q1, r4); __ vcge(NeonS32, q2, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vcge_s32)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); __ vcgt(NeonS32, q2, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vcgt_s32)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); // vtst. __ mov(r4, Operand(0x03)); __ vdup(Neon8, q0, r4); __ mov(r4, Operand(0x02)); __ vdup(Neon16, q1, r4); __ vtst(Neon8, q1, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vtst)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vbsl. __ mov(r4, Operand(0x00ff)); __ vdup(Neon16, q0, r4); __ mov(r4, Operand(0x01)); __ vdup(Neon8, q1, r4); __ mov(r4, Operand(0x02)); __ vdup(Neon8, q2, r4); __ vbsl(q0, q1, q2); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vbsl)))); __ vst1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); // vext. __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, lane_test)))); __ vld1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); __ vmov(q1, q0); __ vext(q2, q0, q1, 3); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vext)))); __ vst1(Neon8, NeonListOperand(q2), NeonMemOperand(r4)); // vzip. __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, lane_test)))); __ vld1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); __ vmov(q1, q0); __ vzip(Neon8, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vzip8a)))); __ vst1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vzip8b)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, lane_test)))); __ vld1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); __ vmov(q1, q0); __ vzip(Neon16, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vzip16a)))); __ vst1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vzip16b)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, lane_test)))); __ vld1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); __ vmov(q1, q0); __ vzip(Neon32, q0, q1); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vzip32a)))); __ vst1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vzip32b)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vrev64/32/16 __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, lane_test)))); __ vld1(Neon8, NeonListOperand(q0), NeonMemOperand(r4)); __ vrev64(Neon32, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vrev64_32)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ vrev64(Neon16, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vrev64_16)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ vrev64(Neon8, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vrev64_8)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ vrev32(Neon16, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vrev32_16)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ vrev32(Neon8, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vrev32_8)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); __ vrev16(Neon8, q1, q0); __ add(r4, r0, Operand(static_cast<int32_t>(offsetof(T, vrev16_8)))); __ vst1(Neon8, NeonListOperand(q1), NeonMemOperand(r4)); // vtb[l/x]. __ mov(r4, Operand(0x06040200)); __ mov(r5, Operand(0xff050301)); __ vmov(d2, r4, r5); // d2 = ff05030106040200 __ vtbl(d0, NeonListOperand(d2, 1), d2); __ vstr(d0, r0, offsetof(T, vtbl)); __ vtbx(d2, NeonListOperand(d2, 1), d2); __ vstr(d2, r0, offsetof(T, vtbx)); // Restore and return. __ ldm(ia_w, sp, r4.bit() | r5.bit() | pc.bit()); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); t.src0 = 0x01020304; t.src1 = 0x11121314; t.src2 = 0x21222324; t.src3 = 0x31323334; t.src4 = 0x41424344; t.src5 = 0x51525354; t.src6 = 0x61626364; t.src7 = 0x71727374; t.dst0 = 0; t.dst1 = 0; t.dst2 = 0; t.dst3 = 0; t.dst4 = 0; t.dst5 = 0; t.dst6 = 0; t.dst7 = 0; t.srcA0 = 0x41424344; t.srcA1 = 0x81828384; t.dstA0 = 0; t.dstA1 = 0; t.dstA2 = 0; t.dstA3 = 0; t.dstA4 = 0; t.dstA5 = 0; t.dstA6 = 0; t.dstA7 = 0; t.lane_test[0] = 0x03020100; t.lane_test[1] = 0x07060504; t.lane_test[2] = 0x0b0a0908; t.lane_test[3] = 0x0f0e0d0c; Object* dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); USE(dummy); CHECK_EQ(0x01020304u, t.dst0); CHECK_EQ(0x11121314u, t.dst1); CHECK_EQ(0x21222324u, t.dst2); CHECK_EQ(0x31323334u, t.dst3); CHECK_EQ(0x41424344u, t.dst4); CHECK_EQ(0x51525354u, t.dst5); CHECK_EQ(0x61626364u, t.dst6); CHECK_EQ(0x71727374u, t.dst7); CHECK_EQ(0x00430044u, t.dstA0); CHECK_EQ(0x00410042u, t.dstA1); CHECK_EQ(0x00830084u, t.dstA2); CHECK_EQ(0x00810082u, t.dstA3); CHECK_EQ(0x00430044u, t.dstA4); CHECK_EQ(0x00410042u, t.dstA5); CHECK_EQ(0x00830084u, t.dstA6); CHECK_EQ(0x00810082u, t.dstA7); CHECK_EQ(0xfffffff8fff8f800u, t.vmov_to_scalar1); CHECK_EQ(0xfff80000f8000000u, t.vmov_to_scalar2); CHECK_EQ(0xFFFFFFFFu, t.vmov_from_scalar_s8); CHECK_EQ(0xFFu, t.vmov_from_scalar_u8); CHECK_EQ(0xFFFFFFFFu, t.vmov_from_scalar_s16); CHECK_EQ(0xFFFFu, t.vmov_from_scalar_u16); CHECK_EQ(0xFFFFFFFFu, t.vmov_from_scalar_32); CHECK_EQ_32X4(vmov, 0x03020100u, 0x07060504u, 0x0b0a0908u, 0x0f0e0d0cu); CHECK_EQ_32X4(vmvn, 0xfcfdfeffu, 0xf8f9fafbu, 0xf4f5f6f7u, 0xf0f1f2f3u); CHECK_EQ_SPLAT(vdup8, 0x0a0a0a0au); CHECK_EQ_SPLAT(vdup16, 0x000a000au); CHECK_EQ_SPLAT(vdup32, 0x0000000au); CHECK_EQ_SPLAT(vdupf, -1.0); // src: [-1, -1, 1, 1] CHECK_EQ_32X4(vcvt_s32_f32, -1, -1, 1, 1); CHECK_EQ_32X4(vcvt_u32_f32, 0u, 0u, 1u, 1u); // src: [kMinInt, kMaxInt, kMaxUInt32, kMinInt + 1] CHECK_EQ_32X4(vcvt_f32_s32, INT32_TO_FLOAT(kMinInt), INT32_TO_FLOAT(kMaxInt), INT32_TO_FLOAT(kMaxUInt32), INT32_TO_FLOAT(kMinInt + 1)); CHECK_EQ_32X4(vcvt_f32_u32, UINT32_TO_FLOAT(kMinInt), UINT32_TO_FLOAT(kMaxInt), UINT32_TO_FLOAT(kMaxUInt32), UINT32_TO_FLOAT(kMinInt + 1)); CHECK_EQ_32X4(vabsf, 1.0, 0.0, 0.0, 1.0); CHECK_EQ_32X4(vnegf, 1.0, 0.0, -0.0, -1.0); // src: [0x7f7f7f7f, 0x01010101, 0xffffffff, 0x80808080] CHECK_EQ_32X4(vabs_s8, 0x7f7f7f7fu, 0x01010101u, 0x01010101u, 0x80808080u); CHECK_EQ_32X4(vabs_s16, 0x7f7f7f7fu, 0x01010101u, 0x00010001u, 0x7f807f80u); CHECK_EQ_32X4(vabs_s32, 0x7f7f7f7fu, 0x01010101u, 0x00000001u, 0x7f7f7f80u); CHECK_EQ_32X4(vneg_s8, 0x81818181u, 0xffffffffu, 0x01010101u, 0x80808080u); CHECK_EQ_32X4(vneg_s16, 0x80818081u, 0xfefffeffu, 0x00010001u, 0x7f807f80u); CHECK_EQ_32X4(vneg_s32, 0x80808081u, 0xfefefeffu, 0x00000001u, 0x7f7f7f80u); CHECK_EQ_SPLAT(veor, 0x00ff00ffu); CHECK_EQ_SPLAT(vand, 0x00fe00feu); CHECK_EQ_SPLAT(vorr, 0x00ff00ffu); CHECK_EQ_SPLAT(vaddf, 2.0); CHECK_EQ_SPLAT(vminf, 1.0); CHECK_EQ_SPLAT(vmaxf, 2.0); CHECK_EQ_SPLAT(vsubf, -1.0); CHECK_EQ_SPLAT(vmulf, 4.0); CHECK_ESTIMATE_SPLAT(vrecpe, 0.5f, 0.1f); // 1 / 2 CHECK_EQ_SPLAT(vrecps, -1.0f); // 2 - (2 * 1.5) CHECK_ESTIMATE_SPLAT(vrsqrte, 0.5f, 0.1f); // 1 / sqrt(4) CHECK_EQ_SPLAT(vrsqrts, -1.0f); // (3 - (2 * 2.5)) / 2 CHECK_EQ_SPLAT(vceqf, 0xffffffffu); // [0] >= [-1, 1, -0, 0] CHECK_EQ_32X4(vcgef, 0u, 0xffffffffu, 0xffffffffu, 0xffffffffu); CHECK_EQ_32X4(vcgtf, 0u, 0xffffffffu, 0u, 0u); // [0, 3, 0, 3, ...] and [3, 3, 3, 3, ...] CHECK_EQ_SPLAT(vmin_s8, 0x00030003u); CHECK_EQ_SPLAT(vmax_s8, 0x03030303u); // [0x00ff, 0x00ff, ...] and [0xffff, 0xffff, ...] CHECK_EQ_SPLAT(vmin_u16, 0x00ff00ffu); CHECK_EQ_SPLAT(vmax_u16, 0xffffffffu); // [0x000000ff, 0x000000ff, ...] and [0xffffffff, 0xffffffff, ...] CHECK_EQ_SPLAT(vmin_s32, 0xffffffffu); CHECK_EQ_SPLAT(vmax_s32, 0xffu); CHECK_EQ_SPLAT(vadd8, 0x03030303u); CHECK_EQ_SPLAT(vadd16, 0x00030003u); CHECK_EQ_SPLAT(vadd32, 0x00000003u); CHECK_EQ_SPLAT(vsub8, 0xfefefefeu); CHECK_EQ_SPLAT(vsub16, 0xfffefffeu); CHECK_EQ_SPLAT(vsub32, 0xfffffffeu); CHECK_EQ_SPLAT(vmul8, 0x04040404u); CHECK_EQ_SPLAT(vmul16, 0x00040004u); CHECK_EQ_SPLAT(vmul32, 0x00000004u); CHECK_EQ_SPLAT(vceq, 0x00ff00ffu); // [0, 3, 0, 3, ...] >= [3, 3, 3, 3, ...] CHECK_EQ_SPLAT(vcge_s8, 0x00ff00ffu); CHECK_EQ_SPLAT(vcgt_s8, 0u); // [0x00ff, 0x00ff, ...] >= [0xffff, 0xffff, ...] CHECK_EQ_SPLAT(vcge_u16, 0u); CHECK_EQ_SPLAT(vcgt_u16, 0u); // [0x000000ff, 0x000000ff, ...] >= [0xffffffff, 0xffffffff, ...] CHECK_EQ_SPLAT(vcge_s32, 0xffffffffu); CHECK_EQ_SPLAT(vcgt_s32, 0xffffffffu); CHECK_EQ_SPLAT(vtst, 0x00ff00ffu); CHECK_EQ_SPLAT(vbsl, 0x02010201u); CHECK_EQ_32X4(vext, 0x06050403u, 0x0a090807u, 0x0e0d0c0bu, 0x0201000fu); CHECK_EQ_32X4(vzip8a, 0x01010000u, 0x03030202u, 0x05050404u, 0x07070606u); CHECK_EQ_32X4(vzip8b, 0x09090808u, 0x0b0b0a0au, 0x0d0d0c0cu, 0x0f0f0e0eu); CHECK_EQ_32X4(vzip16a, 0x01000100u, 0x03020302u, 0x05040504u, 0x07060706u); CHECK_EQ_32X4(vzip16b, 0x09080908u, 0x0b0a0b0au, 0x0d0c0d0cu, 0x0f0e0f0eu); CHECK_EQ_32X4(vzip32a, 0x03020100u, 0x03020100u, 0x07060504u, 0x07060504u); CHECK_EQ_32X4(vzip32b, 0x0b0a0908u, 0x0b0a0908u, 0x0f0e0d0cu, 0x0f0e0d0cu); // src: 0 1 2 3 4 5 6 7 8 9 a b c d e f (little endian) CHECK_EQ_32X4(vrev64_32, 0x07060504u, 0x03020100u, 0x0f0e0d0cu, 0x0b0a0908u); CHECK_EQ_32X4(vrev64_16, 0x05040706u, 0x01000302u, 0x0d0c0f0eu, 0x09080b0au); CHECK_EQ_32X4(vrev64_8, 0x04050607u, 0x00010203u, 0x0c0d0e0fu, 0x08090a0bu); CHECK_EQ_32X4(vrev32_16, 0x01000302u, 0x05040706u, 0x09080b0au, 0x0d0c0f0eu); CHECK_EQ_32X4(vrev32_8, 0x00010203u, 0x04050607u, 0x08090a0bu, 0x0c0d0e0fu); CHECK_EQ_32X4(vrev16_8, 0x02030001u, 0x06070405u, 0x0a0b0809u, 0x0e0f0c0du); CHECK_EQ(0x05010400u, t.vtbl[0]); CHECK_EQ(0x00030602u, t.vtbl[1]); CHECK_EQ(0x05010400u, t.vtbx[0]); CHECK_EQ(0xff030602u, t.vtbx[1]); } } TEST(16) { // Test the pkh, uxtb, uxtab and uxtb16 instructions. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); typedef struct { uint32_t src0; uint32_t src1; uint32_t src2; uint32_t dst0; uint32_t dst1; uint32_t dst2; uint32_t dst3; uint32_t dst4; } T; T t; // Create a function that accepts &t, and loads, manipulates, and stores // the doubles and floats. Assembler assm(isolate, NULL, 0); __ stm(db_w, sp, r4.bit() | lr.bit()); __ mov(r4, Operand(r0)); __ ldr(r0, MemOperand(r4, offsetof(T, src0))); __ ldr(r1, MemOperand(r4, offsetof(T, src1))); __ pkhbt(r2, r0, Operand(r1, LSL, 8)); __ str(r2, MemOperand(r4, offsetof(T, dst0))); __ pkhtb(r2, r0, Operand(r1, ASR, 8)); __ str(r2, MemOperand(r4, offsetof(T, dst1))); __ uxtb16(r2, r0, 8); __ str(r2, MemOperand(r4, offsetof(T, dst2))); __ uxtb(r2, r0, 8); __ str(r2, MemOperand(r4, offsetof(T, dst3))); __ ldr(r0, MemOperand(r4, offsetof(T, src2))); __ uxtab(r2, r0, r1, 8); __ str(r2, MemOperand(r4, offsetof(T, dst4))); __ ldm(ia_w, sp, r4.bit() | pc.bit()); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); t.src0 = 0x01020304; t.src1 = 0x11121314; t.src2 = 0x11121300; t.dst0 = 0; t.dst1 = 0; t.dst2 = 0; t.dst3 = 0; t.dst4 = 0; Object* dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); USE(dummy); CHECK_EQ(0x12130304u, t.dst0); CHECK_EQ(0x01021213u, t.dst1); CHECK_EQ(0x00010003u, t.dst2); CHECK_EQ(0x00000003u, t.dst3); CHECK_EQ(0x11121313u, t.dst4); } TEST(17) { // Test generating labels at high addresses. // Should not assert. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); // Generate a code segment that will be longer than 2^24 bytes. Assembler assm(isolate, NULL, 0); for (size_t i = 0; i < 1 << 23 ; ++i) { // 2^23 __ nop(); } Label target; __ b(eq, &target); __ bind(&target); __ nop(); } #define TEST_SDIV(expected_, dividend_, divisor_) \ t.dividend = dividend_; \ t.divisor = divisor_; \ t.result = 0; \ dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); \ CHECK_EQ(expected_, t.result); TEST(sdiv) { // Test the sdiv. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); struct T { int32_t dividend; int32_t divisor; int32_t result; } t; if (CpuFeatures::IsSupported(SUDIV)) { CpuFeatureScope scope(&assm, SUDIV); __ mov(r3, Operand(r0)); __ ldr(r0, MemOperand(r3, offsetof(T, dividend))); __ ldr(r1, MemOperand(r3, offsetof(T, divisor))); __ sdiv(r2, r0, r1); __ str(r2, MemOperand(r3, offsetof(T, result))); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); Object* dummy; TEST_SDIV(0, kMinInt, 0); TEST_SDIV(0, 1024, 0); TEST_SDIV(1073741824, kMinInt, -2); TEST_SDIV(kMinInt, kMinInt, -1); TEST_SDIV(5, 10, 2); TEST_SDIV(3, 10, 3); TEST_SDIV(-5, 10, -2); TEST_SDIV(-3, 10, -3); TEST_SDIV(-5, -10, 2); TEST_SDIV(-3, -10, 3); TEST_SDIV(5, -10, -2); TEST_SDIV(3, -10, -3); USE(dummy); } } #undef TEST_SDIV #define TEST_UDIV(expected_, dividend_, divisor_) \ t.dividend = dividend_; \ t.divisor = divisor_; \ t.result = 0; \ dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); \ CHECK_EQ(expected_, t.result); TEST(udiv) { // Test the udiv. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); struct T { uint32_t dividend; uint32_t divisor; uint32_t result; } t; if (CpuFeatures::IsSupported(SUDIV)) { CpuFeatureScope scope(&assm, SUDIV); __ mov(r3, Operand(r0)); __ ldr(r0, MemOperand(r3, offsetof(T, dividend))); __ ldr(r1, MemOperand(r3, offsetof(T, divisor))); __ sdiv(r2, r0, r1); __ str(r2, MemOperand(r3, offsetof(T, result))); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); Object* dummy; TEST_UDIV(0u, 0, 0); TEST_UDIV(0u, 1024, 0); TEST_UDIV(5u, 10, 2); TEST_UDIV(3u, 10, 3); USE(dummy); } } #undef TEST_UDIV TEST(smmla) { CcTest::InitializeVM(); Isolate* const isolate = CcTest::i_isolate(); HandleScope scope(isolate); RandomNumberGenerator* const rng = isolate->random_number_generator(); Assembler assm(isolate, nullptr, 0); __ smmla(r1, r1, r2, r3); __ str(r1, MemOperand(r0)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef OBJECT_PRINT code->Print(std::cout); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); for (size_t i = 0; i < 128; ++i) { int32_t r, x = rng->NextInt(), y = rng->NextInt(), z = rng->NextInt(); Object* dummy = CALL_GENERATED_CODE(isolate, f, &r, x, y, z, 0); CHECK_EQ(bits::SignedMulHighAndAdd32(x, y, z), r); USE(dummy); } } TEST(smmul) { CcTest::InitializeVM(); Isolate* const isolate = CcTest::i_isolate(); HandleScope scope(isolate); RandomNumberGenerator* const rng = isolate->random_number_generator(); Assembler assm(isolate, nullptr, 0); __ smmul(r1, r1, r2); __ str(r1, MemOperand(r0)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef OBJECT_PRINT code->Print(std::cout); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); for (size_t i = 0; i < 128; ++i) { int32_t r, x = rng->NextInt(), y = rng->NextInt(); Object* dummy = CALL_GENERATED_CODE(isolate, f, &r, x, y, 0, 0); CHECK_EQ(bits::SignedMulHigh32(x, y), r); USE(dummy); } } TEST(sxtb) { CcTest::InitializeVM(); Isolate* const isolate = CcTest::i_isolate(); HandleScope scope(isolate); RandomNumberGenerator* const rng = isolate->random_number_generator(); Assembler assm(isolate, nullptr, 0); __ sxtb(r1, r1); __ str(r1, MemOperand(r0)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef OBJECT_PRINT code->Print(std::cout); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); for (size_t i = 0; i < 128; ++i) { int32_t r, x = rng->NextInt(); Object* dummy = CALL_GENERATED_CODE(isolate, f, &r, x, 0, 0, 0); CHECK_EQ(static_cast<int32_t>(static_cast<int8_t>(x)), r); USE(dummy); } } TEST(sxtab) { CcTest::InitializeVM(); Isolate* const isolate = CcTest::i_isolate(); HandleScope scope(isolate); RandomNumberGenerator* const rng = isolate->random_number_generator(); Assembler assm(isolate, nullptr, 0); __ sxtab(r1, r2, r1); __ str(r1, MemOperand(r0)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef OBJECT_PRINT code->Print(std::cout); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); for (size_t i = 0; i < 128; ++i) { int32_t r, x = rng->NextInt(), y = rng->NextInt(); Object* dummy = CALL_GENERATED_CODE(isolate, f, &r, x, y, 0, 0); CHECK_EQ(static_cast<int32_t>(static_cast<int8_t>(x)) + y, r); USE(dummy); } } TEST(sxth) { CcTest::InitializeVM(); Isolate* const isolate = CcTest::i_isolate(); HandleScope scope(isolate); RandomNumberGenerator* const rng = isolate->random_number_generator(); Assembler assm(isolate, nullptr, 0); __ sxth(r1, r1); __ str(r1, MemOperand(r0)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef OBJECT_PRINT code->Print(std::cout); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); for (size_t i = 0; i < 128; ++i) { int32_t r, x = rng->NextInt(); Object* dummy = CALL_GENERATED_CODE(isolate, f, &r, x, 0, 0, 0); CHECK_EQ(static_cast<int32_t>(static_cast<int16_t>(x)), r); USE(dummy); } } TEST(sxtah) { CcTest::InitializeVM(); Isolate* const isolate = CcTest::i_isolate(); HandleScope scope(isolate); RandomNumberGenerator* const rng = isolate->random_number_generator(); Assembler assm(isolate, nullptr, 0); __ sxtah(r1, r2, r1); __ str(r1, MemOperand(r0)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef OBJECT_PRINT code->Print(std::cout); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); for (size_t i = 0; i < 128; ++i) { int32_t r, x = rng->NextInt(), y = rng->NextInt(); Object* dummy = CALL_GENERATED_CODE(isolate, f, &r, x, y, 0, 0); CHECK_EQ(static_cast<int32_t>(static_cast<int16_t>(x)) + y, r); USE(dummy); } } TEST(uxtb) { CcTest::InitializeVM(); Isolate* const isolate = CcTest::i_isolate(); HandleScope scope(isolate); RandomNumberGenerator* const rng = isolate->random_number_generator(); Assembler assm(isolate, nullptr, 0); __ uxtb(r1, r1); __ str(r1, MemOperand(r0)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef OBJECT_PRINT code->Print(std::cout); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); for (size_t i = 0; i < 128; ++i) { int32_t r, x = rng->NextInt(); Object* dummy = CALL_GENERATED_CODE(isolate, f, &r, x, 0, 0, 0); CHECK_EQ(static_cast<int32_t>(static_cast<uint8_t>(x)), r); USE(dummy); } } TEST(uxtab) { CcTest::InitializeVM(); Isolate* const isolate = CcTest::i_isolate(); HandleScope scope(isolate); RandomNumberGenerator* const rng = isolate->random_number_generator(); Assembler assm(isolate, nullptr, 0); __ uxtab(r1, r2, r1); __ str(r1, MemOperand(r0)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef OBJECT_PRINT code->Print(std::cout); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); for (size_t i = 0; i < 128; ++i) { int32_t r, x = rng->NextInt(), y = rng->NextInt(); Object* dummy = CALL_GENERATED_CODE(isolate, f, &r, x, y, 0, 0); CHECK_EQ(static_cast<int32_t>(static_cast<uint8_t>(x)) + y, r); USE(dummy); } } TEST(uxth) { CcTest::InitializeVM(); Isolate* const isolate = CcTest::i_isolate(); HandleScope scope(isolate); RandomNumberGenerator* const rng = isolate->random_number_generator(); Assembler assm(isolate, nullptr, 0); __ uxth(r1, r1); __ str(r1, MemOperand(r0)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef OBJECT_PRINT code->Print(std::cout); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); for (size_t i = 0; i < 128; ++i) { int32_t r, x = rng->NextInt(); Object* dummy = CALL_GENERATED_CODE(isolate, f, &r, x, 0, 0, 0); CHECK_EQ(static_cast<int32_t>(static_cast<uint16_t>(x)), r); USE(dummy); } } TEST(uxtah) { CcTest::InitializeVM(); Isolate* const isolate = CcTest::i_isolate(); HandleScope scope(isolate); RandomNumberGenerator* const rng = isolate->random_number_generator(); Assembler assm(isolate, nullptr, 0); __ uxtah(r1, r2, r1); __ str(r1, MemOperand(r0)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef OBJECT_PRINT code->Print(std::cout); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); for (size_t i = 0; i < 128; ++i) { int32_t r, x = rng->NextInt(), y = rng->NextInt(); Object* dummy = CALL_GENERATED_CODE(isolate, f, &r, x, y, 0, 0); CHECK_EQ(static_cast<int32_t>(static_cast<uint16_t>(x)) + y, r); USE(dummy); } } #define TEST_RBIT(expected_, input_) \ t.input = input_; \ t.result = 0; \ dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); \ CHECK_EQ(static_cast<uint32_t>(expected_), t.result); TEST(rbit) { CcTest::InitializeVM(); Isolate* const isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, nullptr, 0); if (CpuFeatures::IsSupported(ARMv7)) { CpuFeatureScope scope(&assm, ARMv7); typedef struct { uint32_t input; uint32_t result; } T; T t; __ ldr(r1, MemOperand(r0, offsetof(T, input))); __ rbit(r1, r1); __ str(r1, MemOperand(r0, offsetof(T, result))); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef OBJECT_PRINT code->Print(std::cout); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); Object* dummy = NULL; TEST_RBIT(0xffffffff, 0xffffffff); TEST_RBIT(0x00000000, 0x00000000); TEST_RBIT(0xffff0000, 0x0000ffff); TEST_RBIT(0xff00ff00, 0x00ff00ff); TEST_RBIT(0xf0f0f0f0, 0x0f0f0f0f); TEST_RBIT(0x1e6a2c48, 0x12345678); USE(dummy); } } TEST(code_relative_offset) { // Test extracting the offset of a label from the beginning of the code // in a register. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); // Initialize a code object that will contain the code. Handle<Object> code_object(isolate->heap()->undefined_value(), isolate); Assembler assm(isolate, NULL, 0); Label start, target_away, target_faraway; __ stm(db_w, sp, r4.bit() | r5.bit() | lr.bit()); // r3 is used as the address zero, the test will crash when we load it. __ mov(r3, Operand::Zero()); // r5 will be a pointer to the start of the code. __ mov(r5, Operand(code_object)); __ mov_label_offset(r4, &start); __ mov_label_offset(r1, &target_faraway); __ str(r1, MemOperand(sp, kPointerSize, NegPreIndex)); __ mov_label_offset(r1, &target_away); // Jump straight to 'target_away' the first time and use the relative // position the second time. This covers the case when extracting the // position of a label which is linked. __ mov(r2, Operand::Zero()); __ bind(&start); __ cmp(r2, Operand::Zero()); __ b(eq, &target_away); __ add(pc, r5, r1); // Emit invalid instructions to push the label between 2^8 and 2^16 // instructions away. The test will crash if they are reached. for (int i = 0; i < (1 << 10); i++) { __ ldr(r3, MemOperand(r3)); } __ bind(&target_away); // This will be hit twice: r0 = r0 + 5 + 5. __ add(r0, r0, Operand(5)); __ ldr(r1, MemOperand(sp, kPointerSize, PostIndex), ne); __ add(pc, r5, r4, LeaveCC, ne); __ mov(r2, Operand(1)); __ b(&start); // Emit invalid instructions to push the label between 2^16 and 2^24 // instructions away. The test will crash if they are reached. for (int i = 0; i < (1 << 21); i++) { __ ldr(r3, MemOperand(r3)); } __ bind(&target_faraway); // r0 = r0 + 5 + 5 + 11 __ add(r0, r0, Operand(11)); __ ldm(ia_w, sp, r4.bit() | r5.bit() | pc.bit()); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), code_object); F1 f = FUNCTION_CAST<F1>(code->entry()); int res = reinterpret_cast<int>(CALL_GENERATED_CODE(isolate, f, 21, 0, 0, 0, 0)); ::printf("f() = %d\n", res); CHECK_EQ(42, res); } TEST(msr_mrs) { // Test msr and mrs. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); // Create a helper function: // void TestMsrMrs(uint32_t nzcv, // uint32_t * result_conditionals, // uint32_t * result_mrs); __ msr(CPSR_f, Operand(r0)); // Test that the condition flags have taken effect. __ mov(r3, Operand(0)); __ orr(r3, r3, Operand(1 << 31), LeaveCC, mi); // N __ orr(r3, r3, Operand(1 << 30), LeaveCC, eq); // Z __ orr(r3, r3, Operand(1 << 29), LeaveCC, cs); // C __ orr(r3, r3, Operand(1 << 28), LeaveCC, vs); // V __ str(r3, MemOperand(r1)); // Also check mrs, ignoring everything other than the flags. __ mrs(r3, CPSR); __ and_(r3, r3, Operand(kSpecialCondition)); __ str(r3, MemOperand(r2)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F5 f = FUNCTION_CAST<F5>(code->entry()); Object* dummy = nullptr; USE(dummy); #define CHECK_MSR_MRS(n, z, c, v) \ do { \ uint32_t nzcv = (n << 31) | (z << 30) | (c << 29) | (v << 28); \ uint32_t result_conditionals = -1; \ uint32_t result_mrs = -1; \ dummy = CALL_GENERATED_CODE(isolate, f, nzcv, &result_conditionals, \ &result_mrs, 0, 0); \ CHECK_EQ(nzcv, result_conditionals); \ CHECK_EQ(nzcv, result_mrs); \ } while (0); // N Z C V CHECK_MSR_MRS(0, 0, 0, 0); CHECK_MSR_MRS(0, 0, 0, 1); CHECK_MSR_MRS(0, 0, 1, 0); CHECK_MSR_MRS(0, 0, 1, 1); CHECK_MSR_MRS(0, 1, 0, 0); CHECK_MSR_MRS(0, 1, 0, 1); CHECK_MSR_MRS(0, 1, 1, 0); CHECK_MSR_MRS(0, 1, 1, 1); CHECK_MSR_MRS(1, 0, 0, 0); CHECK_MSR_MRS(1, 0, 0, 1); CHECK_MSR_MRS(1, 0, 1, 0); CHECK_MSR_MRS(1, 0, 1, 1); CHECK_MSR_MRS(1, 1, 0, 0); CHECK_MSR_MRS(1, 1, 0, 1); CHECK_MSR_MRS(1, 1, 1, 0); CHECK_MSR_MRS(1, 1, 1, 1); #undef CHECK_MSR_MRS } TEST(ARMv8_float32_vrintX) { // Test the vrintX floating point instructions. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); typedef struct { float input; float ar; float nr; float mr; float pr; float zr; } T; T t; // Create a function that accepts &t, and loads, manipulates, and stores // the floats. Assembler assm(isolate, NULL, 0); Label L, C; if (CpuFeatures::IsSupported(ARMv8)) { CpuFeatureScope scope(&assm, ARMv8); __ mov(ip, Operand(sp)); __ stm(db_w, sp, r4.bit() | fp.bit() | lr.bit()); __ mov(r4, Operand(r0)); // Test vrinta __ vldr(s6, r4, offsetof(T, input)); __ vrinta(s5, s6); __ vstr(s5, r4, offsetof(T, ar)); // Test vrintn __ vldr(s6, r4, offsetof(T, input)); __ vrintn(s5, s6); __ vstr(s5, r4, offsetof(T, nr)); // Test vrintp __ vldr(s6, r4, offsetof(T, input)); __ vrintp(s5, s6); __ vstr(s5, r4, offsetof(T, pr)); // Test vrintm __ vldr(s6, r4, offsetof(T, input)); __ vrintm(s5, s6); __ vstr(s5, r4, offsetof(T, mr)); // Test vrintz __ vldr(s6, r4, offsetof(T, input)); __ vrintz(s5, s6); __ vstr(s5, r4, offsetof(T, zr)); __ ldm(ia_w, sp, r4.bit() | fp.bit() | pc.bit()); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); Object* dummy = nullptr; USE(dummy); #define CHECK_VRINT(input_val, ares, nres, mres, pres, zres) \ t.input = input_val; \ dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); \ CHECK_EQ(ares, t.ar); \ CHECK_EQ(nres, t.nr); \ CHECK_EQ(mres, t.mr); \ CHECK_EQ(pres, t.pr); \ CHECK_EQ(zres, t.zr); CHECK_VRINT(-0.5, -1.0, -0.0, -1.0, -0.0, -0.0) CHECK_VRINT(-0.6, -1.0, -1.0, -1.0, -0.0, -0.0) CHECK_VRINT(-1.1, -1.0, -1.0, -2.0, -1.0, -1.0) CHECK_VRINT(0.5, 1.0, 0.0, 0.0, 1.0, 0.0) CHECK_VRINT(0.6, 1.0, 1.0, 0.0, 1.0, 0.0) CHECK_VRINT(1.1, 1.0, 1.0, 1.0, 2.0, 1.0) float inf = std::numeric_limits<float>::infinity(); CHECK_VRINT(inf, inf, inf, inf, inf, inf) CHECK_VRINT(-inf, -inf, -inf, -inf, -inf, -inf) CHECK_VRINT(-0.0, -0.0, -0.0, -0.0, -0.0, -0.0) // Check NaN propagation. float nan = std::numeric_limits<float>::quiet_NaN(); t.input = nan; dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); CHECK_EQ(bit_cast<int32_t>(nan), bit_cast<int32_t>(t.ar)); CHECK_EQ(bit_cast<int32_t>(nan), bit_cast<int32_t>(t.nr)); CHECK_EQ(bit_cast<int32_t>(nan), bit_cast<int32_t>(t.mr)); CHECK_EQ(bit_cast<int32_t>(nan), bit_cast<int32_t>(t.pr)); CHECK_EQ(bit_cast<int32_t>(nan), bit_cast<int32_t>(t.zr)); #undef CHECK_VRINT } } TEST(ARMv8_vrintX) { // Test the vrintX floating point instructions. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); typedef struct { double input; double ar; double nr; double mr; double pr; double zr; } T; T t; // Create a function that accepts &t, and loads, manipulates, and stores // the doubles and floats. Assembler assm(isolate, NULL, 0); Label L, C; if (CpuFeatures::IsSupported(ARMv8)) { CpuFeatureScope scope(&assm, ARMv8); __ mov(ip, Operand(sp)); __ stm(db_w, sp, r4.bit() | fp.bit() | lr.bit()); __ mov(r4, Operand(r0)); // Test vrinta __ vldr(d6, r4, offsetof(T, input)); __ vrinta(d5, d6); __ vstr(d5, r4, offsetof(T, ar)); // Test vrintn __ vldr(d6, r4, offsetof(T, input)); __ vrintn(d5, d6); __ vstr(d5, r4, offsetof(T, nr)); // Test vrintp __ vldr(d6, r4, offsetof(T, input)); __ vrintp(d5, d6); __ vstr(d5, r4, offsetof(T, pr)); // Test vrintm __ vldr(d6, r4, offsetof(T, input)); __ vrintm(d5, d6); __ vstr(d5, r4, offsetof(T, mr)); // Test vrintz __ vldr(d6, r4, offsetof(T, input)); __ vrintz(d5, d6); __ vstr(d5, r4, offsetof(T, zr)); __ ldm(ia_w, sp, r4.bit() | fp.bit() | pc.bit()); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); Object* dummy = nullptr; USE(dummy); #define CHECK_VRINT(input_val, ares, nres, mres, pres, zres) \ t.input = input_val; \ dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); \ CHECK_EQ(ares, t.ar); \ CHECK_EQ(nres, t.nr); \ CHECK_EQ(mres, t.mr); \ CHECK_EQ(pres, t.pr); \ CHECK_EQ(zres, t.zr); CHECK_VRINT(-0.5, -1.0, -0.0, -1.0, -0.0, -0.0) CHECK_VRINT(-0.6, -1.0, -1.0, -1.0, -0.0, -0.0) CHECK_VRINT(-1.1, -1.0, -1.0, -2.0, -1.0, -1.0) CHECK_VRINT(0.5, 1.0, 0.0, 0.0, 1.0, 0.0) CHECK_VRINT(0.6, 1.0, 1.0, 0.0, 1.0, 0.0) CHECK_VRINT(1.1, 1.0, 1.0, 1.0, 2.0, 1.0) double inf = std::numeric_limits<double>::infinity(); CHECK_VRINT(inf, inf, inf, inf, inf, inf) CHECK_VRINT(-inf, -inf, -inf, -inf, -inf, -inf) CHECK_VRINT(-0.0, -0.0, -0.0, -0.0, -0.0, -0.0) // Check NaN propagation. double nan = std::numeric_limits<double>::quiet_NaN(); t.input = nan; dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); CHECK_EQ(bit_cast<int64_t>(nan), bit_cast<int64_t>(t.ar)); CHECK_EQ(bit_cast<int64_t>(nan), bit_cast<int64_t>(t.nr)); CHECK_EQ(bit_cast<int64_t>(nan), bit_cast<int64_t>(t.mr)); CHECK_EQ(bit_cast<int64_t>(nan), bit_cast<int64_t>(t.pr)); CHECK_EQ(bit_cast<int64_t>(nan), bit_cast<int64_t>(t.zr)); #undef CHECK_VRINT } } TEST(ARMv8_vsel) { // Test the vsel floating point instructions. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); // Used to indicate whether a condition passed or failed. static constexpr float kResultPass = 1.0f; static constexpr float kResultFail = -kResultPass; struct ResultsF32 { float vseleq_; float vselge_; float vselgt_; float vselvs_; // The following conditions aren't architecturally supported, but the // assembler implements them by swapping the inputs. float vselne_; float vsellt_; float vselle_; float vselvc_; }; struct ResultsF64 { double vseleq_; double vselge_; double vselgt_; double vselvs_; // The following conditions aren't architecturally supported, but the // assembler implements them by swapping the inputs. double vselne_; double vsellt_; double vselle_; double vselvc_; }; if (CpuFeatures::IsSupported(ARMv8)) { CpuFeatureScope scope(&assm, ARMv8); // Create a helper function: // void TestVsel(uint32_t nzcv, // ResultsF32* results_f32, // ResultsF64* results_f64); __ msr(CPSR_f, Operand(r0)); __ vmov(s1, kResultPass); __ vmov(s2, kResultFail); __ vsel(eq, s0, s1, s2); __ vstr(s0, r1, offsetof(ResultsF32, vseleq_)); __ vsel(ge, s0, s1, s2); __ vstr(s0, r1, offsetof(ResultsF32, vselge_)); __ vsel(gt, s0, s1, s2); __ vstr(s0, r1, offsetof(ResultsF32, vselgt_)); __ vsel(vs, s0, s1, s2); __ vstr(s0, r1, offsetof(ResultsF32, vselvs_)); __ vsel(ne, s0, s1, s2); __ vstr(s0, r1, offsetof(ResultsF32, vselne_)); __ vsel(lt, s0, s1, s2); __ vstr(s0, r1, offsetof(ResultsF32, vsellt_)); __ vsel(le, s0, s1, s2); __ vstr(s0, r1, offsetof(ResultsF32, vselle_)); __ vsel(vc, s0, s1, s2); __ vstr(s0, r1, offsetof(ResultsF32, vselvc_)); __ vmov(d1, kResultPass); __ vmov(d2, kResultFail); __ vsel(eq, d0, d1, d2); __ vstr(d0, r2, offsetof(ResultsF64, vseleq_)); __ vsel(ge, d0, d1, d2); __ vstr(d0, r2, offsetof(ResultsF64, vselge_)); __ vsel(gt, d0, d1, d2); __ vstr(d0, r2, offsetof(ResultsF64, vselgt_)); __ vsel(vs, d0, d1, d2); __ vstr(d0, r2, offsetof(ResultsF64, vselvs_)); __ vsel(ne, d0, d1, d2); __ vstr(d0, r2, offsetof(ResultsF64, vselne_)); __ vsel(lt, d0, d1, d2); __ vstr(d0, r2, offsetof(ResultsF64, vsellt_)); __ vsel(le, d0, d1, d2); __ vstr(d0, r2, offsetof(ResultsF64, vselle_)); __ vsel(vc, d0, d1, d2); __ vstr(d0, r2, offsetof(ResultsF64, vselvc_)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F5 f = FUNCTION_CAST<F5>(code->entry()); Object* dummy = nullptr; USE(dummy); STATIC_ASSERT(kResultPass == -kResultFail); #define CHECK_VSEL(n, z, c, v, vseleq, vselge, vselgt, vselvs) \ do { \ ResultsF32 results_f32; \ ResultsF64 results_f64; \ uint32_t nzcv = (n << 31) | (z << 30) | (c << 29) | (v << 28); \ dummy = CALL_GENERATED_CODE(isolate, f, nzcv, &results_f32, &results_f64, \ 0, 0); \ CHECK_EQ(vseleq, results_f32.vseleq_); \ CHECK_EQ(vselge, results_f32.vselge_); \ CHECK_EQ(vselgt, results_f32.vselgt_); \ CHECK_EQ(vselvs, results_f32.vselvs_); \ CHECK_EQ(-vseleq, results_f32.vselne_); \ CHECK_EQ(-vselge, results_f32.vsellt_); \ CHECK_EQ(-vselgt, results_f32.vselle_); \ CHECK_EQ(-vselvs, results_f32.vselvc_); \ CHECK_EQ(vseleq, results_f64.vseleq_); \ CHECK_EQ(vselge, results_f64.vselge_); \ CHECK_EQ(vselgt, results_f64.vselgt_); \ CHECK_EQ(vselvs, results_f64.vselvs_); \ CHECK_EQ(-vseleq, results_f64.vselne_); \ CHECK_EQ(-vselge, results_f64.vsellt_); \ CHECK_EQ(-vselgt, results_f64.vselle_); \ CHECK_EQ(-vselvs, results_f64.vselvc_); \ } while (0); // N Z C V vseleq vselge vselgt vselvs CHECK_VSEL(0, 0, 0, 0, kResultFail, kResultPass, kResultPass, kResultFail); CHECK_VSEL(0, 0, 0, 1, kResultFail, kResultFail, kResultFail, kResultPass); CHECK_VSEL(0, 0, 1, 0, kResultFail, kResultPass, kResultPass, kResultFail); CHECK_VSEL(0, 0, 1, 1, kResultFail, kResultFail, kResultFail, kResultPass); CHECK_VSEL(0, 1, 0, 0, kResultPass, kResultPass, kResultFail, kResultFail); CHECK_VSEL(0, 1, 0, 1, kResultPass, kResultFail, kResultFail, kResultPass); CHECK_VSEL(0, 1, 1, 0, kResultPass, kResultPass, kResultFail, kResultFail); CHECK_VSEL(0, 1, 1, 1, kResultPass, kResultFail, kResultFail, kResultPass); CHECK_VSEL(1, 0, 0, 0, kResultFail, kResultFail, kResultFail, kResultFail); CHECK_VSEL(1, 0, 0, 1, kResultFail, kResultPass, kResultPass, kResultPass); CHECK_VSEL(1, 0, 1, 0, kResultFail, kResultFail, kResultFail, kResultFail); CHECK_VSEL(1, 0, 1, 1, kResultFail, kResultPass, kResultPass, kResultPass); CHECK_VSEL(1, 1, 0, 0, kResultPass, kResultFail, kResultFail, kResultFail); CHECK_VSEL(1, 1, 0, 1, kResultPass, kResultPass, kResultFail, kResultPass); CHECK_VSEL(1, 1, 1, 0, kResultPass, kResultFail, kResultFail, kResultFail); CHECK_VSEL(1, 1, 1, 1, kResultPass, kResultPass, kResultFail, kResultPass); #undef CHECK_VSEL } } TEST(ARMv8_vminmax_f64) { // Test the vminnm and vmaxnm floating point instructions. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); struct Inputs { double left_; double right_; }; struct Results { double vminnm_; double vmaxnm_; }; if (CpuFeatures::IsSupported(ARMv8)) { CpuFeatureScope scope(&assm, ARMv8); // Create a helper function: // void TestVminmax(const Inputs* inputs, // Results* results); __ vldr(d1, r0, offsetof(Inputs, left_)); __ vldr(d2, r0, offsetof(Inputs, right_)); __ vminnm(d0, d1, d2); __ vstr(d0, r1, offsetof(Results, vminnm_)); __ vmaxnm(d0, d1, d2); __ vstr(d0, r1, offsetof(Results, vmaxnm_)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F4 f = FUNCTION_CAST<F4>(code->entry()); Object* dummy = nullptr; USE(dummy); #define CHECK_VMINMAX(left, right, vminnm, vmaxnm) \ do { \ Inputs inputs = {left, right}; \ Results results; \ dummy = CALL_GENERATED_CODE(isolate, f, &inputs, &results, 0, 0, 0); \ /* Use a bit_cast to correctly identify -0.0 and NaNs. */ \ CHECK_EQ(bit_cast<uint64_t>(vminnm), bit_cast<uint64_t>(results.vminnm_)); \ CHECK_EQ(bit_cast<uint64_t>(vmaxnm), bit_cast<uint64_t>(results.vmaxnm_)); \ } while (0); double nan_a = bit_cast<double>(UINT64_C(0x7ff8000000000001)); double nan_b = bit_cast<double>(UINT64_C(0x7ff8000000000002)); CHECK_VMINMAX(1.0, -1.0, -1.0, 1.0); CHECK_VMINMAX(-1.0, 1.0, -1.0, 1.0); CHECK_VMINMAX(0.0, -1.0, -1.0, 0.0); CHECK_VMINMAX(-1.0, 0.0, -1.0, 0.0); CHECK_VMINMAX(-0.0, -1.0, -1.0, -0.0); CHECK_VMINMAX(-1.0, -0.0, -1.0, -0.0); CHECK_VMINMAX(0.0, 1.0, 0.0, 1.0); CHECK_VMINMAX(1.0, 0.0, 0.0, 1.0); CHECK_VMINMAX(0.0, 0.0, 0.0, 0.0); CHECK_VMINMAX(-0.0, -0.0, -0.0, -0.0); CHECK_VMINMAX(-0.0, 0.0, -0.0, 0.0); CHECK_VMINMAX(0.0, -0.0, -0.0, 0.0); CHECK_VMINMAX(0.0, nan_a, 0.0, 0.0); CHECK_VMINMAX(nan_a, 0.0, 0.0, 0.0); CHECK_VMINMAX(nan_a, nan_b, nan_a, nan_a); CHECK_VMINMAX(nan_b, nan_a, nan_b, nan_b); #undef CHECK_VMINMAX } } TEST(ARMv8_vminmax_f32) { // Test the vminnm and vmaxnm floating point instructions. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); struct Inputs { float left_; float right_; }; struct Results { float vminnm_; float vmaxnm_; }; if (CpuFeatures::IsSupported(ARMv8)) { CpuFeatureScope scope(&assm, ARMv8); // Create a helper function: // void TestVminmax(const Inputs* inputs, // Results* results); __ vldr(s1, r0, offsetof(Inputs, left_)); __ vldr(s2, r0, offsetof(Inputs, right_)); __ vminnm(s0, s1, s2); __ vstr(s0, r1, offsetof(Results, vminnm_)); __ vmaxnm(s0, s1, s2); __ vstr(s0, r1, offsetof(Results, vmaxnm_)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F4 f = FUNCTION_CAST<F4>(code->entry()); Object* dummy = nullptr; USE(dummy); #define CHECK_VMINMAX(left, right, vminnm, vmaxnm) \ do { \ Inputs inputs = {left, right}; \ Results results; \ dummy = CALL_GENERATED_CODE(isolate, f, &inputs, &results, 0, 0, 0); \ /* Use a bit_cast to correctly identify -0.0 and NaNs. */ \ CHECK_EQ(bit_cast<uint32_t>(vminnm), bit_cast<uint32_t>(results.vminnm_)); \ CHECK_EQ(bit_cast<uint32_t>(vmaxnm), bit_cast<uint32_t>(results.vmaxnm_)); \ } while (0); float nan_a = bit_cast<float>(UINT32_C(0x7fc00001)); float nan_b = bit_cast<float>(UINT32_C(0x7fc00002)); CHECK_VMINMAX(1.0f, -1.0f, -1.0f, 1.0f); CHECK_VMINMAX(-1.0f, 1.0f, -1.0f, 1.0f); CHECK_VMINMAX(0.0f, -1.0f, -1.0f, 0.0f); CHECK_VMINMAX(-1.0f, 0.0f, -1.0f, 0.0f); CHECK_VMINMAX(-0.0f, -1.0f, -1.0f, -0.0f); CHECK_VMINMAX(-1.0f, -0.0f, -1.0f, -0.0f); CHECK_VMINMAX(0.0f, 1.0f, 0.0f, 1.0f); CHECK_VMINMAX(1.0f, 0.0f, 0.0f, 1.0f); CHECK_VMINMAX(0.0f, 0.0f, 0.0f, 0.0f); CHECK_VMINMAX(-0.0f, -0.0f, -0.0f, -0.0f); CHECK_VMINMAX(-0.0f, 0.0f, -0.0f, 0.0f); CHECK_VMINMAX(0.0f, -0.0f, -0.0f, 0.0f); CHECK_VMINMAX(0.0f, nan_a, 0.0f, 0.0f); CHECK_VMINMAX(nan_a, 0.0f, 0.0f, 0.0f); CHECK_VMINMAX(nan_a, nan_b, nan_a, nan_a); CHECK_VMINMAX(nan_b, nan_a, nan_b, nan_b); #undef CHECK_VMINMAX } } template <typename T, typename Inputs, typename Results> static F4 GenerateMacroFloatMinMax(MacroAssembler& assm) { T a = T::from_code(0); // d0/s0 T b = T::from_code(1); // d1/s1 T c = T::from_code(2); // d2/s2 // Create a helper function: // void TestFloatMinMax(const Inputs* inputs, // Results* results); Label ool_min_abc, ool_min_aab, ool_min_aba; Label ool_max_abc, ool_max_aab, ool_max_aba; Label done_min_abc, done_min_aab, done_min_aba; Label done_max_abc, done_max_aab, done_max_aba; // a = min(b, c); __ vldr(b, r0, offsetof(Inputs, left_)); __ vldr(c, r0, offsetof(Inputs, right_)); __ FloatMin(a, b, c, &ool_min_abc); __ bind(&done_min_abc); __ vstr(a, r1, offsetof(Results, min_abc_)); // a = min(a, b); __ vldr(a, r0, offsetof(Inputs, left_)); __ vldr(b, r0, offsetof(Inputs, right_)); __ FloatMin(a, a, b, &ool_min_aab); __ bind(&done_min_aab); __ vstr(a, r1, offsetof(Results, min_aab_)); // a = min(b, a); __ vldr(b, r0, offsetof(Inputs, left_)); __ vldr(a, r0, offsetof(Inputs, right_)); __ FloatMin(a, b, a, &ool_min_aba); __ bind(&done_min_aba); __ vstr(a, r1, offsetof(Results, min_aba_)); // a = max(b, c); __ vldr(b, r0, offsetof(Inputs, left_)); __ vldr(c, r0, offsetof(Inputs, right_)); __ FloatMax(a, b, c, &ool_max_abc); __ bind(&done_max_abc); __ vstr(a, r1, offsetof(Results, max_abc_)); // a = max(a, b); __ vldr(a, r0, offsetof(Inputs, left_)); __ vldr(b, r0, offsetof(Inputs, right_)); __ FloatMax(a, a, b, &ool_max_aab); __ bind(&done_max_aab); __ vstr(a, r1, offsetof(Results, max_aab_)); // a = max(b, a); __ vldr(b, r0, offsetof(Inputs, left_)); __ vldr(a, r0, offsetof(Inputs, right_)); __ FloatMax(a, b, a, &ool_max_aba); __ bind(&done_max_aba); __ vstr(a, r1, offsetof(Results, max_aba_)); __ bx(lr); // Generate out-of-line cases. __ bind(&ool_min_abc); __ FloatMinOutOfLine(a, b, c); __ b(&done_min_abc); __ bind(&ool_min_aab); __ FloatMinOutOfLine(a, a, b); __ b(&done_min_aab); __ bind(&ool_min_aba); __ FloatMinOutOfLine(a, b, a); __ b(&done_min_aba); __ bind(&ool_max_abc); __ FloatMaxOutOfLine(a, b, c); __ b(&done_max_abc); __ bind(&ool_max_aab); __ FloatMaxOutOfLine(a, a, b); __ b(&done_max_aab); __ bind(&ool_max_aba); __ FloatMaxOutOfLine(a, b, a); __ b(&done_max_aba); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = assm.isolate()->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif return FUNCTION_CAST<F4>(code->entry()); } TEST(macro_float_minmax_f64) { // Test the FloatMin and FloatMax macros. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); MacroAssembler assm(isolate, NULL, 0, CodeObjectRequired::kYes); struct Inputs { double left_; double right_; }; struct Results { // Check all register aliasing possibilities in order to exercise all // code-paths in the macro assembler. double min_abc_; double min_aab_; double min_aba_; double max_abc_; double max_aab_; double max_aba_; }; F4 f = GenerateMacroFloatMinMax<DwVfpRegister, Inputs, Results>(assm); Object* dummy = nullptr; USE(dummy); #define CHECK_MINMAX(left, right, min, max) \ do { \ Inputs inputs = {left, right}; \ Results results; \ dummy = CALL_GENERATED_CODE(isolate, f, &inputs, &results, 0, 0, 0); \ /* Use a bit_cast to correctly identify -0.0 and NaNs. */ \ CHECK_EQ(bit_cast<uint64_t>(min), bit_cast<uint64_t>(results.min_abc_)); \ CHECK_EQ(bit_cast<uint64_t>(min), bit_cast<uint64_t>(results.min_aab_)); \ CHECK_EQ(bit_cast<uint64_t>(min), bit_cast<uint64_t>(results.min_aba_)); \ CHECK_EQ(bit_cast<uint64_t>(max), bit_cast<uint64_t>(results.max_abc_)); \ CHECK_EQ(bit_cast<uint64_t>(max), bit_cast<uint64_t>(results.max_aab_)); \ CHECK_EQ(bit_cast<uint64_t>(max), bit_cast<uint64_t>(results.max_aba_)); \ } while (0) double nan_a = bit_cast<double>(UINT64_C(0x7ff8000000000001)); double nan_b = bit_cast<double>(UINT64_C(0x7ff8000000000002)); CHECK_MINMAX(1.0, -1.0, -1.0, 1.0); CHECK_MINMAX(-1.0, 1.0, -1.0, 1.0); CHECK_MINMAX(0.0, -1.0, -1.0, 0.0); CHECK_MINMAX(-1.0, 0.0, -1.0, 0.0); CHECK_MINMAX(-0.0, -1.0, -1.0, -0.0); CHECK_MINMAX(-1.0, -0.0, -1.0, -0.0); CHECK_MINMAX(0.0, 1.0, 0.0, 1.0); CHECK_MINMAX(1.0, 0.0, 0.0, 1.0); CHECK_MINMAX(0.0, 0.0, 0.0, 0.0); CHECK_MINMAX(-0.0, -0.0, -0.0, -0.0); CHECK_MINMAX(-0.0, 0.0, -0.0, 0.0); CHECK_MINMAX(0.0, -0.0, -0.0, 0.0); CHECK_MINMAX(0.0, nan_a, nan_a, nan_a); CHECK_MINMAX(nan_a, 0.0, nan_a, nan_a); CHECK_MINMAX(nan_a, nan_b, nan_a, nan_a); CHECK_MINMAX(nan_b, nan_a, nan_b, nan_b); #undef CHECK_MINMAX } TEST(macro_float_minmax_f32) { // Test the FloatMin and FloatMax macros. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); MacroAssembler assm(isolate, NULL, 0, CodeObjectRequired::kYes); struct Inputs { float left_; float right_; }; struct Results { // Check all register aliasing possibilities in order to exercise all // code-paths in the macro assembler. float min_abc_; float min_aab_; float min_aba_; float max_abc_; float max_aab_; float max_aba_; }; F4 f = GenerateMacroFloatMinMax<SwVfpRegister, Inputs, Results>(assm); Object* dummy = nullptr; USE(dummy); #define CHECK_MINMAX(left, right, min, max) \ do { \ Inputs inputs = {left, right}; \ Results results; \ dummy = CALL_GENERATED_CODE(isolate, f, &inputs, &results, 0, 0, 0); \ /* Use a bit_cast to correctly identify -0.0 and NaNs. */ \ CHECK_EQ(bit_cast<uint32_t>(min), bit_cast<uint32_t>(results.min_abc_)); \ CHECK_EQ(bit_cast<uint32_t>(min), bit_cast<uint32_t>(results.min_aab_)); \ CHECK_EQ(bit_cast<uint32_t>(min), bit_cast<uint32_t>(results.min_aba_)); \ CHECK_EQ(bit_cast<uint32_t>(max), bit_cast<uint32_t>(results.max_abc_)); \ CHECK_EQ(bit_cast<uint32_t>(max), bit_cast<uint32_t>(results.max_aab_)); \ CHECK_EQ(bit_cast<uint32_t>(max), bit_cast<uint32_t>(results.max_aba_)); \ } while (0) float nan_a = bit_cast<float>(UINT32_C(0x7fc00001)); float nan_b = bit_cast<float>(UINT32_C(0x7fc00002)); CHECK_MINMAX(1.0f, -1.0f, -1.0f, 1.0f); CHECK_MINMAX(-1.0f, 1.0f, -1.0f, 1.0f); CHECK_MINMAX(0.0f, -1.0f, -1.0f, 0.0f); CHECK_MINMAX(-1.0f, 0.0f, -1.0f, 0.0f); CHECK_MINMAX(-0.0f, -1.0f, -1.0f, -0.0f); CHECK_MINMAX(-1.0f, -0.0f, -1.0f, -0.0f); CHECK_MINMAX(0.0f, 1.0f, 0.0f, 1.0f); CHECK_MINMAX(1.0f, 0.0f, 0.0f, 1.0f); CHECK_MINMAX(0.0f, 0.0f, 0.0f, 0.0f); CHECK_MINMAX(-0.0f, -0.0f, -0.0f, -0.0f); CHECK_MINMAX(-0.0f, 0.0f, -0.0f, 0.0f); CHECK_MINMAX(0.0f, -0.0f, -0.0f, 0.0f); CHECK_MINMAX(0.0f, nan_a, nan_a, nan_a); CHECK_MINMAX(nan_a, 0.0f, nan_a, nan_a); CHECK_MINMAX(nan_a, nan_b, nan_a, nan_a); CHECK_MINMAX(nan_b, nan_a, nan_b, nan_b); #undef CHECK_MINMAX } TEST(unaligned_loads) { // All supported ARM targets allow unaligned accesses. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); typedef struct { uint32_t ldrh; uint32_t ldrsh; uint32_t ldr; } T; T t; Assembler assm(isolate, NULL, 0); __ ldrh(ip, MemOperand(r1, r2)); __ str(ip, MemOperand(r0, offsetof(T, ldrh))); __ ldrsh(ip, MemOperand(r1, r2)); __ str(ip, MemOperand(r0, offsetof(T, ldrsh))); __ ldr(ip, MemOperand(r1, r2)); __ str(ip, MemOperand(r0, offsetof(T, ldr))); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F4 f = FUNCTION_CAST<F4>(code->entry()); Object* dummy = nullptr; USE(dummy); #ifndef V8_TARGET_LITTLE_ENDIAN #error This test assumes a little-endian layout. #endif uint64_t data = UINT64_C(0x84838281807f7e7d); dummy = CALL_GENERATED_CODE(isolate, f, &t, &data, 0, 0, 0); CHECK_EQ(0x00007e7du, t.ldrh); CHECK_EQ(0x00007e7du, t.ldrsh); CHECK_EQ(0x807f7e7du, t.ldr); dummy = CALL_GENERATED_CODE(isolate, f, &t, &data, 1, 0, 0); CHECK_EQ(0x00007f7eu, t.ldrh); CHECK_EQ(0x00007f7eu, t.ldrsh); CHECK_EQ(0x81807f7eu, t.ldr); dummy = CALL_GENERATED_CODE(isolate, f, &t, &data, 2, 0, 0); CHECK_EQ(0x0000807fu, t.ldrh); CHECK_EQ(0xffff807fu, t.ldrsh); CHECK_EQ(0x8281807fu, t.ldr); dummy = CALL_GENERATED_CODE(isolate, f, &t, &data, 3, 0, 0); CHECK_EQ(0x00008180u, t.ldrh); CHECK_EQ(0xffff8180u, t.ldrsh); CHECK_EQ(0x83828180u, t.ldr); } TEST(unaligned_stores) { // All supported ARM targets allow unaligned accesses. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); __ strh(r3, MemOperand(r0, r2)); __ str(r3, MemOperand(r1, r2)); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F4 f = FUNCTION_CAST<F4>(code->entry()); Object* dummy = nullptr; USE(dummy); #ifndef V8_TARGET_LITTLE_ENDIAN #error This test assumes a little-endian layout. #endif { uint64_t strh = 0; uint64_t str = 0; dummy = CALL_GENERATED_CODE(isolate, f, &strh, &str, 0, 0xfedcba98, 0); CHECK_EQ(UINT64_C(0x000000000000ba98), strh); CHECK_EQ(UINT64_C(0x00000000fedcba98), str); } { uint64_t strh = 0; uint64_t str = 0; dummy = CALL_GENERATED_CODE(isolate, f, &strh, &str, 1, 0xfedcba98, 0); CHECK_EQ(UINT64_C(0x0000000000ba9800), strh); CHECK_EQ(UINT64_C(0x000000fedcba9800), str); } { uint64_t strh = 0; uint64_t str = 0; dummy = CALL_GENERATED_CODE(isolate, f, &strh, &str, 2, 0xfedcba98, 0); CHECK_EQ(UINT64_C(0x00000000ba980000), strh); CHECK_EQ(UINT64_C(0x0000fedcba980000), str); } { uint64_t strh = 0; uint64_t str = 0; dummy = CALL_GENERATED_CODE(isolate, f, &strh, &str, 3, 0xfedcba98, 0); CHECK_EQ(UINT64_C(0x000000ba98000000), strh); CHECK_EQ(UINT64_C(0x00fedcba98000000), str); } } TEST(vswp) { if (!CpuFeatures::IsSupported(NEON)) return; CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); typedef struct { uint64_t vswp_d0; uint64_t vswp_d1; uint64_t vswp_d30; uint64_t vswp_d31; uint32_t vswp_q4[4]; uint32_t vswp_q5[4]; } T; T t; __ stm(db_w, sp, r4.bit() | r5.bit() | r6.bit() | r7.bit() | lr.bit()); uint64_t one = bit_cast<uint64_t>(1.0); __ mov(r5, Operand(one >> 32)); __ mov(r4, Operand(one & 0xffffffff)); uint64_t minus_one = bit_cast<uint64_t>(-1.0); __ mov(r7, Operand(minus_one >> 32)); __ mov(r6, Operand(minus_one & 0xffffffff)); __ vmov(d0, r4, r5); // d0 = 1.0 __ vmov(d1, r6, r7); // d1 = -1.0 __ vswp(d0, d1); __ vstr(d0, r0, offsetof(T, vswp_d0)); __ vstr(d1, r0, offsetof(T, vswp_d1)); if (CpuFeatures::IsSupported(VFP32DREGS)) { __ vmov(d30, r4, r5); // d30 = 1.0 __ vmov(d31, r6, r7); // d31 = -1.0 __ vswp(d30, d31); __ vstr(d30, r0, offsetof(T, vswp_d30)); __ vstr(d31, r0, offsetof(T, vswp_d31)); } // q-register swap. const uint32_t test_1 = 0x01234567; const uint32_t test_2 = 0x89abcdef; __ mov(r4, Operand(test_1)); __ mov(r5, Operand(test_2)); // TODO(bbudge) replace with vdup when implemented. __ vmov(d8, r4, r4); __ vmov(d9, r4, r4); // q4 = [1.0, 1.0] __ vmov(d10, r5, r5); __ vmov(d11, r5, r5); // q5 = [-1.0, -1.0] __ vswp(q4, q5); __ add(r6, r0, Operand(static_cast<int32_t>(offsetof(T, vswp_q4)))); __ vst1(Neon8, NeonListOperand(q4), NeonMemOperand(r6)); __ add(r6, r0, Operand(static_cast<int32_t>(offsetof(T, vswp_q5)))); __ vst1(Neon8, NeonListOperand(q5), NeonMemOperand(r6)); __ ldm(ia_w, sp, r4.bit() | r5.bit() | r6.bit() | r7.bit() | pc.bit()); __ bx(lr); CodeDesc desc; assm.GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, Code::ComputeFlags(Code::STUB), Handle<Code>()); #ifdef DEBUG OFStream os(stdout); code->Print(os); #endif F3 f = FUNCTION_CAST<F3>(code->entry()); Object* dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0); USE(dummy); CHECK_EQ(minus_one, t.vswp_d0); CHECK_EQ(one, t.vswp_d1); if (CpuFeatures::IsSupported(VFP32DREGS)) { CHECK_EQ(minus_one, t.vswp_d30); CHECK_EQ(one, t.vswp_d31); } CHECK_EQ(t.vswp_q4[0], test_2); CHECK_EQ(t.vswp_q4[1], test_2); CHECK_EQ(t.vswp_q4[2], test_2); CHECK_EQ(t.vswp_q4[3], test_2); CHECK_EQ(t.vswp_q5[0], test_1); CHECK_EQ(t.vswp_q5[1], test_1); CHECK_EQ(t.vswp_q5[2], test_1); CHECK_EQ(t.vswp_q5[3], test_1); } TEST(regress4292_b) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); Label end; __ mov(r0, Operand(isolate->factory()->infinity_value())); for (int i = 0; i < 1020; ++i) { __ b(hi, &end); } __ bind(&end); } TEST(regress4292_bl) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); Label end; __ mov(r0, Operand(isolate->factory()->infinity_value())); for (int i = 0; i < 1020; ++i) { __ bl(hi, &end); } __ bind(&end); } TEST(regress4292_blx) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); Label end; __ mov(r0, Operand(isolate->factory()->infinity_value())); for (int i = 0; i < 1020; ++i) { __ blx(&end); } __ bind(&end); } TEST(regress4292_CheckConstPool) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Assembler assm(isolate, NULL, 0); __ mov(r0, Operand(isolate->factory()->infinity_value())); __ BlockConstPoolFor(1019); for (int i = 0; i < 1019; ++i) __ nop(); __ vldr(d0, MemOperand(r0, 0)); } #undef __
hkernbach/arangodb
3rdParty/V8/v5.7.492.77/test/cctest/test-assembler-arm.cc
C++
apache-2.0
114,323
package ludum.mighty.ld36.animations; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureRegion; import ludum.mighty.ld36.settings.DefaultValues; public class AnimatorSonicBoom { private Texture kidTexture; private TextureRegion[][] kidTR; private TextureRegion[][] kidTRflip; public Animation animUP, animDOWN, animLEFT, animRIGHT, animStopUP, animStopDOWN, animStopLEFT, animStopRIGHT, animNE, animNW, animSE, animSW, animStopNE, animStopNW, animStopSE, animStopSW, anim; public AnimatorSonicBoom(String textureSheet) { kidTexture = new Texture(textureSheet); kidTR = TextureRegion.split(kidTexture, DefaultValues.TILESIZE, DefaultValues.TILESIZE); kidTRflip = TextureRegion.split(kidTexture, DefaultValues.TILESIZE, DefaultValues.TILESIZE); kidTRflip[2][7].flip(true, false); kidTRflip[2][8].flip(true, false); kidTRflip[2][9].flip(true, false); kidTRflip[3][7].flip(true, false); kidTRflip[3][8].flip(true, false); kidTRflip[3][9].flip(true, false); kidTRflip[4][7].flip(true, false); kidTRflip[4][8].flip(true, false); kidTRflip[4][9].flip(true, false); // Create animations for movement animDOWN = new Animation(0.25f, kidTR[5][7], kidTR[5][8], kidTR[5][9], kidTR[5][7]); animRIGHT = new Animation(0.25f, kidTR[4][7], kidTR[4][8], kidTR[4][9], kidTR[4][7]); animUP = new Animation(0.25f, kidTR[1][7], kidTR[1][8], kidTR[1][9], kidTR[1][7]); animLEFT = new Animation(0.25f, kidTRflip[4][7], kidTRflip[4][8], kidTRflip[4][9], kidTRflip[4][7]); animNE = new Animation(0.25f, kidTR[2][7], kidTR[2][8], kidTR[2][9], kidTR[2][7]); animNW = new Animation(0.25f, kidTRflip[2][7], kidTRflip[2][8], kidTRflip[2][9], kidTRflip[2][7]); animSE = new Animation(0.25f, kidTR[3][7], kidTR[3][8], kidTR[3][9], kidTR[3][7]); animSW = new Animation(0.25f, kidTRflip[3][7], kidTRflip[3][8], kidTRflip[3][9], kidTRflip[3][7]); animStopDOWN = new Animation(0.25f, kidTR[5][7]); animStopRIGHT = new Animation(0.25f, kidTR[4][7]); animStopUP = new Animation(0.25f, kidTR[1][7]); animStopLEFT = new Animation(0.25f, kidTRflip[4][7]); animStopNE = new Animation(0.25f, kidTR[2][7]); animStopNW = new Animation(0.25f, kidTRflip[2][7]); animStopSE = new Animation(0.25f, kidTR[3][7]); animStopSW = new Animation(0.25f, kidTRflip[3][7]); // Set initial position of the kid anim = animStopDOWN; } }
punkto/mightyLD36
core/src/ludum/mighty/ld36/animations/AnimatorSonicBoom.java
Java
apache-2.0
2,485
#include "arg_conversion.h" #include "command_buffer.h" static command_buffer buffer; int piss_off(int a, double b) { return printf("piss_off called with %d, %f\n", a, b); } static const char piss_off_usage[] = "piss_off int double\nYell numbers!"; void kill_player(const std::string& name) { printf("Killing player \"%s\"\n", name.c_str()); } static const char kill_usage[] = "kill player_name"; int main() { function_mapping fm; fm.add_mapping("howdy", piss_off, piss_off_usage); fm.add_mapping("kill", kill_player, kill_usage); buffer.push_command("howdy 5 6.2"); buffer.push_command("no_such_command arg1"); buffer.push_command("kill jared 5"); buffer.push_command("kill jared"); fm.execute_command(buffer.pop_command()); fm.execute_command(buffer.pop_command()); fm.execute_command(buffer.pop_command()); fm.execute_command(buffer.pop_command()); }
n00btime/gen_wrapper
my_test.cpp
C++
apache-2.0
871
package es.tid.pce.client.management; import java.net.ServerSocket; import java.util.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import es.tid.pce.client.emulator.AutomaticTesterStatistics; import es.tid.pce.client.emulator.Emulator; import es.tid.pce.client.tester.InformationRequest; public class AutomaticTesterManagementSever extends Thread { private Logger log; private Timer timer; private Timer printStatisticsTimer; // private Timer planificationTimer; private AutomaticTesterStatistics stats; private InformationRequest informationRequest; private Emulator emulator; // private PCCPCEPSession PCEsession; // private PCCPCEPSession PCEsessionVNTM; public AutomaticTesterManagementSever(/*PCCPCEPSession PCEsession,PCCPCEPSession PCEsessionVNTM,*/Timer timer, Timer printStatisticsTimer, /*Timer planificationTimer,*/AutomaticTesterStatistics stats, InformationRequest info){ log =LoggerFactory.getLogger("PCCClient"); this.timer = timer; this.stats=stats; this.informationRequest=info; this.printStatisticsTimer =printStatisticsTimer; // this.planificationTimer=planificationTimer; // this.PCEsession=PCEsession; // this.PCEsessionVNTM=PCEsessionVNTM; } public AutomaticTesterManagementSever(Emulator emulator){ log =LoggerFactory.getLogger("PCCClient"); this.emulator=emulator; } public void run(){ ServerSocket serverSocket = null; boolean listening=true; int port =emulator.getTesterParams().getManagementClientPort(); try { log.info("Listening on port "+port); serverSocket = new ServerSocket(port); } catch (Exception e){ log.error("Could not listen management on port "+port); e.printStackTrace(); return; } try { while (listening) { if (emulator==null) new AutomaticTesterManagementSession(serverSocket.accept(),timer,printStatisticsTimer,stats,/*PCEsession,PCEsessionVNTM,*/informationRequest,informationRequest.calculateLoad()).start(); else new AutomaticTesterManagementSession(serverSocket.accept(),emulator); } serverSocket.close(); } catch (Exception e) { e.printStackTrace(); } } }
telefonicaid/netphony-gmpls-emulator
src/main/java/es/tid/pce/client/management/AutomaticTesterManagementSever.java
Java
apache-2.0
2,161
package com.joey.bak.base.ui; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.joe.zatuji.MyApplication; import com.joe.zatuji.R; import com.joe.zatuji.base.BasePresenter; import com.joe.zatuji.base.LoadingView; import com.joe.zatuji.utils.KToast; import com.joe.zatuji.utils.TUtil; import com.joe.zatuji.view.LoadingDialog; import com.squareup.leakcanary.RefWatcher; /** * Created by Joe on 2016/4/16. */ public abstract class BaseFragment<T extends BasePresenter> extends android.support.v4.app.Fragment implements LoadingView { protected Activity mActivity; protected View mRootView; protected AlertDialog dialog; protected MyApplication myApplication; protected LoadingDialog mLoadingDialog; protected T mPresenter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.mActivity=getActivity(); this.myApplication= (MyApplication) mActivity.getApplication(); //initLeakCanary(); onSaveFragmentInstance(savedInstanceState); initLoading(); } private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN"; private void onSaveFragmentInstance(Bundle savedInstanceState) { if (savedInstanceState != null) { boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN); FragmentTransaction ft = getFragmentManager().beginTransaction(); if (isSupportHidden) { ft.hide(this); } else { ft.show(this); } ft.commit(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(STATE_SAVE_IS_HIDDEN,isHidden()); } protected void initLeakCanary(){ RefWatcher refWatcher = MyApplication.getRefWatcher(mActivity); refWatcher.watch(this); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); this.mActivity=getActivity(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(getLayout(),null); initPM(); initView(); initPresenter(); initListener(); return mRootView; } protected void initPM() { mPresenter = TUtil.getT(this,0); if(mPresenter!=null) mPresenter.onStart(); } protected void initLoading() { dialog = new AlertDialog.Builder(mActivity).create(); } protected void initListener() { } protected abstract int getLayout(); protected void initView(){ } protected abstract void initPresenter(); @Override public void showLoading() { View loadingView=View.inflate(mActivity, R.layout.dialog_loading,null); dialog.setContentView(loadingView); dialog.show(); } @Override public void doneLoading() { if(mLoadingDialog!=null){ mLoadingDialog.dismiss(); } // dialog.dismiss(); } @Override public void showError(String str) { KToast.show(str); } protected void showEmptyView(){ } public void showLoading(String msg){ if(mLoadingDialog==null) mLoadingDialog = new LoadingDialog(mActivity,msg); mLoadingDialog.setMessage(msg); mLoadingDialog.show(); } @Override public void onDestroy() { super.onDestroy(); if(mPresenter!=null) mPresenter.onRemove(); } protected View findView(int id){ return mRootView.findViewById(id); } }
JoeSteven/HuaBan
bak/src/main/java/com/joey/bak/base/ui/BaseFragment.java
Java
apache-2.0
3,988
/*! * ${copyright} */ // Provides control sap.ui.commons.HorizontalDivider. sap.ui.define([ './library', 'sap/ui/core/Control', './HorizontalDividerRenderer' ], function(library, Control, HorizontalDividerRenderer) { "use strict"; // shortcut for sap.ui.commons.HorizontalDividerHeight var HorizontalDividerHeight = library.HorizontalDividerHeight; // shortcut for sap.ui.commons.HorizontalDividerType var HorizontalDividerType = library.HorizontalDividerType; /** * Constructor for a new HorizontalDivider. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * Divides the screen in visual areas. * @extends sap.ui.core.Control * @version ${version} * * @constructor * @public * @deprecated Since version 1.38. * @alias sap.ui.commons.HorizontalDivider * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var HorizontalDivider = Control.extend("sap.ui.commons.HorizontalDivider", /** @lends sap.ui.commons.HorizontalDivider.prototype */ { metadata : { library : "sap.ui.commons", deprecated: true, properties : { /** * Defines the width of the divider. */ width : {type : "sap.ui.core.CSSSize", group : "Appearance", defaultValue : '100%'}, /** * Defines the type of the divider. */ type : {type : "sap.ui.commons.HorizontalDividerType", group : "Appearance", defaultValue : HorizontalDividerType.Area}, /** * Defines the height of the divider. */ height : {type : "sap.ui.commons.HorizontalDividerHeight", group : "Appearance", defaultValue : HorizontalDividerHeight.Medium} } }}); // No Behaviour return HorizontalDivider; });
SAP/openui5
src/sap.ui.commons/src/sap/ui/commons/HorizontalDivider.js
JavaScript
apache-2.0
1,812
/* * 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 mina.udp.perf; import java.io.IOException; import java.net.InetSocketAddress; import java.util.concurrent.atomic.AtomicInteger; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.transport.socket.DatagramSessionConfig; import org.apache.mina.transport.socket.nio.NioDatagramAcceptor; /** * An UDP server used for performance tests. * * It does nothing fancy, except receiving the messages, and counting the number of * received messages. * * @author <a href="http://mina.apache.org">Apache MINA Project</a> */ public class UdpServer extends IoHandlerAdapter { /** The listening port (check that it's not already in use) */ public static final int PORT = 18567; /** The number of message to receive */ public static final int MAX_RECEIVED = 100000; /** The starting point, set when we receive the first message */ private static long t0; /** A counter incremented for every recieved message */ private AtomicInteger nbReceived = new AtomicInteger(0); /** * {@inheritDoc} */ @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { cause.printStackTrace(); session.close(true); } /** * {@inheritDoc} */ @Override public void messageReceived(IoSession session, Object message) throws Exception { int nb = nbReceived.incrementAndGet(); if (nb == 1) { t0 = System.currentTimeMillis(); } if (nb == MAX_RECEIVED) { long t1 = System.currentTimeMillis(); System.out.println("-------------> end " + (t1 - t0)); } if (nb % 10000 == 0) { System.out.println("Received " + nb + " messages"); } // If we want to MapDB.test the write operation, uncomment this line session.write(message); } /** * {@inheritDoc} */ @Override public void sessionClosed(IoSession session) throws Exception { System.out.println("Session closed..."); // Reinitialize the counter and expose the number of received messages System.out.println("Nb message received : " + nbReceived.get()); nbReceived.set(0); } /** * {@inheritDoc} */ @Override public void sessionCreated(IoSession session) throws Exception { System.out.println("Session created..."); } /** * {@inheritDoc} */ @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { System.out.println("Session idle..."); } /** * {@inheritDoc} */ @Override public void sessionOpened(IoSession session) throws Exception { System.out.println("Session Opened..."); } /** * Create the UDP server */ public UdpServer() throws IOException { NioDatagramAcceptor acceptor = new NioDatagramAcceptor(); acceptor.setHandler(this); // The logger, if needed. Commented atm //DefaultIoFilterChainBuilder chain = acceptor.getFilterChain(); //chain.addLast("logger", new LoggingFilter()); DatagramSessionConfig dcfg = acceptor.getSessionConfig(); acceptor.bind(new InetSocketAddress(PORT)); System.out.println("Server started..."); } /** * The entry point. */ public static void main(String[] args) throws IOException { new UdpServer(); } }
iloveyou416068/CookNIOServer
demos/mina/src/mina/udp/perf/UdpServer.java
Java
apache-2.0
4,387
/* * Copyright (C) 2011-2016 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <assert.h> #include "parserfactory.h" #include "util.h" #include "elf32parser.h" #include "elf64parser.h" namespace { bin_fmt_t check_elf_format(const uint8_t* start_addr, uint64_t len) { assert(start_addr != NULL); const Elf32_Ehdr* ehdr = (const Elf32_Ehdr *) start_addr; if (len < sizeof(Elf32_Ehdr)) return BF_UNKNOWN; if (strncmp((const char *)ehdr->e_ident, ELFMAG, SELFMAG) != 0) return BF_UNKNOWN; switch (ehdr->e_ident[EI_CLASS]) { case ELFCLASS32: return BF_ELF32; case ELFCLASS64: return BF_ELF64; default: return BF_UNKNOWN; } } } namespace binparser { /* Note, the `start_addr' should NOT be NULL! */ BinParser* get_parser(const uint8_t* start_addr, uint64_t len) { assert(start_addr != NULL); bin_fmt_t bf = BF_UNKNOWN; bf = check_elf_format(start_addr, len); if (bf == BF_ELF64) return new Elf64Parser(start_addr, len); /* Doesn't matter whether it is an ELF32 shared library or not, * here we just make sure that the factory method won't return * NULL. */ return new Elf32Parser(start_addr, len); } }
shwetasshinde24/Panoply
patched-driver-sdk/customSDK/psw/urts/parser/parserfactory.cpp
C++
apache-2.0
2,856
<?php // Heading $_['heading_title'] = 'Quốc Gia'; // Text $_['text_success'] = 'Hoàn tất: Bạn đã sửa đổi các Quốc Gia!'; $_['text_list'] = 'Danh sách các Quốc gia'; $_['text_add'] = 'Thêm Quốc gia'; $_['text_edit'] = 'Sửa Quốc Gia'; // Column $_['column_name'] = 'Tên Quốc Gia'; $_['column_iso_code_2'] = 'Mã ISO (2)'; $_['column_iso_code_3'] = 'Mã ISO (3)'; $_['column_action'] = 'Thao tác'; // Entry $_['entry_name'] = 'Tên Quốc Gia:'; $_['entry_iso_code_2'] = 'Mã ISO (2):'; $_['entry_iso_code_3'] = 'Mã ISO (3):'; $_['entry_address_format'] = 'Định dạng địa chỉ :'; $_['entry_postcode_required']= 'Yêu cầu mã vùng:'; $_['entry_status'] = 'Tình trạng:'; // Help $_['help_address_format'] = 'Họ = {firstname}<br />Tên = {lastname}<br />Công ty = {company}<br />Địa chỉ 1 = {address_1}<br />Địa chỉ 2 = {address_2}<br />Quận, Huyện = {city}<br />Mã vùng = {postcode}<br />Tỉnh, Thành phố = {zone}<br />Mã Tỉnh, Thành phố = {zone_code}<br />Quốc Gia = {country}'; // Error $_['error_permission'] = 'Cảnh báo: Bạn không được phép sửa đổi các quốc gia!'; $_['error_name'] = 'Tên quốc gia phải lớn hơn 3 và nhỏ hơn 128 ký tự!'; $_['error_default'] = 'Cảnh báo: Bạn không thể xóa Quốc gia này!'; $_['error_store'] = 'Cảnh báo: Bạn không thể xóa Quốc gia này vì nó đang được thiết lập cho gian hàng %s!'; $_['error_address'] = 'Cảnh báo: Bạn không thể xóa Quốc gia này!'; $_['error_affiliate'] = 'Cảnh báo: Nước này không thể bị xóa khi nó hiện thời được gán tới %s chi nhánh.!'; $_['error_zone'] = 'Cảnh báo: Quốc gia này có thể không bị xóa!'; $_['error_zone_to_geo_zone'] = 'Cảnh báo: Quốc gia này có thể không bị xóa!'; ?>
duythanhitc/ShopCartClean
admin/language/vi-vn/localisation/country.php
PHP
apache-2.0
2,084
<?php /** * Copyright 2015 Xenofon Spafaridis * * 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. */ //Show all errors error_reporting(E_ALL); ini_set('display_errors', '1'); //This autoload path is for loading current version of phramework require __DIR__ . '/../vendor/autoload.php'; //define controller namespace, as shortcut define('NS', '\\Phramework\\Examples\\API\\Controllers\\'); use \Phramework\Phramework; /** * @package examples/post * Define APP as function */ $APP = function () { //Include settings $settings = include __DIR__ . '/../settings.php'; $URIStrategy = new \Phramework\URIStrategy\URITemplate([ ['book/', NS . 'BookController', 'GET', Phramework::METHOD_GET], ['book/{id}', NS . 'BookController', 'GETSingle', Phramework::METHOD_GET], ['book/', NS . 'BookController', 'POST', Phramework::METHOD_POST] ]); //Initialize API $phramework = new Phramework($settings, $URIStrategy); unset($settings); Phramework::setViewer( \Phramework\Viewers\JSON::class ); //Execute API $phramework->invoke(); }; /** * Execute APP */ $APP();
phramework/examples-api
public/index.php
PHP
apache-2.0
1,649
/* * Copyright 2010-2012 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.storagegateway.model; /** * <p> * A JSON object containing the following fields: * </p> * * <ul> * <li> GatewayARN </li> * <li> DescribeMaintenanceStartTimeOutput$DayOfWeek </li> * <li> DescribeMaintenanceStartTimeOutput$HourOfDay </li> * <li> DescribeMaintenanceStartTimeOutput$MinuteOfHour </li> * <li> DescribeMaintenanceStartTimeOutput$Timezone </li> * * </ul> */ public class DescribeMaintenanceStartTimeResult { /** * The Amazon Resource Name (ARN) of the gateway. Use the * <a>ListGateways</a> operation to return a list of gateways for your * account and region. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>50 - 500<br/> */ private String gatewayARN; /** * A number between 0 and 23 that represents the hour of day. The hour of * day is in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>0 - 23<br/> */ private Integer hourOfDay; /** * A number between 0 and 59 that represents the minute of hour. The * minute of hour is in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>0 - 59<br/> */ private Integer minuteOfHour; /** * An ordinal number between 0 and 6 that represents the day of the week, * where 0 represents Sunday and 6 represents Saturday. The day of week * is in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>0 - 6<br/> */ private Integer dayOfWeek; /** * One of the <a>GatewayTimezone</a> values that indicates the time zone * that is set for the gateway. The start time and day of week specified * should be in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>GMT-12:00, GMT-11:00, GMT-10:00, GMT-9:00, GMT-8:00, GMT-7:00, GMT-6:00, GMT-5:00, GMT-4:00, GMT-3:30, GMT-3:00, GMT-2:00, GMT-1:00, GMT, GMT+1:00, GMT+2:00, GMT+3:00, GMT+3:30, GMT+4:00, GMT+4:30, GMT+5:00, GMT+5:30, GMT+5:45, GMT+6:00, GMT+7:00, GMT+8:00, GMT+9:00, GMT+9:30, GMT+10:00, GMT+11:00, GMT+12:00 */ private String timezone; /** * The Amazon Resource Name (ARN) of the gateway. Use the * <a>ListGateways</a> operation to return a list of gateways for your * account and region. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>50 - 500<br/> * * @return The Amazon Resource Name (ARN) of the gateway. Use the * <a>ListGateways</a> operation to return a list of gateways for your * account and region. */ public String getGatewayARN() { return gatewayARN; } /** * The Amazon Resource Name (ARN) of the gateway. Use the * <a>ListGateways</a> operation to return a list of gateways for your * account and region. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>50 - 500<br/> * * @param gatewayARN The Amazon Resource Name (ARN) of the gateway. Use the * <a>ListGateways</a> operation to return a list of gateways for your * account and region. */ public void setGatewayARN(String gatewayARN) { this.gatewayARN = gatewayARN; } /** * The Amazon Resource Name (ARN) of the gateway. Use the * <a>ListGateways</a> operation to return a list of gateways for your * account and region. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>50 - 500<br/> * * @param gatewayARN The Amazon Resource Name (ARN) of the gateway. Use the * <a>ListGateways</a> operation to return a list of gateways for your * account and region. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeMaintenanceStartTimeResult withGatewayARN(String gatewayARN) { this.gatewayARN = gatewayARN; return this; } /** * A number between 0 and 23 that represents the hour of day. The hour of * day is in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>0 - 23<br/> * * @return A number between 0 and 23 that represents the hour of day. The hour of * day is in the time zone of the gateway. */ public Integer getHourOfDay() { return hourOfDay; } /** * A number between 0 and 23 that represents the hour of day. The hour of * day is in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>0 - 23<br/> * * @param hourOfDay A number between 0 and 23 that represents the hour of day. The hour of * day is in the time zone of the gateway. */ public void setHourOfDay(Integer hourOfDay) { this.hourOfDay = hourOfDay; } /** * A number between 0 and 23 that represents the hour of day. The hour of * day is in the time zone of the gateway. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>0 - 23<br/> * * @param hourOfDay A number between 0 and 23 that represents the hour of day. The hour of * day is in the time zone of the gateway. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeMaintenanceStartTimeResult withHourOfDay(Integer hourOfDay) { this.hourOfDay = hourOfDay; return this; } /** * A number between 0 and 59 that represents the minute of hour. The * minute of hour is in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>0 - 59<br/> * * @return A number between 0 and 59 that represents the minute of hour. The * minute of hour is in the time zone of the gateway. */ public Integer getMinuteOfHour() { return minuteOfHour; } /** * A number between 0 and 59 that represents the minute of hour. The * minute of hour is in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>0 - 59<br/> * * @param minuteOfHour A number between 0 and 59 that represents the minute of hour. The * minute of hour is in the time zone of the gateway. */ public void setMinuteOfHour(Integer minuteOfHour) { this.minuteOfHour = minuteOfHour; } /** * A number between 0 and 59 that represents the minute of hour. The * minute of hour is in the time zone of the gateway. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>0 - 59<br/> * * @param minuteOfHour A number between 0 and 59 that represents the minute of hour. The * minute of hour is in the time zone of the gateway. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeMaintenanceStartTimeResult withMinuteOfHour(Integer minuteOfHour) { this.minuteOfHour = minuteOfHour; return this; } /** * An ordinal number between 0 and 6 that represents the day of the week, * where 0 represents Sunday and 6 represents Saturday. The day of week * is in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>0 - 6<br/> * * @return An ordinal number between 0 and 6 that represents the day of the week, * where 0 represents Sunday and 6 represents Saturday. The day of week * is in the time zone of the gateway. */ public Integer getDayOfWeek() { return dayOfWeek; } /** * An ordinal number between 0 and 6 that represents the day of the week, * where 0 represents Sunday and 6 represents Saturday. The day of week * is in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>0 - 6<br/> * * @param dayOfWeek An ordinal number between 0 and 6 that represents the day of the week, * where 0 represents Sunday and 6 represents Saturday. The day of week * is in the time zone of the gateway. */ public void setDayOfWeek(Integer dayOfWeek) { this.dayOfWeek = dayOfWeek; } /** * An ordinal number between 0 and 6 that represents the day of the week, * where 0 represents Sunday and 6 represents Saturday. The day of week * is in the time zone of the gateway. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>0 - 6<br/> * * @param dayOfWeek An ordinal number between 0 and 6 that represents the day of the week, * where 0 represents Sunday and 6 represents Saturday. The day of week * is in the time zone of the gateway. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeMaintenanceStartTimeResult withDayOfWeek(Integer dayOfWeek) { this.dayOfWeek = dayOfWeek; return this; } /** * One of the <a>GatewayTimezone</a> values that indicates the time zone * that is set for the gateway. The start time and day of week specified * should be in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>GMT-12:00, GMT-11:00, GMT-10:00, GMT-9:00, GMT-8:00, GMT-7:00, GMT-6:00, GMT-5:00, GMT-4:00, GMT-3:30, GMT-3:00, GMT-2:00, GMT-1:00, GMT, GMT+1:00, GMT+2:00, GMT+3:00, GMT+3:30, GMT+4:00, GMT+4:30, GMT+5:00, GMT+5:30, GMT+5:45, GMT+6:00, GMT+7:00, GMT+8:00, GMT+9:00, GMT+9:30, GMT+10:00, GMT+11:00, GMT+12:00 * * @return One of the <a>GatewayTimezone</a> values that indicates the time zone * that is set for the gateway. The start time and day of week specified * should be in the time zone of the gateway. * * @see GatewayTimezone */ public String getTimezone() { return timezone; } /** * One of the <a>GatewayTimezone</a> values that indicates the time zone * that is set for the gateway. The start time and day of week specified * should be in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>GMT-12:00, GMT-11:00, GMT-10:00, GMT-9:00, GMT-8:00, GMT-7:00, GMT-6:00, GMT-5:00, GMT-4:00, GMT-3:30, GMT-3:00, GMT-2:00, GMT-1:00, GMT, GMT+1:00, GMT+2:00, GMT+3:00, GMT+3:30, GMT+4:00, GMT+4:30, GMT+5:00, GMT+5:30, GMT+5:45, GMT+6:00, GMT+7:00, GMT+8:00, GMT+9:00, GMT+9:30, GMT+10:00, GMT+11:00, GMT+12:00 * * @param timezone One of the <a>GatewayTimezone</a> values that indicates the time zone * that is set for the gateway. The start time and day of week specified * should be in the time zone of the gateway. * * @see GatewayTimezone */ public void setTimezone(String timezone) { this.timezone = timezone; } /** * One of the <a>GatewayTimezone</a> values that indicates the time zone * that is set for the gateway. The start time and day of week specified * should be in the time zone of the gateway. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>GMT-12:00, GMT-11:00, GMT-10:00, GMT-9:00, GMT-8:00, GMT-7:00, GMT-6:00, GMT-5:00, GMT-4:00, GMT-3:30, GMT-3:00, GMT-2:00, GMT-1:00, GMT, GMT+1:00, GMT+2:00, GMT+3:00, GMT+3:30, GMT+4:00, GMT+4:30, GMT+5:00, GMT+5:30, GMT+5:45, GMT+6:00, GMT+7:00, GMT+8:00, GMT+9:00, GMT+9:30, GMT+10:00, GMT+11:00, GMT+12:00 * * @param timezone One of the <a>GatewayTimezone</a> values that indicates the time zone * that is set for the gateway. The start time and day of week specified * should be in the time zone of the gateway. * * @return A reference to this updated object so that method calls can be chained * together. * * @see GatewayTimezone */ public DescribeMaintenanceStartTimeResult withTimezone(String timezone) { this.timezone = timezone; return this; } /** * One of the <a>GatewayTimezone</a> values that indicates the time zone * that is set for the gateway. The start time and day of week specified * should be in the time zone of the gateway. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>GMT-12:00, GMT-11:00, GMT-10:00, GMT-9:00, GMT-8:00, GMT-7:00, GMT-6:00, GMT-5:00, GMT-4:00, GMT-3:30, GMT-3:00, GMT-2:00, GMT-1:00, GMT, GMT+1:00, GMT+2:00, GMT+3:00, GMT+3:30, GMT+4:00, GMT+4:30, GMT+5:00, GMT+5:30, GMT+5:45, GMT+6:00, GMT+7:00, GMT+8:00, GMT+9:00, GMT+9:30, GMT+10:00, GMT+11:00, GMT+12:00 * * @param timezone One of the <a>GatewayTimezone</a> values that indicates the time zone * that is set for the gateway. The start time and day of week specified * should be in the time zone of the gateway. * * @see GatewayTimezone */ public void setTimezone(GatewayTimezone timezone) { this.timezone = timezone.toString(); } /** * One of the <a>GatewayTimezone</a> values that indicates the time zone * that is set for the gateway. The start time and day of week specified * should be in the time zone of the gateway. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>GMT-12:00, GMT-11:00, GMT-10:00, GMT-9:00, GMT-8:00, GMT-7:00, GMT-6:00, GMT-5:00, GMT-4:00, GMT-3:30, GMT-3:00, GMT-2:00, GMT-1:00, GMT, GMT+1:00, GMT+2:00, GMT+3:00, GMT+3:30, GMT+4:00, GMT+4:30, GMT+5:00, GMT+5:30, GMT+5:45, GMT+6:00, GMT+7:00, GMT+8:00, GMT+9:00, GMT+9:30, GMT+10:00, GMT+11:00, GMT+12:00 * * @param timezone One of the <a>GatewayTimezone</a> values that indicates the time zone * that is set for the gateway. The start time and day of week specified * should be in the time zone of the gateway. * * @return A reference to this updated object so that method calls can be chained * together. * * @see GatewayTimezone */ public DescribeMaintenanceStartTimeResult withTimezone(GatewayTimezone timezone) { this.timezone = timezone.toString(); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (gatewayARN != null) sb.append("GatewayARN: " + gatewayARN + ", "); if (hourOfDay != null) sb.append("HourOfDay: " + hourOfDay + ", "); if (minuteOfHour != null) sb.append("MinuteOfHour: " + minuteOfHour + ", "); if (dayOfWeek != null) sb.append("DayOfWeek: " + dayOfWeek + ", "); if (timezone != null) sb.append("Timezone: " + timezone + ", "); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getGatewayARN() == null) ? 0 : getGatewayARN().hashCode()); hashCode = prime * hashCode + ((getHourOfDay() == null) ? 0 : getHourOfDay().hashCode()); hashCode = prime * hashCode + ((getMinuteOfHour() == null) ? 0 : getMinuteOfHour().hashCode()); hashCode = prime * hashCode + ((getDayOfWeek() == null) ? 0 : getDayOfWeek().hashCode()); hashCode = prime * hashCode + ((getTimezone() == null) ? 0 : getTimezone().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeMaintenanceStartTimeResult == false) return false; DescribeMaintenanceStartTimeResult other = (DescribeMaintenanceStartTimeResult)obj; if (other.getGatewayARN() == null ^ this.getGatewayARN() == null) return false; if (other.getGatewayARN() != null && other.getGatewayARN().equals(this.getGatewayARN()) == false) return false; if (other.getHourOfDay() == null ^ this.getHourOfDay() == null) return false; if (other.getHourOfDay() != null && other.getHourOfDay().equals(this.getHourOfDay()) == false) return false; if (other.getMinuteOfHour() == null ^ this.getMinuteOfHour() == null) return false; if (other.getMinuteOfHour() != null && other.getMinuteOfHour().equals(this.getMinuteOfHour()) == false) return false; if (other.getDayOfWeek() == null ^ this.getDayOfWeek() == null) return false; if (other.getDayOfWeek() != null && other.getDayOfWeek().equals(this.getDayOfWeek()) == false) return false; if (other.getTimezone() == null ^ this.getTimezone() == null) return false; if (other.getTimezone() != null && other.getTimezone().equals(this.getTimezone()) == false) return false; return true; } }
frsyuki/aws-sdk-for-java
src/main/java/com/amazonaws/services/storagegateway/model/DescribeMaintenanceStartTimeResult.java
Java
apache-2.0
18,484
from __future__ import absolute_import from django.utils.translation import ugettext as _ from django.conf import settings from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import authenticate from zerver.decorator import authenticated_json_post_view, has_request_variables, REQ from zerver.lib.actions import do_change_password, \ do_change_full_name, do_change_enable_desktop_notifications, \ do_change_enter_sends, do_change_enable_sounds, \ do_change_enable_offline_email_notifications, do_change_enable_digest_emails, \ do_change_enable_offline_push_notifications, do_change_autoscroll_forever, \ do_change_default_desktop_notifications, \ do_change_enable_stream_desktop_notifications, do_change_enable_stream_sounds, \ do_regenerate_api_key, do_change_avatar_source, do_change_twenty_four_hour_time, do_change_left_side_userlist from zerver.lib.avatar import avatar_url from zerver.lib.response import json_success, json_error from zerver.lib.upload import upload_avatar_image from zerver.lib.validator import check_bool from zerver.models import UserProfile from zerver.lib.rest import rest_dispatch as _rest_dispatch rest_dispatch = csrf_exempt((lambda request, *args, **kwargs: _rest_dispatch(request, globals(), *args, **kwargs))) def name_changes_disabled(realm): return settings.NAME_CHANGES_DISABLED or realm.name_changes_disabled @authenticated_json_post_view @has_request_variables def json_change_ui_settings(request, user_profile, autoscroll_forever=REQ(validator=check_bool, default=None), default_desktop_notifications=REQ(validator=check_bool, default=None)): result = {} if autoscroll_forever is not None and \ user_profile.autoscroll_forever != autoscroll_forever: do_change_autoscroll_forever(user_profile, autoscroll_forever) result['autoscroll_forever'] = autoscroll_forever if default_desktop_notifications is not None and \ user_profile.default_desktop_notifications != default_desktop_notifications: do_change_default_desktop_notifications(user_profile, default_desktop_notifications) result['default_desktop_notifications'] = default_desktop_notifications return json_success(result) @authenticated_json_post_view @has_request_variables def json_change_settings(request, user_profile, full_name=REQ(), old_password=REQ(default=""), new_password=REQ(default=""), confirm_password=REQ(default="")): if new_password != "" or confirm_password != "": if new_password != confirm_password: return json_error(_("New password must match confirmation password!")) if not authenticate(username=user_profile.email, password=old_password): return json_error(_("Wrong password!")) do_change_password(user_profile, new_password) result = {} if user_profile.full_name != full_name and full_name.strip() != "": if name_changes_disabled(user_profile.realm): # Failingly silently is fine -- they can't do it through the UI, so # they'd have to be trying to break the rules. pass else: new_full_name = full_name.strip() if len(new_full_name) > UserProfile.MAX_NAME_LENGTH: return json_error(_("Name too long!")) do_change_full_name(user_profile, new_full_name) result['full_name'] = new_full_name return json_success(result) @authenticated_json_post_view @has_request_variables def json_time_setting(request, user_profile, twenty_four_hour_time=REQ(validator=check_bool, default=None)): result = {} if twenty_four_hour_time is not None and \ user_profile.twenty_four_hour_time != twenty_four_hour_time: do_change_twenty_four_hour_time(user_profile, twenty_four_hour_time) result['twenty_four_hour_time'] = twenty_four_hour_time return json_success(result) @authenticated_json_post_view @has_request_variables def json_left_side_userlist(request, user_profile, left_side_userlist=REQ(validator=check_bool, default=None)): result = {} if left_side_userlist is not None and \ user_profile.left_side_userlist != left_side_userlist: do_change_left_side_userlist(user_profile, left_side_userlist) result['left_side_userlist'] = left_side_userlist return json_success(result) @authenticated_json_post_view @has_request_variables def json_change_notify_settings(request, user_profile, enable_stream_desktop_notifications=REQ(validator=check_bool, default=None), enable_stream_sounds=REQ(validator=check_bool, default=None), enable_desktop_notifications=REQ(validator=check_bool, default=None), enable_sounds=REQ(validator=check_bool, default=None), enable_offline_email_notifications=REQ(validator=check_bool, default=None), enable_offline_push_notifications=REQ(validator=check_bool, default=None), enable_digest_emails=REQ(validator=check_bool, default=None)): result = {} # Stream notification settings. if enable_stream_desktop_notifications is not None and \ user_profile.enable_stream_desktop_notifications != enable_stream_desktop_notifications: do_change_enable_stream_desktop_notifications( user_profile, enable_stream_desktop_notifications) result['enable_stream_desktop_notifications'] = enable_stream_desktop_notifications if enable_stream_sounds is not None and \ user_profile.enable_stream_sounds != enable_stream_sounds: do_change_enable_stream_sounds(user_profile, enable_stream_sounds) result['enable_stream_sounds'] = enable_stream_sounds # PM and @-mention settings. if enable_desktop_notifications is not None and \ user_profile.enable_desktop_notifications != enable_desktop_notifications: do_change_enable_desktop_notifications(user_profile, enable_desktop_notifications) result['enable_desktop_notifications'] = enable_desktop_notifications if enable_sounds is not None and \ user_profile.enable_sounds != enable_sounds: do_change_enable_sounds(user_profile, enable_sounds) result['enable_sounds'] = enable_sounds if enable_offline_email_notifications is not None and \ user_profile.enable_offline_email_notifications != enable_offline_email_notifications: do_change_enable_offline_email_notifications(user_profile, enable_offline_email_notifications) result['enable_offline_email_notifications'] = enable_offline_email_notifications if enable_offline_push_notifications is not None and \ user_profile.enable_offline_push_notifications != enable_offline_push_notifications: do_change_enable_offline_push_notifications(user_profile, enable_offline_push_notifications) result['enable_offline_push_notifications'] = enable_offline_push_notifications if enable_digest_emails is not None and \ user_profile.enable_digest_emails != enable_digest_emails: do_change_enable_digest_emails(user_profile, enable_digest_emails) result['enable_digest_emails'] = enable_digest_emails return json_success(result) @authenticated_json_post_view def json_set_avatar(request, user_profile): if len(request.FILES) != 1: return json_error(_("You must upload exactly one avatar.")) user_file = list(request.FILES.values())[0] upload_avatar_image(user_file, user_profile, user_profile.email) do_change_avatar_source(user_profile, UserProfile.AVATAR_FROM_USER) user_avatar_url = avatar_url(user_profile) json_result = dict( avatar_url = user_avatar_url ) return json_success(json_result) @has_request_variables def regenerate_api_key(request, user_profile): do_regenerate_api_key(user_profile) json_result = dict( api_key = user_profile.api_key ) return json_success(json_result) @has_request_variables def change_enter_sends(request, user_profile, enter_sends=REQ('enter_sends', validator=check_bool)): do_change_enter_sends(user_profile, enter_sends) return json_success()
peiwei/zulip
zerver/views/user_settings.py
Python
apache-2.0
9,076
import path from 'path' import chromedriver from 'chromedriver' import webdriver from 'selenium-webdriver' import electronPath from 'electron-prebuilt' import homeStyles from '../app/components/Home.css' import counterStyles from '../app/components/Counter.css' chromedriver.start() // on port 9515 process.on('exit', chromedriver.stop) const delay = time => new Promise(resolve => setTimeout(resolve, time)) describe('main window', function spec() { this.timeout(5000) before(async () => { await delay(1000) // wait chromedriver start time this.driver = new webdriver.Builder() .usingServer('http://localhost:9515') .withCapabilities({ chromeOptions: { binary: electronPath, args: ['app=' + path.resolve()], }, }) .forBrowser('electron') .build() }) after(async () => { await this.driver.quit() }) const findCounter = () => { return this.driver.findElement(webdriver.By.className(counterStyles.counter)) } const findButtons = () => { return this.driver.findElements(webdriver.By.className(counterStyles.btn)) } it('should open window', async () => { const title = await this.driver.getTitle() expect(title).to.equal('Hello Electron React!') }) it('should to Counter with click "to Counter" link', async () => { const link = await this.driver.findElement(webdriver.By.css(`.${homeStyles.container} > a`)) link.click() const counter = await findCounter() expect(await counter.getText()).to.equal('0') }) it('should display updated count after increment button click', async () => { const buttons = await findButtons() buttons[0].click() const counter = await findCounter() expect(await counter.getText()).to.equal('1') }) it('should display updated count after descrement button click', async () => { const buttons = await findButtons() const counter = await findCounter() buttons[1].click() // - expect(await counter.getText()).to.equal('0') }) it('shouldnt change if even and if odd button clicked', async () => { const buttons = await findButtons() const counter = await findCounter() buttons[2].click() // odd expect(await counter.getText()).to.equal('0') }) it('should change if odd and if odd button clicked', async () => { const buttons = await findButtons() const counter = await findCounter() buttons[0].click() // + buttons[2].click() // odd expect(await counter.getText()).to.equal('2') }) it('should change if async button clicked and a second later', async () => { const buttons = await findButtons() const counter = await findCounter() buttons[3].click() // async expect(await counter.getText()).to.equal('2') await this.driver.wait(() => counter.getText().then(text => text === '3') , 1000, 'count not as expected') }) it('should back to home if back button clicked', async () => { const link = await this.driver.findElement(webdriver.By.css(`.${counterStyles.backButton} > a`)) link.click() await this.driver.findElement(webdriver.By.className(homeStyles.container)) }) })
3-strand-code/3sc-desktop
test/e2e.js
JavaScript
apache-2.0
3,188
package com.example.apkdownloadspeedtest; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper_downloader extends SQLiteOpenHelper { public DBHelper_downloader(Context context) { //"download.db" is the name of database super(context, "download.db", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table IF NOT EXISTS download_info(" + "task_id integer," + "thread_id integer," + "start_pos integer," + "end_pos integer," + "cur_pos integer," + "seg_size integer," + "complete_size integer," + "is_done integer," + "url text," + "primary key(url, thread_id)" + ")" ); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // TODO Auto-generated method stub } }
princegyw/Personal-Utils
keep-old/FileDownloader_v5.0/DBHelper_downloader.java
Java
apache-2.0
929
package com.ogove.hr.Activities.Notification; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.ogove.hr.R; public class NotificationDepartmentCreate extends AppCompatActivity implements View.OnClickListener{ private EditText ndcTitle,ndcContent; private Button ndcCreate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification_department_create); addControl(); } private void addControl() { ndcCreate = (Button) findViewById(R.id.ndcCreate); ndcTitle = (EditText) findViewById(R.id.ndcTitle); ndcContent = (EditText) findViewById(R.id.ndcContent); ndcCreate.setOnClickListener(this); ndcTitle.setOnClickListener(this); ndcContent.setOnClickListener(this); } @Override public void onClick(View v) { } }
LyokoVN/HRManager
app/src/main/java/com/ogove/hr/Activities/Notification/NotificationDepartmentCreate.java
Java
apache-2.0
1,077
/* * 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.exec.store.hive; import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import org.apache.drill.common.exceptions.ExecutionSetupException; import org.apache.drill.common.expression.SchemaPath; import org.apache.drill.exec.store.StoragePluginRegistry; import java.io.IOException; import java.util.List; /** * Extension of {@link HiveSubScan} which support reading Hive tables using Drill's native parquet reader. */ @JsonTypeName("hive-drill-native-parquet-sub-scan") public class HiveDrillNativeParquetSubScan extends HiveSubScan { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(HiveDrillNativeParquetSubScan.class); @JsonCreator public HiveDrillNativeParquetSubScan(@JacksonInject StoragePluginRegistry registry, @JsonProperty("userName") String userName, @JsonProperty("splits") List<List<String>> splits, @JsonProperty("hiveReadEntry") HiveReadEntry hiveReadEntry, @JsonProperty("splitClasses") List<String> splitClasses, @JsonProperty("columns") List<SchemaPath> columns, @JsonProperty("hiveStoragePluginConfig") HiveStoragePluginConfig hiveStoragePluginConfig) throws IOException, ExecutionSetupException, ReflectiveOperationException { super(registry, userName, splits, hiveReadEntry, splitClasses, columns, hiveStoragePluginConfig); } public HiveDrillNativeParquetSubScan(final HiveSubScan subScan) throws IOException, ExecutionSetupException, ReflectiveOperationException { super(subScan.getUserName(), subScan.getSplits(), subScan.getHiveReadEntry(), subScan.getSplitClasses(), subScan.getColumns(), subScan.getStoragePlugin()); } }
KulykRoman/drill
contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveDrillNativeParquetSubScan.java
Java
apache-2.0
2,845
/* * Copyright (c) 2012-2018, Peter Abeles. All Rights Reserved. * * This file is part of DDogleg (http://ddogleg.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.ddogleg.fitting.modelset; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Peter Abeles */ public class TestModelManagerDefault { @Test public void basic() { ModelManagerDefault<Dummy> alg = new ModelManagerDefault<Dummy>(Dummy.class); Dummy a = alg.createModelInstance(); Dummy b = alg.createModelInstance(); assertTrue(a!=b); a.value = 5; alg.copyModel(a,b); assertEquals(5,a.value); assertEquals(5,b.value); } public static class Dummy { public int value; public Dummy() { } public void set(Dummy src ) { value = src.value; } } }
lessthanoptimal/ddogleg
test/org/ddogleg/fitting/modelset/TestModelManagerDefault.java
Java
apache-2.0
1,395
/* * 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.wicket.settings; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import org.apache.wicket.Application; import org.apache.wicket.Component; import org.apache.wicket.IResourceFactory; import org.apache.wicket.Localizer; import org.apache.wicket.core.util.resource.locator.IResourceStreamLocator; import org.apache.wicket.core.util.resource.locator.ResourceStreamLocator; import org.apache.wicket.core.util.resource.locator.caching.CachingResourceStreamLocator; import org.apache.wicket.css.ICssCompressor; import org.apache.wicket.javascript.IJavaScriptCompressor; import org.apache.wicket.markup.head.PriorityFirstComparator; import org.apache.wicket.markup.head.ResourceAggregator.RecordedHeaderItem; import org.apache.wicket.markup.html.IPackageResourceGuard; import org.apache.wicket.markup.html.SecurePackageResourceGuard; import org.apache.wicket.request.http.WebResponse; import org.apache.wicket.request.resource.caching.FilenameWithVersionResourceCachingStrategy; import org.apache.wicket.request.resource.caching.IResourceCachingStrategy; import org.apache.wicket.request.resource.caching.NoOpResourceCachingStrategy; import org.apache.wicket.request.resource.caching.version.CachingResourceVersion; import org.apache.wicket.request.resource.caching.version.IResourceVersion; import org.apache.wicket.request.resource.caching.version.LastModifiedResourceVersion; import org.apache.wicket.request.resource.caching.version.MessageDigestResourceVersion; import org.apache.wicket.request.resource.caching.version.RequestCycleCachedResourceVersion; import org.apache.wicket.resource.IPropertiesFactoryContext; import org.apache.wicket.resource.PropertiesFactory; import org.apache.wicket.resource.loader.ClassStringResourceLoader; import org.apache.wicket.resource.loader.ComponentStringResourceLoader; import org.apache.wicket.resource.loader.IStringResourceLoader; import org.apache.wicket.resource.loader.InitializerStringResourceLoader; import org.apache.wicket.resource.loader.PackageStringResourceLoader; import org.apache.wicket.resource.loader.ValidatorStringResourceLoader; import org.apache.wicket.util.file.IFileCleaner; import org.apache.wicket.util.file.IResourceFinder; import org.apache.wicket.util.lang.Args; import org.apache.wicket.util.lang.Generics; import org.apache.wicket.util.resource.IResourceStream; import org.apache.wicket.util.time.Duration; import org.apache.wicket.util.watch.IModificationWatcher; import org.apache.wicket.util.watch.ModificationWatcher; /** * Class for resource related settings * <p> * <i>resourcePollFrequency </i> (defaults to no polling frequency) - Frequency at which resources * should be polled for changes. * <p> * <i>resourceFinders</i> - Add/modify this to alter the search path for resources. * <p> * <i>useDefaultOnMissingResource </i> (defaults to true) - Set to true to return a default value if * available when a required string resource is not found. If set to false then the * throwExceptionOnMissingResource flag is used to determine how to behave. If no default is * available then this is the same as if this flag were false * <p> * <i>A ResourceStreamLocator </i>- An Application's ResourceStreamLocator is used to find resources * such as images or markup files. You can supply your own ResourceStreamLocator if your prefer to * store your application's resources in a non-standard location (such as a different filesystem * location, a particular JAR file or even a database) by overriding the getResourceLocator() * method. * <p> * <i>Resource Factories </i>- Resource factories can be used to create resources dynamically from * specially formatted HTML tag attribute values. For more details, see {@link IResourceFactory}, * {@link org.apache.wicket.markup.html.image.resource.DefaultButtonImageResourceFactory} and * especially {@link org.apache.wicket.markup.html.image.resource.LocalizedImageResource}. * <p> * <i>A Localizer </i> The getLocalizer() method returns an object encapsulating all of the * functionality required to access localized resources. For many localization problems, even this * will not be required, as there are convenience methods available to all components: * {@link org.apache.wicket.Component#getString(String key)} and * {@link org.apache.wicket.Component#getString(String key, org.apache.wicket.model.IModel model)}. * <p> * <i>stringResourceLoaders </i>- A chain of <code>IStringResourceLoader</code> instances that are * searched in order to obtain string resources used during localization. By default the chain is * set up to first search for resources against a particular component (e.g. page etc.) and then * against the application. * </p> * * @author Jonathan Locke * @author Chris Turner * @author Eelco Hillenius * @author Juergen Donnerstag * @author Johan Compagner * @author Igor Vaynberg (ivaynberg) * @author Martijn Dashorst * @author James Carman */ public class ResourceSettings implements IPropertiesFactoryContext { /** I18N support */ private Localizer localizer; /** Map to look up resource factories by name */ private final Map<String, IResourceFactory> nameToResourceFactory = Generics.newHashMap(); /** The package resource guard. */ private IPackageResourceGuard packageResourceGuard = new SecurePackageResourceGuard( new SecurePackageResourceGuard.SimpleCache(100)); /** The factory to be used for the property files */ private org.apache.wicket.resource.IPropertiesFactory propertiesFactory; /** Filesystem Path to search for resources */ private List<IResourceFinder> resourceFinders = new ArrayList<IResourceFinder>(); /** Frequency at which files should be polled */ private Duration resourcePollFrequency = null; /** resource locator for this application */ private IResourceStreamLocator resourceStreamLocator; /** ModificationWatcher to watch for changes in markup files */ private IModificationWatcher resourceWatcher; /** * A cleaner that removes files asynchronously. * <p> * Used internally to remove the temporary files created by FileUpload functionality. */ private IFileCleaner fileCleaner; /** Chain of string resource loaders to use */ private final List<IStringResourceLoader> stringResourceLoaders = Generics.newArrayList(6); /** Flags used to determine how to behave if resources are not found */ private boolean throwExceptionOnMissingResource = true; /** Determines behavior of string resource loading if string is missing */ private boolean useDefaultOnMissingResource = true; /** Default cache duration */ private Duration defaultCacheDuration = WebResponse.MAX_CACHE_DURATION; /** The JavaScript compressor */ private IJavaScriptCompressor javascriptCompressor; /** The Css compressor */ private ICssCompressor cssCompressor; /** escape string for '..' within resource keys */ private String parentFolderPlaceholder = "::"; // resource caching strategy private IResourceCachingStrategy resourceCachingStrategy; // application these settings are bound to private final Application application; private boolean useMinifiedResources = true; private Comparator<? super RecordedHeaderItem> headerItemComparator = new PriorityFirstComparator( false); private boolean encodeJSessionId = false; /** * Configures Wicket's default ResourceLoaders.<br> * For an example in {@code FooApplication} let {@code bar.Foo} extend {@link Component}, this * results in the following ordering: * <dl> * <dt>component specific</dt> * <dd> * <ul> * <li>bar/Foo.properties</li> * <li>org/apache/wicket/Component.properties</li> * </ul> * </dd> * <dt>package specific</dt> * <dd> * <ul> * <li>bar/package.properties</li> * <li>package.properties (on Foo's class loader)</li> * <li>org/apache/wicket/package.properties</li> * <li>org/apache/package.properties</li> * <li>org/package.properties</li> * <li>package.properties (on Component's class loader)</li> * </ul> * </dd> * <dt>application specific</dt> * <dd> * <ul> * <li>FooApplication.properties</li> * <li>Application.properties</li> * </ul> * </dd> * <dt>validator specific</dt> * <dt>Initializer specific</dt> * <dd> * <ul> * <li>bar.Foo.properties (Foo implementing IInitializer)</li> * </ul> * </dd> * </dl> * * @param application */ public ResourceSettings(final Application application) { this.application = application; stringResourceLoaders.add(new ComponentStringResourceLoader()); stringResourceLoaders.add(new PackageStringResourceLoader()); stringResourceLoaders.add(new ClassStringResourceLoader(application.getClass())); stringResourceLoaders.add(new ValidatorStringResourceLoader()); stringResourceLoaders.add(new InitializerStringResourceLoader(application.getInitializers())); } /** * Adds a resource factory to the list of factories to consult when generating resources * automatically * * @param name * The name to give to the factory * @param resourceFactory * The resource factory to add * @return {@code this} object for chaining */ public ResourceSettings addResourceFactory(final String name, IResourceFactory resourceFactory) { nameToResourceFactory.put(name, resourceFactory); return this; } @Override public Localizer getLocalizer() { if (localizer == null) { localizer = new Localizer(); } return localizer; } /** * Gets the {@link org.apache.wicket.markup.html.PackageResourceGuard package resource guard}. * * @return The package resource guard */ public IPackageResourceGuard getPackageResourceGuard() { return packageResourceGuard; } /** * Get the property factory which will be used to load property files * * @return PropertiesFactory */ public org.apache.wicket.resource.IPropertiesFactory getPropertiesFactory() { if (propertiesFactory == null) { propertiesFactory = new PropertiesFactory(this); } return propertiesFactory; } /** * @param name * Name of the factory to get * @return The IResourceFactory with the given name. */ public IResourceFactory getResourceFactory(final String name) { return nameToResourceFactory.get(name); } /** * Gets the resource finders to use when searching for resources. By default, a finder that * looks in the classpath root is configured. {@link org.apache.wicket.protocol.http.WebApplication} adds the classpath * directory META-INF/resources. To configure additional search paths or filesystem paths, add * to this list. * * @return Returns the resourceFinders. */ public List<IResourceFinder> getResourceFinders() { return resourceFinders; } /** * @return Returns the resourcePollFrequency. */ public Duration getResourcePollFrequency() { return resourcePollFrequency; } @Override public IResourceStreamLocator getResourceStreamLocator() { if (resourceStreamLocator == null) { // Create compound resource locator using source path from // application settings resourceStreamLocator = new ResourceStreamLocator(getResourceFinders()); resourceStreamLocator = new CachingResourceStreamLocator(resourceStreamLocator); } return resourceStreamLocator; } @Override public IModificationWatcher getResourceWatcher(boolean start) { if (resourceWatcher == null && start) { synchronized (this) { if (resourceWatcher == null) { final Duration pollFrequency = getResourcePollFrequency(); if (pollFrequency != null) { resourceWatcher = new ModificationWatcher(pollFrequency); } } } } return resourceWatcher; } /** * Sets the resource watcher * * @param watcher * @return {@code this} object for chaining */ public ResourceSettings setResourceWatcher(IModificationWatcher watcher) { resourceWatcher = watcher; return this; } /** * @return the a cleaner which can be used to remove files asynchronously. */ public IFileCleaner getFileCleaner() { return fileCleaner; } /** * Sets a cleaner that can be used to remove files asynchronously. * <p> * Used internally to delete the temporary files created by FileUpload functionality * * @param fileUploadCleaner * the actual cleaner implementation. Can be <code>null</code> * @return {@code this} object for chaining */ public ResourceSettings setFileCleaner(IFileCleaner fileUploadCleaner) { fileCleaner = fileUploadCleaner; return this; } /** * @return mutable list of all available string resource loaders */ public List<IStringResourceLoader> getStringResourceLoaders() { return stringResourceLoaders; } public boolean getThrowExceptionOnMissingResource() { return throwExceptionOnMissingResource; } /** * @return Whether to use a default value (if available) when a missing resource is requested */ public boolean getUseDefaultOnMissingResource() { return useDefaultOnMissingResource; } /** * Sets the localizer which will be used to find property values. * * @param localizer * @since 1.3.0 * @return {@code this} object for chaining */ public ResourceSettings setLocalizer(final Localizer localizer) { this.localizer = localizer; return this; } /** * Sets the {@link org.apache.wicket.markup.html.PackageResourceGuard package resource guard}. * * @param packageResourceGuard * The package resource guard * @return {@code this} object for chaining */ public ResourceSettings setPackageResourceGuard(IPackageResourceGuard packageResourceGuard) { this.packageResourceGuard = Args.notNull(packageResourceGuard, "packageResourceGuard"); return this; } /** * Set the property factory which will be used to load property files * * @param factory * @return {@code this} object for chaining */ public ResourceSettings setPropertiesFactory(org.apache.wicket.resource.IPropertiesFactory factory) { propertiesFactory = factory; return this; } /** * Sets the finders to use when searching for resources. By default, the resources are located * on the classpath. To add additional search paths, add to the list given by * {@link #getResourceFinders()}. Use this method if you want to completely exchange the list of * resource finders. * * @param resourceFinders * The resourceFinders to set * @return {@code this} object for chaining */ public ResourceSettings setResourceFinders(final List<IResourceFinder> resourceFinders) { Args.notNull(resourceFinders, "resourceFinders"); this.resourceFinders = resourceFinders; // Cause resource locator to get recreated resourceStreamLocator = null; return this; } /** * Sets the resource polling frequency. This is the duration of time between checks of resource * modification times. If a resource, such as an HTML file, has changed, it will be reloaded. * The default is one second in 'development' mode and 'never' in deployment mode. * * @param resourcePollFrequency * Frequency at which to poll resources or <code>null</code> if polling should be * disabled * @return {@code this} object for chaining */ public ResourceSettings setResourcePollFrequency(final Duration resourcePollFrequency) { this.resourcePollFrequency = resourcePollFrequency; return this; } /** * /** * Sets the resource stream locator for this application * * Consider wrapping <code>resourceStreamLocator</code> in {@link CachingResourceStreamLocator}. * This way the locator will not be asked more than once for {@link IResourceStream}s which do * not exist. * @param resourceStreamLocator * new resource stream locator * * @see #getResourceStreamLocator() * @return {@code this} object for chaining */ public ResourceSettings setResourceStreamLocator(IResourceStreamLocator resourceStreamLocator) { this.resourceStreamLocator = resourceStreamLocator; return this; } /** * @param throwExceptionOnMissingResource * @return {@code this} object for chaining */ public ResourceSettings setThrowExceptionOnMissingResource(final boolean throwExceptionOnMissingResource) { this.throwExceptionOnMissingResource = throwExceptionOnMissingResource; return this; } /** * @param useDefaultOnMissingResource * Whether to use a default value (if available) when a missing resource is requested * @return {@code this} object for chaining */ public ResourceSettings setUseDefaultOnMissingResource(final boolean useDefaultOnMissingResource) { this.useDefaultOnMissingResource = useDefaultOnMissingResource; return this; } /** * Get the the default cache duration for resources. * <p/> * * @return cache duration (Duration.NONE will be returned if caching is disabled) * * @see org.apache.wicket.util.time.Duration#NONE */ public final Duration getDefaultCacheDuration() { return defaultCacheDuration; } /** * Set the the default cache duration for resources. * <p/> * Based on RFC-2616 this should not exceed one year. If you set Duration.NONE caching will be * disabled. * * @param duration * default cache duration in seconds * * @see org.apache.wicket.util.time.Duration#NONE * @see org.apache.wicket.request.http.WebResponse#MAX_CACHE_DURATION * @return {@code this} object for chaining */ public final ResourceSettings setDefaultCacheDuration(Duration duration) { Args.notNull(duration, "duration"); defaultCacheDuration = duration; return this; } /** * Get the javascript compressor to remove comments and whitespace characters from javascripts * * @return whether the comments and whitespace characters will be stripped from resources served * through {@link org.apache.wicket.request.resource.JavaScriptPackageResource * JavaScriptPackageResource}. Null is a valid value. */ public IJavaScriptCompressor getJavaScriptCompressor() { return javascriptCompressor; } /** * Set the javascript compressor implemententation use e.g. by * {@link org.apache.wicket.request.resource.JavaScriptPackageResource * JavaScriptPackageResource}. A typical implementation will remove comments and whitespace. But * a no-op implementation is available as well. * * @param compressor * The implementation to be used * @return The old value * @return {@code this} object for chaining */ public IJavaScriptCompressor setJavaScriptCompressor(IJavaScriptCompressor compressor) { IJavaScriptCompressor old = javascriptCompressor; javascriptCompressor = compressor; return old; } /** * Get the CSS compressor to remove comments and whitespace characters from css resources * * @return whether the comments and whitespace characters will be stripped from resources served * through {@link org.apache.wicket.request.resource.CssPackageResource * CssPackageResource}. Null is a valid value. */ public ICssCompressor getCssCompressor() { return cssCompressor; } /** * Set the CSS compressor implemententation use e.g. by * {@link org.apache.wicket.request.resource.CssPackageResource CssPackageResource}. A typical * implementation will remove comments and whitespace. But a no-op implementation is available * as well. * * @param compressor * The implementation to be used * @return The old value * @return {@code this} object for chaining */ public ICssCompressor setCssCompressor(ICssCompressor compressor) { ICssCompressor old = cssCompressor; cssCompressor = compressor; return old; } /** * Placeholder string for '..' within resource urls (which will be crippled by the browser and * not work anymore). Note that by default the placeholder string is <code>::</code>. Resources * are protected by a {@link org.apache.wicket.markup.html.IPackageResourceGuard * IPackageResourceGuard} implementation such as * {@link org.apache.wicket.markup.html.PackageResourceGuard} which you may use or extend based * on your needs. * * @return placeholder */ public String getParentFolderPlaceholder() { return parentFolderPlaceholder; } /** * Placeholder string for '..' within resource urls (which will be crippled by the browser and * not work anymore). Note that by default the placeholder string is <code>null</code> and thus * will not allow to access parent folders. That is by purpose and for security reasons (see * Wicket-1992). In case you really need it, a good value for placeholder would e.g. be "$up$". * Resources additionally are protected by a * {@link org.apache.wicket.markup.html.IPackageResourceGuard IPackageResourceGuard} * implementation such as {@link org.apache.wicket.markup.html.PackageResourceGuard} which you * may use or extend based on your needs. * * @see #getParentFolderPlaceholder() * * @param sequence * character sequence which must not be ambiguous within urls * @return {@code this} object for chaining */ public ResourceSettings setParentFolderPlaceholder(final String sequence) { parentFolderPlaceholder = sequence; return this; } /** * gets the resource caching strategy * * @return strategy */ public IResourceCachingStrategy getCachingStrategy() { if (resourceCachingStrategy == null) { final IResourceVersion resourceVersion; if (application.usesDevelopmentConfig()) { // development mode: // use last-modified timestamp of packaged resource for resource caching // cache the version information for the lifetime of the current http request resourceVersion = new RequestCycleCachedResourceVersion( new LastModifiedResourceVersion()); } else { // deployment mode: // use message digest over resource content for resource caching // cache the version information for the lifetime of the application resourceVersion = new CachingResourceVersion(new MessageDigestResourceVersion()); } // cache resource with a version string in the filename resourceCachingStrategy = new FilenameWithVersionResourceCachingStrategy( resourceVersion); } return resourceCachingStrategy; } /** * sets the resource caching strategy * * @param strategy * instance of resource caching strategy * * @see IResourceCachingStrategy * @return {@code this} object for chaining */ public ResourceSettings setCachingStrategy(IResourceCachingStrategy strategy) { if (strategy == null) { throw new NullPointerException( "It is not allowed to set the resource caching strategy to value NULL. " + "Please use " + NoOpResourceCachingStrategy.class.getName() + " instead."); } resourceCachingStrategy = strategy; return this; } /** * Sets whether to use pre-minified resources when available. Minified resources are detected by * name. The minified version of {@code x.js} is expected to be called {@code x.min.js}. For css * files, the same convention is used: {@code x.min.css} is the minified version of * {@code x.css}. When this is null, minified resources will only be used in deployment * configuration. * * @param useMinifiedResources * The new value for the setting * @return {@code this} object for chaining */ public ResourceSettings setUseMinifiedResources(boolean useMinifiedResources) { this.useMinifiedResources = useMinifiedResources; return this; } /** * @return Whether pre-minified resources will be used. */ public boolean getUseMinifiedResources() { return useMinifiedResources; } /** * @return The comparator used to sort header items. */ public Comparator<? super RecordedHeaderItem> getHeaderItemComparator() { return headerItemComparator; } /** * Sets the comparator used by the {@linkplain org.apache.wicket.markup.head.ResourceAggregator resource aggregator} for * sorting header items. It should be noted that sorting header items may break resource * dependencies. This comparator should therefore at least respect dependencies declared by * resource references. By default, items are sorted using the {@link PriorityFirstComparator}. * * @param headerItemComparator * The comparator used to sort header items, when null, header items will not be * sorted. * @return {@code this} object for chaining */ public ResourceSettings setHeaderItemComparator(Comparator<? super RecordedHeaderItem> headerItemComparator) { this.headerItemComparator = headerItemComparator; return this; } /** * A flag indicating whether static resources should have <tt>jsessionid</tt> encoded in their * url. * * @return {@code true} if the jsessionid should be encoded in the url for resources * implementing * {@link org.apache.wicket.request.resource.caching.IStaticCacheableResource} when the * cookies are disabled and there is an active http session. */ public boolean isEncodeJSessionId() { return encodeJSessionId; } /** * Sets a flag indicating whether the jsessionid should be encoded in the url for resources * implementing {@link org.apache.wicket.request.resource.caching.IStaticCacheableResource} when * the cookies are disabled and there is an active http session. * * @param encodeJSessionId * {@code true} when the jsessionid should be encoded, {@code false} - otherwise * @return {@code this} object for chaining */ public ResourceSettings setEncodeJSessionId(boolean encodeJSessionId) { this.encodeJSessionId = encodeJSessionId; return this; } }
dashorst/wicket
wicket-core/src/main/java/org/apache/wicket/settings/ResourceSettings.java
Java
apache-2.0
26,459
/* * Copyright (C) 2016 Intel Corporation * * 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 OptimizationTests.Devirtualization.InvokeInterfaceIntTryCatchFinally; class Main { public static int div(int d) { return 1 / d; } public static int runTest() { try { return div(0); } catch (Exception e) { // ignore } finally { CondVirtBase test = new CondVirtExt(); int result = test.getThingies(); return result; } } public static void main(String[] args) { int result = runTest(); System.out.println("Result " + result); } }
android-art-intel/Nougat
art-extension/opttests/src/OptimizationTests/Devirtualization/InvokeInterfaceIntTryCatchFinally/Main.java
Java
apache-2.0
1,187
/** * */ package org.apache.hadoop.hdfs.server.namenodeFBT.lock; import org.apache.hadoop.hdfs.server.namenodeFBT.Response; /** * @author hanhlh * */ public final class EndLockResponse extends Response { /** * */ private static final long serialVersionUID = 1L; /** * EndLockRequest ¤ËÂФ¹¤ë¿·¤·¤¤±þÅú¥ª¥Ö¥¸¥§¥¯¥È¤òÀ¸À®¤·¤Þ¤¹. * ±þÅú¤òȯÀ¸¤µ¤»¤¿¸¶°ø¤È¤Ê¤ë * Í׵ᥪ¥Ö¥¸¥§¥¯¥È (EndLockRequest) ¤òÍ¿¤¨¤ëɬÍפ¬¤¢¤ê¤Þ¤¹. * * @param request ±þÅú¤Ëµ¯°ø¤¹¤ëÍ׵ᥪ¥Ö¥¸¥§¥¯¥È (EndLockRequest) */ public EndLockResponse(EndLockRequest request) { super(request); } }
hanhlh/hadoop-0.20.2_FatBTree
src/hdfs/org/apache/hadoop/hdfs/server/namenodeFBT/lock/EndLockResponse.java
Java
apache-2.0
646
# coding=utf-8 from ..base import BitbucketBase class BitbucketCloudBase(BitbucketBase): def __init__(self, url, *args, **kwargs): """ Init the rest api wrapper :param url: string: The base url used for the rest api. :param *args: list: The fixed arguments for the AtlassianRestApi. :param **kwargs: dict: The keyword arguments for the AtlassianRestApi. :return: nothing """ expected_type = kwargs.pop("expected_type", None) super(BitbucketCloudBase, self).__init__(url, *args, **kwargs) if expected_type is not None and not expected_type == self.get_data("type"): raise ValueError("Expected type of data is [{}], got [{}].".format(expected_type, self.get_data("type"))) def get_link(self, link): """ Get a link from the data. :param link: string: The link identifier :return: The requested link or None if it isn't present """ links = self.get_data("links") if links is None or link not in links: return None return links[link]["href"] def _get_paged(self, url, params=None, data=None, flags=None, trailing=None, absolute=False): """ Used to get the paged data :param url: string: The url to retrieve :param params: dict (default is None): The parameters :param data: dict (default is None): The data :param flags: string[] (default is None): The flags :param trailing: bool (default is None): If True, a trailing slash is added to the url :param absolute: bool (default is False): If True, the url is used absolute and not relative to the root :return: A generator object for the data elements """ if params is None: params = {} while True: response = super(BitbucketCloudBase, self).get( url, trailing=trailing, params=params, data=data, flags=flags, absolute=absolute, ) if "values" not in response: return for value in response.get("values", []): yield value url = response.get("next") if url is None: break # From now on we have absolute URLs absolute = True return
MattAgile/atlassian-python-api
atlassian/bitbucket/cloud/base.py
Python
apache-2.0
2,467
/* * Copyright 2002-2014 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.springframework.messaging.handler.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation which indicates that a method parameter should be bound to a message header. * * @author Rossen Stoyanchev * @since 4.0 */ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Header { /** * The name of the request header to bind to. */ String value() default ""; /** * Whether the header is required. * <p>Default is {@code true}, leading to an exception if the header missing. Switch this * to {@code false} if you prefer a {@code null} in case of the header missing. */ boolean required() default true; /** * The default value to use as a fallback. Supplying a default value implicitly * sets {@link #required} to {@code false}. */ String defaultValue() default ValueConstants.DEFAULT_NONE; }
qobel/esoguproject
spring-framework/spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/Header.java
Java
apache-2.0
1,673