code
stringlengths
4
1.01M
language
stringclasses
2 values
#ifndef LAYER_H_INCLUDED #define LAYER_H_INCLUDED #include "basicresource.h" #include "Drawable.h" class Layer : public Drawable { private: void transformation() override; void onDraw() override; void postDraw() override; public: Layer(): Drawable() { // } }; #endif // LAYER_H_INCLUDED
Java
/** * Copyright 2017 dialog LLC <info@dlg.im> * @flow */ import type { PeerInfo } from '@dlghq/dialog-types'; import type { AvatarSize } from '../Avatar/getAvatarSize'; import type { Gradient } from '../Avatar/getAvatarColor'; import React, { PureComponent } from 'react'; import classNames from 'classnames'; import getAvatarSize from '../Avatar/getAvatarSize'; import getAvatarText from '../Avatar/getAvatarText'; import getAvatarColor from '../Avatar/getAvatarColor'; import createSequence from '../../utils/createSequence'; import styles from '../PeerAvatar/PeerAvatar.css'; export type Props = { className?: string, peerBig: PeerInfo, peerSmall: PeerInfo, size: AvatarSize, onClick?: (event: SyntheticMouseEvent) => any }; type DefaultProps = { size: AvatarSize }; const seq = createSequence(); class DoublePeerAvatar extends PureComponent<DefaultProps, Props, void> { id: string; ids: { big: string, clip: string, small: string }; static defaultProps = { size: 'medium' }; constructor(props: Props) { super(props); this.id = 'double_peer_avatar_' + seq.next(); this.ids = { big: `${this.id}_big`, clip: `${this.id}_big_clip`, small: `${this.id}_small` }; } getAvatarSize(): number { return getAvatarSize(this.props.size); } renderDefsBig(): React.Element<any> { if (this.props.peerBig.avatar) { return ( <pattern id={this.ids.big} width="100%" height="100%" patternUnits="userSpaceOnUse"> <image x="0" y="0" width="100px" height="100px" xlinkHref={this.props.peerBig.avatar} /> </pattern> ); } const colors: Gradient = getAvatarColor(this.props.peerBig.placeholder); return ( <linearGradient id={this.ids.big} gradientUnits="userSpaceOnUse" x1="6.79%" y1="105.31%" x2="93.21%" y2="-5.31%" > <stop stopColor={colors.payload.from} /> <stop offset="1" stopColor={colors.payload.to} /> </linearGradient> ); } renderClipMaskBig(): React.Element<any> { return ( <clipPath id={this.ids.clip}> <path // eslint-disable-next-line d="M58.2070074,99.3297063 C55.5367715,99.7706374 52.795171,100 50,100 C22.3857625,100 0,77.6142375 0,50 C0,22.3857625 22.3857625,0 50,0 C77.6142375,0 100,22.3857625 100,50 C100,52.795171 99.7706374,55.5367715 99.3297063,58.2070074 C94.8434182,55.5348957 89.6009561,54 84,54 C67.4314575,54 54,67.4314575 54,84 C54,89.6009561 55.5348957,94.8434182 58.2070074,99.3297063 Z" /> </clipPath> ); } renderDefsSmall(): React.Element<any> { if (this.props.peerSmall.avatar) { return ( <pattern id={this.ids.small} width="100%" height="100%" x="58" y="58" patternUnits="userSpaceOnUse" > <image x="0" y="0" width="100px" height="100px" xlinkHref={this.props.peerSmall.avatar} transform="scale(0.507046569,0.507046569)" /> </pattern> ); } const colors: Gradient = getAvatarColor(this.props.peerSmall.placeholder); return ( <linearGradient id={this.ids.small} gradientUnits="userSpaceOnUse" x1="6.79%" y1="105.31%" x2="93.21%" y2="-5.31%" > <stop stopColor={colors.payload.from} /> <stop offset="1" stopColor={colors.payload.to} /> </linearGradient> ); } renderSmallAvatar(): React.Element<any> { return ( <circle cx="84" cy="84" r="25" fill={`url(#${this.ids.small})`} /> ); } renderBigAvatar(): React.Element<any> { return ( <path // eslint-disable-next-line d="M58.2070074,99.3297063 C55.5367715,99.7706374 52.795171,100 50,100 C22.3857625,100 0,77.6142375 0,50 C0,22.3857625 22.3857625,0 50,0 C77.6142375,0 100,22.3857625 100,50 C100,52.795171 99.7706374,55.5367715 99.3297063,58.2070074 C94.8434182,55.5348957 89.6009561,54 84,54 C67.4314575,54 54,67.4314575 54,84 C54,89.6009561 55.5348957,94.8434182 58.2070074,99.3297063 Z" fill={`url(#${this.ids.big})`} /> ); } renderPeerSmallText(): ?React.Element<any> { if (this.props.peerSmall.avatar) { return null; } const size = this.getAvatarSize(); const text = size >= 20 ? getAvatarText(this.props.peerSmall.title) : null; const twoChars = Boolean(text && text.length !== 1); const textStyles = { fontSize: twoChars ? 20 : 24 }; return ( <text className={styles.text} x="84" y="84" textAnchor="middle" alignmentBaseline="central" dominantBaseline="central" style={textStyles} > {text} </text> ); } renderPeerBigText(): ?React.Element<any> { if (this.props.peerBig.avatar) { return null; } const size = this.getAvatarSize(); const text = size >= 20 ? getAvatarText(this.props.peerBig.title) : null; const twoChars = Boolean(text && text.length !== 1); const textStyles = { fontSize: twoChars ? 38 : 48 }; return ( <text className={styles.text} x="50" y="50" textAnchor="middle" alignmentBaseline="central" dominantBaseline="central" style={textStyles} clipPath={`url(#${this.ids.clip})`} > {text} </text> ); } render(): React.Element<any> { const className = classNames(styles.container, { [styles.clickable]: this.props.onClick }, this.props.className); const size = this.getAvatarSize(); return ( <svg viewBox="0 0 109 109" width={size} height={size} className={className} onClick={this.props.onClick} > <defs> {this.renderDefsBig()} {this.renderClipMaskBig()} {this.renderDefsSmall()} </defs> {this.renderBigAvatar()} {this.renderSmallAvatar()} {this.renderPeerBigText()} {this.renderPeerSmallText()} </svg> ); } } export default DoublePeerAvatar;
Java
# This file describes the standard way to build Docker, using docker # # Usage: # # # Assemble the full dev environment. This is slow the first time. # docker build -t docker . # # # Mount your source in an interactive container for quick testing: # docker run -v `pwd`:/go/src/github.com/dotcloud/docker -privileged -i -t docker bash # # # Run the test suite: # docker run -privileged docker hack/make.sh test # # # Publish a release: # docker run -privileged \ # -e AWS_S3_BUCKET=baz \ # -e AWS_ACCESS_KEY=foo \ # -e AWS_SECRET_KEY=bar \ # -e GPG_PASSPHRASE=gloubiboulga \ # docker hack/release.sh # # Note: Apparmor used to mess with privileged mode, but this is no longer # the case. Therefore, you don't have to disable it anymore. # docker-version 0.6.1 from ubuntu:12.04 maintainer Solomon Hykes <solomon@dotcloud.com> # Build dependencies run echo 'deb http://archive.ubuntu.com/ubuntu precise main universe' > /etc/apt/sources.list run apt-get update run apt-get install -y -q curl run apt-get install -y -q git run apt-get install -y -q mercurial run apt-get install -y -q build-essential libsqlite3-dev # Install Go run curl -s https://go.googlecode.com/files/go1.2rc2.src.tar.gz | tar -v -C /usr/local -xz env PATH /usr/local/go/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin env GOPATH /go:/go/src/github.com/dotcloud/docker/vendor run cd /usr/local/go/src && ./make.bash && go install -ldflags '-w -linkmode external -extldflags "-static -Wl,--unresolved-symbols=ignore-in-shared-libs"' -tags netgo -a std # Ubuntu stuff run apt-get install -y -q ruby1.9.3 rubygems libffi-dev run gem install --no-rdoc --no-ri fpm run apt-get install -y -q reprepro dpkg-sig # Install s3cmd 1.0.1 (earlier versions don't support env variables in the config) run apt-get install -y -q python-pip run pip install s3cmd run pip install python-magic run /bin/echo -e '[default]\naccess_key=$AWS_ACCESS_KEY\nsecret_key=$AWS_SECRET_KEY\n' > /.s3cfg # Runtime dependencies run apt-get install -y -q iptables run apt-get install -y -q lxc run apt-get install -y -q aufs-tools volume /var/lib/docker workdir /go/src/github.com/dotcloud/docker # Wrap all commands in the "docker-in-docker" script to allow nested containers entrypoint ["hack/dind"] # Upload docker source add . /go/src/github.com/dotcloud/docker
Java
/* ** Copyright (c) 2007, DNA Pty Ltd and contributors ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** copies of the Software, and to permit persons to whom the Software is ** furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in ** all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ** THE SOFTWARE. */ #include "libxatmi.h" int tpdiscon(int cd) { write(2, "tpdiscon not supported\n", 23); tperrno = TPEPROTO; return -1; }
Java
# ormbad.version # Helper module for ORMBad version information # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Thu Aug 13 12:38:42 2015 -0400 # # Copyright (C) 2015 Tipsy Bear Studios # For license information, see LICENSE.txt # # ID: version.py [] benjamin@bengfort.com $ """ Helper module for ORMBad version information. """ ########################################################################## ## Versioning ########################################################################## __version_info__ = { 'major': 0, 'minor': 1, 'micro': 0, 'releaselevel': 'final', 'serial': 0, } def get_version(short=False): """ Returns the version from the version info. """ assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final') vers = ["%(major)i.%(minor)i" % __version_info__, ] if __version_info__['micro']: vers.append(".%(micro)i" % __version_info__) if __version_info__['releaselevel'] != 'final' and not short: vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial'])) return ''.join(vers)
Java
/** * Created by raj on 19/8/14. */ var fs = require('fs'); var content = fs.read ('animeEpisode.json'); console.log(JSON.stringify(JSON.parse(content)[1][0].title)); videolinks=JSON.parse(content); links=[]; function pages(k) { var page = new WebPage(); page.open('http://www.gogoanime.com/', function (status) { console.log('opened gogoanime :++++ ', status); if (status==fail){ page.close(); pages(k); } if (status == success) { page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function () { console.log('jq included') var data = page.evaluate(function (data) { var tempdata=[]; for (var i = 0; i <$('.post div:eq(1) table tbody tr td:eq(0) ul').length; i = i + 1) { data.links.push($('.post div:eq(1) table tbody tr td:eq(0) ul li a').attr('href')); } return JSON.stringify(data); }); links[k][m] = JSON.parse(data); console.log(data); if (m < links[k].length - 1) { page.close(); console.log('next episoide called'); pages(k, m + 1); } ; if (m == links[k].length - 1) { page.close(); console.log('next anime called'); var path = 'links.json'; fs.write(path, links[k], 'w'); pages(k + 1, 1); } if (k == links.length - 1) { var path = 'links.json'; fs.write(path, links, 'w'); } }); } }); } pages(1,1);
Java
#!/usr/bin/python # # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example creates a bidder-level filter set. A bidder-level filter set can be used to retrieve aggregated data for all Authorized Buyers accounts under the given bidder account, including the bidder account itself. """ import argparse from datetime import date from datetime import datetime from datetime import timedelta import os import pprint import sys import uuid sys.path.insert(0, os.path.abspath('..')) from googleapiclient.errors import HttpError import samples_util _DATE_FORMAT = '%Y%m%d' _FILTER_SET_NAME_TEMPLATE = ('bidders/{bidders_resource_id}/' 'filterSets/{filtersets_resource_id}') _OWNER_NAME_TEMPLATE = 'bidders/{bidders_resource_id}' _TODAY = date.today() _VALID_ENVIRONMENTS = ('WEB', 'APP') _VALID_FORMATS = ('DISPLAY', 'VIDEO') _VALID_PLATFORMS = ('DESKTOP', 'TABLET', 'MOBILE') _VALID_TIME_SERIES_GRANULARITIES = ('HOURLY', 'DAILY') DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE' DEFAULT_FILTER_SET_RESOURCE_ID = f'FilterSet_{uuid.uuid4()}' DEFAULT_END_DATE = _TODAY.strftime(_DATE_FORMAT) DEFAULT_START_DATE = (_TODAY - timedelta(days=7)).strftime( _DATE_FORMAT) def main(ad_exchange_buyer, owner_name, body, is_transient): try: # Construct and execute the request. filter_set = ad_exchange_buyer.bidders().filterSets().create( ownerName=owner_name, isTransient=is_transient, body=body).execute() print(f'FilterSet created for bidder: "{owner_name}".') pprint.pprint(filter_set) except HttpError as e: print(e) if __name__ == '__main__': def time_series_granularity_type(s): if s not in _VALID_TIME_SERIES_GRANULARITIES: raise argparse.ArgumentTypeError('Invalid TimeSeriesGranularity ' f'specified: "{s}".') return s def environment_type(s): if s not in _VALID_ENVIRONMENTS: raise argparse.ArgumentTypeError( f'Invalid Environment specified: "{s}".') return s def format_type(s): if s not in _VALID_FORMATS: raise argparse.ArgumentTypeError(f'Invalid Format specified: "{s}".') return s def platform_type(s): if s not in _VALID_PLATFORMS: raise argparse.ArgumentTypeError(f'Invalid Platform specified: "{s}".') return s def valid_date(s): try: return datetime.strptime(s, _DATE_FORMAT).date() except ValueError: raise argparse.ArgumentTypeError(f'Invalid date specified: "{s}".') parser = argparse.ArgumentParser( description=('Creates a bidder-level filter set with the specified ' 'options.')) # Required fields. parser.add_argument( '-b', '--bidder_resource_id', default=DEFAULT_BIDDER_RESOURCE_ID, help=('The resource ID of the bidders resource for which the filter set ' 'is being created. This will be used to construct the ownerName ' 'used as a path parameter for filter set requests. For additional ' 'information on how to configure the ownerName path parameter, ' 'see: https://developers.google.com/authorized-buyers/apis/' 'reference/rest/v2beta1/bidders.filterSets/create' '#body.PATH_PARAMETERS.owner_name')) parser.add_argument( '-r', '--resource_id', default=DEFAULT_FILTER_SET_RESOURCE_ID, help=('The resource ID of the filter set. Note that this must be ' 'unique. This will be used to construct the filter set\'s name. ' 'For additional information on how to configure a filter set\'s ' 'name, see: https://developers.google.com/authorized-buyers/apis/' 'reference/rest/v2beta1/bidders.filterSets#FilterSet.FIELDS.name')) parser.add_argument( '--end_date', default=DEFAULT_END_DATE, type=valid_date, help=('The end date for the filter set\'s absoluteDateRange field, which ' 'will be accepted in this example in YYYYMMDD format.')) parser.add_argument( '--start_date', default=DEFAULT_START_DATE, type=valid_date, help=('The start date for the filter set\'s time_range field, which ' 'will be accepted in this example in YYYYMMDD format.')) # Optional fields. parser.add_argument( '-e', '--environment', required=False, type=environment_type, help=('The environment on which to filter.')) parser.add_argument( '-f', '--format', required=False, type=format_type, help=('The format on which to filter.')) parser.add_argument( '-p', '--platforms', required=False, nargs='*', type=platform_type, help=('The platforms on which to filter. The filters represented by ' 'multiple platforms are ORed together. Note that you may specify ' 'more than one using a space as a delimiter.')) parser.add_argument( '-s', '--seller_network_ids', required=False, nargs='*', type=int, help=('The list of IDs for seller networks on which to filter. The ' 'filters represented by multiple seller network IDs are ORed ' 'together. Note that you may specify more than one using a space ' 'as a delimiter.')) parser.add_argument( '-t', '--time_series_granularity', required=False, type=time_series_granularity_type, help=('The granularity of time intervals if a time series breakdown is ' 'desired.')) parser.add_argument( '--is_transient', required=False, default=True, type=bool, help=('Whether the filter set is transient, or should be persisted ' 'indefinitely. In this example, this will default to True.')) args = parser.parse_args() # Build the time_range as an AbsoluteDateRange. time_range = { 'startDate': { 'year': args.start_date.year, 'month': args.start_date.month, 'day': args.start_date.day }, 'endDate': { 'year': args.end_date.year, 'month': args.end_date.month, 'day': args.end_date.day } } # Create a body containing the required fields. BODY = { 'name': _FILTER_SET_NAME_TEMPLATE.format( bidders_resource_id=args.bidder_resource_id, filtersets_resource_id=args.resource_id), # Note: You may alternatively specify relativeDateRange or # realtimeTimeRange. 'absoluteDateRange': time_range } # Add optional fields to body if specified. if args.environment: BODY['environment'] = args.environment if args.format: BODY['format'] = args.format if args.platforms: BODY['platforms'] = args.platforms if args.seller_network_ids: BODY['sellerNetworkIds'] = args.seller_network_ids if args.time_series_granularity: BODY['timeSeriesGranularity'] = args.time_series_granularity try: service = samples_util.GetService('v2beta1') except IOError as ex: print(f'Unable to create adexchangebuyer service - {ex}') print('Did you specify the key file in samples_util.py?') sys.exit(1) main(service, _OWNER_NAME_TEMPLATE.format( bidders_resource_id=args.bidder_resource_id), BODY, args.is_transient)
Java
/******************************************************************************* * Copyright 2006 - 2012 Vienna University of Technology, * Department of Software Technology and Interactive Systems, IFS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This work originates from the Planets project, co-funded by the European Union under the Sixth Framework Programme. ******************************************************************************/ package eu.scape_project.planning.model.transform; import java.io.Serializable; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.DiscriminatorColumn; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.ManyToOne; import eu.scape_project.planning.model.ChangeLog; import eu.scape_project.planning.model.IChangesHandler; import eu.scape_project.planning.model.ITouchable; import eu.scape_project.planning.model.Values; import eu.scape_project.planning.model.values.INumericValue; import eu.scape_project.planning.model.values.IOrdinalValue; import eu.scape_project.planning.model.values.TargetValues; import eu.scape_project.planning.model.values.Value; import eu.scape_project.planning.validation.ValidationError; /** * Implements basic transformation functionality, i.e. aggregation over {@link Values} and * common properties of transformers. * @author Hannes Kulovits */ @Entity @Inheritance @DiscriminatorColumn(name = "type") public abstract class Transformer implements ITransformer, Serializable, ITouchable { private static final long serialVersionUID = -3708795251848706848L; @Id @GeneratedValue protected int id; public int getId() { return id; } public void setId(int id) { this.id = id; } @ManyToOne(cascade=CascadeType.ALL) private ChangeLog changeLog = new ChangeLog(); /** * Transforms all the values in the list of the provided {@link Values}. * According to the type of each {@link Value}, either * {@link ITransformer#transform(INumericValue)} or {@link ITransformer#transform(IOrdinalValue)} * is called. * @param values List of values to be transformed * @return {@link TargetValues}, which contains a list of all transformed values corresponding to the provided input */ public TargetValues transformValues(Values values) { TargetValues result = new TargetValues(); for (Value v : values.getList()) { if (v instanceof INumericValue) { result.add(transform((INumericValue) v)); } else { result.add(transform((IOrdinalValue) v)); } } return result; } public ChangeLog getChangeLog() { return this.changeLog; } public void setChangeLog(ChangeLog value) { changeLog = value; } public boolean isChanged() { return changeLog.isAltered(); } public void touch(String username) { getChangeLog().touch(username); } public void touch() { getChangeLog().touch(); } /** * @see ITouchable#handleChanges(IChangesHandler) */ public void handleChanges(IChangesHandler h){ h.visit(this); } /** * If this Transformer is not correctly configured, this method adds * an appropriate error-message to the given list and returns false. * * @return true if this transformer is correctly configured */ public abstract boolean isTransformable(List<ValidationError> errors); public abstract Transformer clone(); }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_67) on Fri Nov 14 18:25:20 PST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.apache.hadoop.hbase.thrift.ThriftServerRunner (HBase 0.98.8-hadoop2 API)</title> <meta name="date" content="2014-11-14"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.hbase.thrift.ThriftServerRunner (HBase 0.98.8-hadoop2 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/hadoop/hbase/thrift/ThriftServerRunner.html" title="class in org.apache.hadoop.hbase.thrift">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/hbase/thrift/class-use/ThriftServerRunner.html" target="_top">Frames</a></li> <li><a href="ThriftServerRunner.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.hadoop.hbase.thrift.ThriftServerRunner" class="title">Uses of Class<br>org.apache.hadoop.hbase.thrift.ThriftServerRunner</h2> </div> <div class="classUseContainer">No usage of org.apache.hadoop.hbase.thrift.ThriftServerRunner</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/hadoop/hbase/thrift/ThriftServerRunner.html" title="class in org.apache.hadoop.hbase.thrift">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/hbase/thrift/class-use/ThriftServerRunner.html" target="_top">Frames</a></li> <li><a href="ThriftServerRunner.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
Java
# Copyright 2016 The TensorFlow 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. # ============================================================================== """Tests for Keras core layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python import keras from tensorflow.python.eager import context from tensorflow.python.framework import ops from tensorflow.python.keras import keras_parameterized from tensorflow.python.keras import testing_utils from tensorflow.python.keras.mixed_precision.experimental import policy from tensorflow.python.ops import math_ops from tensorflow.python.platform import test @keras_parameterized.run_all_keras_modes class DropoutLayersTest(keras_parameterized.TestCase): def test_dropout(self): testing_utils.layer_test( keras.layers.Dropout, kwargs={'rate': 0.5}, input_shape=(3, 2)) testing_utils.layer_test( keras.layers.Dropout, kwargs={'rate': 0.5, 'noise_shape': [3, 1]}, input_shape=(3, 2)) def test_dropout_supports_masking(self): dropout = keras.layers.Dropout(0.5) self.assertEqual(True, dropout.supports_masking) def test_spatial_dropout_1d(self): testing_utils.layer_test( keras.layers.SpatialDropout1D, kwargs={'rate': 0.5}, input_shape=(2, 3, 4)) def test_spatial_dropout_2d(self): testing_utils.layer_test( keras.layers.SpatialDropout2D, kwargs={'rate': 0.5}, input_shape=(2, 3, 4, 5)) testing_utils.layer_test( keras.layers.SpatialDropout2D, kwargs={'rate': 0.5, 'data_format': 'channels_first'}, input_shape=(2, 3, 4, 5)) def test_spatial_dropout_3d(self): testing_utils.layer_test( keras.layers.SpatialDropout3D, kwargs={'rate': 0.5}, input_shape=(2, 3, 4, 4, 5)) testing_utils.layer_test( keras.layers.SpatialDropout3D, kwargs={'rate': 0.5, 'data_format': 'channels_first'}, input_shape=(2, 3, 4, 4, 5)) @keras_parameterized.run_all_keras_modes class LambdaLayerTest(keras_parameterized.TestCase): def test_lambda(self): testing_utils.layer_test( keras.layers.Lambda, kwargs={'function': lambda x: x + 1}, input_shape=(3, 2)) testing_utils.layer_test( keras.layers.Lambda, kwargs={ 'function': lambda x, a, b: x * a + b, 'arguments': { 'a': 0.6, 'b': 0.4 } }, input_shape=(3, 2)) # test serialization with function def f(x): return x + 1 ld = keras.layers.Lambda(f) config = ld.get_config() ld = keras.layers.deserialize({ 'class_name': 'Lambda', 'config': config }) # test with lambda ld = keras.layers.Lambda( lambda x: keras.backend.concatenate([math_ops.square(x), x])) config = ld.get_config() ld = keras.layers.Lambda.from_config(config) def test_lambda_multiple_inputs(self): ld = keras.layers.Lambda(lambda x: x[0], output_shape=lambda x: x[0]) x1 = np.ones([3, 2], np.float32) x2 = np.ones([3, 5], np.float32) out = ld([x1, x2]) self.assertAllEqual(out.shape, [3, 2]) def test_lambda_output_shape(self): l = keras.layers.Lambda(lambda x: x + 1, output_shape=(1, 1)) l(keras.backend.variable(np.ones((1, 1)))) self.assertEqual((1, 1), l.get_config()['output_shape']) def test_lambda_output_shape_function(self): def get_output_shape(input_shape): return 1 * input_shape l = keras.layers.Lambda(lambda x: x + 1, output_shape=get_output_shape) l(keras.backend.variable(np.ones((1, 1)))) self.assertEqual('lambda', l.get_config()['output_shape_type']) def test_lambda_output_shape_autocalculate_multiple_inputs(self): def lambda_fn(x): return math_ops.matmul(x[0], x[1]) l = keras.layers.Lambda(lambda_fn) output_shape = l.compute_output_shape([(10, 10), (10, 20)]) self.assertAllEqual((10, 20), output_shape) def test_lambda_output_shape_list_multiple_outputs(self): def lambda_fn(x): return x l = keras.layers.Lambda(lambda_fn, output_shape=[(10,), (20,)]) output_shape = l.compute_output_shape([(10, 10), (10, 20)]) self.assertAllEqual([(10, 10), (10, 20)], output_shape) def test_lambda_output_shape_tuple_with_none(self): def lambda_fn(x): return x l = keras.layers.Lambda(lambda_fn, output_shape=(None, 10)) output_shape = l.compute_output_shape((5, 10, 20)) self.assertAllEqual([5, None, 10], output_shape.as_list()) def test_lambda_output_shape_function_multiple_outputs(self): def lambda_fn(x): return x def output_shape_fn(input_shape): return input_shape l = keras.layers.Lambda(lambda_fn, output_shape=output_shape_fn) output_shape = l.compute_output_shape([(10, 10), (10, 20)]) self.assertAllEqual([(10, 10), (10, 20)], output_shape) def test_lambda_config_serialization(self): # Test serialization with output_shape and output_shape_type layer = keras.layers.Lambda(lambda x: x + 1, output_shape=(1, 1)) layer(keras.backend.variable(np.ones((1, 1)))) config = layer.get_config() layer = keras.layers.deserialize({ 'class_name': 'Lambda', 'config': config }) layer = keras.layers.Lambda.from_config(config) @keras_parameterized.run_all_keras_modes class CoreLayersTest(keras_parameterized.TestCase): def test_masking(self): testing_utils.layer_test( keras.layers.Masking, kwargs={}, input_shape=(3, 2, 3)) def test_keras_mask(self): x = np.ones((10, 10)) y = keras.layers.Masking(1.)(x) self.assertTrue(hasattr(y, '_keras_mask')) self.assertTrue(y._keras_mask is not None) self.assertAllClose(self.evaluate(y._keras_mask), np.zeros((10,))) def test_activation(self): # with string argument testing_utils.layer_test( keras.layers.Activation, kwargs={'activation': 'relu'}, input_shape=(3, 2)) # with function argument testing_utils.layer_test( keras.layers.Activation, kwargs={'activation': keras.backend.relu}, input_shape=(3, 2)) def test_reshape(self): testing_utils.layer_test( keras.layers.Reshape, kwargs={'target_shape': (8, 1)}, input_shape=(3, 2, 4)) testing_utils.layer_test( keras.layers.Reshape, kwargs={'target_shape': (-1, 1)}, input_shape=(3, 2, 4)) testing_utils.layer_test( keras.layers.Reshape, kwargs={'target_shape': (1, -1)}, input_shape=(3, 2, 4)) testing_utils.layer_test( keras.layers.Reshape, kwargs={'target_shape': (-1, 1)}, input_shape=(None, None, 2)) def test_permute(self): testing_utils.layer_test( keras.layers.Permute, kwargs={'dims': (2, 1)}, input_shape=(3, 2, 4)) def test_permute_errors_on_invalid_starting_dims_index(self): with self.assertRaisesRegexp(ValueError, r'Invalid permutation .*dims.*'): testing_utils.layer_test( keras.layers.Permute, kwargs={'dims': (0, 1, 2)}, input_shape=(3, 2, 4)) def test_permute_errors_on_invalid_set_of_dims_indices(self): with self.assertRaisesRegexp(ValueError, r'Invalid permutation .*dims.*'): testing_utils.layer_test( keras.layers.Permute, kwargs={'dims': (1, 4, 2)}, input_shape=(3, 2, 4)) def test_flatten(self): testing_utils.layer_test( keras.layers.Flatten, kwargs={}, input_shape=(3, 2, 4)) # Test channels_first inputs = np.random.random((10, 3, 5, 5)).astype('float32') outputs = testing_utils.layer_test( keras.layers.Flatten, kwargs={'data_format': 'channels_first'}, input_data=inputs) target_outputs = np.reshape( np.transpose(inputs, (0, 2, 3, 1)), (-1, 5 * 5 * 3)) self.assertAllClose(outputs, target_outputs) def test_flatten_scalar_channels(self): testing_utils.layer_test( keras.layers.Flatten, kwargs={}, input_shape=(3,)) # Test channels_first inputs = np.random.random((10,)).astype('float32') outputs = testing_utils.layer_test( keras.layers.Flatten, kwargs={'data_format': 'channels_first'}, input_data=inputs) target_outputs = np.expand_dims(inputs, -1) self.assertAllClose(outputs, target_outputs) def test_repeat_vector(self): testing_utils.layer_test( keras.layers.RepeatVector, kwargs={'n': 3}, input_shape=(3, 2)) def test_dense(self): testing_utils.layer_test( keras.layers.Dense, kwargs={'units': 3}, input_shape=(3, 2)) testing_utils.layer_test( keras.layers.Dense, kwargs={'units': 3}, input_shape=(3, 4, 2)) testing_utils.layer_test( keras.layers.Dense, kwargs={'units': 3}, input_shape=(None, None, 2)) testing_utils.layer_test( keras.layers.Dense, kwargs={'units': 3}, input_shape=(3, 4, 5, 2)) def test_dense_dtype(self): inputs = ops.convert_to_tensor( np.random.randint(low=0, high=7, size=(2, 2))) layer = keras.layers.Dense(5, dtype='float32') outputs = layer(inputs) self.assertEqual(outputs.dtype, 'float32') def test_dense_with_policy(self): inputs = ops.convert_to_tensor( np.random.randint(low=0, high=7, size=(2, 2)), dtype='float16') layer = keras.layers.Dense(5, dtype=policy.Policy('infer_float32_vars')) outputs = layer(inputs) self.assertEqual(outputs.dtype, 'float16') self.assertEqual(layer.kernel.dtype, 'float32') def test_dense_regularization(self): layer = keras.layers.Dense( 3, kernel_regularizer=keras.regularizers.l1(0.01), bias_regularizer='l1', activity_regularizer='l2', name='dense_reg') layer(keras.backend.variable(np.ones((2, 4)))) self.assertEqual(3, len(layer.losses)) def test_dense_constraints(self): k_constraint = keras.constraints.max_norm(0.01) b_constraint = keras.constraints.max_norm(0.01) layer = keras.layers.Dense( 3, kernel_constraint=k_constraint, bias_constraint=b_constraint) layer(keras.backend.variable(np.ones((2, 4)))) self.assertEqual(layer.kernel.constraint, k_constraint) self.assertEqual(layer.bias.constraint, b_constraint) def test_activity_regularization(self): layer = keras.layers.ActivityRegularization(l1=0.1) layer(keras.backend.variable(np.ones((2, 4)))) self.assertEqual(1, len(layer.losses)) config = layer.get_config() self.assertEqual(config.pop('l1'), 0.1) def test_numpy_inputs(self): if context.executing_eagerly(): layer = keras.layers.RepeatVector(2) x = np.ones((10, 10)) self.assertAllEqual(np.ones((10, 2, 10)), layer(x)) layer = keras.layers.Concatenate() x, y = np.ones((10, 10)), np.ones((10, 10)) self.assertAllEqual(np.ones((10, 20)), layer([x, y])) if __name__ == '__main__': test.main()
Java
/* * Copyright 2016 SimplifyOps, Inc. (http://simplifyops.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.dtolabs.rundeck.core.execution.workflow; /* * StepFirstWorkflowStrategyTests.java * * User: Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a> * Created: 3/25/11 9:30 AM * */ import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.dtolabs.rundeck.core.common.*; import com.dtolabs.rundeck.core.execution.*; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.tools.ant.BuildListener; import org.junit.Assert; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import com.dtolabs.rundeck.core.execution.dispatch.Dispatchable; import com.dtolabs.rundeck.core.execution.dispatch.DispatcherResult; import com.dtolabs.rundeck.core.execution.service.NodeExecutorResult; import com.dtolabs.rundeck.core.execution.workflow.steps.FailureReason; import com.dtolabs.rundeck.core.execution.workflow.steps.NodeDispatchStepExecutor; import com.dtolabs.rundeck.core.execution.workflow.steps.StepExecutionResult; import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException; import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepExecutionItem; import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepExecutionService; import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepExecutor; import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepResult; import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepResultImpl; import com.dtolabs.rundeck.core.execution.workflow.steps.node.impl.ExecCommandBase; import com.dtolabs.rundeck.core.execution.workflow.steps.node.impl.ExecCommandExecutionItem; import com.dtolabs.rundeck.core.execution.workflow.steps.node.impl.ScriptFileCommandBase; import com.dtolabs.rundeck.core.execution.workflow.steps.node.impl.ScriptFileCommandExecutionItem; import com.dtolabs.rundeck.core.tools.AbstractBaseTest; import com.dtolabs.rundeck.core.utils.FileUtils; import com.dtolabs.rundeck.core.utils.NodeSet; public class TestStepFirstWorkflowStrategy extends AbstractBaseTest { Framework testFramework; String testnode; private static final String TEST_PROJECT = "StepFirstWorkflowStrategyTests"; public TestStepFirstWorkflowStrategy(String name) { super(name); } public static Test suite() { return new TestSuite(TestStepFirstWorkflowStrategy.class); } protected void setUp() { super.setUp(); testFramework = getFrameworkInstance(); testnode=testFramework.getFrameworkNodeName(); final IRundeckProject frameworkProject = testFramework.getFrameworkProjectMgr().createFrameworkProject( TEST_PROJECT, generateProjectResourcesFile( new File("src/test/resources/com/dtolabs/rundeck/core/common/test-nodes1.xml") ) ); } protected void tearDown() throws Exception { super.tearDown(); File projectdir = new File(getFrameworkProjectsBase(), TEST_PROJECT); FileUtils.deleteDir(projectdir); } public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } static class testWorkflowCmdItem extends BaseExecutionItem implements NodeStepExecutionItem { private String type; int flag=-1; @Override public String toString() { return "testWorkflowCmdItem{" + "type='" + type + '\'' + ", flag=" + flag + '}'; } @Override public String getNodeStepType() { return type; } public String getType() { return "NodeDispatch"; } } /*static class testWorkflowJobCmdItem extends testWorkflowCmdItem implements IWorkflowJobItem { private String jobIdentifier; public String getJobIdentifier() { return jobIdentifier; } }*/ static class testListener implements ExecutionListenerOverride { public boolean isTerse() { return false; } public String getLogFormat() { return null; } public void log(int i, String s) { } @Override public void event(String eventType, String message, Map eventMeta) { } public FailedNodesListener getFailedNodesListener() { return null; } public void beginStepExecution(ExecutionContext context, StepExecutionItem item) { } public void finishStepExecution(StatusResult result, ExecutionContext context, StepExecutionItem item) { } public void beginNodeExecution(ExecutionContext context, String[] command, INodeEntry node) { } public void finishNodeExecution(NodeExecutorResult result, ExecutionContext context, String[] command, INodeEntry node) { } public void beginNodeDispatch(ExecutionContext context, StepExecutionItem item) { } public void beginNodeDispatch(ExecutionContext context, Dispatchable item) { } public void finishNodeDispatch(DispatcherResult result, ExecutionContext context, StepExecutionItem item) { } public void finishNodeDispatch(DispatcherResult result, ExecutionContext context, Dispatchable item) { } public void beginFileCopyFileStream(ExecutionContext context, InputStream input, INodeEntry node) { } public void beginFileCopyFile(ExecutionContext context, File input, INodeEntry node) { } public void beginFileCopyScriptContent(ExecutionContext context, String input, INodeEntry node) { } public void finishFileCopy(String result, ExecutionContext context, INodeEntry node) { } public void beginExecuteNodeStep(ExecutionContext context, NodeStepExecutionItem item, INodeEntry node) { } public void finishExecuteNodeStep(NodeStepResult result, ExecutionContext context, StepExecutionItem item, INodeEntry node) { } public BuildListener getBuildListener() { return null; } public ExecutionListenerOverride createOverride() { return this; } public void setTerse(boolean terse) { } public void setLogFormat(String format) { } public void setFailedNodesListener(FailedNodesListener listener) { } } static class testInterpreter implements NodeStepExecutor { List<StepExecutionItem> executionItemList = new ArrayList<StepExecutionItem>(); List<ExecutionContext> executionContextList = new ArrayList<ExecutionContext>(); List<INodeEntry> nodeEntryList = new ArrayList<INodeEntry>(); int index = 0; List<NodeStepResult> resultList = new ArrayList<NodeStepResult>(); boolean shouldThrowException = false; public NodeStepResult executeNodeStep(StepExecutionContext executionContext, NodeStepExecutionItem executionItem, INodeEntry iNodeEntry) throws NodeStepException { executionItemList.add(executionItem); executionContextList.add(executionContext); nodeEntryList.add(iNodeEntry); if (shouldThrowException) { throw new NodeStepException("testInterpreter test exception",null,iNodeEntry.getNodename()); } // System.out.println("return index: (" + index + ") in size: " + resultList.size()); return resultList.get(index++); } } static enum Reason implements FailureReason{ Test } static class testResult extends NodeStepResultImpl { boolean success; int flag; INodeEntry node; testResult(boolean success, int flag) { super(null,success?null: TestStepFirstWorkflowStrategy.Reason.Test,success?null:"test failure",null); this.success = success; this.flag = flag; } @Override public Exception getException() { return null; } public boolean isSuccess() { return success; } @Override public String toString() { return "testResult{" + "success=" + success + ", flag=" + flag + '}'; } public INodeEntry getNode() { return node; } } public void testExecuteWorkflow() throws Exception { final IRundeckProject frameworkProject = testFramework.getFrameworkProjectMgr().getFrameworkProject( TEST_PROJECT); final INodeSet nodes = frameworkProject.getNodeSet(); assertNotNull(nodes); assertEquals(2, nodes.getNodes().size()); } public void testExecuteWorkflow_empty() throws Exception { //test empty workflow final NodeSet nodeset = new NodeSet(); final WorkflowImpl workflow = new WorkflowImpl(new ArrayList<StepExecutionItem>(), 1, false, WorkflowExecutor.STEP_FIRST); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset) .executionListener(new testListener()) .framework(testFramework) .nodes(testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet()) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); interpreterService.registerInstance("exec", interpreterMock); interpreterService.registerInstance("script", interpreterMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, interpreterMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, interpreterMock); // interpreterService.registerInstance(JobExecutionItem.COMMAND_TYPE, interpreterMock); final WorkflowExecutionResult result = strategy.executeWorkflow(context, executionItem); assertNotNull(result); if (!result.isSuccess() && null != result.getException()) { result.getException().printStackTrace(System.err); } assertNull("threw exception: " + result.getException(), result.getException()); assertTrue(result.isSuccess()); assertEquals(0, interpreterMock.executionItemList.size()); } public void testExecuteWorkflow_undefined_item() throws Exception { //test undefined workflow item final NodeSet nodeset = new NodeSet(); final ArrayList<StepExecutionItem> commands = new ArrayList<StepExecutionItem>(); commands.add(new testWorkflowCmdItem()); final WorkflowImpl workflow = new WorkflowImpl(commands, 1, false, WorkflowExecutor.STEP_FIRST); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset.nodeSelectorWithDefaultAll()) .executionListener(new testListener()) .framework(testFramework) .nodes(NodeFilter.filterNodes(nodeset.nodeSelectorWithDefaultAll(), testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet())) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); interpreterService.registerInstance("exec", interpreterMock); interpreterService.registerInstance("script", interpreterMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, interpreterMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, interpreterMock); // interpreterService.registerInstance(JobExecutionItem.COMMAND_TYPE, interpreterMock); final WorkflowExecutionResult result = strategy.executeWorkflow(context, executionItem); assertNotNull(result); if (!result.isSuccess() && null != result.getException()) { result.getException().printStackTrace(System.out); } assertFalse(result.isSuccess()); assertEquals(0, interpreterMock.executionItemList.size()); assertNotNull("threw exception: " + result.getException(), result.getException()); assertTrue("threw exception: " + result.getException(), result.getException() instanceof NullPointerException); assertEquals("threw exception: " + result.getException(), "provider name was null for Service: WorkflowNodeStep", result.getException().getMessage()); } public void testExecuteWorkflow_scriptExec() throws Exception { //test script exec item final NodesSelector nodeset = SelectorUtils.singleNode(testFramework.getFrameworkNodeName()); final ArrayList<StepExecutionItem> commands = new ArrayList<StepExecutionItem>(); final StepExecutionItem testWorkflowCmdItem = new ScriptFileCommandBase(){ @Override public String getScript() { return "a command"; } }; commands.add(testWorkflowCmdItem); final WorkflowImpl workflow = new WorkflowImpl(commands, 1, false, WorkflowExecutor.STEP_FIRST); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset) .executionListener(new testListener()) .framework(testFramework) .nodes(NodeFilter.filterNodes( nodeset, testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet() )) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); testInterpreter failMock = new testInterpreter(); failMock.shouldThrowException = true; interpreterService.registerInstance("exec", failMock); interpreterService.registerInstance("script", interpreterMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, failMock); // interpreterService.registerInstance(JobExecutionItem.COMMAND_TYPE, failMock); //set resturn result interpreterMock.resultList.add(new NodeStepResultImpl(null)); final WorkflowExecutionResult result = strategy.executeWorkflow(context, executionItem); assertNotNull(result); if (!result.isSuccess() && null != result.getException()) { result.getException().printStackTrace(System.err); } assertNull("threw exception: " + result.getException(), result.getException()); assertTrue(result.isSuccess()); assertEquals(1, interpreterMock.executionItemList.size()); final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(0); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof ScriptFileCommandExecutionItem); ScriptFileCommandExecutionItem scriptItem = (ScriptFileCommandExecutionItem) executionItem1; assertEquals("a command", scriptItem.getScript()); assertNull(scriptItem.getScriptAsStream()); assertNull(scriptItem.getServerScriptFilePath()); assertEquals(1, interpreterMock.executionContextList.size()); final ExecutionContext executionContext = interpreterMock.executionContextList.get(0); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals("expected " + nodeset + ", but was " + executionContext.getNodeSelector(), nodeset, executionContext.getNodeSelector()); } public void testExecuteWorkflow_commandexec() throws Exception { //test command exec item final NodesSelector nodeset = SelectorUtils.singleNode(testFramework.getFrameworkNodeName()); final ArrayList<StepExecutionItem> commands = new ArrayList<StepExecutionItem>(); final StepExecutionItem testWorkflowCmdItem = new ExecCommandBase() { @Override public String[] getCommand() { return new String[]{"a", "command"}; } }; commands.add(testWorkflowCmdItem); final WorkflowImpl workflow = new WorkflowImpl(commands, 1, false, WorkflowExecutor.STEP_FIRST); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset) .executionListener(new testListener()) .framework(testFramework) .nodes(NodeFilter.filterNodes( nodeset, testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet() )) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); testInterpreter failMock = new testInterpreter(); failMock.shouldThrowException = true; interpreterService.registerInstance("exec", interpreterMock); interpreterService.registerInstance("script", failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, failMock); // interpreterService.registerInstance(JobExecutionItem.COMMAND_TYPE, failMock); //set resturn result interpreterMock.resultList.add(new NodeStepResultImpl(null)); final WorkflowExecutionResult result = strategy.executeWorkflow(context, executionItem); assertNotNull(result); if (!result.isSuccess() && null != result.getException()) { result.getException().printStackTrace(System.err); } assertNull("threw exception: " + result.getException(), result.getException()); assertTrue(result.isSuccess()); assertEquals(1, interpreterMock.executionItemList.size()); final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(0); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof ExecCommandExecutionItem); ExecCommandExecutionItem execItem = (ExecCommandExecutionItem) executionItem1; assertNotNull(execItem.getCommand()); assertEquals(2, execItem.getCommand().length); assertEquals("a", execItem.getCommand()[0]); assertEquals("command", execItem.getCommand()[1]); assertEquals(1, interpreterMock.executionContextList.size()); final ExecutionContext executionContext = interpreterMock.executionContextList.get(0); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(nodeset, executionContext.getNodeSelector()); } public void testExecuteWorkflowThreeItems() throws Exception{ { //test workflow of three successful items final NodesSelector nodeset = SelectorUtils.singleNode(testFramework.getFrameworkNodeName()); final ArrayList<StepExecutionItem> commands = new ArrayList<StepExecutionItem>(); final StepExecutionItem testWorkflowCmdItem = new ExecCommandBase() { @Override public String[] getCommand() { return new String[]{"a", "2","command"}; } }; commands.add(testWorkflowCmdItem); final StepExecutionItem testWorkflowCmdItemScript = new ScriptFileCommandBase() { @Override public String getScript() { return "a command"; } @Override public String[] getArgs() { return new String[]{"-testargs", "1"}; } }; commands.add(testWorkflowCmdItemScript); final StepExecutionItem testWorkflowCmdItemScript2 = new ScriptFileCommandBase() { @Override public String getServerScriptFilePath() { return "/some/file/path"; } @Override public String[] getArgs() { return new String[]{"-testargs", "2"}; } }; commands.add(testWorkflowCmdItemScript2); final WorkflowImpl workflow = new WorkflowImpl(commands, 1, false, WorkflowExecutor.STEP_FIRST); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset) .executionListener(new testListener()) .framework(testFramework) .nodes(NodeFilter.filterNodes( nodeset, testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet() )) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); testInterpreter failMock = new testInterpreter(); failMock.shouldThrowException = true; // interpreterService.registerInstance(JobExecutionItem.COMMAND_TYPE, interpreterMock); interpreterService.registerInstance("exec", interpreterMock); interpreterService.registerInstance("script", interpreterMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, failMock); //set resturn results interpreterMock.resultList.add(new testResult(true, 0)); interpreterMock.resultList.add(new testResult(true, 1)); interpreterMock.resultList.add(new testResult(true, 2)); final WorkflowExecutionResult result = strategy.executeWorkflow(context,executionItem); assertNotNull(result); if (!result.isSuccess() && null != result.getException()) { result.getException().printStackTrace(System.err); } assertNull("threw exception: " + result.getException(), result.getException()); assertTrue(result.isSuccess()); assertNotNull(result.getResultSet()); final List<StepExecutionResult> test1 = result.getResultSet(); assertEquals(3, test1.size()); for (final int i : new int[]{0, 1, 2}) { final StepExecutionResult interpreterResult = test1.get(i); final DispatcherResult dr = NodeDispatchStepExecutor.extractDispatcherResult(interpreterResult); assertEquals(1, dr.getResults().size()); final NodeStepResult nrs = dr.getResults().values().iterator().next(); assertTrue("unexpected class: " + nrs.getClass(), nrs instanceof testResult); testResult val = (testResult) nrs; assertTrue(val.isSuccess()); assertEquals(i, val.flag); } assertEquals(3, interpreterMock.executionItemList.size()); final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(0); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof ExecCommandExecutionItem); ExecCommandExecutionItem execItem = (ExecCommandExecutionItem) executionItem1; assertNotNull(execItem.getCommand()); assertEquals(3, execItem.getCommand().length); assertEquals("a", execItem.getCommand()[0]); assertEquals("2", execItem.getCommand()[1]); assertEquals("command", execItem.getCommand()[2]); final StepExecutionItem item2 = interpreterMock.executionItemList.get(1); assertTrue("wrong class: " + item2.getClass().getName(), item2 instanceof ScriptFileCommandExecutionItem); ScriptFileCommandExecutionItem scriptItem = (ScriptFileCommandExecutionItem) item2; assertEquals("a command", scriptItem.getScript()); assertNull(scriptItem.getScriptAsStream()); assertNull(scriptItem.getServerScriptFilePath()); final StepExecutionItem item3 = interpreterMock.executionItemList.get(2); assertTrue("wrong class: " + item3.getClass().getName(), item2 instanceof ScriptFileCommandExecutionItem); ScriptFileCommandExecutionItem scriptItem2 = (ScriptFileCommandExecutionItem) item3; assertNull(scriptItem2.getScript()); assertNull(scriptItem2.getScriptAsStream()); assertEquals("/some/file/path", scriptItem2.getServerScriptFilePath()); assertNotNull(scriptItem2.getArgs()); assertEquals(2, scriptItem2.getArgs().length); assertEquals("-testargs", scriptItem2.getArgs()[0]); assertEquals("2", scriptItem2.getArgs()[1]); assertEquals(3, interpreterMock.executionContextList.size()); for (final int i : new int[]{0, 1, 2}) { final ExecutionContext executionContext = interpreterMock.executionContextList.get(i); assertEquals("item "+i,TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull("item " + i, executionContext.getDataContext()); assertNotNull("item " + i, executionContext.getDataContext().get("node")); assertEquals("item " + i,0, executionContext.getLoglevel()); assertEquals("item " + i,"user1", executionContext.getUser()); assertEquals("item " + i,nodeset, executionContext.getNodeSelector()); } } } public void testWorkflowFailNoKeepgoing() throws Exception{ { //test a workflow with a failing item (1), with keepgoing=false final NodesSelector nodeset = SelectorUtils.singleNode(testFramework.getFrameworkNodeName()); final ArrayList<StepExecutionItem> commands = new ArrayList<StepExecutionItem>(); final StepExecutionItem testWorkflowCmdItem = new ExecCommandBase() { @Override public String[] getCommand() { return new String[]{"a", "2", "command"}; } }; commands.add(testWorkflowCmdItem); final StepExecutionItem testWorkflowCmdItemScript = new ScriptFileCommandBase() { @Override public String getScript() { return "a command"; } @Override public String[] getArgs() { return new String[]{"-testargs", "1"}; } }; commands.add(testWorkflowCmdItemScript); final StepExecutionItem testWorkflowCmdItemScript2 = new ScriptFileCommandBase() { @Override public String getServerScriptFilePath() { return "/some/file/path"; } @Override public String[] getArgs() { return new String[]{"-testargs", "2"}; } }; commands.add(testWorkflowCmdItemScript2); final WorkflowImpl workflow = new WorkflowImpl(commands, 1, false, WorkflowExecutor.STEP_FIRST); workflow.setKeepgoing(false); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset) .executionListener(new testListener()) .framework(testFramework) .nodes(NodeFilter.filterNodes( nodeset, testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet() )) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); testInterpreter failMock = new testInterpreter(); failMock.shouldThrowException = true; // interpreterService.registerInstance(JobExecutionItem.COMMAND_TYPE, interpreterMock); interpreterService.registerInstance("exec", interpreterMock); interpreterService.registerInstance("script", interpreterMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, failMock); //set resturn results, fail on second item interpreterMock.resultList.add(new testResult(true, 0)); interpreterMock.resultList.add(new testResult(false, 1)); interpreterMock.resultList.add(new testResult(true, 2)); final WorkflowExecutionResult result = strategy.executeWorkflow(context, executionItem); assertNotNull(result); if (null != result.getException()) { result.getException().printStackTrace(System.out); } assertFalse(result.isSuccess()); assertNull("threw exception: " + result.getException(), result.getException()); StepExecutionResult result1 = result.getResultSet().get(1); final DispatcherResult executionResult = NodeDispatchStepExecutor.extractDispatcherResult(result1); assertNotNull(executionResult.getResults()); assertEquals(1, executionResult.getResults().size()); assertNotNull(executionResult.getResults().get(testnode)); final StatusResult testnode1 = executionResult.getResults().get(testnode); assertNotNull(testnode1); assertTrue(testnode1 instanceof testResult); testResult failResult = (testResult) testnode1; assertEquals(1, failResult.flag); assertNotNull(result.getResultSet()); final List<StepExecutionResult> test1 = result.getResultSet(); assertEquals(2, test1.size()); for (final int i : new int[]{0, 1}) { final StepExecutionResult interpreterResult = test1.get(i); final DispatcherResult dr = NodeDispatchStepExecutor.extractDispatcherResult(interpreterResult); assertEquals(1, dr.getResults().size()); final NodeStepResult nrs = dr.getResults().values().iterator().next(); assertTrue("unexpected class: " + nrs.getClass(), nrs instanceof testResult); testResult val = (testResult) nrs; assertEquals(i, val.flag); if(0==i){ assertTrue(val.isSuccess()); }else{ assertFalse(val.isSuccess()); } } assertEquals(2, interpreterMock.executionItemList.size()); final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(0); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof ExecCommandExecutionItem); ExecCommandExecutionItem execItem = (ExecCommandExecutionItem) executionItem1; assertNotNull(execItem.getCommand()); assertEquals(3, execItem.getCommand().length); assertEquals("a", execItem.getCommand()[0]); assertEquals("2", execItem.getCommand()[1]); assertEquals("command", execItem.getCommand()[2]); final StepExecutionItem item2 = interpreterMock.executionItemList.get(1); assertTrue("wrong class: " + item2.getClass().getName(), item2 instanceof ScriptFileCommandExecutionItem); ScriptFileCommandExecutionItem scriptItem = (ScriptFileCommandExecutionItem) item2; assertEquals("a command", scriptItem.getScript()); assertNull(scriptItem.getScriptAsStream()); assertNull(scriptItem.getServerScriptFilePath()); assertNotNull(scriptItem.getArgs()); assertEquals(2, scriptItem.getArgs().length); assertEquals("-testargs", scriptItem.getArgs()[0]); assertEquals("1",scriptItem.getArgs()[1]); assertEquals(2, interpreterMock.executionContextList.size()); for (final int i : new int[]{0, 1}) { final ExecutionContext executionContext = interpreterMock.executionContextList.get(i); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(nodeset, executionContext.getNodeSelector()); } } } public void testWorkflowFailYesKeepgoing() throws Exception{ { //test a workflow with a failing item (1), with keepgoing=true final NodesSelector nodeset = SelectorUtils.singleNode(testFramework.getFrameworkNodeName()); final ArrayList<StepExecutionItem> commands = new ArrayList<StepExecutionItem>(); final StepExecutionItem testWorkflowCmdItem = new ExecCommandBase() { @Override public String[] getCommand() { return new String[]{"a", "2", "command"}; } }; commands.add(testWorkflowCmdItem); final StepExecutionItem testWorkflowCmdItemScript = new ScriptFileCommandBase() { @Override public String getScript() { return "a command"; } @Override public String[] getArgs() { return new String[]{"-testargs", "1"}; } }; commands.add(testWorkflowCmdItemScript); final StepExecutionItem testWorkflowCmdItemScript2 = new ScriptFileCommandBase() { @Override public String getServerScriptFilePath() { return "/some/file/path"; } @Override public String[] getArgs() { return new String[]{"-testargs", "2"}; } }; commands.add(testWorkflowCmdItemScript2); final WorkflowImpl workflow = new WorkflowImpl(commands, 1, false, WorkflowExecutor.STEP_FIRST); workflow.setKeepgoing(true); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset) .executionListener(new testListener()) .framework(testFramework) .nodes(NodeFilter.filterNodes( nodeset, testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet() )) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); testInterpreter failMock = new testInterpreter(); failMock.shouldThrowException = true; // interpreterService.registerInstance(JobExecutionItem.COMMAND_TYPE, interpreterMock); interpreterService.registerInstance("exec", interpreterMock); interpreterService.registerInstance("script", interpreterMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, failMock); //set resturn results, fail on second item interpreterMock.resultList.add(new testResult(true, 0)); interpreterMock.resultList.add(new testResult(false, 1)); interpreterMock.resultList.add(new testResult(true, 2)); final WorkflowExecutionResult result = strategy.executeWorkflow(context, executionItem); assertNotNull(result); if (!result.isSuccess() && null != result.getException()) { result.getException().printStackTrace(System.err); } assertFalse(result.isSuccess()); assertNull("threw exception: " + result.getException(), result.getException()); assertNotNull(result.getResultSet()); final List<StepExecutionResult> test1 = result.getResultSet(); assertEquals(3, test1.size()); for (final int i : new int[]{0, 1, 2}) { final StepExecutionResult interpreterResult = test1.get(i); assertTrue(NodeDispatchStepExecutor.isWrappedDispatcherResult(interpreterResult)); final DispatcherResult dr = NodeDispatchStepExecutor.extractDispatcherResult(interpreterResult); assertEquals(1, dr.getResults().size()); final NodeStepResult nrs = dr.getResults().values().iterator().next(); assertTrue("unexpected class: " + nrs.getClass(), nrs instanceof testResult); testResult val = (testResult) nrs; assertEquals(i, val.flag); if (1 == i) { assertFalse(val.isSuccess()); } else { assertTrue(val.isSuccess()); } } assertEquals(3, interpreterMock.executionItemList.size()); final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(0); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof ExecCommandExecutionItem); ExecCommandExecutionItem execItem = (ExecCommandExecutionItem) executionItem1; assertNotNull(execItem.getCommand()); assertEquals(3, execItem.getCommand().length); assertEquals("a", execItem.getCommand()[0]); assertEquals("2", execItem.getCommand()[1]); assertEquals("command", execItem.getCommand()[2]); final StepExecutionItem item2 = interpreterMock.executionItemList.get(1); assertTrue("wrong class: " + item2.getClass().getName(), item2 instanceof ScriptFileCommandExecutionItem); ScriptFileCommandExecutionItem scriptItem = (ScriptFileCommandExecutionItem) item2; assertEquals("a command", scriptItem.getScript()); assertNull(scriptItem.getScriptAsStream()); assertNull(scriptItem.getServerScriptFilePath()); assertNotNull(scriptItem.getArgs()); assertEquals(2, scriptItem.getArgs().length); assertEquals("-testargs", scriptItem.getArgs()[0]); assertEquals("1",scriptItem.getArgs()[1]); final StepExecutionItem item3 = interpreterMock.executionItemList.get(2); assertTrue("wrong class: " + item2.getClass().getName(), item2 instanceof ScriptFileCommandExecutionItem); ScriptFileCommandExecutionItem scriptItem3 = (ScriptFileCommandExecutionItem) item3; assertEquals("/some/file/path", scriptItem3.getServerScriptFilePath()); assertNull(scriptItem3.getScript()); assertNull(scriptItem3.getScriptAsStream()); assertNotNull(scriptItem3.getArgs()); assertEquals(2, scriptItem3.getArgs().length); assertEquals("-testargs", scriptItem3.getArgs()[0]); assertEquals("2", scriptItem3.getArgs()[1]); assertEquals(3, interpreterMock.executionContextList.size()); for (final int i : new int[]{0, 1}) { final ExecutionContext executionContext = interpreterMock.executionContextList.get(i); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(nodeset, executionContext.getNodeSelector()); } } } public void testFailureHandlerItemNoKeepgoing() throws Exception{ { //test a workflow with a failing item (1), with keepgoing=false, and a failureHandler final boolean KEEPGOING_TEST = false; final boolean STEP_0_RESULT = false; final boolean STEP_1_RESULT = true; final boolean HANDLER_RESULT = true; final NodesSelector nodeset = SelectorUtils.singleNode(testFramework.getFrameworkNodeName()); final ArrayList<StepExecutionItem> commands = new ArrayList<StepExecutionItem>(); final StepExecutionItem testHandlerItem = new ScriptFileCommandBase() { @Override public String getScript() { return "failure handler script"; } @Override public String[] getArgs() { return new String[]{"failure","script","args"}; } }; final StepExecutionItem testWorkflowCmdItem = new ExecCommandBase() { @Override public String[] getCommand() { return new String[]{"a", "2", "command"}; } @Override public StepExecutionItem getFailureHandler() { return testHandlerItem; } }; commands.add(testWorkflowCmdItem); final StepExecutionItem testWorkflowCmdItemScript = new ScriptFileCommandBase() { @Override public String getScript() { return "a command"; } @Override public String[] getArgs() { return new String[]{"-testargs", "1"}; } }; commands.add(testWorkflowCmdItemScript); final WorkflowImpl workflow = new WorkflowImpl(commands, 1, false, WorkflowExecutor.STEP_FIRST); workflow.setKeepgoing(KEEPGOING_TEST); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset) .executionListener(new testListener()) .framework(testFramework) .nodes(NodeFilter.filterNodes( nodeset, testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet() )) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); testInterpreter handlerInterpreterMock = new testInterpreter(); testInterpreter failMock = new testInterpreter(); failMock.shouldThrowException = true; // interpreterService.registerInstance(JobExecutionItem.COMMAND_TYPE, interpreterMock); interpreterService.registerInstance("exec", interpreterMock); interpreterService.registerInstance("script", handlerInterpreterMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, failMock); //set resturn results, fail on second item interpreterMock.resultList.add(new testResult(STEP_0_RESULT, 0)); interpreterMock.resultList.add(new testResult(STEP_1_RESULT, 1)); handlerInterpreterMock.resultList.add(new testResult(HANDLER_RESULT, 0)); final WorkflowExecutionResult result = strategy.executeWorkflow(context, executionItem); assertNotNull(result); if (!result.isSuccess() && null != result.getException()) { result.getException().printStackTrace(System.err); } assertFalse(result.isSuccess()); assertNull("threw exception: " + result.getException(), result.getException()); StepExecutionResult result1 = result.getResultSet().get(0); final DispatcherResult executionResult = NodeDispatchStepExecutor.extractDispatcherResult(result1); assertNotNull(executionResult.getResults()); assertEquals(1, executionResult.getResults().size()); assertNotNull(executionResult.getResults().get(testnode)); final StatusResult testnode1 = executionResult.getResults().get(testnode); assertNotNull(testnode1); assertTrue(testnode1 instanceof testResult); testResult failResult = (testResult) testnode1; assertEquals(0, failResult.flag); assertEquals(1, result.getResultSet().size()); assertNotNull(result.getResultSet()); final List<StepExecutionResult> test1 = result.getResultSet(); assertEquals(1, test1.size()); final int i =0; final StepExecutionResult interpreterResult = test1.get(i); final DispatcherResult dr = NodeDispatchStepExecutor.extractDispatcherResult(interpreterResult); assertEquals(1, dr.getResults().size()); final NodeStepResult nrs = dr.getResults().values().iterator().next(); assertTrue("unexpected class: " + nrs.getClass(), nrs instanceof testResult); testResult val = (testResult) nrs; assertEquals(i, val.flag); assertFalse(val.isSuccess()); assertEquals(1, interpreterMock.executionItemList.size()); final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(0); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof ExecCommandExecutionItem); ExecCommandExecutionItem execItem = (ExecCommandExecutionItem) executionItem1; assertNotNull(execItem.getCommand()); assertEquals(3, execItem.getCommand().length); assertEquals("a", execItem.getCommand()[0]); assertEquals("2", execItem.getCommand()[1]); assertEquals("command", execItem.getCommand()[2]); assertEquals(1, interpreterMock.executionContextList.size()); final ExecutionContext executionContext = interpreterMock.executionContextList.get(i); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(nodeset, executionContext.getNodeSelector()); //check handler item was executed assertEquals(1, handlerInterpreterMock.executionItemList.size()); final StepExecutionItem executionItemX = handlerInterpreterMock.executionItemList.get(0); assertTrue("wrong class: " + executionItemX.getClass().getName(), executionItemX instanceof ScriptFileCommandExecutionItem); ScriptFileCommandExecutionItem execItemX = (ScriptFileCommandExecutionItem) executionItemX; assertNotNull(execItemX.getScript()); assertNotNull(execItemX.getArgs()); assertEquals("failure handler script", execItemX.getScript()); assertEquals(3, execItemX.getArgs().length); assertEquals("failure", execItemX.getArgs()[0]); assertEquals("script", execItemX.getArgs()[1]); assertEquals("args", execItemX.getArgs()[2]); assertEquals(1, handlerInterpreterMock.executionContextList.size()); final ExecutionContext executionContextX = handlerInterpreterMock.executionContextList.get(i); assertEquals(TEST_PROJECT, executionContextX.getFrameworkProject()); assertNotNull(executionContextX.getDataContext()); assertNotNull(executionContextX.getDataContext().get("node")); assertEquals(0, executionContextX.getLoglevel()); assertEquals("user1", executionContextX.getUser()); assertEquals(nodeset, executionContextX.getNodeSelector()); } } public void testFailureHandlerItemYesKeepgoing() throws Exception{ { //test a workflow with a failing item (1), with keepgoing=true, and a failureHandler that fails final boolean KEEPGOING_TEST = true; final boolean STEP_0_RESULT = false; final boolean STEP_1_RESULT = true; final boolean HANDLER_RESULT = false; final NodesSelector nodeset = SelectorUtils.singleNode(testFramework.getFrameworkNodeName()); final ArrayList<StepExecutionItem> commands = new ArrayList<StepExecutionItem>(); final StepExecutionItem testHandlerItem = new ScriptFileCommandBase() { @Override public String getScript() { return "failure handler script"; } @Override public String[] getArgs() { return new String[]{"failure","script","args"}; } @Override public String toString() { return "testHandlerItem"; } }; final StepExecutionItem testWorkflowCmdItem = new ExecCommandBase() { @Override public String[] getCommand() { return new String[]{"a", "2", "command"}; } @Override public StepExecutionItem getFailureHandler() { return testHandlerItem; } @Override public String toString() { return "testWorkflowCmdItem"; } }; commands.add(testWorkflowCmdItem); final StepExecutionItem testWorkflowCmdItem2 = new ExecCommandBase() { @Override public String[] getCommand() { return new String[]{"a", "3", "command"}; } @Override public StepExecutionItem getFailureHandler() { return testHandlerItem; } @Override public String toString() { return "testWorkflowCmdItem2"; } }; commands.add(testWorkflowCmdItem2); final WorkflowImpl workflow = new WorkflowImpl(commands, 1, false, WorkflowExecutor.STEP_FIRST); workflow.setKeepgoing(KEEPGOING_TEST); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset) .executionListener(new testListener()) .framework(testFramework) .nodes(NodeFilter.filterNodes( nodeset, testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet() )) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); testInterpreter handlerInterpreterMock = new testInterpreter(); testInterpreter failMock = new testInterpreter(); failMock.shouldThrowException = true; // interpreterService.registerInstance(JobExecutionItem.COMMAND_TYPE, interpreterMock); interpreterService.registerInstance("exec", interpreterMock); interpreterService.registerInstance("script", handlerInterpreterMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, failMock); //set resturn results interpreterMock.resultList.add(new testResult(STEP_0_RESULT, 0)); interpreterMock.resultList.add(new testResult(STEP_1_RESULT, 1)); handlerInterpreterMock.resultList.add(new testResult(HANDLER_RESULT, 0)); final WorkflowExecutionResult result = strategy.executeWorkflow(context, executionItem); assertNotNull(result); if (!result.isSuccess() && null != result.getException()) { result.getException().printStackTrace(System.err); } assertFalse(result.isSuccess()); assertNull("threw exception: " + result.getException(), result.getException()); assertNotNull(result.getResultSet()); final List<StepExecutionResult> test1 = result.getResultSet(); System.out.println("results: "+test1); assertEquals(2, interpreterMock.executionItemList.size()); assertEquals(2, interpreterMock.executionContextList.size()); //check handler item was executed assertEquals(1, handlerInterpreterMock.executionItemList.size()); assertEquals(1, handlerInterpreterMock.executionContextList.size()); assertEquals(2, test1.size()); int resultIndex =0; int stepNum=0; { //first step result final StepExecutionResult interpreterResult = test1.get(resultIndex); final DispatcherResult dr = NodeDispatchStepExecutor.extractDispatcherResult(interpreterResult); assertEquals(1, dr.getResults().size()); final NodeStepResult nrs = dr.getResults().values().iterator().next(); assertTrue("unexpected class: " + nrs.getClass(), nrs instanceof testResult); testResult val = (testResult) nrs; assertEquals(0, val.flag); assertFalse(val.isSuccess()); final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(stepNum); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof ExecCommandExecutionItem); ExecCommandExecutionItem execItem = (ExecCommandExecutionItem) executionItem1; assertNotNull(execItem.getCommand()); assertEquals(3, execItem.getCommand().length); assertEquals("a", execItem.getCommand()[0]); assertEquals("2", execItem.getCommand()[1]); assertEquals("command", execItem.getCommand()[2]); final ExecutionContext executionContext = interpreterMock.executionContextList.get(stepNum); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(nodeset, executionContext.getNodeSelector()); } resultIndex=1; // // { // //failure handler result // final StepExecutionResult interpreterResult = test1.get(resultIndex); // final DispatcherResult dr = NodeDispatchStepExecutor.extractDispatcherResult(interpreterResult); // assertEquals(1, dr.getResults().size()); // final NodeStepResult nrs = dr.getResults().values().iterator().next(); // assertTrue("unexpected class: " + nrs.getClass(), // nrs instanceof testResult); // testResult val = (testResult) nrs; // assertEquals(0, val.flag); // assertFalse(val.isSuccess()); // // final StepExecutionItem executionItemX = handlerInterpreterMock.executionItemList.get(stepNum); // assertTrue("wrong class: " + executionItemX.getClass().getName(), // executionItemX instanceof ScriptFileCommandExecutionItem); // ScriptFileCommandExecutionItem execItemX = (ScriptFileCommandExecutionItem) executionItemX; // assertNotNull(execItemX.getScript()); // assertNotNull(execItemX.getArgs()); // assertEquals("failure handler script", execItemX.getScript()); // assertEquals(3, execItemX.getArgs().length); // assertEquals("failure", execItemX.getArgs()[0]); // assertEquals("script", execItemX.getArgs()[1]); // assertEquals("args", execItemX.getArgs()[2]); // // // final ExecutionContext executionContextX = handlerInterpreterMock.executionContextList.get(stepNum); // assertEquals(TEST_PROJECT, executionContextX.getFrameworkProject()); // assertNull(executionContextX.getDataContext()); // assertEquals(0, executionContextX.getLoglevel()); // assertEquals("user1", executionContextX.getUser()); // assertEquals(nodeset, executionContextX.getNodeSelector()); // assertNull(executionContextX.getArgs()); // } // resultIndex=2; stepNum = 1; { //second step result final StepExecutionResult interpreterResult = test1.get(resultIndex); final DispatcherResult dr = NodeDispatchStepExecutor.extractDispatcherResult(interpreterResult); assertEquals(1, dr.getResults().size()); final NodeStepResult nrs = dr.getResults().values().iterator().next(); assertTrue("unexpected class: " + nrs.getClass(), nrs instanceof testResult); testResult val = (testResult) nrs; assertEquals(1, val.flag); assertTrue(val.isSuccess()); final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(stepNum); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof ExecCommandExecutionItem); ExecCommandExecutionItem execItem = (ExecCommandExecutionItem) executionItem1; assertNotNull(execItem.getCommand()); assertEquals(3, execItem.getCommand().length); assertEquals("a", execItem.getCommand()[0]); assertEquals("3", execItem.getCommand()[1]); assertEquals("command", execItem.getCommand()[2]); final ExecutionContext executionContext = interpreterMock.executionContextList.get(stepNum); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(nodeset, executionContext.getNodeSelector()); } } } public void testFailureHandlerItemYesKeepgoingHandlerSuccess() throws Exception { { //test a workflow with a failing item (1), with keepgoing=true, and a failureHandler that succeeds final boolean KEEPGOING_TEST = true; final boolean STEP_0_RESULT = false; final boolean STEP_1_RESULT = true; final boolean HANDLER_RESULT = true; final NodesSelector nodeset = SelectorUtils.singleNode(testFramework.getFrameworkNodeName()); final ArrayList<StepExecutionItem> commands = new ArrayList<StepExecutionItem>(); final StepExecutionItem testHandlerItem = new ScriptFileCommandBase() { @Override public String getScript() { return "failure handler script"; } @Override public String[] getArgs() { return new String[]{"failure","script","args"}; } @Override public String toString() { return "testHandlerItem"; } }; final StepExecutionItem testWorkflowCmdItem = new ExecCommandBase() { @Override public String[] getCommand() { return new String[]{"a", "2", "command"}; } @Override public StepExecutionItem getFailureHandler() { return testHandlerItem; } @Override public String toString() { return "testWorkflowCmdItem"; } }; commands.add(testWorkflowCmdItem); final StepExecutionItem testWorkflowCmdItem2 = new ExecCommandBase() { @Override public String[] getCommand() { return new String[]{"a", "3", "command"}; } @Override public StepExecutionItem getFailureHandler() { return testHandlerItem; } @Override public String toString() { return "testWorkflowCmdItem2"; } }; commands.add(testWorkflowCmdItem2); final WorkflowImpl workflow = new WorkflowImpl(commands, 1, false, WorkflowExecutor.STEP_FIRST); workflow.setKeepgoing(KEEPGOING_TEST); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset) .executionListener(new testListener()) .framework(testFramework) .nodes(NodeFilter.filterNodes( nodeset, testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet() )) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); testInterpreter handlerInterpreterMock = new testInterpreter(); testInterpreter failMock = new testInterpreter(); failMock.shouldThrowException = true; // interpreterService.registerInstance(JobExecutionItem.COMMAND_TYPE, interpreterMock); interpreterService.registerInstance("exec", interpreterMock); interpreterService.registerInstance("script", handlerInterpreterMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, failMock); //set resturn results interpreterMock.resultList.add(new testResult(STEP_0_RESULT, 0)); interpreterMock.resultList.add(new testResult(STEP_1_RESULT, 1)); handlerInterpreterMock.resultList.add(new testResult(HANDLER_RESULT, 0)); final WorkflowExecutionResult result = strategy.executeWorkflow(context, executionItem); assertNotNull(result); if (!result.isSuccess() && null != result.getException()) { result.getException().printStackTrace(System.err); } assertTrue(result.isSuccess()); assertNull("threw exception: " + result.getException(), result.getException()); assertNotNull(result.getResultSet()); final List<StepExecutionResult> test1 = result.getResultSet(); System.err.println("results: "+test1); assertEquals(2, test1.size()); assertEquals(2, interpreterMock.executionItemList.size()); assertEquals(2, interpreterMock.executionContextList.size()); //check handler item was executed assertEquals(1, handlerInterpreterMock.executionItemList.size()); assertEquals(1, handlerInterpreterMock.executionContextList.size()); int resultIndex =0; int stepNum=0; { //failure handler result final StepExecutionResult interpreterResult = test1.get(resultIndex); final DispatcherResult dr = NodeDispatchStepExecutor.extractDispatcherResult(interpreterResult); assertEquals(1, dr.getResults().size()); final NodeStepResult nrs = dr.getResults().values().iterator().next(); assertTrue("unexpected class: " + nrs.getClass(), nrs instanceof testResult); testResult val = (testResult) nrs; assertEquals(0, val.flag); assertTrue(val.isSuccess()); final StepExecutionItem executionItemX = handlerInterpreterMock.executionItemList.get(stepNum); assertTrue("wrong class: " + executionItemX.getClass().getName(), executionItemX instanceof ScriptFileCommandExecutionItem); ScriptFileCommandExecutionItem execItemX = (ScriptFileCommandExecutionItem) executionItemX; assertNotNull(execItemX.getScript()); assertNotNull(execItemX.getArgs()); assertEquals("failure handler script", execItemX.getScript()); assertEquals(3, execItemX.getArgs().length); assertEquals("failure", execItemX.getArgs()[0]); assertEquals("script", execItemX.getArgs()[1]); assertEquals("args", execItemX.getArgs()[2]); final ExecutionContext executionContextX = handlerInterpreterMock.executionContextList.get(stepNum); assertEquals(TEST_PROJECT, executionContextX.getFrameworkProject()); assertNotNull(executionContextX.getDataContext()); assertNotNull(executionContextX.getDataContext().get("node")); assertEquals(0, executionContextX.getLoglevel()); assertEquals("user1", executionContextX.getUser()); assertEquals(nodeset, executionContextX.getNodeSelector()); } resultIndex=1; stepNum = 1; { //second step result final StepExecutionResult interpreterResult = test1.get(resultIndex); final DispatcherResult dr = NodeDispatchStepExecutor.extractDispatcherResult(interpreterResult); assertEquals(1, dr.getResults().size()); final NodeStepResult nrs = dr.getResults().values().iterator().next(); assertTrue("unexpected class: " + nrs.getClass(), nrs instanceof testResult); testResult val = (testResult) nrs; assertEquals(1, val.flag); assertTrue(val.isSuccess()); final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(stepNum); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof ExecCommandExecutionItem); ExecCommandExecutionItem execItem = (ExecCommandExecutionItem) executionItem1; assertNotNull(execItem.getCommand()); assertEquals(3, execItem.getCommand().length); assertEquals("a", execItem.getCommand()[0]); assertEquals("3", execItem.getCommand()[1]); assertEquals("command", execItem.getCommand()[2]); final ExecutionContext executionContext = interpreterMock.executionContextList.get(stepNum); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(nodeset, executionContext.getNodeSelector()); } } } public void testGenericItem() throws Exception{ { //test jobref item final NodesSelector nodeset = SelectorUtils.singleNode(testFramework.getFrameworkNodeName()); final ArrayList<StepExecutionItem> commands = new ArrayList<StepExecutionItem>(); final testWorkflowCmdItem item = new testWorkflowCmdItem(); item.type = "my-type"; commands.add(item); final WorkflowImpl workflow = new WorkflowImpl(commands, 1, false, WorkflowExecutor.STEP_FIRST); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset) .executionListener(new testListener()) .framework(testFramework) .nodes(NodeFilter.filterNodes( nodeset, testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet() )) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); testInterpreter failMock = new testInterpreter(); failMock.shouldThrowException = true; interpreterService.registerInstance("my-type", interpreterMock); interpreterService.registerInstance("exec", failMock); interpreterService.registerInstance("script", failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, failMock); //set resturn result interpreterMock.resultList.add(new NodeStepResultImpl(null)); final WorkflowExecutionResult result = strategy.executeWorkflow(context, executionItem); assertNotNull(result); if (!result.isSuccess() && null != result.getException()) { result.getException().printStackTrace(System.err); } assertNull("threw exception: " + result.getException(), result.getException()); assertTrue(result.isSuccess()); assertEquals(1, interpreterMock.executionItemList.size()); final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(0); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof testWorkflowCmdItem); testWorkflowCmdItem execItem = (testWorkflowCmdItem) executionItem1; assertNotNull(execItem.getNodeStepType()); assertEquals("my-type", execItem.getNodeStepType()); assertEquals(1, interpreterMock.executionContextList.size()); final ExecutionContext executionContext = interpreterMock.executionContextList.get(0); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(nodeset, executionContext.getNodeSelector()); } } public void testMultipleNodes() throws Exception{ { //test jobref item final NodeSet nodeset = new NodeSet(); nodeset.createInclude().setName(".*"); final ArrayList<StepExecutionItem> commands = new ArrayList<StepExecutionItem>(); final testWorkflowCmdItem item = new testWorkflowCmdItem(); item.type = "my-type"; commands.add(item); final WorkflowImpl workflow = new WorkflowImpl(commands, 1, false, WorkflowExecutor.STEP_FIRST); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset) .executionListener(new testListener()) .framework(testFramework) .nodes(NodeFilter.filterNodes( nodeset, testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet() )) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); testInterpreter failMock = new testInterpreter(); failMock.shouldThrowException = true; interpreterService.registerInstance("my-type", interpreterMock); interpreterService.registerInstance("exec", failMock); interpreterService.registerInstance("script", failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, failMock); //set resturn result node 1 interpreterMock.resultList.add(new NodeStepResultImpl(null)); //set resturn result node 2 interpreterMock.resultList.add(new NodeStepResultImpl(null)); final WorkflowExecutionResult result = strategy.executeWorkflow(context, executionItem); assertNotNull(result); if (!result.isSuccess() && null != result.getException()) { result.getException().printStackTrace(System.err); } assertNull("threw exception: " + result.getException(), result.getException()); assertTrue(result.isSuccess()); assertEquals(2, interpreterMock.executionItemList.size()); assertEquals(2, interpreterMock.executionContextList.size()); { final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(0); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof testWorkflowCmdItem); testWorkflowCmdItem execItem = (testWorkflowCmdItem) executionItem1; assertNotNull(execItem.getNodeStepType()); assertEquals("my-type", execItem.getNodeStepType()); final ExecutionContext executionContext = interpreterMock.executionContextList.get(0); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(SelectorUtils.singleNode("test1"), executionContext.getNodeSelector()); } { final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(1); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof testWorkflowCmdItem); testWorkflowCmdItem execItem = (testWorkflowCmdItem) executionItem1; assertNotNull(execItem.getNodeStepType()); assertEquals("my-type", execItem.getNodeStepType()); final ExecutionContext executionContext = interpreterMock.executionContextList.get(1); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(SelectorUtils.singleNode("testnode2"), executionContext.getNodeSelector()); } } } public void testMultipleItemsAndNodes() throws Exception{ { //test jobref item final NodeSet nodeset = new NodeSet(); nodeset.createInclude().setName(".*"); final ArrayList<StepExecutionItem> commands = new ArrayList<StepExecutionItem>(); final testWorkflowCmdItem item = new testWorkflowCmdItem(); item.flag=0; item.type = "my-type"; commands.add(item); final testWorkflowCmdItem item2 = new testWorkflowCmdItem(); item2.flag = 1; item2.type = "my-type"; commands.add(item2); final WorkflowImpl workflow = new WorkflowImpl(commands, 1, false, WorkflowExecutor.STEP_FIRST); final WorkflowExecutionItemImpl executionItem = new WorkflowExecutionItemImpl(workflow); final StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); final StepExecutionContext context = new ExecutionContextImpl.Builder() .frameworkProject(TEST_PROJECT) .user("user1") .nodeSelector(nodeset) .executionListener(new testListener()) .framework(testFramework) .nodes(NodeFilter.filterNodes( nodeset, testFramework.getFrameworkProjectMgr().getFrameworkProject(TEST_PROJECT).getNodeSet() )) .build(); //setup testInterpreter for all command types final NodeStepExecutionService interpreterService = NodeStepExecutionService.getInstanceForFramework( testFramework); testInterpreter interpreterMock = new testInterpreter(); testInterpreter failMock = new testInterpreter(); failMock.shouldThrowException = true; interpreterService.registerInstance("my-type", interpreterMock); interpreterService.registerInstance("exec", failMock); interpreterService.registerInstance("script", failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_NODE_FIRST, failMock); interpreterService.registerInstance(WorkflowExecutionItem.COMMAND_TYPE_STEP_FIRST, failMock); //set resturn result node 1 step 1 interpreterMock.resultList.add(new NodeStepResultImpl(null)); //set resturn result node 2 step 1 interpreterMock.resultList.add(new NodeStepResultImpl(null)); //set resturn result node 1 step 2 interpreterMock.resultList.add(new NodeStepResultImpl(null)); //set resturn result node 2 step 2 interpreterMock.resultList.add(new NodeStepResultImpl(null)); final WorkflowExecutionResult result = strategy.executeWorkflow(context, executionItem); assertNotNull(result); if (!result.isSuccess() && null != result.getException()) { result.getException().printStackTrace(System.err); } assertNull("threw exception: " + result.getException(), result.getException()); assertTrue(result.isSuccess()); assertEquals(4, interpreterMock.executionItemList.size()); assertEquals(4, interpreterMock.executionContextList.size()); {//node 1 step 1 final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(0); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof testWorkflowCmdItem); testWorkflowCmdItem execItem = (testWorkflowCmdItem) executionItem1; assertNotNull(execItem.getNodeStepType()); assertEquals("my-type", execItem.getNodeStepType()); assertEquals(0, execItem.flag); final ExecutionContext executionContext = interpreterMock.executionContextList.get(0); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(SelectorUtils.singleNode("test1"), executionContext.getNodeSelector()); } {//node 2 step 1 final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(1); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof testWorkflowCmdItem); testWorkflowCmdItem execItem = (testWorkflowCmdItem) executionItem1; assertNotNull(execItem.getNodeStepType()); assertEquals("my-type", execItem.getNodeStepType()); assertEquals(0, execItem.flag); final ExecutionContext executionContext = interpreterMock.executionContextList.get(1); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(SelectorUtils.singleNode("testnode2"), executionContext.getNodeSelector()); } {//node 1 step 2 final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(2); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof testWorkflowCmdItem); testWorkflowCmdItem execItem = (testWorkflowCmdItem) executionItem1; assertNotNull(execItem.getNodeStepType()); assertEquals("my-type", execItem.getNodeStepType()); assertEquals(1, execItem.flag); final ExecutionContext executionContext = interpreterMock.executionContextList.get(2); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(SelectorUtils.singleNode("test1"), executionContext.getNodeSelector()); } {//node 2 step 2 final StepExecutionItem executionItem1 = interpreterMock.executionItemList.get(3); assertTrue("wrong class: " + executionItem1.getClass().getName(), executionItem1 instanceof testWorkflowCmdItem); testWorkflowCmdItem execItem = (testWorkflowCmdItem) executionItem1; assertNotNull(execItem.getNodeStepType()); assertEquals("my-type", execItem.getNodeStepType()); assertEquals(1, execItem.flag); final ExecutionContext executionContext = interpreterMock.executionContextList.get(3); assertEquals(TEST_PROJECT, executionContext.getFrameworkProject()); assertNotNull(executionContext.getDataContext()); assertNotNull(executionContext.getDataContext().get("node")); assertEquals(0, executionContext.getLoglevel()); assertEquals("user1", executionContext.getUser()); assertEquals(SelectorUtils.singleNode("testnode2"), executionContext.getNodeSelector()); } } } public void testCreatePrintableDataContext() { Map<String, Map<String, String>> dataContext = new HashMap<String, Map<String, String>>(); String otherKey = "other"; Map<String, String> otherData = new HashMap<String, String>(); dataContext.put(otherKey, otherData); Map<String, String> secureData = new HashMap<String, String>(); String secureKey = "secureKey"; secureData.put(secureKey, "secureValue"); dataContext.put(StepFirstWorkflowExecutor.SECURE_OPTION_KEY, secureData); Map<String, String> regularData = new HashMap<String, String>(); String insecureKey = "insecureKey"; regularData.put(insecureKey, "insecureValue"); regularData.put(secureKey, "secureValue"); dataContext.put(StepFirstWorkflowExecutor.OPTION_KEY, regularData); StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); Map<String, Map<String, String>> result = strategy.createPrintableDataContext(dataContext); Assert.assertSame("Expected other data to be present", otherData, result.get(otherKey)); Map<String, String> resultSecureData = result.get(StepFirstWorkflowExecutor.SECURE_OPTION_KEY); Assert.assertEquals("Expected secure value to be replaced", StepFirstWorkflowExecutor.SECURE_OPTION_VALUE, resultSecureData.get(secureKey)); Map<String, String> resultRegularData = result.get(StepFirstWorkflowExecutor.OPTION_KEY); Assert.assertEquals("Expected secure value to be replaced", StepFirstWorkflowExecutor.SECURE_OPTION_VALUE, resultRegularData.get(secureKey)); Assert.assertEquals("Expected insecure value to be untouched", regularData.get(insecureKey), resultRegularData.get(insecureKey)); } public void testCreatePrintableDataContextNoDataContext() { StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); Map<String, Map<String, String>> result = strategy.createPrintableDataContext(null); Assert.assertTrue("Expected empty data context", result.isEmpty()); } public void testCreatePrintableDataContextEmptyDataContext() { Map<String, Map<String, String>> dataContext = new HashMap<String, Map<String, String>>(); StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); Map<String, Map<String, String>> result = strategy.createPrintableDataContext(dataContext); Assert.assertTrue("Expected empty data context", result.isEmpty()); } public void testCreatePrintableDataContextNoSecureData() { Map<String, Map<String, String>> dataContext = new HashMap<String, Map<String, String>>(); String otherKey = "other"; Map<String, String> otherData = new HashMap<String, String>(); dataContext.put(otherKey, otherData); Map<String, String> regularData = new HashMap<String, String>(); String insecureKey = "insecureKey"; regularData.put(insecureKey, "insecureValue"); dataContext.put(StepFirstWorkflowExecutor.OPTION_KEY, regularData); StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); Map<String, Map<String, String>> result = strategy.createPrintableDataContext(dataContext); Assert.assertSame("Expected other data to be present", otherData, result.get(otherKey)); Map<String, String> resultRegularData = result.get(StepFirstWorkflowExecutor.OPTION_KEY); Assert.assertEquals("Expected insecure value to be untouched", regularData.get(insecureKey), resultRegularData.get(insecureKey)); } public void testCreatePrintableDataContextNoRegularData() { Map<String, Map<String, String>> dataContext = new HashMap<String, Map<String, String>>(); String otherKey = "other"; Map<String, String> otherData = new HashMap<String, String>(); dataContext.put(otherKey, otherData); Map<String, String> secureData = new HashMap<String, String>(); String secureKey = "secureKey"; secureData.put(secureKey, "secureValue"); dataContext.put(StepFirstWorkflowExecutor.SECURE_OPTION_KEY, secureData); StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); Map<String, Map<String, String>> result = strategy.createPrintableDataContext(dataContext); Assert.assertSame("Expected other data to be present", otherData, result.get(otherKey)); Map<String, String> resultSecureData = result.get(StepFirstWorkflowExecutor.SECURE_OPTION_KEY); Assert.assertEquals("Expected secure value to be replaced", StepFirstWorkflowExecutor.SECURE_OPTION_VALUE, resultSecureData.get(secureKey)); } @SuppressWarnings("unchecked") public void testExecuteWorkflowUsesPrintableDataContext() { ExecutionListener listener = Mockito.mock(ExecutionListener.class); StepExecutionContext context = Mockito.mock(StepExecutionContext.class); Mockito.when(context.getExecutionListener()).thenReturn(listener); String printableContextToString = "this is hopefully some string that won't appear elsewhere"; Map<String, Map<String, String>> printableContext = Mockito.mock(Map.class); Mockito.when(printableContext.toString()).thenReturn(printableContextToString); String dataContextToString = "this is another magic string that hopefully won't appear elsewhere"; Map<String, Map<String, String>> dataContext = Mockito.mock(Map.class); Mockito.when(dataContext.toString()).thenReturn(dataContextToString); Mockito.when(context.getDataContext()).thenReturn(dataContext); StepFirstWorkflowExecutor strategy = new StepFirstWorkflowExecutor(testFramework); strategy = Mockito.spy(strategy); Mockito.doReturn(printableContext).when(strategy).createPrintableDataContext(Mockito.same(dataContext)); WorkflowExecutionItem item = Mockito.mock(WorkflowExecutionItem.class); IWorkflow workflow = Mockito.mock(IWorkflow.class); Mockito.doReturn(workflow).when(item).getWorkflow(); strategy.executeWorkflowImpl(context, item); ArgumentCaptor<String> logLineCaptor = ArgumentCaptor.forClass(String.class); Mockito.verify(listener, Mockito.atLeastOnce()).log(Mockito.anyInt(), logLineCaptor.capture()); for (String line : logLineCaptor.getAllValues()) { if (line.startsWith(StepFirstWorkflowExecutor.DATA_CONTEXT_PREFIX)) { Assert.assertTrue("Expected printable data context string.", line.contains(printableContextToString)); Assert.assertFalse("Not expecting raw data context string.", line.contains(dataContextToString)); } } } }
Java
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.hooks.rtc.network; import java.net.URI; import org.apache.http.client.methods.HttpPost; public class HttpPatch extends HttpPost { public HttpPatch() { super(); } public HttpPatch(String uri) { super(uri); } public HttpPatch(URI uri) { super(uri); } @Override public String getMethod() { return "PATCH"; } }
Java
/* * 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.flink.test.runtime; import org.apache.flink.api.common.JobExecutionResult; import org.apache.flink.configuration.Configuration; import org.apache.flink.core.io.IOReadableWritable; import org.apache.flink.core.memory.DataInputView; import org.apache.flink.core.memory.DataOutputView; import org.apache.flink.runtime.io.network.api.reader.RecordReader; import org.apache.flink.runtime.io.network.api.writer.RecordWriter; import org.apache.flink.runtime.io.network.partition.ResultPartitionType; import org.apache.flink.runtime.jobgraph.DistributionPattern; import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobgraph.JobVertex; import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable; import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup; import org.apache.flink.test.util.JavaProgramTestBase; import org.apache.flink.util.TestLogger; import org.junit.Ignore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.TimeUnit; /** * Manually test the throughput of the network stack. */ @Ignore public class NetworkStackThroughputITCase extends TestLogger { private static final Logger LOG = LoggerFactory.getLogger(NetworkStackThroughputITCase.class); private static final String DATA_VOLUME_GB_CONFIG_KEY = "data.volume.gb"; private static final String USE_FORWARDER_CONFIG_KEY = "use.forwarder"; private static final String PARALLELISM_CONFIG_KEY = "num.subtasks"; private static final String NUM_SLOTS_PER_TM_CONFIG_KEY = "num.slots.per.tm"; private static final String IS_SLOW_SENDER_CONFIG_KEY = "is.slow.sender"; private static final String IS_SLOW_RECEIVER_CONFIG_KEY = "is.slow.receiver"; private static final int IS_SLOW_SLEEP_MS = 10; private static final int IS_SLOW_EVERY_NUM_RECORDS = (2 * 32 * 1024) / SpeedTestRecord.RECORD_SIZE; // ------------------------------------------------------------------------ // wrapper to reuse JavaProgramTestBase code in runs via main() private static class TestBaseWrapper extends JavaProgramTestBase { private int dataVolumeGb; private boolean useForwarder; private boolean isSlowSender; private boolean isSlowReceiver; private int parallelism; public TestBaseWrapper(Configuration config) { super(config); dataVolumeGb = config.getInteger(DATA_VOLUME_GB_CONFIG_KEY, 1); useForwarder = config.getBoolean(USE_FORWARDER_CONFIG_KEY, true); isSlowSender = config.getBoolean(IS_SLOW_SENDER_CONFIG_KEY, false); isSlowReceiver = config.getBoolean(IS_SLOW_RECEIVER_CONFIG_KEY, false); parallelism = config.getInteger(PARALLELISM_CONFIG_KEY, 1); int numSlots = config.getInteger(NUM_SLOTS_PER_TM_CONFIG_KEY, 1); if (parallelism % numSlots != 0) { throw new RuntimeException("The test case defines a parallelism that is not a multiple of the slots per task manager."); } setNumTaskManagers(parallelism / numSlots); setTaskManagerNumSlots(numSlots); } protected JobGraph getJobGraph() throws Exception { return createJobGraph(dataVolumeGb, useForwarder, isSlowSender, isSlowReceiver, parallelism); } private JobGraph createJobGraph(int dataVolumeGb, boolean useForwarder, boolean isSlowSender, boolean isSlowReceiver, int numSubtasks) { JobGraph jobGraph = new JobGraph("Speed Test"); SlotSharingGroup sharingGroup = new SlotSharingGroup(); JobVertex producer = new JobVertex("Speed Test Producer"); jobGraph.addVertex(producer); producer.setSlotSharingGroup(sharingGroup); producer.setInvokableClass(SpeedTestProducer.class); producer.setParallelism(numSubtasks); producer.getConfiguration().setInteger(DATA_VOLUME_GB_CONFIG_KEY, dataVolumeGb); producer.getConfiguration().setBoolean(IS_SLOW_SENDER_CONFIG_KEY, isSlowSender); JobVertex forwarder = null; if (useForwarder) { forwarder = new JobVertex("Speed Test Forwarder"); jobGraph.addVertex(forwarder); forwarder.setSlotSharingGroup(sharingGroup); forwarder.setInvokableClass(SpeedTestForwarder.class); forwarder.setParallelism(numSubtasks); } JobVertex consumer = new JobVertex("Speed Test Consumer"); jobGraph.addVertex(consumer); consumer.setSlotSharingGroup(sharingGroup); consumer.setInvokableClass(SpeedTestConsumer.class); consumer.setParallelism(numSubtasks); consumer.getConfiguration().setBoolean(IS_SLOW_RECEIVER_CONFIG_KEY, isSlowReceiver); if (useForwarder) { forwarder.connectNewDataSetAsInput(producer, DistributionPattern.ALL_TO_ALL, ResultPartitionType.PIPELINED); consumer.connectNewDataSetAsInput(forwarder, DistributionPattern.ALL_TO_ALL, ResultPartitionType.PIPELINED); } else { consumer.connectNewDataSetAsInput(producer, DistributionPattern.ALL_TO_ALL, ResultPartitionType.PIPELINED); } return jobGraph; } @Override protected void testProgram() throws Exception { JobExecutionResult jer = executor.submitJobAndWait(getJobGraph(), false); int dataVolumeGb = this.config.getInteger(DATA_VOLUME_GB_CONFIG_KEY, 1); long dataVolumeMbit = dataVolumeGb * 8192; long runtimeSecs = jer.getNetRuntime(TimeUnit.SECONDS); int mbitPerSecond = (int) (((double) dataVolumeMbit) / runtimeSecs); LOG.info(String.format("Test finished with throughput of %d MBit/s (runtime [secs]: %d, " + "data volume [gb/mbits]: %d/%d)", mbitPerSecond, runtimeSecs, dataVolumeGb, dataVolumeMbit)); } } // ------------------------------------------------------------------------ private static class SpeedTestProducer extends AbstractInvokable { @Override public void invoke() throws Exception { RecordWriter<SpeedTestRecord> writer = new RecordWriter<>(getEnvironment().getWriter(0)); try { // Determine the amount of data to send per subtask int dataVolumeGb = getTaskConfiguration().getInteger(NetworkStackThroughputITCase.DATA_VOLUME_GB_CONFIG_KEY, 1); long dataMbPerSubtask = (dataVolumeGb * 1024) / getCurrentNumberOfSubtasks(); long numRecordsToEmit = (dataMbPerSubtask * 1024 * 1024) / SpeedTestRecord.RECORD_SIZE; LOG.info(String.format("%d/%d: Producing %d records (each record: %d bytes, total: %.2f GB)", getIndexInSubtaskGroup() + 1, getCurrentNumberOfSubtasks(), numRecordsToEmit, SpeedTestRecord.RECORD_SIZE, dataMbPerSubtask / 1024.0)); boolean isSlow = getTaskConfiguration().getBoolean(IS_SLOW_SENDER_CONFIG_KEY, false); int numRecords = 0; SpeedTestRecord record = new SpeedTestRecord(); for (long i = 0; i < numRecordsToEmit; i++) { if (isSlow && (numRecords++ % IS_SLOW_EVERY_NUM_RECORDS) == 0) { Thread.sleep(IS_SLOW_SLEEP_MS); } writer.emit(record); } } finally { writer.flush(); } } } private static class SpeedTestForwarder extends AbstractInvokable { @Override public void invoke() throws Exception { RecordReader<SpeedTestRecord> reader = new RecordReader<>( getEnvironment().getInputGate(0), SpeedTestRecord.class, getEnvironment().getTaskManagerInfo().getTmpDirectories()); RecordWriter<SpeedTestRecord> writer = new RecordWriter<>(getEnvironment().getWriter(0)); try { SpeedTestRecord record; while ((record = reader.next()) != null) { writer.emit(record); } } finally { reader.clearBuffers(); writer.flush(); } } } private static class SpeedTestConsumer extends AbstractInvokable { @Override public void invoke() throws Exception { RecordReader<SpeedTestRecord> reader = new RecordReader<>( getEnvironment().getInputGate(0), SpeedTestRecord.class, getEnvironment().getTaskManagerInfo().getTmpDirectories()); try { boolean isSlow = getTaskConfiguration().getBoolean(IS_SLOW_RECEIVER_CONFIG_KEY, false); int numRecords = 0; while (reader.next() != null) { if (isSlow && (numRecords++ % IS_SLOW_EVERY_NUM_RECORDS) == 0) { Thread.sleep(IS_SLOW_SLEEP_MS); } } } finally { reader.clearBuffers(); } } } private static class SpeedTestRecord implements IOReadableWritable { private static final int RECORD_SIZE = 128; private final byte[] buf = new byte[RECORD_SIZE]; public SpeedTestRecord() { for (int i = 0; i < RECORD_SIZE; ++i) { this.buf[i] = (byte) (i % 128); } } @Override public void write(DataOutputView out) throws IOException { out.write(this.buf); } @Override public void read(DataInputView in) throws IOException { in.readFully(this.buf); } } // ------------------------------------------------------------------------ public void testThroughput() throws Exception { Object[][] configParams = new Object[][]{ new Object[]{1, false, false, false, 4, 2}, new Object[]{1, true, false, false, 4, 2}, new Object[]{1, true, true, false, 4, 2}, new Object[]{1, true, false, true, 4, 2}, new Object[]{2, true, false, false, 4, 2}, new Object[]{4, true, false, false, 4, 2}, new Object[]{4, true, false, false, 8, 4}, }; for (Object[] p : configParams) { Configuration config = new Configuration(); config.setInteger(DATA_VOLUME_GB_CONFIG_KEY, (Integer) p[0]); config.setBoolean(USE_FORWARDER_CONFIG_KEY, (Boolean) p[1]); config.setBoolean(IS_SLOW_SENDER_CONFIG_KEY, (Boolean) p[2]); config.setBoolean(IS_SLOW_RECEIVER_CONFIG_KEY, (Boolean) p[3]); config.setInteger(PARALLELISM_CONFIG_KEY, (Integer) p[4]); config.setInteger(NUM_SLOTS_PER_TM_CONFIG_KEY, (Integer) p[5]); TestBaseWrapper test = new TestBaseWrapper(config); test.startCluster(); System.out.println(Arrays.toString(p)); test.testProgram(); test.stopCluster(); } } private void runAllTests() throws Exception { testThroughput(); System.out.println("Done."); } public static void main(String[] args) throws Exception { new NetworkStackThroughputITCase().runAllTests(); } }
Java
/*******************************************************/ /* "C" Language Integrated Production System */ /* */ /* CLIPS Version 6.20 01/31/02 */ /* */ /* DEFFACTS PARSER HEADER FILE */ /*******************************************************/ /*************************************************************/ /* Purpose: */ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ /* Brian L. Donnell */ /* */ /* Revision History: */ /* */ /*************************************************************/ #ifndef _H_dffctpsr #define _H_dffctpsr #ifdef LOCALE #undef LOCALE #endif #ifdef _DFFCTPSR_SOURCE_ #define LOCALE #else #define LOCALE extern #endif LOCALE int ParseDeffacts(void *,char *); #endif
Java
/* * ************************************************************************* * Copyright (C) FRS Belgium NV ("FRSGlobal"). All rights reserved. * * This computer program is protected by copyright law and international * treaties. Unauthorized reproduction or distribution of this program, * or any portion of it, may result in severe civil and criminal penalties, * and will be prosecuted to the maximum extent possible under the law. * ************************************************************************* */ package org.cluj.bus.servlet; import com.google.gson.Gson; import org.cluj.bus.model.BusSchedule; import org.cluj.bus.model.BusScheduleDTO; import org.cluj.bus.model.CategorySchedule; import org.cluj.bus.services.JPARepository; import org.cluj.bus.util.ScheduleUtilities; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.ParseException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; public class BusScheduleServlet extends HttpServlet { private static final Logger LOGGER = Logger.getLogger(BusScheduleServlet.class.getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { String busId = httpServletRequest.getParameter(ServletUtils.BUS_ID_PARAMETER_KEY); ServletUtils.sendResponse(httpServletResponse, getResponseString(busId)); } private String getResponseString(String busId) { List<BusSchedule> busSchedules = new JPARepository<>(BusSchedule.class).findAll("busId", busId); Map<String, CategorySchedule> categorySchedules = new HashMap<>(); for (BusSchedule busSchedule : busSchedules) { String days = busSchedule.getDays(); CategorySchedule categorySchedule = categorySchedules.get(days); if (categorySchedule == null) { categorySchedule = new CategorySchedule(); categorySchedules.put(days, categorySchedule); categorySchedule.setDisplayName(busSchedule.getCategory()); categorySchedule.setApplicableDays(getApplicableDays(days)); } Collection<Date> startTimes = categorySchedule.getStartTimes(); if (startTimes == null) { startTimes = new ArrayList<>(); categorySchedule.setStartTimes(startTimes); } try { startTimes.add(ScheduleUtilities.getStartTime(busSchedule.getStartTime())); } catch (ParseException e) { LOGGER.log(Level.SEVERE, "Error parsing start time", e); } } BusScheduleDTO schedule = new BusScheduleDTO(); schedule.setSchedules(categorySchedules.values()); return new Gson().toJson(schedule); } private Collection<Integer> getApplicableDays(String days) { List<Integer> applicableDays = new ArrayList<>(); for (char aChar : days.toCharArray()) { int day = Integer.parseInt(String.valueOf(aChar)); applicableDays.add(day); } return applicableDays; } }
Java
# Rhodocybe fallax (Quél.) Singer, 1946 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Farlowia 2: 549 (1946) #### Original name Omphalia fallax Quél., 1896 ### Remarks null
Java
# XML Data Source for Apache Spark [![Build Status](https://travis-ci.org/databricks/spark-xml.svg?branch=master)](https://travis-ci.org/databricks/spark-xml) [![codecov.io](http://codecov.io/github/databricks/spark-xml/coverage.svg?branch=master)](http://codecov.io/github/databricks/spark-xml?branch=master) - A library for parsing and querying XML data with Apache Spark, for Spark SQL and DataFrames. The structure and test tools are mostly copied from [CSV Data Source for Spark](https://github.com/databricks/spark-csv). - This package supports to process format-free XML files in a distributed way, unlike JSON datasource in Spark restricts in-line JSON format. ## Requirements This library requires Spark 1.3+ ## Linking You can link against this library in your program at the following coordinates: ### Scala 2.10 ``` groupId: com.databricks artifactId: spark-xml_2.10 version: 0.3.3 ``` ### Scala 2.11 ``` groupId: com.databricks artifactId: spark-xml_2.11 version: 0.3.3 ``` ## Using with Spark shell This package can be added to Spark using the `--packages` command line option. For example, to include it when starting the spark shell: ### Spark compiled with Scala 2.10 ``` $SPARK_HOME/bin/spark-shell --packages com.databricks:spark-xml_2.10:0.3.3 ``` ### Spark compiled with Scala 2.11 ``` $SPARK_HOME/bin/spark-shell --packages com.databricks:spark-xml_2.11:0.3.3 ``` ## Features This package allows reading XML files in local or distributed filesystem as [Spark DataFrames](https://spark.apache.org/docs/1.6.0/sql-programming-guide.html). When reading files the API accepts several options: * `path`: Location of files. Similar to Spark can accept standard Hadoop globbing expressions. * `rowTag`: The row tag of your xml files to treat as a row. For example, in this xml `<books> <book><book> ...</books>`, the appropriate value would be `book`. Default is `ROW`. * `samplingRatio`: Sampling ratio for inferring schema (0.0 ~ 1). Default is 1. Possible types are `StructType`, `ArrayType`, `StringType`, `LongType`, `DoubleType`, `BooleanType`, `TimestampType` and `NullType`, unless user provides a schema for this. * `excludeAttribute` : Whether you want to exclude attributes in elements or not. Default is false. * `treatEmptyValuesAsNulls` : Whether you want to treat whitespaces as a null value. Default is false. * `failFast` : Whether you want to fail when it fails to parse malformed rows in XML files, instead of dropping the rows. Default is false. * `attributePrefix`: The prefix for attributes so that we can differentiate attributes and elements. This will be the prefix for field names. Default is `@`. * `valueTag`: The tag used for the value when there are attributes in the element having no child. Default is `#VALUE`. * `charset`: Defaults to 'UTF-8' but can be set to other valid charset names When writing files the API accepts several options: * `path`: Location to write files. * `rowTag`: The row tag of your xml files to treat as a row. For example, in this xml `<books> <book><book> ...</books>`, the appropriate value would be `book`. Default is `ROW`. * `rootTag`: The root tag of your xml files to treat as the root. For example, in this xml `<books> <book><book> ...</books>`, the appropriate value would be `books`. Default is `ROWS`. * `nullValue`: The value to write `null` value. Default is string `null`. When this is `null`, it does not write attributes and elements for fields. * `attributePrefix`: The prefix for attributes so that we can differentiating attributes and elements. This will be the prefix for field names. Default is `@`. * `valueTag`: The tag used for the value when there are attributes in the element having no child. Default is `#VALUE`. * `codec`: compression codec to use when saving to file. Should be the fully qualified name of a class implementing `org.apache.hadoop.io.compress.CompressionCodec` or one of case-insensitive shorten names (`bzip2`, `gzip`, `lz4`, and `snappy`). Defaults to no compression when a codec is not specified. Currently it supports the shortened name usage. You can use just `xml` instead of `com.databricks.spark.xml` from Spark 1.5.0+ ## Structure Conversion Due to the structure differences between `DataFrame` and XML, there are some conversion rules from XML data to `DataFrame` and from `DataFrame` to XML data. Note that handling attributes can be disabled with the option `excludeAttribute`. ### Conversion from XML to `DataFrame` - __Attributes__: Attributes are converted as fields with the heading prefix, `attributePrefix`. ```xml ... <one myOneAttrib="AAAA"> <two>two</two> <three>three</three> </one> ... ``` produces a schema below: ``` root |-- @myOneAttrib: string (nullable = true) |-- two: string (nullable = true) |-- three: string (nullable = true) ``` - __Value in an element that has no child elements but attributes__: The value is put in a separate field, `valueTag`. ```xml ... <one> <two myTwoAttrib="BBBBB">two</two> <three>three</three> </one> ... ``` produces a schema below: ``` root |-- two: struct (nullable = true) | |-- #VALUE: string (nullable = true) | |-- @myTwoAttrib: string (nullable = true) |-- three: string (nullable = true) ``` ### Conversion from `DataFrame` to XML - __Element as an array in an array__: Writing a XML file from `DataFrame` having a field `ArrayType` with its element as `ArrayType` would have an additional nested field for the element. This would not happen in reading and writing XML data but writing a `DataFrame` read from other sources. Therefore, roundtrip in reading and writing XML files has the same structure but writing a `DataFrame` read from other sources is possible to have a different structure. `DataFrame` with a schema below: ``` |-- a: array (nullable = true) | |-- element: array (containsNull = true) | | |-- element: string (containsNull = true) ``` with data below: ``` +------------------------------------+ | a| +------------------------------------+ |[WrappedArray(aa), WrappedArray(bb)]| +------------------------------------+ ``` produces a XML file below: ```xml ... <a> <item>aa</item> </a> <a> <item>bb</item> </a> ... ``` ## Examples These examples use a XML file available for download [here](https://github.com/databricks/spark-xml/raw/master/src/test/resources/books.xml): ``` $ wget https://github.com/databricks/spark-xml/raw/master/src/test/resources/books.xml ``` ### SQL API XML data source for Spark can infer data types: ```sql CREATE TABLE books USING com.databricks.spark.xml OPTIONS (path "books.xml", rowTag "book") ``` You can also specify column names and types in DDL. In this case, we do not infer schema. ```sql CREATE TABLE books (author string, description string, genre string, @id string, price double, publish_date string, title string) USING com.databricks.spark.xml OPTIONS (path "books.xml", rowTag "book") ``` ### Scala API __Spark 1.4+:__ ```scala import org.apache.spark.sql.SQLContext val sqlContext = new SQLContext(sc) val df = sqlContext.read .format("com.databricks.spark.xml") .option("rowTag", "book") .load("books.xml") val selectedData = df.select("author", "@id") selectedData.write .format("com.databricks.spark.xml") .option("rootTag", "books") .option("rowTag", "book") .save("newbooks.xml") ``` You can manually specify the schema when reading data: ```scala import org.apache.spark.sql.SQLContext import org.apache.spark.sql.types.{StructType, StructField, StringType, DoubleType}; val sqlContext = new SQLContext(sc) val customSchema = StructType(Array( StructField("@id", StringType, nullable = true), StructField("author", StringType, nullable = true), StructField("description", StringType, nullable = true), StructField("genre", StringType ,nullable = true), StructField("price", DoubleType, nullable = true), StructField("publish_date", StringType, nullable = true), StructField("title", StringType, nullable = true))) val df = sqlContext.read .format("com.databricks.spark.xml") .option("rowTag", "book") .schema(customSchema) .load("books.xml") val selectedData = df.select("author", "@id") selectedData.write .format("com.databricks.spark.xml") .option("rootTag", "books") .option("rowTag", "book") .save("newbooks.xml") ``` __Spark 1.3:__ ```scala import org.apache.spark.sql.SQLContext val sqlContext = new SQLContext(sc) val df = sqlContext.load( "com.databricks.spark.xml", Map("path" -> "books.xml", "rowTag" -> "book")) val selectedData = df.select("author", "@id") selectedData.save("com.databricks.spark.xml", SaveMode.ErrorIfExists, Map("path" -> "newbooks.xml", "rootTag" -> "books", "rowTag" -> "book")) ``` You can manually specify the schema when reading data: ```scala import org.apache.spark.sql.SQLContext import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType}; val sqlContext = new SQLContext(sc) val customSchema = StructType(Array( StructField("@id", StringType, nullable = true), StructField("author", StringType, nullable = true), StructField("description", StringType, nullable = true), StructField("genre", StringType ,nullable = true), StructField("price", DoubleType, nullable = true), StructField("publish_date", StringType, nullable = true), StructField("title", StringType, nullable = true))) val df = sqlContext.load( "com.databricks.spark.xml", schema = customSchema, Map("path" -> "books.xml", "rowTag" -> "book")) val selectedData = df.select("author", "@id") selectedData.save("com.databricks.spark.xml", SaveMode.ErrorIfExists, Map("path" -> "newbooks.xml", "rootTag" -> "books", "rowTag" -> "book")) ``` ### Java API __Spark 1.4+:__ ```java import org.apache.spark.sql.SQLContext SQLContext sqlContext = new SQLContext(sc); DataFrame df = sqlContext.read() .format("com.databricks.spark.xml") .option("rowTag", "book") .load("books.xml"); df.select("author", "@id").write() .format("com.databricks.spark.xml") .option("rootTag", "books") .option("rowTag", "book") .save("newbooks.xml"); ``` You can manually specify schema: ```java import org.apache.spark.sql.SQLContext; import org.apache.spark.sql.types.*; SQLContext sqlContext = new SQLContext(sc); StructType customSchema = new StructType(new StructField[] { new StructField("@id", DataTypes.StringType, true, Metadata.empty()), new StructField("author", DataTypes.StringType, true, Metadata.empty()), new StructField("description", DataTypes.StringType, true, Metadata.empty()), new StructField("genre", DataTypes.StringType, true, Metadata.empty()), new StructField("price", DataTypes.DoubleType, true, Metadata.empty()), new StructField("publish_date", DataTypes.StringType, true, Metadata.empty()), new StructField("title", DataTypes.StringType, true, Metadata.empty()) }); DataFrame df = sqlContext.read() .format("com.databricks.spark.xml") .option("rowTag", "book") .schema(customSchema) .load("books.xml"); df.select("author", "@id").write() .format("com.databricks.spark.xml") .option("rootTag", "books") .option("rowTag", "book") .save("newbooks.xml"); ``` __Spark 1.3:__ ```java import org.apache.spark.sql.SQLContext SQLContext sqlContext = new SQLContext(sc); HashMap<String, String> options = new HashMap<String, String>(); options.put("rowTag", "book"); options.put("path", "books.xml"); DataFrame df = sqlContext.load("com.databricks.spark.xml", options); HashMap<String, String> options = new HashMap<String, String>(); options.put("rowTag", "book"); options.put("rootTag", "books"); options.put("path", "newbooks.xml"); df.select("author", "@id").save("com.databricks.spark.xml", SaveMode.ErrorIfExists, options) ``` You can manually specify schema: ```java import org.apache.spark.sql.SQLContext; import org.apache.spark.sql.types.*; SQLContext sqlContext = new SQLContext(sc); StructType customSchema = new StructType(new StructField[] { new StructField("@id", DataTypes.StringType, true, Metadata.empty()), new StructField("author", DataTypes.StringType, true, Metadata.empty()), new StructField("description", DataTypes.StringType, true, Metadata.empty()), new StructField("genre", DataTypes.StringType, true, Metadata.empty()), new StructField("price", DataTypes.DoubleType, true, Metadata.empty()), new StructField("publish_date", DataTypes.StringType, true, Metadata.empty()), new StructField("title", DataTypes.StringType, true, Metadata.empty()) }); HashMap<String, String> options = new HashMap<String, String>(); options.put("rowTag", "book"); options.put("path", "books.xml"); DataFrame df = sqlContext.load("com.databricks.spark.xml", customSchema, options); HashMap<String, String> options = new HashMap<String, String>(); options.put("rowTag", "book"); options.put("rootTag", "books"); options.put("path", "newbooks.xml"); df.select("author", "@id").save("com.databricks.spark.xml", SaveMode.ErrorIfExists, options) ``` ### Python API __Spark 1.4+:__ ```python from pyspark.sql import SQLContext sqlContext = SQLContext(sc) df = sqlContext.read.format('com.databricks.spark.xml').options(rowTag='book').load('books.xml') df.select("author", "@id").write \ .format('com.databricks.spark.xml') \ .options(rowTag='book', rootTag='books') \ .save('newbooks.xml') ``` You can manually specify schema: ```python from pyspark.sql import SQLContext from pyspark.sql.types import * sqlContext = SQLContext(sc) customSchema = StructType([ \ StructField("@id", StringType(), True), \ StructField("author", StringType(), True), \ StructField("description", StringType(), True), \ StructField("genre", StringType(), True), \ StructField("price", DoubleType(), True), \ StructField("publish_date", StringType(), True), \ StructField("title", StringType(), True)]) df = sqlContext.read \ .format('com.databricks.spark.xml') \ .options(rowTag='book') \ .load('books.xml', schema = customSchema) df.select("author", "@id").write \ .format('com.databricks.spark.xml') \ .options(rowTag='book', rootTag='books') \ .save('newbooks.xml') ``` __Spark 1.3:__ ```python from pyspark.sql import SQLContext sqlContext = SQLContext(sc) df = sqlContext.load(source="com.databricks.spark.xml", rowTag = 'book', path = 'books.xml') df.select("author", "@id").save('newbooks.xml', rootTag = 'books', rowTag = 'book', path = 'newbooks.xml') ``` You can manually specify schema: ```python from pyspark.sql import SQLContext from pyspark.sql.types import * sqlContext = SQLContext(sc) customSchema = StructType([ \ StructField("@id", StringType(), True), \ StructField("author", StringType(), True), \ StructField("description", StringType(), True), \ StructField("genre", StringType(), True), \ StructField("price", DoubleType(), True), \ StructField("publish_date", StringType(), True), \ StructField("title", StringType(), True)]) df = sqlContext.load(source="com.databricks.spark.xml", rowTag = 'book', schema = customSchema, path = 'books.xml') df.select("author", "@id").save('newbooks.xml', rootTag = 'books', rowTag = 'book', path = 'newbooks.xml') ``` ### R API __Spark 1.4+:__ Automatically infer schema (data types) ```R library(SparkR) Sys.setenv('SPARKR_SUBMIT_ARGS'='"--packages" "com.databricks:spark-xml_2.10:0.3.3" "sparkr-shell"') sqlContext <- sparkRSQL.init(sc) df <- read.df(sqlContext, "books.xml", source = "com.databricks.spark.xml", rowTag = "book") # In this case, `rootTag` is set to "ROWS" and `rowTag` is set to "ROW". write.df(df, "newbooks.csv", "com.databricks.spark.xml", "overwrite") ``` You can manually specify schema: ```R library(SparkR) Sys.setenv('SPARKR_SUBMIT_ARGS'='"--packages" "com.databricks:spark-csv_2.10:0.3.3" "sparkr-shell"') sqlContext <- sparkRSQL.init(sc) customSchema <- structType( structField("@id", "string"), structField("author", "string"), structField("description", "string"), structField("genre", "string"), structField("price", "double"), structField("publish_date", "string"), structField("title", "string")) df <- read.df(sqlContext, "books.xml", source = "com.databricks.spark.xml", rowTag = "book") # In this case, `rootTag` is set to "ROWS" and `rowTag` is set to "ROW". write.df(df, "newbooks.csv", "com.databricks.spark.xml", "overwrite") ``` ## Hadoop InputFormat The library contains a Hadoop input format for reading XML files by a start tag and an end tag. This is similar with [XmlInputFormat.java](https://github.com/apache/mahout/blob/9d14053c80a1244bdf7157ab02748a492ae9868a/integration/src/main/java/org/apache/mahout/text/wikipedia/XmlInputFormat.java) in [Mahout](http://mahout.apache.org) but supports to read compressed files, different encodings and read elements including attributes, which you may make direct use of as follows: ```scala import com.databricks.spark.xml.XmlInputFormat // This will detect the tags including attributes sc.hadoopConfiguration.set(XmlInputFormat.START_TAG_KEY, "<book>") sc.hadoopConfiguration.set(XmlInputFormat.END_TAG_KEY, "</book>") sc.hadoopConfiguration.set(XmlInputFormat.ENCODING_KEY, "utf-8") val records = sc.newAPIHadoopFile( path, classOf[XmlInputFormat], classOf[LongWritable], classOf[Text]) ``` ## Building From Source This library is built with [SBT](http://www.scala-sbt.org/0.13/docs/Command-Line-Reference.html), which is automatically downloaded by the included shell script. To build a JAR file simply run `sbt/sbt package` from the project root. The build configuration includes support for both Scala 2.10 and 2.11. ## Acknowledgements This project was initially created by [HyukjinKwon](https://github.com/HyukjinKwon) and donated to [Databricks](https://databricks.com).
Java
/** * 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.camel.component.netty4; import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ThreadFactory; import io.netty.util.concurrent.DefaultEventExecutorGroup; import io.netty.util.concurrent.EventExecutorGroup; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.impl.UriEndpointComponent; import org.apache.camel.util.IntrospectionSupport; import org.apache.camel.util.concurrent.CamelThreadFactory; public class NettyComponent extends UriEndpointComponent { private NettyConfiguration configuration; private volatile EventExecutorGroup executorService; public NettyComponent() { super(NettyEndpoint.class); } public NettyComponent(Class<? extends Endpoint> endpointClass) { super(endpointClass); } public NettyComponent(CamelContext context) { super(context, NettyEndpoint.class); } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { NettyConfiguration config; if (configuration != null) { config = configuration.copy(); } else { config = new NettyConfiguration(); } config = parseConfiguration(config, remaining, parameters); // merge any custom bootstrap configuration on the config NettyServerBootstrapConfiguration bootstrapConfiguration = resolveAndRemoveReferenceParameter(parameters, "bootstrapConfiguration", NettyServerBootstrapConfiguration.class); if (bootstrapConfiguration != null) { Map<String, Object> options = new HashMap<String, Object>(); if (IntrospectionSupport.getProperties(bootstrapConfiguration, options, null, false)) { IntrospectionSupport.setProperties(getCamelContext().getTypeConverter(), config, options); } } // validate config config.validateConfiguration(); NettyEndpoint nettyEndpoint = new NettyEndpoint(remaining, this, config); setProperties(nettyEndpoint.getConfiguration(), parameters); return nettyEndpoint; } /** * Parses the configuration * * @return the parsed and valid configuration to use */ protected NettyConfiguration parseConfiguration(NettyConfiguration configuration, String remaining, Map<String, Object> parameters) throws Exception { configuration.parseURI(new URI(remaining), parameters, this, "tcp", "udp"); return configuration; } public NettyConfiguration getConfiguration() { return configuration; } public void setConfiguration(NettyConfiguration configuration) { this.configuration = configuration; } public void setExecutorService(EventExecutorGroup executorService) { this.executorService = executorService; } public synchronized EventExecutorGroup getExecutorService() { if (executorService == null) { executorService = createExecutorService(); } return executorService; } @Override protected void doStart() throws Exception { if (configuration == null) { configuration = new NettyConfiguration(); } if (configuration.isUsingExecutorService() && executorService == null) { executorService = createExecutorService(); } super.doStart(); } protected EventExecutorGroup createExecutorService() { // Provide the executor service for the application // and use a Camel thread factory so we have consistent thread namings // we should use a shared thread pool as recommended by Netty String pattern = getCamelContext().getExecutorServiceManager().getThreadNamePattern(); ThreadFactory factory = new CamelThreadFactory(pattern, "NettyEventExecutorGroup", true); return new DefaultEventExecutorGroup(configuration.getMaximumPoolSize(), factory); } @Override protected void doStop() throws Exception { if (executorService != null) { getCamelContext().getExecutorServiceManager().shutdownNow(executorService); executorService = null; } super.doStop(); } }
Java
/* * 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.catalina.valves.rewrite; import java.nio.charset.Charset; /** * Resolver abstract class. */ public abstract class Resolver { public abstract String resolve(String key); public String resolveEnv(String key) { return System.getProperty(key); } public abstract String resolveSsl(String key); public abstract String resolveHttp(String key); public abstract boolean resolveResource(int type, String name); /** * @return The name of the encoding to use to %nn encode URIs * * @deprecated This will be removed in Tomcat 9.0.x */ @Deprecated public abstract String getUriEncoding(); public abstract Charset getUriCharset(); }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta httpEquiv="Content-Type" content="text/html; charset=utf-8"/> <title>Test results - Class carlosgsouza.vinylshop.functional.v1.SummaryFunctionalSpec</title> <link href="base-style.css" rel="stylesheet" type="text/css"/> <link href="style.css" rel="stylesheet" type="text/css"/> <script src="report.js" type="text/javascript"></script> </head> <body> <div id="content"> <h1>Class carlosgsouza.vinylshop.functional.v1.SummaryFunctionalSpec</h1> <div class="breadcrumbs"> <a href="index.html">all</a> &gt; <a href="carlosgsouza.vinylshop.functional.v1.html">carlosgsouza.vinylshop.functional.v1</a> &gt; SummaryFunctionalSpec</div> <div id="summary"> <table> <tr> <td> <div class="summaryGroup"> <table> <tr> <td> <div class="infoBox" id="tests"> <div class="counter">1</div> <p>tests</p> </div> </td> <td> <div class="infoBox" id="failures"> <div class="counter">0</div> <p>failures</p> </div> </td> <td> <div class="infoBox" id="duration"> <div class="counter">0.054s</div> <p>duration</p> </div> </td> </tr> </table> </div> </td> <td> <div class="infoBox success" id="successRate"> <div class="percent">100%</div> <p>successful</p> </div> </td> </tr> </table> </div> <div id="tabs"> <ul class="tabLinks"> <li> <a href="#tab0">Tests</a> </li> </ul> <div id="tab0" class="tab"> <h2>Tests</h2> <table> <thead> <tr> <th>Test</th> <th>Duration</th> <th>Result</th> </tr> </thead> <tr> <td class="success">should show a summary of the vinyls</td> <td>0.054s</td> <td class="success">passed</td> </tr> </table> </div> </div> <div id="footer"> <p>Generated by <a href="http://www.gradle.org">Gradle 1.8</a> at Dec 14, 2013 2:32:16 PM</p> </div> </div> </body>
Java
/* * 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.droids.impl; import java.util.Date; import java.util.Queue; import java.util.concurrent.TimeUnit; import org.apache.droids.api.DelayTimer; import org.apache.droids.api.Droid; import org.apache.droids.api.Task; import org.apache.droids.api.TaskExceptionHandler; import org.apache.droids.api.TaskExceptionResult; import org.apache.droids.api.TaskMaster; import org.apache.droids.api.Worker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SequentialTaskMaster<T extends Task> implements TaskMaster<T> { private static final Logger LOG = LoggerFactory.getLogger(SequentialTaskMaster.class); private final Object mutex; private volatile boolean completed; private volatile Date startedWorking = null; private volatile Date finishedWorking = null; private volatile int completedTask = 0; private volatile T lastCompletedTask = null; private volatile ExecutionState state = ExecutionState.INITIALIZED; private DelayTimer delayTimer = null; private TaskExceptionHandler exHandler = null; public SequentialTaskMaster() { super(); this.mutex = new Object(); } /** * The queue has been initialized */ @Override public synchronized void start(final Queue<T> queue, final Droid<T> droid) { this.completed = false; this.startedWorking = new Date(); this.finishedWorking = null; this.completedTask = 0; this.state = ExecutionState.RUNNING; boolean terminated = false; while (!terminated) { T task = queue.poll(); if (task == null) { break; } if (delayTimer != null) { long delay = delayTimer.getDelayMillis(); if (delay > 0) { try { Thread.sleep(delay); } catch (InterruptedException e) { } } } Worker<T> worker = droid.getNewWorker(); try { if (!task.isAborted()) { worker.execute(task); } completedTask++; lastCompletedTask = task; } catch (Exception ex) { TaskExceptionResult result = TaskExceptionResult.WARN; if (exHandler != null) { result = exHandler.handleException(ex); } switch (result) { case WARN: LOG.warn(ex.toString() + " " + task.getId()); if (LOG.isDebugEnabled()) { LOG.debug(ex.toString(), ex); } break; case FATAL: LOG.error(ex.getMessage(), ex); terminated = true; break; } } } finishedWorking = new Date(); this.state = ExecutionState.STOPPED; droid.finished(); synchronized (mutex) { completed = true; mutex.notifyAll(); } } @Override public final void setExceptionHandler(TaskExceptionHandler exHandler) { this.exHandler = exHandler; } @Override public final void setDelayTimer(DelayTimer delayTimer) { this.delayTimer = delayTimer; } public boolean isWorking() { return startedWorking != null && finishedWorking == null; } @Override public Date getStartTime() { return startedWorking; } @Override public Date getFinishedWorking() { return finishedWorking; } @Override public long getCompletedTasks() { return completedTask; } @Override public T getLastCompletedTask() { return lastCompletedTask; } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { if (timeout < 0) { timeout = 0; } synchronized (this.mutex) { long deadline = System.currentTimeMillis() + unit.toMillis(timeout); long remaining = timeout; while (!completed) { this.mutex.wait(remaining); if (timeout >= 0) { remaining = deadline - System.currentTimeMillis(); if (remaining <= 0) { return false; // Reach if timeout is over and no finish. } } } } return true; } @Override public ExecutionState getExecutionState() { return state; } }
Java
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(KeywordCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(NamedParameterCompletionProvider))] [Shared] internal class KeywordCompletionProvider : AbstractKeywordCompletionProvider<CSharpSyntaxContext> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public KeywordCompletionProvider() : base(GetKeywordRecommenders()) { } private static ImmutableArray<IKeywordRecommender<CSharpSyntaxContext>> GetKeywordRecommenders() { return new IKeywordRecommender<CSharpSyntaxContext>[] { new AbstractKeywordRecommender(), new AddKeywordRecommender(), new AliasKeywordRecommender(), new AnnotationsKeywordRecommender(), new AscendingKeywordRecommender(), new AsKeywordRecommender(), new AssemblyKeywordRecommender(), new AsyncKeywordRecommender(), new AwaitKeywordRecommender(), new BaseKeywordRecommender(), new BoolKeywordRecommender(), new BreakKeywordRecommender(), new ByKeywordRecommender(), new ByteKeywordRecommender(), new CaseKeywordRecommender(), new CatchKeywordRecommender(), new CharKeywordRecommender(), new CheckedKeywordRecommender(), new ChecksumKeywordRecommender(), new ClassKeywordRecommender(), new ConstKeywordRecommender(), new ContinueKeywordRecommender(), new DecimalKeywordRecommender(), new DefaultKeywordRecommender(), new DefineKeywordRecommender(), new DelegateKeywordRecommender(), new DescendingKeywordRecommender(), new DisableKeywordRecommender(), new DoKeywordRecommender(), new DoubleKeywordRecommender(), new DynamicKeywordRecommender(), new ElifKeywordRecommender(), new ElseKeywordRecommender(), new EnableKeywordRecommender(), new EndIfKeywordRecommender(), new EndRegionKeywordRecommender(), new EnumKeywordRecommender(), new EqualsKeywordRecommender(), new ErrorKeywordRecommender(), new EventKeywordRecommender(), new ExplicitKeywordRecommender(), new ExternKeywordRecommender(), new FalseKeywordRecommender(), new FieldKeywordRecommender(), new FinallyKeywordRecommender(), new FixedKeywordRecommender(), new FloatKeywordRecommender(), new ForEachKeywordRecommender(), new ForKeywordRecommender(), new FromKeywordRecommender(), new GetKeywordRecommender(), new GlobalKeywordRecommender(), new GotoKeywordRecommender(), new GroupKeywordRecommender(), new HiddenKeywordRecommender(), new IfKeywordRecommender(), new ImplicitKeywordRecommender(), new InKeywordRecommender(), new InterfaceKeywordRecommender(), new InternalKeywordRecommender(), new IntKeywordRecommender(), new IntoKeywordRecommender(), new IsKeywordRecommender(), new JoinKeywordRecommender(), new LetKeywordRecommender(), new LineKeywordRecommender(), new LoadKeywordRecommender(), new LockKeywordRecommender(), new LongKeywordRecommender(), new MethodKeywordRecommender(), new ModuleKeywordRecommender(), new NameOfKeywordRecommender(), new NamespaceKeywordRecommender(), new NewKeywordRecommender(), new NintKeywordRecommender(), new NotNullKeywordRecommender(), new NuintKeywordRecommender(), new NullableKeywordRecommender(), new NullKeywordRecommender(), new ObjectKeywordRecommender(), new OnKeywordRecommender(), new OperatorKeywordRecommender(), new OrderByKeywordRecommender(), new OutKeywordRecommender(), new OverrideKeywordRecommender(), new ParamKeywordRecommender(), new ParamsKeywordRecommender(), new PartialKeywordRecommender(), new PragmaKeywordRecommender(), new PrivateKeywordRecommender(), new PropertyKeywordRecommender(), new ProtectedKeywordRecommender(), new PublicKeywordRecommender(), new ReadOnlyKeywordRecommender(), new ReferenceKeywordRecommender(), new RefKeywordRecommender(), new RegionKeywordRecommender(), new RemoveKeywordRecommender(), new RestoreKeywordRecommender(), new ReturnKeywordRecommender(), new SByteKeywordRecommender(), new SealedKeywordRecommender(), new SelectKeywordRecommender(), new SetKeywordRecommender(), new ShortKeywordRecommender(), new SizeOfKeywordRecommender(), new StackAllocKeywordRecommender(), new StaticKeywordRecommender(), new StringKeywordRecommender(), new StructKeywordRecommender(), new SwitchKeywordRecommender(), new ThisKeywordRecommender(), new ThrowKeywordRecommender(), new TrueKeywordRecommender(), new TryKeywordRecommender(), new TypeKeywordRecommender(), new TypeOfKeywordRecommender(), new TypeVarKeywordRecommender(), new UIntKeywordRecommender(), new ULongKeywordRecommender(), new UncheckedKeywordRecommender(), new UndefKeywordRecommender(), new UnmanagedKeywordRecommender(), new UnsafeKeywordRecommender(), new UShortKeywordRecommender(), new UsingKeywordRecommender(), new VarKeywordRecommender(), new VirtualKeywordRecommender(), new VoidKeywordRecommender(), new VolatileKeywordRecommender(), new WarningKeywordRecommender(), new WarningsKeywordRecommender(), new WhenKeywordRecommender(), new WhereKeywordRecommender(), new WhileKeywordRecommender(), new YieldKeywordRecommender(), }.ToImmutableArray(); } internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); internal override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; protected override async Task<CSharpSyntaxContext> CreateContextAsync(Document document, int position, CancellationToken cancellationToken) { var span = new TextSpan(position, length: 0); var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false); return CSharpSyntaxContext.CreateContext(document.Project.Solution.Workspace, semanticModel, position, cancellationToken); } private static readonly CompletionItemRules s_tupleRules = CompletionItemRules.Default. WithCommitCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ':')); protected override CompletionItem CreateItem(RecommendedKeyword keyword, CSharpSyntaxContext context) { var rules = context.IsPossibleTupleContext ? s_tupleRules : CompletionItemRules.Default; return CommonCompletionItem.Create( displayText: keyword.Keyword, displayTextSuffix: "", description: keyword.DescriptionFactory(CancellationToken.None), glyph: Glyph.Keyword, rules: rules.WithMatchPriority(keyword.MatchPriority) .WithFormatOnCommit(keyword.ShouldFormatOnCommit)); } internal override TextSpan GetCurrentSpan(TextSpan span, SourceText text) => CompletionUtilities.GetCompletionItemSpan(text, span.End); } }
Java
# Cymbosetaria sagittifolia (A.Rich.) Schweick. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Hook. F. , Icon. Pl. 34 (T. 3320):1. 1936 #### Original name null ### Remarks null
Java
# Psoralea harveyana Meisn. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
package com.wjyup.coolq.util; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import com.google.gson.JsonObject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.util.DigestUtils; import java.nio.charset.StandardCharsets; /** * 发送消息工具类 * @author WJY */ public class SendMessageUtil { private static Logger log = LogManager.getLogger(SendMessageUtil.class); /** * 发送json数据并获取返回值 * @param message 消息 * @return 发送消息的结果 */ public static String sendSocketData(String message){ try { ConfigCache configCache = SpringContext.getConfigCache(); //判断发送消息方式 if(StaticConf.MSG_SEND_TYPE_HTTP.equalsIgnoreCase(configCache.getMSG_SEND_TYPE())){// http String url = String.format("http://%s:%s", configCache.getHTTP_HOST(), configCache.getHTTP_PORT()); if(configCache.isUSE_TOKEN()){// 使用token long authTime = System.currentTimeMillis() / 1000; String key = configCache.getKEY()+":"+authTime; String authToken = DigestUtils.md5DigestAsHex(key.getBytes(StandardCharsets.UTF_8)); JSONObject jsonObject = JSON.parseObject(message); jsonObject.put("authTime", authTime); jsonObject.put("authToken", authToken); message = jsonObject.toJSONString(); } log.debug("发送的json文本:"+message); try{ String result = WebUtil.post(url, message); log.debug("返回结果:" + result); return result; }catch (Exception e){ log.error(e.getMessage(),e); } } } catch (Exception e) { log.error(e.getMessage(), e); } return null; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_222) on Thu Jan 16 21:49:29 PST 2020 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.apache.datasketches.quantiles.DoublesUnionBuilder (datasketches-java 1.2.0-incubating API)</title> <meta name="date" content="2020-01-16"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.datasketches.quantiles.DoublesUnionBuilder (datasketches-java 1.2.0-incubating API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/datasketches/quantiles/DoublesUnionBuilder.html" title="class in org.apache.datasketches.quantiles">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/datasketches/quantiles/class-use/DoublesUnionBuilder.html" target="_top">Frames</a></li> <li><a href="DoublesUnionBuilder.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.datasketches.quantiles.DoublesUnionBuilder" class="title">Uses of Class<br>org.apache.datasketches.quantiles.DoublesUnionBuilder</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/apache/datasketches/quantiles/DoublesUnionBuilder.html" title="class in org.apache.datasketches.quantiles">DoublesUnionBuilder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.datasketches.quantiles">org.apache.datasketches.quantiles</a></td> <td class="colLast"> <div class="block">The quantiles package contains stochastic streaming algorithms that enable single-pass analysis of the distribution of a stream of real (double) values or generic items.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.datasketches.quantiles"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/apache/datasketches/quantiles/DoublesUnionBuilder.html" title="class in org.apache.datasketches.quantiles">DoublesUnionBuilder</a> in <a href="../../../../../org/apache/datasketches/quantiles/package-summary.html">org.apache.datasketches.quantiles</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/apache/datasketches/quantiles/package-summary.html">org.apache.datasketches.quantiles</a> that return <a href="../../../../../org/apache/datasketches/quantiles/DoublesUnionBuilder.html" title="class in org.apache.datasketches.quantiles">DoublesUnionBuilder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../org/apache/datasketches/quantiles/DoublesUnionBuilder.html" title="class in org.apache.datasketches.quantiles">DoublesUnionBuilder</a></code></td> <td class="colLast"><span class="typeNameLabel">DoublesUnion.</span><code><span class="memberNameLink"><a href="../../../../../org/apache/datasketches/quantiles/DoublesUnion.html#builder--">builder</a></span>()</code> <div class="block">Returns a new UnionBuilder</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../org/apache/datasketches/quantiles/DoublesUnionBuilder.html" title="class in org.apache.datasketches.quantiles">DoublesUnionBuilder</a></code></td> <td class="colLast"><span class="typeNameLabel">DoublesUnionBuilder.</span><code><span class="memberNameLink"><a href="../../../../../org/apache/datasketches/quantiles/DoublesUnionBuilder.html#setMaxK-int-">setMaxK</a></span>(int&nbsp;maxK)</code> <div class="block">Sets the parameter <i>masK</i> that determines the maximum size of the sketch that results from a union and its accuracy.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/datasketches/quantiles/DoublesUnionBuilder.html" title="class in org.apache.datasketches.quantiles">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/datasketches/quantiles/class-use/DoublesUnionBuilder.html" target="_top">Frames</a></li> <li><a href="DoublesUnionBuilder.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2015&#x2013;2020 <a href="https://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
Java
/* * Copyright 2014–2017 SlamData 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 quasar.physical.mongodb import slamdata.Predef.{ Eq => _, _ } import quasar._ import quasar.javascript.Js import quasar.jscore._ import java.time.Instant final case class javascript[R](embed: JsCoreF[R] => R) { val js = jscore.fixpoint[R](embed) import js._ /** Convert a `Bson.Date` to a JavaScript `Date`. */ def toJsDate(value: Bson.Date): R = New(Name("Date"), List( Literal(Js.Str(Instant.ofEpochMilli(value.millis).toString)))) /** Convert a `Bson.ObjectId` to a JavaScript `ObjectId`. */ def toJsObjectId(value: Bson.ObjectId): R = New(Name("ObjectId"), List(Literal(Js.Str(value.str)))) def isNull(expr: R): R = BinOp(Eq, Literal(Js.Null), expr) def isAnyNumber(expr: R): R = BinOp(Or, isDec(expr), isInt(expr)) def isInt[A](expr: R): R = BinOp(Or, BinOp(Instance, expr, ident("NumberInt")), BinOp(Instance, expr, ident("NumberLong"))) def isDec(expr: R): R = Call(ident("isNumber"), List(expr)) def isString(expr: R): R = Call(ident("isString"), List(expr)) def isObjectOrArray(expr: R): R = Call(ident("isObject"), List(expr)) def isArray(expr: R): R = Call(select(ident("Array"), "isArray"), List(expr)) def isObject(expr: R): R = BinOp(And, isObjectOrArray(expr), UnOp(Not, isArray(expr))) def isArrayOrString(expr: R): R = BinOp(Or, isArray(expr), isString(expr)) def isBoolean(expr: R): R = BinOp(Eq, UnOp(TypeOf, expr), Literal(Js.Str("boolean"))) def isTimestamp(expr: R): R = BinOp(Instance, expr, ident("Timestamp")) def isDate(expr: R): R = BinOp(Instance, expr, ident("Date")) def isBinary(expr: R): R = BinOp(Instance, expr, ident("Binary")) def isObjectId(expr: R): R = BinOp(Instance, expr, ident("ObjectId")) }
Java
# Lepiota olivaceomammosa var. irritans Raithelh. VARIETY #### Status ACCEPTED #### According to Index Fungorum #### Published in Metrodiana 16(1-3): 19 (1988) #### Original name Lepiota olivaceomammosa var. irritans Raithelh. ### Remarks null
Java
# vim: set et sw=4 sts=4 fileencoding=utf-8: # # Python header conversion # Copyright (c) 2013,2014 Dave Hughes <dave@waveform.org.uk> # # Original headers # Copyright (c) 2012, Broadcom Europe Ltd # 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 the copyright holder 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 HOLDER 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. from __future__ import ( unicode_literals, print_function, division, absolute_import, ) # Make Py2's str equivalent to Py3's str = type('') import ctypes as ct import warnings _lib = ct.CDLL('libbcm_host.so') # bcm_host.h ################################################################# bcm_host_init = _lib.bcm_host_init bcm_host_init.argtypes = [] bcm_host_init.restype = None bcm_host_deinit = _lib.bcm_host_deinit bcm_host_deinit.argtypes = [] bcm_host_deinit.restype = None graphics_get_display_size = _lib.graphics_get_display_size graphics_get_display_size.argtypes = [ct.c_uint16, ct.POINTER(ct.c_uint32), ct.POINTER(ct.c_uint32)] graphics_get_display_size.restype = ct.c_int32
Java
# quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): count = 0 while (count < 9): sleep(0.5) image1 = newphoto() if lastfilter is not "none": dofilter(lastfilter,image1) count = count + 1 def newphoto(): global image1 image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def invert(): global image1 image1= ImageChops.invert(image1) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def grayscale(): global image1 r, g, b = image1.split() image1 = Image.merge("RGB", (g,g,g)) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 def dofilter (theimage,thefilter): lastfilter = thefilter global image1 image1 = image1.filter(thefilter) tkimage1 = ImageTk.PhotoImage(image1) panel1.configure(image=tkimage1) panel1.image = tkimage1 # Setup a window root = tk.Tk() root.title('Image') image1 = takephoto() tkimage1 = ImageTk.PhotoImage(image1) w = tkimage1.width() h = tkimage1.height() root.geometry("%dx%d+%d+%d" % (w, h, 0, 0)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=tkimage1) panel1.pack(side='top', fill='both', expand='yes') # save the panel's image from 'garbage collection' panel1.image = tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INVERT',command = lambda: invert()) button.pack(side='left',) button = tk.Button(buttonrow, text='GRAY',command = lambda: grayscale()) button.pack(side='left',) # add some filter buttons button = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(image1,ImageFilter.FIND_EDGES)) button.pack(side='left') button = tk.Button(buttonrow, text='EMBOSS',command = lambda: dofilter(image1,ImageFilter.EMBOSS)) button.pack(side='left') button = tk.Button(buttonrow, text='EDGE_ENHANCE',command = lambda: dofilter(image1,ImageFilter.EDGE_ENHANCE)) button.pack(side='left') button = tk.Button(buttonrow, text='CLOSE',command = lambda: root.destroy()) button.pack(side='left') root.mainloop()
Java
/** * Copyright (c) 2008-2010 Andrey Somov * * 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.yaml.snakeyaml.tokens; import java.util.List; import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.YAMLException; /** * @see <a href="http://pyyaml.org/wiki/PyYAML">PyYAML</a> for more information */ public final class DirectiveToken<T> extends Token { private final String name; private final List<T> value; public DirectiveToken(String name, List<T> value, Mark startMark, Mark endMark) { super(startMark, endMark); this.name = name; if (value != null && value.size() != 2) { throw new YAMLException("Two strings must be provided instead of " + String.valueOf(value.size())); } this.value = value; } public String getName() { return this.name; } public List<T> getValue() { return this.value; } @Override protected String getArguments() { if (value != null) { return "name=" + name + ", value=[" + value.get(0) + ", " + value.get(1) + "]"; } else { return "name=" + name; } } @Override public Token.ID getTokenId() { return ID.Directive; } }
Java
var a02307 = [ [ "GenericVector", "a02307.html#a60d42eebf02708482a8b506edd417990", null ], [ "GenericVector", "a02307.html#a28a69767bcadb6058a2a9df4afecd5fc", null ], [ "GenericVector", "a02307.html#a2b61cd1cd756770518f5ac30f817a9bf", null ], [ "~GenericVector", "a02307.html#a49840c8743a063b87839baef7e19b968", null ], [ "back", "a02307.html#a48b82547ebbaa5fedecfdebe7e2f155a", null ], [ "binary_search", "a02307.html#ad561e19e75a0fb30f0118774d7fa5621", null ], [ "bool_binary_search", "a02307.html#a8c261f66a24da67aac1acca7aa8f650a", null ], [ "choose_nth_item", "a02307.html#a5c4218ef833d0fe5db9b9749abd81ea5", null ], [ "choose_nth_item", "a02307.html#ae1e555b0cdded2c36dd6cf15345f659f", null ], [ "clear", "a02307.html#a9cdbff49b186574b83e43afba606fdd9", null ], [ "compact", "a02307.html#a080f7786e007523bcaa3f69913a82882", null ], [ "compact_sorted", "a02307.html#a8cb22ff55d6dd125d93cd03fd73bf8ad", null ], [ "contains", "a02307.html#a997e0fcaaa6b6533401dc54c0691e2e5", null ], [ "contains_index", "a02307.html#ac1aae0b1c22248f264dad02481123398", null ], [ "delete_data_pointers", "a02307.html#a98f62dccd75224a60437c2761bd215cd", null ], [ "DeSerialize", "a02307.html#aa4f5b1bc0d044fbd1fc77363b798c39c", null ], [ "DeSerialize", "a02307.html#a2e4fca9599eff590b76affc0a0aa0a2b", null ], [ "DeSerializeClasses", "a02307.html#a698ebd328d22f1edc114053ca2eba48e", null ], [ "DeSerializeClasses", "a02307.html#ade729c7d5429fbd5be304e3493a8a95f", null ], [ "dot_product", "a02307.html#a6f6dfbc607499173e7809656c6c505bc", null ], [ "double_the_size", "a02307.html#af0214c8c21da9eb57dfebc78611d0cd6", null ], [ "empty", "a02307.html#a172c4aa23ba397e24319ae095281cbcc", null ], [ "get", "a02307.html#abd0a875f98a1d78613ed3521d96e5300", null ], [ "get_index", "a02307.html#a6dee574daf4a3d4f0fc7048964f8f252", null ], [ "init", "a02307.html#a5b010723588fe15f303e4f3474d8479e", null ], [ "init_to_size", "a02307.html#a6751521fd3eb461d81fc83ef93a0def3", null ], [ "insert", "a02307.html#a57ca5259541548a97bcfd4d0925a27ff", null ], [ "length", "a02307.html#a6af4e0a2a30dda267d19bf783ae22eb7", null ], [ "move", "a02307.html#abae057ce589be25aae9b80958f84e34c", null ], [ "operator+=", "a02307.html#af73fadcdb08f0a12a5615f2bcf6fa6a8", null ], [ "operator+=", "a02307.html#acc7df2256174b32632e4d5b6c8d05d29", null ], [ "operator=", "a02307.html#af6fd5b3891b276c10add96f9411bec05", null ], [ "operator[]", "a02307.html#afd51f3f981284adb20bdf3b0bfd1c1f7", null ], [ "pop_back", "a02307.html#a0621dd57ce58dae3cb5f3d61e76bd233", null ], [ "push_back", "a02307.html#a0dc89fe2a365b04a61017f9d78c1a303", null ], [ "push_back_new", "a02307.html#a393f9f8dcc55ad759a5c7fbdc4840a89", null ], [ "push_front", "a02307.html#ae08e7cece0097ad356b5e565cbb2cf0b", null ], [ "read", "a02307.html#a10a273cab07e56c1654b2167f8aa9408", null ], [ "remove", "a02307.html#a3fd37a240a42f1c3052e8d28614d3702", null ], [ "reserve", "a02307.html#aa225ea3fc9374961482bc804028317eb", null ], [ "resize_no_init", "a02307.html#a09005e8f2b51d033d60eb5690aa5d112", null ], [ "reverse", "a02307.html#a58f6d73009cc3c56d0efb0d96ad35b5b", null ], [ "Serialize", "a02307.html#a206a6fe71c3780d862d97ef7c5fc9546", null ], [ "Serialize", "a02307.html#a3e994fd938468ff4fc4b4a902e970876", null ], [ "SerializeClasses", "a02307.html#ad0e8164e4c5c82e9e367c8a6d9b755b1", null ], [ "SerializeClasses", "a02307.html#a7d0060c687429049a0ea5cf21d067b8e", null ], [ "set", "a02307.html#a067b7833ee66238b7b5e230404525fcb", null ], [ "set_clear_callback", "a02307.html#af2bbca5b3258035a333b62679835a253", null ], [ "set_compare_callback", "a02307.html#aa3ec670c7f68a95f84641a0ded8cb61f", null ], [ "size", "a02307.html#a20cfad5c58c50cb85a9529d8ddbd96af", null ], [ "size_reserved", "a02307.html#a1c273622446ec7b5a6669fa9c9fdd8e5", null ], [ "sort", "a02307.html#a999bbd8ff336c81fe1198ea714c7936d", null ], [ "sort", "a02307.html#a461142d4ff7c61f22119552b7c0b2755", null ], [ "swap", "a02307.html#ac10b1de04fdfd4f5e4b90ac6d03f35b9", null ], [ "truncate", "a02307.html#a980882b5ebc3e72fdedbdbe345196f21", null ], [ "unsigned_size", "a02307.html#a47bd2385b28d536e8b6e87b689d61ede", null ], [ "WithinBounds", "a02307.html#a367914d03777eef59176d48155d06b72", null ], [ "write", "a02307.html#a8745d1d8394e852d12398d0458684dee", null ], [ "clear_cb_", "a02307.html#a57a833bdcc07a53e9a7b57d07cac2131", null ], [ "compare_cb_", "a02307.html#acd69761952fb39cbe7d7b43a6b06a432", null ], [ "data_", "a02307.html#ab88657a46d06c175dcfc76c0fcdaac7d", null ], [ "size_reserved_", "a02307.html#a4a02eb2a4ed31e8454cd8ae06eb8d7c5", null ], [ "size_used_", "a02307.html#a99185b084a6ace7536818ce2f17b11fb", null ] ];
Java
/* Copyright 2018 Nationale-Nederlanden 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 nl.nn.adapterframework.http.cxf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Iterator; import java.util.Properties; import javax.activation.DataHandler; import javax.xml.soap.AttachmentPart; import javax.xml.soap.MessageFactory; import javax.xml.soap.MimeHeader; import javax.xml.soap.SOAPConstants; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.stream.StreamSource; import javax.xml.ws.WebServiceContext; import org.apache.soap.util.mime.ByteArrayDataSource; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.w3c.dom.Element; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.stream.Message; import nl.nn.adapterframework.util.DomBuilderException; import nl.nn.adapterframework.util.Misc; import nl.nn.adapterframework.util.XmlUtils; @RunWith(MockitoJUnitRunner.class) public class SoapProviderTest { @BeforeClass public static void setUp() { Properties prop = System.getProperties(); String vendor = prop.getProperty("java.vendor"); System.out.println("JVM Vendor : " + vendor); assumeThat(vendor, not(equalTo("IBM Corporation"))); /* * The above exclusion of IBM JDK to work around the below error, seen when executing these tests with an IBM JDK: * java.lang.VerifyError: JVMVRFY012 stack shape inconsistent; class=com/sun/xml/messaging/saaj/soap/SOAPDocumentImpl, method=createDocumentFragment()Lorg/w3c/dom/DocumentFragment;, pc=5; Type Mismatch, argument 0 in signature com/sun/xml/messaging/saaj/soap/SOAPDocumentFragment.<init>:(Lcom/sun/org/apache/xerces/internal/dom/CoreDocumentImpl;)V does not match Exception Details: Location: com/sun/xml/messaging/saaj/soap/SOAPDocumentImpl.createDocumentFragment()Lorg/w3c/dom/DocumentFragment; @5: JBinvokespecial Reason: Type 'com/sun/xml/messaging/saaj/soap/SOAPDocumentImpl' (current frame, stack[2]) is not assignable to 'com/sun/org/apache/xerces/internal/dom/CoreDocumentImpl' Current Frame: bci: @5 flags: { } locals: { 'com/sun/xml/messaging/saaj/soap/SOAPDocumentImpl' } stack: { 'uninitialized', 'uninitialized', 'com/sun/xml/messaging/saaj/soap/SOAPDocumentImpl' } at com.sun.xml.messaging.saaj.soap.SOAPPartImpl.<init>(SOAPPartImpl.java:106) at com.sun.xml.messaging.saaj.soap.ver1_1.SOAPPart1_1Impl.<init>(SOAPPart1_1Impl.java:70) at com.sun.xml.messaging.saaj.soap.ver1_1.Message1_1Impl.getSOAPPart(Message1_1Impl.java:90) at nl.nn.adapterframework.extensions.cxf.SoapProviderTest.createMessage(SoapProviderTest.java:109) at nl.nn.adapterframework.extensions.cxf.SoapProviderTest.createMessage(SoapProviderTest.java:98) at nl.nn.adapterframework.extensions.cxf.SoapProviderTest.createMessage(SoapProviderTest.java:94) at nl.nn.adapterframework.extensions.cxf.SoapProviderTest.sendMessageWithInputStreamAttachmentsTest(SoapProviderTest.java:228) */ } @Spy WebServiceContext webServiceContext = new WebServiceContextStub(); @InjectMocks private SoapProviderStub SOAPProvider = new SoapProviderStub(); private final String ATTACHMENT_CONTENT = "<dummy/>"; private final String ATTACHMENT_MIMETYPE = "plain/text"; private final String ATTACHMENT2_CONTENT = "<I'm a pdf file/>"; private final String ATTACHMENT2_NAME = "document.pdf"; private final String ATTACHMENT2_MIMETYPE = "application/pdf"; private final String MULTIPART_XML = "<parts><part type=\"file\" name=\""+ATTACHMENT2_NAME+"\" " + "sessionKey=\"part_file\" size=\"72833\" " + "mimeType=\""+ATTACHMENT2_MIMETYPE+"\"/></parts>"; private final String BASEDIR = "/Soap/"; protected InputStream getFile(String file) throws IOException { URL url = this.getClass().getResource(BASEDIR+file); if (url == null) { throw new IOException("file not found"); } return url.openStream(); } private SOAPMessage createMessage(String filename) throws IOException, SOAPException { return createMessage(filename, false, false); } private SOAPMessage createMessage(String filename, boolean addAttachment, boolean isSoap1_1) throws IOException, SOAPException { MessageFactory factory = MessageFactory.newInstance(isSoap1_1 ? SOAPConstants.SOAP_1_1_PROTOCOL : SOAPConstants.SOAP_1_2_PROTOCOL); SOAPMessage soapMessage = factory.createMessage(); StreamSource streamSource = new StreamSource(getFile(filename)); soapMessage.getSOAPPart().setContent(streamSource); if(addAttachment) { InputStream fis = new ByteArrayInputStream(ATTACHMENT_CONTENT.getBytes()); DataHandler dataHander = new DataHandler(new ByteArrayDataSource(fis, ATTACHMENT_MIMETYPE)); AttachmentPart part = soapMessage.createAttachmentPart(dataHander); soapMessage.addAttachmentPart(part); } return soapMessage; } private void assertAttachmentInSession(PipeLineSession session) throws DomBuilderException, IOException { assertNotNull(session.get("mimeHeaders")); assertNotNull(session.get("attachments")); Element xml = XmlUtils.buildElement((String) session.get("attachments")); Element attachment = XmlUtils.getFirstChildTag(xml, "attachment"); assertNotNull(attachment); //Retrieve sessionkey the attachment was stored in String sessionKey = XmlUtils.getChildTagAsString(attachment, "sessionKey"); assertNotNull(sessionKey); Message attachmentMessage = session.getMessage(sessionKey); //Verify that the attachment sent, was received properly assertEquals(ATTACHMENT_CONTENT, attachmentMessage.asString()); //Verify the content type Element mimeTypes = XmlUtils.getFirstChildTag(attachment, "mimeHeaders"); mimeTypes.getElementsByTagName("mimeHeader"); //TODO check what happens when multiple attachments are returned... String mimeType = XmlUtils.getChildTagAsString(mimeTypes, "mimeHeader"); assertEquals(ATTACHMENT_MIMETYPE, mimeType); } private void assertAttachmentInReceivedMessage(SOAPMessage message) throws SOAPException, IOException { assertEquals(1, message.countAttachments()); Iterator<?> attachmentParts = message.getAttachments(); while (attachmentParts.hasNext()) { AttachmentPart soapAttachmentPart = (AttachmentPart)attachmentParts.next(); String attachment = Misc.streamToString(soapAttachmentPart.getRawContent()); //ContentID should be equal to the filename assertEquals(ATTACHMENT2_NAME, soapAttachmentPart.getContentId()); //Validate the attachment's content assertEquals(ATTACHMENT2_CONTENT, attachment); //Make sure at least the content-type header has been set Iterator<?> headers = soapAttachmentPart.getAllMimeHeaders(); String contentType = null; while (headers.hasNext()) { MimeHeader header = (MimeHeader) headers.next(); if("Content-Type".equalsIgnoreCase(header.getName())) contentType = header.getValue(); } assertEquals(ATTACHMENT2_MIMETYPE, contentType); } } @Test /** * Receive SOAP message without attachment * Reply SOAP message without attachment * @throws Throwable */ public void simpleMessageTest() throws Throwable { SOAPMessage request = createMessage("correct-soapmsg.xml"); SOAPMessage message = SOAPProvider.invoke(request); String result = XmlUtils.nodeToString(message.getSOAPPart()); String expected = Misc.streamToString(getFile("correct-soapmsg.xml")); assertEquals(expected.replaceAll("\r", ""), result.replaceAll("\r", "")); PipeLineSession session = SOAPProvider.getSession(); assertNotNull(session.get("mimeHeaders")); assertNotNull(session.get("attachments")); assertEquals("<attachments/>", session.get("attachments").toString().trim()); } @Test /** * Receive faulty message without attachment * @throws Throwable */ public void errorMessageTest() throws Throwable { SOAPMessage message = SOAPProvider.invoke(null); String result = XmlUtils.nodeToString(message.getSOAPPart()); assertTrue(result.indexOf("SOAPMessage is null") > 0); } @Test /** * Receive SOAP message with MTOM attachment * Reply SOAP message without attachment * @throws Throwable */ public void receiveMessageWithAttachmentsTest() throws Throwable { SOAPMessage request = createMessage("correct-soapmsg.xml", true, false); SOAPMessage message = SOAPProvider.invoke(request); String result = XmlUtils.nodeToString(message.getSOAPPart()); String expected = Misc.streamToString(getFile("correct-soapmsg.xml")); assertEquals(expected.replaceAll("\r", ""), result.replaceAll("\r", "")); PipeLineSession session = SOAPProvider.getSession(); assertAttachmentInSession(session); } @Test /** * Receive SOAP message without attachment * Reply SOAP message with (InputStream) attachment * @throws Throwable */ public void sendMessageWithInputStreamAttachmentsTest() throws Throwable { SOAPMessage request = createMessage("correct-soapmsg.xml"); PipeLineSession session = new PipeLineSession(); session.put("attachmentXmlSessionKey", MULTIPART_XML); session.put("part_file", new ByteArrayInputStream(ATTACHMENT2_CONTENT.getBytes())); SOAPProvider.setAttachmentXmlSessionKey("attachmentXmlSessionKey"); SOAPProvider.setSession(session); SOAPMessage message = SOAPProvider.invoke(request); String result = XmlUtils.nodeToString(message.getSOAPPart()); String expected = Misc.streamToString(getFile("correct-soapmsg.xml")); assertEquals(expected.replaceAll("\r", ""), result.replaceAll("\r", "")); assertAttachmentInReceivedMessage(message); } @Test /** * Receive SOAP message without attachment * Reply SOAP message with (String) attachment * @throws Throwable */ public void sendMessageWithStringAttachmentsTest() throws Throwable { SOAPMessage request = createMessage("correct-soapmsg.xml"); PipeLineSession session = new PipeLineSession(); session.put("attachmentXmlSessionKey", MULTIPART_XML); session.put("part_file", ATTACHMENT2_CONTENT); SOAPProvider.setAttachmentXmlSessionKey("attachmentXmlSessionKey"); SOAPProvider.setSession(session); SOAPMessage message = SOAPProvider.invoke(request); String result = XmlUtils.nodeToString(message.getSOAPPart()); String expected = Misc.streamToString(getFile("correct-soapmsg.xml")); assertEquals(expected.replaceAll("\r", ""), result.replaceAll("\r", "")); assertAttachmentInReceivedMessage(message); } @Test /** * Receive SOAP message with attachment * Reply SOAP message with attachment * @throws Throwable */ public void receiveAndSendMessageWithAttachmentsTest() throws Throwable { SOAPMessage request = createMessage("correct-soapmsg.xml", true, false); PipeLineSession session = new PipeLineSession(); session.put("attachmentXmlSessionKey", MULTIPART_XML); session.put("part_file", ATTACHMENT2_CONTENT); SOAPProvider.setAttachmentXmlSessionKey("attachmentXmlSessionKey"); SOAPProvider.setSession(session); SOAPMessage message = SOAPProvider.invoke(request); String result = XmlUtils.nodeToString(message.getSOAPPart()); String expected = Misc.streamToString(getFile("correct-soapmsg.xml")); assertEquals(expected.replaceAll("\r", ""), result.replaceAll("\r", "")); //Validate an attachment was sent to the listener assertAttachmentInSession(SOAPProvider.getSession()); //Validate the listener returned an attachment back assertAttachmentInReceivedMessage(message); } @Test public void soapActionInSessionKeySOAP1_1() throws Throwable { // Soap protocol 1.1 SOAPMessage request = createMessage("soapmsg1_1.xml", false, true); String value = "1.1-SoapAction"; webServiceContext.getMessageContext().put("SOAPAction", value); SOAPProvider.invoke(request); webServiceContext.getMessageContext().clear(); assertEquals(value, SOAPProvider.getSession().get("SOAPAction")); } @Test public void noSoapActionInSessionKeySOAP1_1() throws Throwable { // Soap protocol 1.1 SOAPMessage request = createMessage("soapmsg1_1.xml", false, true); SOAPProvider.invoke(request); assertNull(SOAPProvider.getSession().get("SOAPAction")); } @Test public void soap1_1MessageWithActionInContentTypeHeader() throws Throwable { // Soap protocol 1.1 SOAPMessage request = createMessage("soapmsg1_1.xml", false, true); String value = "ActionInContentTypeHeader"; webServiceContext.getMessageContext().put("Content-Type", "application/soap+xml; action="+value); SOAPProvider.invoke(request); webServiceContext.getMessageContext().clear(); assertNull(SOAPProvider.getSession().get("SOAPAction")); } @Test public void soapActionInSessionKeySOAP1_2ActionIsTheLastItem() throws Throwable { SOAPMessage request = createMessage("soapmsg1_2.xml"); String value = "SOAP1_2ActionIsTheLastItem"; webServiceContext.getMessageContext().put("Content-Type", "application/soap+xml; action="+value); SOAPProvider.invoke(request); webServiceContext.getMessageContext().clear(); assertEquals(value, SOAPProvider.getSession().get("SOAPAction")); } @Test public void soapActionInSessionKeySOAP1_2ActionIsInMiddle() throws Throwable { SOAPMessage request = createMessage("soapmsg1_2.xml"); String value = "SOAP1_2ActionIsInMiddle"; webServiceContext.getMessageContext().put("Content-Type", "application/soap+xml; action="+value+";somethingelse"); SOAPProvider.invoke(request); webServiceContext.getMessageContext().clear(); assertEquals(value, SOAPProvider.getSession().get("SOAPAction")); } @Test public void soapActionInSessionKeySOAP1_2ActionIsAtTheBeginning() throws Throwable { SOAPMessage request = createMessage("soapmsg1_2.xml"); String value = "SOAP1_2ActionIsAtTheBeginning"; webServiceContext.getMessageContext().put("Content-Type", "action="+value+";application/soap+xml; somethingelse"); SOAPProvider.invoke(request); webServiceContext.getMessageContext().clear(); assertEquals(value, SOAPProvider.getSession().get("SOAPAction")); } @Test public void noSoapActionInSessionKey1_2() throws Throwable { SOAPMessage request = createMessage("soapmsg1_2.xml"); webServiceContext.getMessageContext().put("Content-Type", "application/soap+xml; somethingelse"); SOAPProvider.invoke(request); webServiceContext.getMessageContext().clear(); assertNull(SOAPProvider.getSession().get("SOAPAction")); } @Test public void emptySoapActionInSessionKey1_2() throws Throwable { SOAPMessage request = createMessage("soapmsg1_2.xml"); webServiceContext.getMessageContext().put("Content-Type", "application/soap+xml; action=; somethingelse"); SOAPProvider.invoke(request); webServiceContext.getMessageContext().clear(); assertNull(SOAPProvider.getSession().get("SOAPAction")); } @Test public void soap1_2MessageWithSOAPActionHeader() throws Throwable { SOAPMessage request = createMessage("soapmsg1_2.xml"); webServiceContext.getMessageContext().put("SOAPAction", "action"); SOAPProvider.invoke(request); webServiceContext.getMessageContext().clear(); assertNull(SOAPProvider.getSession().get("SOAPAction")); } }
Java
### note * this is a resuable container for a given project/volume ### initial steps * ensure current directory contains `resources/jdk-9+175_linux-x64_bin.tar.gz` * run: `docker build -t="jdk9/b175" .` * run: `docker run -i -t -v $(pwd):/data jdk9/b175` * inside container, run: `/data/resources/install.sh` * inside container, run: `. /data/resources/setvars.sh` * confirm: `java --version` ### subsequent steps * `docker start [container name]` * `docker attach [container name]` * run: `. /data/resources/setvars.sh` * confirm: `java --version`
Java
package template import ( "bytes" "io" "io/ioutil" "log" "os" "testing" "text/template" "github.com/k8sp/sextant/cloud-config-server/certgen" "github.com/k8sp/sextant/clusterdesc" "github.com/stretchr/testify/assert" "github.com/topicai/candy" "gopkg.in/yaml.v2" ) func TestExecute(t *testing.T) { out, err := ioutil.TempDir("", "") candy.Must(err) defer func() { if e := os.RemoveAll(out); e != nil { log.Printf("Generator.Gen failed deleting %s", out) } }() caKey, caCrt := certgen.GenerateRootCA(out) config := candy.WithOpened("./cluster-desc.sample.yaml", func(r io.Reader) interface{} { b, e := ioutil.ReadAll(r) candy.Must(e) c := &clusterdesc.Cluster{} assert.Nil(t, yaml.Unmarshal(b, &c)) return c }).(*clusterdesc.Cluster) tmpl, e := template.ParseFiles("cloud-config.template") candy.Must(e) var ccTmpl bytes.Buffer Execute(tmpl, config, "00:25:90:c0:f7:80", caKey, caCrt, &ccTmpl) yml := make(map[interface{}]interface{}) candy.Must(yaml.Unmarshal(ccTmpl.Bytes(), yml)) initialEtcdCluster := yml["coreos"].(map[interface{}]interface{})["etcd2"].(map[interface{}]interface{})["initial-cluster-token"] assert.Equal(t, initialEtcdCluster, "etcd-cluster-1") }
Java
package mx.emite.sdk.scot.request; import java.util.List; import javax.validation.Valid; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import lombok.Builder; import lombok.Data; import lombok.Singular; import mx.emite.sdk.cfdi32.anotaciones.Rfc; import mx.emite.sdk.scot.request.extra.SucursalInfo; @Data @Builder public class SucursalesAltaRequest { /** * Token del <b>Integrador</b> obtenido con el servicio de Token * -- SETTER -- * * @param token * Token del <b>Integrador</b> obtenido de Scot&copy; * */ @NotNull private String token; /** * @param rfc del emisor, si se deja en blanco se consultan todos los emisores */ @Rfc private String rfc; /** * @param sucursales lista de sucursales a dar de alta */ @Valid @NotEmpty @Singular("sucursal") private List<SucursalInfo> sucursales; /** * modificar si la sucursal ya se encuentra dado de alta */ @NotNull public Boolean modificar; }
Java
/* * Copyright 2016-present Facebook, 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.facebook.buck.rust; import com.facebook.buck.cxx.CxxPlatform; import com.facebook.buck.cxx.CxxPlatforms; import com.facebook.buck.cxx.Linker; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.Flavor; import com.facebook.buck.model.FlavorDomain; import com.facebook.buck.model.Flavored; import com.facebook.buck.model.InternalFlavor; import com.facebook.buck.parser.NoSuchBuildTargetException; import com.facebook.buck.rules.AbstractDescriptionArg; import com.facebook.buck.rules.BinaryWrapperRule; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.CellPathResolver; import com.facebook.buck.rules.Description; import com.facebook.buck.rules.ImplicitDepsInferringDescription; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.rules.Tool; import com.facebook.buck.rules.ToolProvider; import com.facebook.buck.versions.VersionRoot; import com.facebook.infer.annotation.SuppressFieldNotInitialized; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; public class RustTestDescription implements Description<RustTestDescription.Arg>, ImplicitDepsInferringDescription<RustTestDescription.Arg>, Flavored, VersionRoot<RustTestDescription.Arg> { private final RustBuckConfig rustBuckConfig; private final FlavorDomain<CxxPlatform> cxxPlatforms; private final CxxPlatform defaultCxxPlatform; public RustTestDescription( RustBuckConfig rustBuckConfig, FlavorDomain<CxxPlatform> cxxPlatforms, CxxPlatform defaultCxxPlatform) { this.rustBuckConfig = rustBuckConfig; this.cxxPlatforms = cxxPlatforms; this.defaultCxxPlatform = defaultCxxPlatform; } @Override public Arg createUnpopulatedConstructorArg() { return new Arg(); } @Override public <A extends Arg> BuildRule createBuildRule( TargetGraph targetGraph, BuildRuleParams params, BuildRuleResolver resolver, CellPathResolver cellRoots, A args) throws NoSuchBuildTargetException { final BuildTarget buildTarget = params.getBuildTarget(); BuildTarget exeTarget = params.getBuildTarget() .withAppendedFlavors(InternalFlavor.of("unittest")); Optional<Map.Entry<Flavor, RustBinaryDescription.Type>> type = RustBinaryDescription.BINARY_TYPE.getFlavorAndValue(buildTarget); boolean isCheck = type.map(t -> t.getValue().isCheck()).orElse(false); BinaryWrapperRule testExeBuild = resolver.addToIndex( RustCompileUtils.createBinaryBuildRule( params.withBuildTarget(exeTarget), resolver, rustBuckConfig, cxxPlatforms, defaultCxxPlatform, args.crate, args.features, Stream.of( args.framework ? Stream.of("--test") : Stream.<String>empty(), rustBuckConfig.getRustTestFlags().stream(), args.rustcFlags.stream()) .flatMap(x -> x).iterator(), args.linkerFlags.iterator(), RustCompileUtils.getLinkStyle(params.getBuildTarget(), args.linkStyle), args.rpath, args.srcs, args.crateRoot, ImmutableSet.of("lib.rs", "main.rs"), isCheck )); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver); Tool testExe = testExeBuild.getExecutableCommand(); BuildRuleParams testParams = params.copyAppendingExtraDeps( testExe.getDeps(ruleFinder)); return new RustTest( testParams, ruleFinder, testExeBuild, args.labels, args.contacts); } @Override public void findDepsForTargetFromConstructorArgs( BuildTarget buildTarget, CellPathResolver cellRoots, Arg constructorArg, ImmutableCollection.Builder<BuildTarget> extraDepsBuilder, ImmutableCollection.Builder<BuildTarget> targetGraphOnlyDepsBuilder) { ToolProvider compiler = rustBuckConfig.getRustCompiler(); extraDepsBuilder.addAll(compiler.getParseTimeDeps()); extraDepsBuilder.addAll(CxxPlatforms.getParseTimeDeps(cxxPlatforms.getValues())); } @Override public boolean hasFlavors(ImmutableSet<Flavor> flavors) { if (cxxPlatforms.containsAnyOf(flavors)) { return true; } for (RustBinaryDescription.Type type : RustBinaryDescription.Type.values()) { if (flavors.contains(type.getFlavor())) { return true; } } return false; } @Override public Optional<ImmutableSet<FlavorDomain<?>>> flavorDomains() { return Optional.of(ImmutableSet.of(cxxPlatforms, RustBinaryDescription.BINARY_TYPE)); } @Override public boolean isVersionRoot(ImmutableSet<Flavor> flavors) { return true; } @SuppressFieldNotInitialized public static class Arg extends AbstractDescriptionArg { public ImmutableSortedSet<SourcePath> srcs = ImmutableSortedSet.of(); public ImmutableSet<String> contacts = ImmutableSet.of(); public ImmutableSortedSet<String> features = ImmutableSortedSet.of(); public ImmutableList<String> rustcFlags = ImmutableList.of(); public ImmutableList<String> linkerFlags = ImmutableList.of(); public ImmutableSortedSet<BuildTarget> deps = ImmutableSortedSet.of(); public Optional<Linker.LinkableDepType> linkStyle; public boolean rpath = true; public boolean framework = true; public Optional<String> crate; public Optional<SourcePath> crateRoot; } }
Java
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MassTransit.Publisher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MassTransit.Publisher")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("918f334e-cfe9-4000-bd5d-8154d3f88163")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Java
/* Copyright IBM Corp. 2016 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 attributes import ( "bytes" "crypto/x509" "encoding/asn1" "errors" "fmt" "strconv" "strings" pb "github.com/fabric_sdk_golang/core/crypto/attributes/proto" "github.com/fabric_sdk_golang/core/crypto/primitives" "github.com/golang/protobuf/proto" ) var ( // TCertEncAttributesBase is the base ASN1 object identifier for attributes. // When generating an extension to include the attribute an index will be // appended to this Object Identifier. TCertEncAttributesBase = asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6} // TCertAttributesHeaders is the ASN1 object identifier of attributes header. TCertAttributesHeaders = asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6, 9} padding = []byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255} //headerPrefix is the prefix used in the header exteion of the certificate. headerPrefix = "00HEAD" //HeaderAttributeName is the name used to derivate the K used to encrypt/decrypt the header. HeaderAttributeName = "attributeHeader" ) //ParseAttributesHeader parses a string and returns a map with the attributes. func ParseAttributesHeader(header string) (map[string]int, error) { if !strings.HasPrefix(header, headerPrefix) { return nil, errors.New("Invalid header") } headerBody := strings.Replace(header, headerPrefix, "", 1) tokens := strings.Split(headerBody, "#") result := make(map[string]int) for _, token := range tokens { pair := strings.Split(token, "->") if len(pair) == 2 { key := pair[0] valueStr := pair[1] value, err := strconv.Atoi(valueStr) if err != nil { return nil, err } result[key] = value } } return result, nil } //ReadAttributeHeader read the header of the attributes. func ReadAttributeHeader(tcert *x509.Certificate, headerKey []byte) (map[string]int, bool, error) { var err error var headerRaw []byte encrypted := false if headerRaw, err = primitives.GetCriticalExtension(tcert, TCertAttributesHeaders); err != nil { return nil, encrypted, err } headerStr := string(headerRaw) var header map[string]int header, err = ParseAttributesHeader(headerStr) if err != nil { if headerKey == nil { return nil, false, errors.New("Is not possible read an attribute encrypted without the headerKey") } headerRaw, err = DecryptAttributeValue(headerKey, headerRaw) if err != nil { return nil, encrypted, errors.New("error decrypting header value '" + err.Error() + "''") } headerStr = string(headerRaw) header, err = ParseAttributesHeader(headerStr) if err != nil { return nil, encrypted, err } encrypted = true } return header, encrypted, nil } //ReadTCertAttributeByPosition read the attribute stored in the position "position" of the tcert. func ReadTCertAttributeByPosition(tcert *x509.Certificate, position int) ([]byte, error) { if position <= 0 { return nil, fmt.Errorf("Invalid attribute position. Received [%v]", position) } oid := asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6, 9 + position} value, err := primitives.GetCriticalExtension(tcert, oid) if err != nil { return nil, err } return value, nil } //ReadTCertAttribute read the attribute with name "attributeName" and returns the value and a boolean indicating if the returned value is encrypted or not. func ReadTCertAttribute(tcert *x509.Certificate, attributeName string, headerKey []byte) ([]byte, bool, error) { header, encrypted, err := ReadAttributeHeader(tcert, headerKey) if err != nil { return nil, false, err } position := header[attributeName] if position == 0 { return nil, encrypted, errors.New("Failed attribute '" + attributeName + "' doesn't exists in the TCert.") } value, err := ReadTCertAttributeByPosition(tcert, position) if err != nil { return nil, encrypted, err } return value, encrypted, nil } //EncryptAttributeValue encrypts "attributeValue" using "attributeKey" func EncryptAttributeValue(attributeKey []byte, attributeValue []byte) ([]byte, error) { value := append(attributeValue, padding...) return primitives.CBCPKCS7Encrypt(attributeKey, value) } //getAttributeKey returns the attributeKey derived from the preK0 to the attributeName. func getAttributeKey(preK0 []byte, attributeName string) []byte { return primitives.HMACTruncated(preK0, []byte(attributeName), 32) } //EncryptAttributeValuePK0 encrypts "attributeValue" using a key derived from preK0. func EncryptAttributeValuePK0(preK0 []byte, attributeName string, attributeValue []byte) ([]byte, error) { attributeKey := getAttributeKey(preK0, attributeName) return EncryptAttributeValue(attributeKey, attributeValue) } //DecryptAttributeValue decrypts "encryptedValue" using "attributeKey" and return the decrypted value. func DecryptAttributeValue(attributeKey []byte, encryptedValue []byte) ([]byte, error) { value, err := primitives.CBCPKCS7Decrypt(attributeKey, encryptedValue) if err != nil { return nil, err } lenPadding := len(padding) lenValue := len(value) if lenValue < lenPadding { return nil, errors.New("Error invalid value. Decryption verification failed.") } lenWithoutPadding := lenValue - lenPadding if bytes.Compare(padding[0:lenPadding], value[lenWithoutPadding:lenValue]) != 0 { return nil, errors.New("Error generating decryption key for value. Decryption verification failed.") } value = value[0:lenWithoutPadding] return value, nil } //getKAndValueForAttribute derives K for the attribute "attributeName", checks the value padding and returns both key and decrypted value func getKAndValueForAttribute(attributeName string, preK0 []byte, cert *x509.Certificate) ([]byte, []byte, error) { headerKey := getAttributeKey(preK0, HeaderAttributeName) value, encrypted, err := ReadTCertAttribute(cert, attributeName, headerKey) if err != nil { return nil, nil, err } attributeKey := getAttributeKey(preK0, attributeName) if encrypted { value, err = DecryptAttributeValue(attributeKey, value) if err != nil { return nil, nil, err } } return attributeKey, value, nil } //GetKForAttribute derives the K for the attribute "attributeName" and returns the key func GetKForAttribute(attributeName string, preK0 []byte, cert *x509.Certificate) ([]byte, error) { key, _, err := getKAndValueForAttribute(attributeName, preK0, cert) return key, err } //GetValueForAttribute derives the K for the attribute "attributeName" and returns the value func GetValueForAttribute(attributeName string, preK0 []byte, cert *x509.Certificate) ([]byte, error) { _, value, err := getKAndValueForAttribute(attributeName, preK0, cert) return value, err } func createAttributesHeaderEntry(preK0 []byte) *pb.AttributesMetadataEntry { attKey := getAttributeKey(preK0, HeaderAttributeName) return &pb.AttributesMetadataEntry{AttributeName: HeaderAttributeName, AttributeKey: attKey} } func createAttributesMetadataEntry(attributeName string, preK0 []byte) *pb.AttributesMetadataEntry { attKey := getAttributeKey(preK0, attributeName) return &pb.AttributesMetadataEntry{AttributeName: attributeName, AttributeKey: attKey} } //CreateAttributesMetadataObjectFromCert creates an AttributesMetadata object from certificate "cert", metadata and the attributes keys. func CreateAttributesMetadataObjectFromCert(cert *x509.Certificate, metadata []byte, preK0 []byte, attributeKeys []string) *pb.AttributesMetadata { var entries []*pb.AttributesMetadataEntry for _, key := range attributeKeys { if len(key) == 0 { continue } entry := createAttributesMetadataEntry(key, preK0) entries = append(entries, entry) } headerEntry := createAttributesHeaderEntry(preK0) entries = append(entries, headerEntry) return &pb.AttributesMetadata{Metadata: metadata, Entries: entries} } //CreateAttributesMetadataFromCert creates the AttributesMetadata from the original metadata and certificate "cert". func CreateAttributesMetadataFromCert(cert *x509.Certificate, metadata []byte, preK0 []byte, attributeKeys []string) ([]byte, error) { attributesMetadata := CreateAttributesMetadataObjectFromCert(cert, metadata, preK0, attributeKeys) return proto.Marshal(attributesMetadata) } //CreateAttributesMetadata create the AttributesMetadata from the original metadata func CreateAttributesMetadata(raw []byte, metadata []byte, preK0 []byte, attributeKeys []string) ([]byte, error) { cert, err := primitives.DERToX509Certificate(raw) if err != nil { return nil, err } return CreateAttributesMetadataFromCert(cert, metadata, preK0, attributeKeys) } //GetAttributesMetadata object from the original metadata "metadata". func GetAttributesMetadata(metadata []byte) (*pb.AttributesMetadata, error) { attributesMetadata := &pb.AttributesMetadata{} err := proto.Unmarshal(metadata, attributesMetadata) return attributesMetadata, err } //BuildAttributesHeader builds a header attribute from a map of attribute names and positions. func BuildAttributesHeader(attributesHeader map[string]int) ([]byte, error) { var header []byte var headerString string var positions = make(map[int]bool) for k, v := range attributesHeader { if positions[v] { return nil, errors.New("Duplicated position found in attributes header") } positions[v] = true vStr := strconv.Itoa(v) headerString = headerString + k + "->" + vStr + "#" } header = []byte(headerPrefix + headerString) return header, nil }
Java
/* bme680.c - Driver for Bosch Sensortec's BME680 temperature, pressure, * humidity and gas sensor * * https://www.bosch-sensortec.com/bst/products/all_products/bme680 */ /* * Copyright (c) 2018 Bosch Sensortec GmbH * * SPDX-License-Identifier: Apache-2.0 */ #include "bme680.h" #include <gpio.h> #include <i2c.h> #include <init.h> #include <kernel.h> #include <misc/byteorder.h> #include <misc/__assert.h> #include <sensor.h> #include <logging/log.h> LOG_MODULE_REGISTER(bme680, CONFIG_SENSOR_LOG_LEVEL); static int bme680_reg_read(struct bme680_data *data, u8_t start, u8_t *buf, int size) { return i2c_burst_read(data->i2c_master, data->i2c_slave_addr, start, buf, size); return 0; } static int bme680_reg_write(struct bme680_data *data, u8_t reg, u8_t val) { return i2c_reg_write_byte(data->i2c_master, data->i2c_slave_addr, reg, val); return 0; } static void bme680_calc_temp(struct bme680_data *data, u32_t adc_temp) { s64_t var1, var2, var3; var1 = ((s32_t)adc_temp >> 3) - ((s32_t)data->par_t1 << 1); var2 = (var1 * (s32_t)data->par_t2) >> 11; var3 = ((var1 >> 1) * (var1 >> 1)) >> 12; var3 = ((var3) * ((s32_t)data->par_t3 << 4)) >> 14; data->t_fine = var2 + var3; data->calc_temp = ((data->t_fine * 5) + 128) >> 8; } static void bme680_calc_press(struct bme680_data *data, u32_t adc_press) { s32_t var1, var2, var3, calc_press; var1 = (((s32_t)data->t_fine) >> 1) - 64000; var2 = ((((var1 >> 2) * (var1 >> 2)) >> 11) * (s32_t)data->par_p6) >> 2; var2 = var2 + ((var1 * (s32_t)data->par_p5) << 1); var2 = (var2 >> 2) + ((s32_t)data->par_p4 << 16); var1 = (((((var1 >> 2) * (var1 >> 2)) >> 13) * ((s32_t)data->par_p3 << 5)) >> 3) + (((s32_t)data->par_p2 * var1) >> 1); var1 = var1 >> 18; var1 = ((32768 + var1) * (s32_t)data->par_p1) >> 15; calc_press = 1048576 - adc_press; calc_press = (calc_press - (var2 >> 12)) * ((u32_t)3125); /* This max value is used to provide precedence to multiplication or * division in the pressure calculation equation to achieve least * loss of precision and avoiding overflows. * i.e Comparing value, signed int 32bit (1 << 30) */ if (calc_press >= (s32_t)0x40000000) { calc_press = ((calc_press / var1) << 1); } else { calc_press = ((calc_press << 1) / var1); } var1 = ((s32_t)data->par_p9 * (s32_t)(((calc_press >> 3) * (calc_press >> 3)) >> 13)) >> 12; var2 = ((s32_t)(calc_press >> 2) * (s32_t)data->par_p8) >> 13; var3 = ((s32_t)(calc_press >> 8) * (s32_t)(calc_press >> 8) * (s32_t)(calc_press >> 8) * (s32_t)data->par_p10) >> 17; data->calc_press = calc_press + ((var1 + var2 + var3 + ((s32_t)data->par_p7 << 7)) >> 4); } static void bme680_calc_humidity(struct bme680_data *data, u16_t adc_humidity) { s32_t var1, var2_1, var2_2, var2, var3, var4, var5, var6; s32_t temp_scaled, calc_hum; temp_scaled = (((s32_t)data->t_fine * 5) + 128) >> 8; var1 = (s32_t)(adc_humidity - ((s32_t)((s32_t)data->par_h1 * 16))) - (((temp_scaled * (s32_t)data->par_h3) / ((s32_t)100)) >> 1); var2_1 = (s32_t)data->par_h2; var2_2 = ((temp_scaled * (s32_t)data->par_h4) / (s32_t)100) + (((temp_scaled * ((temp_scaled * (s32_t)data->par_h5) / ((s32_t)100))) >> 6) / ((s32_t)100)) + (s32_t)(1 << 14); var2 = (var2_1 * var2_2) >> 10; var3 = var1 * var2; var4 = (s32_t)data->par_h6 << 7; var4 = ((var4) + ((temp_scaled * (s32_t)data->par_h7) / ((s32_t)100))) >> 4; var5 = ((var3 >> 14) * (var3 >> 14)) >> 10; var6 = (var4 * var5) >> 1; calc_hum = (((var3 + var6) >> 10) * ((s32_t)1000)) >> 12; if (calc_hum > 100000) { /* Cap at 100%rH */ calc_hum = 100000; } else if (calc_hum < 0) { calc_hum = 0; } data->calc_humidity = calc_hum; } static void bme680_calc_gas_resistance(struct bme680_data *data, u8_t gas_range, u16_t adc_gas_res) { s64_t var1, var3; u64_t var2; static const u32_t look_up1[16] = { 2147483647, 2147483647, 2147483647, 2147483647, 2147483647, 2126008810, 2147483647, 2130303777, 2147483647, 2147483647, 2143188679, 2136746228, 2147483647, 2126008810, 2147483647, 2147483647 }; static const u32_t look_up2[16] = { 4096000000, 2048000000, 1024000000, 512000000, 255744255, 127110228, 64000000, 32258064, 16016016, 8000000, 4000000, 2000000, 1000000, 500000, 250000, 125000 }; var1 = (s64_t)((1340 + (5 * (s64_t)data->range_sw_err)) * ((s64_t)look_up1[gas_range])) >> 16; var2 = (((s64_t)((s64_t)adc_gas_res << 15) - (s64_t)(16777216)) + var1); var3 = (((s64_t)look_up2[gas_range] * (s64_t)var1) >> 9); data->calc_gas_resistance = (u32_t)((var3 + ((s64_t)var2 >> 1)) / (s64_t)var2); } static u8_t bme680_calc_res_heat(struct bme680_data *data, u16_t heatr_temp) { u8_t heatr_res; s32_t var1, var2, var3, var4, var5; s32_t heatr_res_x100; s32_t amb_temp = 25; /* Assume ambient temperature to be 25 deg C */ if (heatr_temp > 400) { /* Cap temperature */ heatr_temp = 400; } var1 = ((amb_temp * data->par_gh3) / 1000) * 256; var2 = (data->par_gh1 + 784) * (((((data->par_gh2 + 154009) * heatr_temp * 5) / 100) + 3276800) / 10); var3 = var1 + (var2 / 2); var4 = (var3 / (data->res_heat_range + 4)); var5 = (131 * data->res_heat_val) + 65536; heatr_res_x100 = ((var4 / var5) - 250) * 34; heatr_res = (heatr_res_x100 + 50) / 100; return heatr_res; } static u8_t bme680_calc_gas_wait(u16_t dur) { u8_t factor = 0, durval; if (dur >= 0xfc0) { durval = 0xff; /* Max duration*/ } else { while (dur > 0x3F) { dur = dur / 4; factor += 1; } durval = dur + (factor * 64); } return durval; } static int bme680_sample_fetch(struct device *dev, enum sensor_channel chan) { struct bme680_data *data = dev->driver_data; u8_t buff[BME680_LEN_FIELD] = { 0 }; u8_t gas_range; u32_t adc_temp, adc_press; u16_t adc_hum, adc_gas_res; int size = BME680_LEN_FIELD; int ret; __ASSERT_NO_MSG(chan == SENSOR_CHAN_ALL); ret = bme680_reg_read(data, BME680_REG_FIELD0, buff, size); if (ret < 0) { return ret; } data->new_data = buff[0] & BME680_MSK_NEW_DATA; data->heatr_stab = buff[14] & BME680_MSK_HEATR_STAB; adc_press = (u32_t)(((u32_t)buff[2] << 12) | ((u32_t)buff[3] << 4) | ((u32_t)buff[4] >> 4)); adc_temp = (u32_t)(((u32_t)buff[5] << 12) | ((u32_t)buff[6] << 4) | ((u32_t)buff[7] >> 4)); adc_hum = (u16_t)(((u32_t)buff[8] << 8) | (u32_t)buff[9]); adc_gas_res = (u16_t)((u32_t)buff[13] << 2 | (((u32_t)buff[14]) >> 6)); gas_range = buff[14] & BME680_MSK_GAS_RANGE; if (data->new_data) { bme680_calc_temp(data, adc_temp); bme680_calc_press(data, adc_press); bme680_calc_humidity(data, adc_hum); bme680_calc_gas_resistance(data, gas_range, adc_gas_res); } /* Trigger the next measurement */ ret = bme680_reg_write(data, BME680_REG_CTRL_MEAS, BME680_CTRL_MEAS_VAL); if (ret < 0) { return ret; } return 0; } static int bme680_channel_get(struct device *dev, enum sensor_channel chan, struct sensor_value *val) { struct bme680_data *data = dev->driver_data; switch (chan) { case SENSOR_CHAN_AMBIENT_TEMP: /* * data->calc_temp has a resolution of 0.01 degC. * So 5123 equals 51.23 degC. */ val->val1 = data->calc_temp / 100; val->val2 = data->calc_temp % 100 * 10000; break; case SENSOR_CHAN_PRESS: /* * data->calc_press has a resolution of 1 Pa. * So 96321 equals 96.321 kPa. */ val->val1 = data->calc_press / 1000; val->val2 = (data->calc_press % 1000) * 1000; break; case SENSOR_CHAN_HUMIDITY: /* * data->calc_humidity has a resolution of 0.001 %RH. * So 46333 equals 46.333 %RH. */ val->val1 = data->calc_humidity / 1000; val->val2 = (data->calc_humidity % 1000) * 1000; break; case SENSOR_CHAN_GAS_RES: /* * data->calc_gas_resistance has a resolution of 1 ohm. * So 100000 equals 100000 ohms. */ val->val1 = data->calc_gas_resistance; val->val2 = 0; break; default: return -EINVAL; } return 0; } static int bme680_read_compensation(struct bme680_data *data) { u8_t buff[BME680_LEN_COEFF_ALL]; int err = 0; err = bme680_reg_read(data, BME680_REG_COEFF1, buff, BME680_LEN_COEFF1); if (err < 0) { return err; } err = bme680_reg_read(data, BME680_REG_COEFF2, &buff[BME680_LEN_COEFF1], 16); if (err < 0) { return err; } err = bme680_reg_read(data, BME680_REG_COEFF3, &buff[BME680_LEN_COEFF1 + BME680_LEN_COEFF2], BME680_LEN_COEFF3); if (err < 0) { return err; } /* Temperature related coefficients */ data->par_t1 = (u16_t)(BME680_CONCAT_BYTES(buff[32], buff[31])); data->par_t2 = (s16_t)(BME680_CONCAT_BYTES(buff[1], buff[0])); data->par_t3 = (u8_t)(buff[2]); /* Pressure related coefficients */ data->par_p1 = (u16_t)(BME680_CONCAT_BYTES(buff[5], buff[4])); data->par_p2 = (s16_t)(BME680_CONCAT_BYTES(buff[7], buff[6])); data->par_p3 = (s8_t)buff[8]; data->par_p4 = (s16_t)(BME680_CONCAT_BYTES(buff[11], buff[10])); data->par_p5 = (s16_t)(BME680_CONCAT_BYTES(buff[13], buff[12])); data->par_p6 = (s8_t)(buff[15]); data->par_p7 = (s8_t)(buff[14]); data->par_p8 = (s16_t)(BME680_CONCAT_BYTES(buff[19], buff[18])); data->par_p9 = (s16_t)(BME680_CONCAT_BYTES(buff[21], buff[20])); data->par_p10 = (u8_t)(buff[22]); /* Humidity related coefficients */ data->par_h1 = (u16_t)(((u16_t)buff[25] << 4) | (buff[24] & 0x0f)); data->par_h2 = (u16_t)(((u16_t)buff[23] << 4) | ((buff[24]) >> 4)); data->par_h3 = (s8_t)buff[26]; data->par_h4 = (s8_t)buff[27]; data->par_h5 = (s8_t)buff[28]; data->par_h6 = (u8_t)buff[29]; data->par_h7 = (s8_t)buff[30]; /* Gas heater related coefficients */ data->par_gh1 = (s8_t)buff[35]; data->par_gh2 = (s16_t)(BME680_CONCAT_BYTES(buff[34], buff[33])); data->par_gh3 = (s8_t)buff[36]; data->res_heat_val = (s8_t)buff[37]; data->res_heat_range = ((buff[39] & BME680_MSK_RH_RANGE) >> 4); data->range_sw_err = ((s8_t)(buff[41] & BME680_MSK_RANGE_SW_ERR)) / 16; return 0; } static int bme680_chip_init(struct device *dev) { struct bme680_data *data = (struct bme680_data *)dev->driver_data; int err; err = bme680_reg_read(data, BME680_REG_CHIP_ID, &data->chip_id, 1); if (err < 0) { return err; } if (data->chip_id == BME680_CHIP_ID) { LOG_ERR("BME680 chip detected"); } else { LOG_ERR("Bad BME680 chip id 0x%x", data->chip_id); return -ENOTSUP; } err = bme680_read_compensation(data); if (err < 0) { return err; } err = bme680_reg_write(data, BME680_REG_CTRL_HUM, BME680_HUMIDITY_OVER); if (err < 0) { return err; } err = bme680_reg_write(data, BME680_REG_CONFIG, BME680_CONFIG_VAL); if (err < 0) { return err; } err = bme680_reg_write(data, BME680_REG_CTRL_GAS_1, BME680_CTRL_GAS_1_VAL); if (err < 0) { return err; } err = bme680_reg_write(data, BME680_REG_RES_HEAT0, bme680_calc_res_heat(data, BME680_HEATR_TEMP)); if (err < 0) { return err; } err = bme680_reg_write(data, BME680_REG_GAS_WAIT0, bme680_calc_gas_wait(BME680_HEATR_DUR_MS)); if (err < 0) { return err; } err = bme680_reg_write(data, BME680_REG_CTRL_MEAS, BME680_CTRL_MEAS_VAL); if (err < 0) { return err; } return 0; } static int bme680_init(struct device *dev) { struct bme680_data *data = dev->driver_data; data->i2c_master = device_get_binding( DT_INST_0_BOSCH_BME680_BUS_NAME); if (!data->i2c_master) { LOG_ERR("I2C master not found: %s", DT_INST_0_BOSCH_BME680_BUS_NAME); return -EINVAL; } data->i2c_slave_addr = DT_INST_0_BOSCH_BME680_BASE_ADDRESS; if (bme680_chip_init(dev) < 0) { return -EINVAL; } return 0; } static const struct sensor_driver_api bme680_api_funcs = { .sample_fetch = bme680_sample_fetch, .channel_get = bme680_channel_get, }; static struct bme680_data bme680_data; DEVICE_AND_API_INIT(bme680, DT_INST_0_BOSCH_BME680_LABEL, bme680_init, &bme680_data, NULL, POST_KERNEL, CONFIG_SENSOR_INIT_PRIORITY, &bme680_api_funcs);
Java
var crypto = require("crypto"), Request = require("./../request"), Response = require("./../response"); module.exports = sessionCookie; /** * A middleware for storing and retrieving session data using HTTP cookies. * The `options` may be any of the following: * * - secret A secret string to use to verify the cookie's contents, * defaults to `null`. If this is set the session's contents * will be cleared if the cookie has been tampered with * - name The name of the cookie, defaults to "strata.session" * - path The path of the cookie, defaults to "/" * - domain The cookie's domain, defaults to `null` * - expireAfter A number of seconds after which this cookie will expire, * defaults to `null` * - secure True to only send this cookie over HTTPS, defaults to `false` * - httpOnly True to only send this cookie over HTTP, defaults to `true` */ function sessionCookie(app, options) { var readSession = sessionCookieReader(options); var writeSession = sessionCookieWriter(options); return function (env, callback) { if (env.session) { app(env, callback); return; } readSession(env, function (err, session) { if (err) { env.session = {}; } else { env.session = session; } app(env, function (status, headers, body) { var res = new Response(body, headers, status); writeSession(env, res); res.send(callback); }); }); } } function sessionCookieReader(options) { options = sessionCookieOptions(options); return function readSessionCookie(env, callback) { var req = new Request(env); req.cookies(function (err, cookies) { if (err) { callback(err, cookies); return; } var cookie = cookies[options.name]; if (cookie) { cookie = new Buffer(cookie, "base64").toString("utf8"); var parts = cookie.split("--"), data = parts[0], digest = parts[1]; if (digest === sessionDigest(data, options.secret)) { try { callback(null, JSON.parse(data)); return; } catch (e) { // The cookie does not contain valid JSON. callback(e, {}); return; } } } callback(null, {}); }); } } function sessionCookieWriter(options) { options = sessionCookieOptions(options); return function writeSessionCookie(env, res) { var session = env.session; if (session) { var data = JSON.stringify(session); var digest = sessionDigest(data, options.secret); var cookie = new Buffer(data + "--" + digest, "utf8").toString("base64"); if (cookie.length > 4096) { env.error.write("Session cookie data size exceeds 4k; content dropped\n"); return; } var cookieOptions = { value: cookie, path: options.path, domain: options.domain, secure: options.secure, httpOnly: options.httpOnly }; if (options.expireAfter) { // expireAfter is given in seconds. var expires = new Date().getTime() + (options.expireAfter * 1000); cookieOptions.expires = new Date(expires); } res.setCookie(options.name, cookieOptions); } } } function sessionDigest(data, secret) { var shasum = crypto.createHash("sha1"); shasum.update(data); if (secret) { shasum.update(secret); } return shasum.digest("hex"); } /** * Creates a new options object from the given session cookie `options` with * sane defaults. */ function sessionCookieOptions(options) { options = options || {}; var opts = { secret: options.secret || null, name: options.name || "strata.session", path: options.path || "/", domain: options.domain || null, expireAfter: options.expireAfter || null, secure: options.secure || false }; if ("httpOnly" in options) { opts.httpOnly = options.httpOnly || false; } else { opts.httpOnly = true; } return opts; }
Java
use inkwell::context::Context; use inkwell::values::{BasicValue, InstructionOpcode::*}; use inkwell::{AddressSpace, AtomicOrdering, AtomicRMWBinOp, FloatPredicate, IntPredicate}; #[test] fn test_operands() { let context = Context::create(); let module = context.create_module("ivs"); let builder = context.create_builder(); let void_type = context.void_type(); let f32_type = context.f32_type(); let f32_ptr_type = f32_type.ptr_type(AddressSpace::Generic); let fn_type = void_type.fn_type(&[f32_ptr_type.into()], false); let function = module.add_function("take_f32_ptr", fn_type, None); let basic_block = context.append_basic_block(function, "entry"); builder.position_at_end(basic_block); let arg1 = function.get_first_param().unwrap().into_pointer_value(); let f32_val = f32_type.const_float(::std::f64::consts::PI); let store_instruction = builder.build_store(arg1, f32_val); let free_instruction = builder.build_free(arg1); let return_instruction = builder.build_return(None); assert_eq!(store_instruction.get_opcode(), Store); assert_eq!(free_instruction.get_opcode(), Call); assert_eq!(return_instruction.get_opcode(), Return); assert!(arg1.as_instruction_value().is_none()); // Test operands assert_eq!(store_instruction.get_num_operands(), 2); assert_eq!(free_instruction.get_num_operands(), 2); let store_operand0 = store_instruction.get_operand(0).unwrap(); let store_operand1 = store_instruction.get_operand(1).unwrap(); assert_eq!(store_operand0.left().unwrap(), f32_val); // f32 const assert_eq!(store_operand1.left().unwrap(), arg1); // f32* arg1 assert!(store_instruction.get_operand(2).is_none()); assert!(store_instruction.get_operand(3).is_none()); assert!(store_instruction.get_operand(4).is_none()); let free_operand0 = free_instruction.get_operand(0).unwrap().left().unwrap(); let free_operand1 = free_instruction.get_operand(1).unwrap().left().unwrap(); let free_operand0_instruction = free_operand0.as_instruction_value().unwrap(); assert!(free_operand0.is_pointer_value()); // (implictly casted) i8* arg1 assert!(free_operand1.is_pointer_value()); // Free function ptr assert_eq!(free_operand0_instruction.get_opcode(), BitCast); assert_eq!(free_operand0_instruction.get_operand(0).unwrap().left().unwrap(), arg1); assert!(free_operand0_instruction.get_operand(1).is_none()); assert!(free_operand0_instruction.get_operand(2).is_none()); assert!(free_instruction.get_operand(2).is_none()); assert!(free_instruction.get_operand(3).is_none()); assert!(free_instruction.get_operand(4).is_none()); assert!(module.verify().is_ok()); assert!(free_instruction.set_operand(0, arg1)); // Module is no longer valid because free takes an i8* not f32* assert!(module.verify().is_err()); assert!(free_instruction.set_operand(0, free_operand0)); assert!(module.verify().is_ok()); // No-op, free only has two (0-1) operands assert!(!free_instruction.set_operand(2, free_operand0)); assert!(module.verify().is_ok()); assert_eq!(return_instruction.get_num_operands(), 0); assert!(return_instruction.get_operand(0).is_none()); assert!(return_instruction.get_operand(1).is_none()); assert!(return_instruction.get_operand(2).is_none()); // Test Uses let bitcast_use_value = free_operand0_instruction .get_first_use() .unwrap() .get_used_value() .left() .unwrap(); let free_call_param = free_instruction.get_operand(0).unwrap().left().unwrap(); assert_eq!(bitcast_use_value, free_call_param); // These instructions/calls don't return any ir value so they aren't used anywhere assert!(store_instruction.get_first_use().is_none()); assert!(free_instruction.get_first_use().is_none()); assert!(return_instruction.get_first_use().is_none()); // arg1 (%0) has two uses: // store float 0x400921FB60000000, float* %0 // %1 = bitcast float* %0 to i8* let arg1_first_use = arg1.get_first_use().unwrap(); let arg1_second_use = arg1_first_use.get_next_use().unwrap(); // However their operands are used let store_operand_use0 = store_instruction.get_operand_use(0).unwrap(); let store_operand_use1 = store_instruction.get_operand_use(1).unwrap(); assert!(store_operand_use0.get_next_use().is_none()); assert!(store_operand_use1.get_next_use().is_none()); assert_eq!(store_operand_use1, arg1_second_use); assert_eq!(store_operand_use0.get_user().into_instruction_value(), store_instruction); assert_eq!(store_operand_use1.get_user().into_instruction_value(), store_instruction); assert_eq!(store_operand_use0.get_used_value().left().unwrap(), f32_val); assert_eq!(store_operand_use1.get_used_value().left().unwrap(), arg1); assert!(store_instruction.get_operand_use(2).is_none()); assert!(store_instruction.get_operand_use(3).is_none()); assert!(store_instruction.get_operand_use(4).is_none()); assert!(store_instruction.get_operand_use(5).is_none()); assert!(store_instruction.get_operand_use(6).is_none()); let free_operand_use0 = free_instruction.get_operand_use(0).unwrap(); let free_operand_use1 = free_instruction.get_operand_use(1).unwrap(); assert!(free_operand_use0.get_next_use().is_none()); assert!(free_operand_use1.get_next_use().is_none()); assert!(free_instruction.get_operand_use(2).is_none()); assert!(free_instruction.get_operand_use(3).is_none()); assert!(free_instruction.get_operand_use(4).is_none()); assert!(free_instruction.get_operand_use(5).is_none()); assert!(free_instruction.get_operand_use(6).is_none()); assert!(module.verify().is_ok()); } #[test] fn test_basic_block_operand() { let context = Context::create(); let module = context.create_module("ivs"); let builder = context.create_builder(); let void_type = context.void_type(); let fn_type = void_type.fn_type(&[], false); let function = module.add_function("bb_op", fn_type, None); let basic_block = context.append_basic_block(function, "entry"); let basic_block2 = context.append_basic_block(function, "exit"); builder.position_at_end(basic_block); let branch_instruction = builder.build_unconditional_branch(basic_block2); let bb_operand = branch_instruction.get_operand(0).unwrap().right().unwrap(); assert_eq!(bb_operand, basic_block2); let bb_operand_use = branch_instruction.get_operand_use(0).unwrap(); assert_eq!(bb_operand_use.get_used_value().right().unwrap(), basic_block2); builder.position_at_end(basic_block2); builder.build_return(None); assert!(module.verify().is_ok()); } #[test] fn test_get_next_use() { let context = Context::create(); let module = context.create_module("ivs"); let builder = context.create_builder(); let f32_type = context.f32_type(); let fn_type = f32_type.fn_type(&[f32_type.into()], false); let function = module.add_function("take_f32", fn_type, None); let basic_block = context.append_basic_block(function, "entry"); builder.position_at_end(basic_block); let arg1 = function.get_first_param().unwrap().into_float_value(); let f32_val = f32_type.const_float(::std::f64::consts::PI); let add_pi0 = builder.build_float_add(arg1, f32_val, "add_pi"); let add_pi1 = builder.build_float_add(add_pi0, f32_val, "add_pi"); builder.build_return(Some(&add_pi1)); // f32_val constant appears twice, so there are two uses (first, next) let first_use = f32_val.get_first_use().unwrap(); assert_eq!(first_use.get_user(), add_pi1.as_instruction_value().unwrap()); assert_eq!(first_use.get_next_use().map(|x| x.get_user().into_float_value()), Some(add_pi0)); assert!(arg1.get_first_use().is_some()); assert!(module.verify().is_ok()); } #[test] fn test_instructions() { let context = Context::create(); let module = context.create_module("testing"); let builder = context.create_builder(); let void_type = context.void_type(); let i64_type = context.i64_type(); let f32_type = context.f32_type(); let f32_ptr_type = f32_type.ptr_type(AddressSpace::Generic); let fn_type = void_type.fn_type(&[f32_ptr_type.into(), f32_type.into()], false); let function = module.add_function("free_f32", fn_type, None); let basic_block = context.append_basic_block(function, "entry"); builder.position_at_end(basic_block); let arg1 = function.get_first_param().unwrap().into_pointer_value(); let arg2 = function.get_nth_param(1).unwrap().into_float_value(); assert!(arg1.get_first_use().is_none()); assert!(arg2.get_first_use().is_none()); let f32_val = f32_type.const_float(::std::f64::consts::PI); let store_instruction = builder.build_store(arg1, f32_val); let ptr_val = builder.build_ptr_to_int(arg1, i64_type, "ptr_val"); let ptr = builder.build_int_to_ptr(ptr_val, f32_ptr_type, "ptr"); let icmp = builder.build_int_compare(IntPredicate::EQ, ptr_val, ptr_val, "icmp"); let f32_sum = builder.build_float_add(arg2, f32_val, "f32_sum"); let fcmp = builder.build_float_compare(FloatPredicate::OEQ, f32_sum, arg2, "fcmp"); let free_instruction = builder.build_free(arg1); let return_instruction = builder.build_return(None); assert_eq!(store_instruction.get_opcode(), Store); assert_eq!(ptr_val.as_instruction().unwrap().get_opcode(), PtrToInt); assert_eq!(ptr.as_instruction().unwrap().get_opcode(), IntToPtr); assert_eq!(icmp.as_instruction().unwrap().get_opcode(), ICmp); assert_eq!(ptr.as_instruction().unwrap().get_icmp_predicate(), None); assert_eq!(icmp.as_instruction().unwrap().get_icmp_predicate().unwrap(), IntPredicate::EQ); assert_eq!(f32_sum.as_instruction().unwrap().get_opcode(), FAdd); assert_eq!(fcmp.as_instruction().unwrap().get_opcode(), FCmp); assert_eq!(f32_sum.as_instruction().unwrap().get_fcmp_predicate(), None); assert_eq!(icmp.as_instruction().unwrap().get_fcmp_predicate(), None); assert_eq!(fcmp.as_instruction().unwrap().get_fcmp_predicate().unwrap(), FloatPredicate::OEQ); assert_eq!(free_instruction.get_opcode(), Call); assert_eq!(return_instruction.get_opcode(), Return); // test instruction cloning let instruction_clone = return_instruction.clone(); assert_eq!(instruction_clone.get_opcode(), return_instruction.get_opcode()); assert_ne!(instruction_clone, return_instruction); // test copying let instruction_clone_copy = instruction_clone; assert_eq!(instruction_clone, instruction_clone_copy); } #[llvm_versions(10.0..=latest)] #[test] fn test_volatile_atomicrmw_cmpxchg() { let context = Context::create(); let module = context.create_module("testing"); let builder = context.create_builder(); let void_type = context.void_type(); let i32_type = context.i32_type(); let i32_ptr_type = i32_type.ptr_type(AddressSpace::Generic); let fn_type = void_type.fn_type(&[i32_ptr_type.into(), i32_type.into()], false); let function = module.add_function("mem_inst", fn_type, None); let basic_block = context.append_basic_block(function, "entry"); builder.position_at_end(basic_block); let arg1 = function.get_first_param().unwrap().into_pointer_value(); let arg2 = function.get_nth_param(1).unwrap().into_int_value(); assert!(arg1.get_first_use().is_none()); assert!(arg2.get_first_use().is_none()); let i32_val = i32_type.const_int(7, false); let atomicrmw = builder .build_atomicrmw(AtomicRMWBinOp::Add, arg1, arg2, AtomicOrdering::Unordered) .unwrap() .as_instruction_value() .unwrap(); let cmpxchg = builder .build_cmpxchg( arg1, arg2, i32_val, AtomicOrdering::Monotonic, AtomicOrdering::Monotonic, ) .unwrap() .as_instruction_value() .unwrap(); assert_eq!(atomicrmw.get_volatile().unwrap(), false); assert_eq!(cmpxchg.get_volatile().unwrap(), false); atomicrmw.set_volatile(true).unwrap(); cmpxchg.set_volatile(true).unwrap(); assert_eq!(atomicrmw.get_volatile().unwrap(), true); assert_eq!(cmpxchg.get_volatile().unwrap(), true); atomicrmw.set_volatile(false).unwrap(); cmpxchg.set_volatile(false).unwrap(); assert_eq!(atomicrmw.get_volatile().unwrap(), false); assert_eq!(cmpxchg.get_volatile().unwrap(), false); } #[llvm_versions(3.6..=10.0)] #[test] fn test_mem_instructions() { let context = Context::create(); let module = context.create_module("testing"); let builder = context.create_builder(); let void_type = context.void_type(); let f32_type = context.f32_type(); let f32_ptr_type = f32_type.ptr_type(AddressSpace::Generic); let fn_type = void_type.fn_type(&[f32_ptr_type.into(), f32_type.into()], false); let function = module.add_function("mem_inst", fn_type, None); let basic_block = context.append_basic_block(function, "entry"); builder.position_at_end(basic_block); let arg1 = function.get_first_param().unwrap().into_pointer_value(); let arg2 = function.get_nth_param(1).unwrap().into_float_value(); assert!(arg1.get_first_use().is_none()); assert!(arg2.get_first_use().is_none()); let f32_val = f32_type.const_float(::std::f64::consts::PI); let store_instruction = builder.build_store(arg1, f32_val); let load = builder.build_load(arg1, ""); let load_instruction = load.as_instruction_value().unwrap(); assert_eq!(store_instruction.get_volatile().unwrap(), false); assert_eq!(load_instruction.get_volatile().unwrap(), false); store_instruction.set_volatile(true).unwrap(); load_instruction.set_volatile(true).unwrap(); assert_eq!(store_instruction.get_volatile().unwrap(), true); assert_eq!(load_instruction.get_volatile().unwrap(), true); store_instruction.set_volatile(false).unwrap(); load_instruction.set_volatile(false).unwrap(); assert_eq!(store_instruction.get_volatile().unwrap(), false); assert_eq!(load_instruction.get_volatile().unwrap(), false); assert_eq!(store_instruction.get_alignment().unwrap(), 0); assert_eq!(load_instruction.get_alignment().unwrap(), 0); assert!(store_instruction.set_alignment(16).is_ok()); assert!(load_instruction.set_alignment(16).is_ok()); assert_eq!(store_instruction.get_alignment().unwrap(), 16); assert_eq!(load_instruction.get_alignment().unwrap(), 16); assert!(store_instruction.set_alignment(0).is_ok()); assert!(load_instruction.set_alignment(0).is_ok()); assert_eq!(store_instruction.get_alignment().unwrap(), 0); assert_eq!(load_instruction.get_alignment().unwrap(), 0); assert!(store_instruction.set_alignment(14).is_err()); assert_eq!(store_instruction.get_alignment().unwrap(), 0); let fadd_instruction = builder.build_float_add(load.into_float_value(), f32_val, "").as_instruction_value().unwrap(); assert!(fadd_instruction.get_volatile().is_err()); assert!(fadd_instruction.set_volatile(false).is_err()); assert!(fadd_instruction.get_alignment().is_err()); assert!(fadd_instruction.set_alignment(16).is_err()); } #[llvm_versions(11.0..=latest)] #[test] fn test_mem_instructions() { let context = Context::create(); let module = context.create_module("testing"); let builder = context.create_builder(); let void_type = context.void_type(); let f32_type = context.f32_type(); let f32_ptr_type = f32_type.ptr_type(AddressSpace::Generic); let fn_type = void_type.fn_type(&[f32_ptr_type.into(), f32_type.into()], false); let function = module.add_function("mem_inst", fn_type, None); let basic_block = context.append_basic_block(function, "entry"); builder.position_at_end(basic_block); let arg1 = function.get_first_param().unwrap().into_pointer_value(); let arg2 = function.get_nth_param(1).unwrap().into_float_value(); assert!(arg1.get_first_use().is_none()); assert!(arg2.get_first_use().is_none()); let f32_val = f32_type.const_float(::std::f64::consts::PI); let store_instruction = builder.build_store(arg1, f32_val); let load = builder.build_load(arg1, ""); let load_instruction = load.as_instruction_value().unwrap(); assert_eq!(store_instruction.get_volatile().unwrap(), false); assert_eq!(load_instruction.get_volatile().unwrap(), false); store_instruction.set_volatile(true).unwrap(); load_instruction.set_volatile(true).unwrap(); assert_eq!(store_instruction.get_volatile().unwrap(), true); assert_eq!(load_instruction.get_volatile().unwrap(), true); store_instruction.set_volatile(false).unwrap(); load_instruction.set_volatile(false).unwrap(); assert_eq!(store_instruction.get_volatile().unwrap(), false); assert_eq!(load_instruction.get_volatile().unwrap(), false); assert_eq!(store_instruction.get_alignment().unwrap(), 4); assert_eq!(load_instruction.get_alignment().unwrap(), 4); assert!(store_instruction.set_alignment(16).is_ok()); assert!(load_instruction.set_alignment(16).is_ok()); assert_eq!(store_instruction.get_alignment().unwrap(), 16); assert_eq!(load_instruction.get_alignment().unwrap(), 16); assert!(store_instruction.set_alignment(4).is_ok()); assert!(load_instruction.set_alignment(4).is_ok()); assert_eq!(store_instruction.get_alignment().unwrap(), 4); assert_eq!(load_instruction.get_alignment().unwrap(), 4); assert!(store_instruction.set_alignment(14).is_err()); assert_eq!(store_instruction.get_alignment().unwrap(), 4); let fadd_instruction = builder.build_float_add(load.into_float_value(), f32_val, "").as_instruction_value().unwrap(); assert!(fadd_instruction.get_volatile().is_err()); assert!(fadd_instruction.set_volatile(false).is_err()); assert!(fadd_instruction.get_alignment().is_err()); assert!(fadd_instruction.set_alignment(16).is_err()); } #[llvm_versions(3.8..=latest)] #[test] fn test_atomic_ordering_mem_instructions() { let context = Context::create(); let module = context.create_module("testing"); let builder = context.create_builder(); let void_type = context.void_type(); let f32_type = context.f32_type(); let f32_ptr_type = f32_type.ptr_type(AddressSpace::Generic); let fn_type = void_type.fn_type(&[f32_ptr_type.into(), f32_type.into()], false); let function = module.add_function("mem_inst", fn_type, None); let basic_block = context.append_basic_block(function, "entry"); builder.position_at_end(basic_block); let arg1 = function.get_first_param().unwrap().into_pointer_value(); let arg2 = function.get_nth_param(1).unwrap().into_float_value(); assert!(arg1.get_first_use().is_none()); assert!(arg2.get_first_use().is_none()); let f32_val = f32_type.const_float(::std::f64::consts::PI); let store_instruction = builder.build_store(arg1, f32_val); let load = builder.build_load(arg1, ""); let load_instruction = load.as_instruction_value().unwrap(); assert_eq!(store_instruction.get_atomic_ordering().unwrap(), AtomicOrdering::NotAtomic); assert_eq!(load_instruction.get_atomic_ordering().unwrap(), AtomicOrdering::NotAtomic); assert!(store_instruction.set_atomic_ordering(AtomicOrdering::Monotonic).is_ok()); assert_eq!(store_instruction.get_atomic_ordering().unwrap(), AtomicOrdering::Monotonic); assert!(store_instruction.set_atomic_ordering(AtomicOrdering::Release).is_ok()); assert!(load_instruction.set_atomic_ordering(AtomicOrdering::Acquire).is_ok()); assert!(store_instruction.set_atomic_ordering(AtomicOrdering::Acquire).is_err()); assert!(store_instruction.set_atomic_ordering(AtomicOrdering::AcquireRelease).is_err()); assert!(load_instruction.set_atomic_ordering(AtomicOrdering::AcquireRelease).is_err()); assert!(load_instruction.set_atomic_ordering(AtomicOrdering::Release).is_err()); let fadd_instruction = builder.build_float_add(load.into_float_value(), f32_val, "").as_instruction_value().unwrap(); assert!(fadd_instruction.get_atomic_ordering().is_err()); assert!(fadd_instruction.set_atomic_ordering(AtomicOrdering::NotAtomic).is_err()); } #[test] fn test_metadata_kinds() { let context = Context::create(); let i8_type = context.i8_type(); let f32_type = context.f32_type(); let ptr_type = i8_type.ptr_type(AddressSpace::Generic); let struct_type = context.struct_type(&[i8_type.into(), f32_type.into()], false); let vector_type = i8_type.vec_type(2); let i8_value = i8_type.const_zero(); let i8_array_value = i8_type.const_array(&[i8_value]); let f32_value = f32_type.const_zero(); let ptr_value = ptr_type.const_null(); let struct_value = struct_type.get_undef(); let vector_value = vector_type.const_zero(); let md_string = context.metadata_string("lots of metadata here"); context.metadata_node(&[ i8_array_value.into(), i8_value.into(), f32_value.into(), ptr_value.into(), struct_value.into(), vector_value.into(), md_string.into(), ]); }
Java
package org.efix.util.buffer; import org.efix.util.ByteSequenceWrapper; import org.efix.util.StringUtil; public class BufferUtil { public static UnsafeBuffer fromString(String string) { return new UnsafeBuffer(StringUtil.asciiBytes(string)); } public static String toString(Buffer buffer) { return toString(buffer, 0, buffer.capacity()); } public static String toString(Buffer buffer, int offset, int length) { return new ByteSequenceWrapper(buffer, offset, length).toString(); } }
Java
/* * 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.shardingsphere.example.db.discovery.spring.namespace.jdbc.repository; import org.apache.shardingsphere.example.db.discovery.spring.namespace.jdbc.entity.Address; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedList; import java.util.List; public final class AddressRepository { private final DataSource dataSource; public AddressRepository(final DataSource dataSource) { this.dataSource = dataSource; } public void createTableIfNotExists() throws SQLException { String sql = "CREATE TABLE IF NOT EXISTS t_address " + "(address_id BIGINT NOT NULL, address_name VARCHAR(100) NOT NULL, PRIMARY KEY (address_id))"; try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.executeUpdate(sql); } } public void dropTable() throws SQLException { String sql = "DROP TABLE t_address"; try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.executeUpdate(sql); } } public void truncateTable() throws SQLException { String sql = "TRUNCATE TABLE t_address"; try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.executeUpdate(sql); } } public Long insert(final Address entity) throws SQLException { String sql = "INSERT INTO t_address (address_id, address_name) VALUES (?, ?)"; try (Connection connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setLong(1, entity.getAddressId()); preparedStatement.setString(2, entity.getAddressName()); preparedStatement.executeUpdate(); } return entity.getAddressId(); } public void delete(final Long primaryKey) throws SQLException { String sql = "DELETE FROM t_address WHERE address_id=?"; try (Connection connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setLong(1, primaryKey); preparedStatement.executeUpdate(); } } public List<Address> selectAll() throws SQLException { String sql = "SELECT * FROM t_address"; return getAddress(sql); } private List<Address> getAddress(final String sql) throws SQLException { List<Address> result = new LinkedList<>(); try (Connection connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { Address address = new Address(); address.setAddressId(resultSet.getLong(1)); address.setAddressName(resultSet.getString(2)); result.add(address); } } return result; } }
Java
package dao import ( "go-common/app/admin/ep/merlin/model" "testing" . "github.com/smartystreets/goconvey/convey" ) var ( username = "fengyifenguitest@bilibili.com" ) func Test_Mail_Log(t *testing.T) { Convey("test add mail log", t, func() { ml := &model.MailLog{ ReceiverName: username, MailType: 1, SendContext: "test add mail log", } err := d.InsertMailLog(ml) So(err, ShouldBeNil) }) Convey("test find mail log", t, func() { mailLogs, err := d.FindMailLog(username) So(len(mailLogs), ShouldBeGreaterThan, 0) So(err, ShouldBeNil) }) Convey("test delete mail log", t, func() { err := d.DelMailLog(username) So(err, ShouldBeNil) }) Convey("test find mail log", t, func() { mailLogs, err := d.FindMailLog(username) So(len(mailLogs), ShouldEqual, 0) So(err, ShouldBeNil) }) }
Java
<!DOCTYPE html> <html layout:decorate="~{layouts/adminlte}"> <head> <title>FormKiQ Server - Setup</title> </head> <body> <div layout:fragment="content"> <!-- Main content --> <section class="content"> <div class="row"> <form method="post"> <div class="box-body"> <th:block th:with="form=${flow.currentState.data},fielderrors=${flow.currentState.fielderrors}" th:if="${!flow.currentState.end}" th:include="fragments/component/form" /> <th:block th:with="form=${T(com.formkiq.forms.JSONService).instance().loadForm('com.formkiq.core.service.dto.Setupcomplete.form')}" th:if="${flow.currentState.end}" th:include="fragments/component/form" /> </div> </form> </div> </section> </div> </body> </html>
Java
# Pseudocercospora membranaceae H.S.G. Rao & S. Narayan SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Journal of Living World 6(2): 14 (1999) #### Original name Pseudocercospora membranaceae H.S.G. Rao & S. Narayan ### Remarks null
Java
/** * @file eigen-tools.h * @brief header file containing all header with eigen API and tools functions * * .. invisible: * _ _ _____ _ _____ _____ * * | | | | ___| | | ___/ ___| * * | | | | |__ | | | |__ \ `--. * * | | | | __|| | | __| `--. \ * * \ \_/ / |___| |___| |___/\__/ / * * \___/\____/\_____|____/\____/ * * 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 * */ #ifndef EIGEN_TOOLS #define EIGEN_TOOLS #include "eigen-data-types.h" #include <sstream> #include <iostream> #include <fstream> #include "time.h" using namespace Eigen; using std::vector; using std::ios; namespace eigentools { /** *Splitts sparse matrix (columns of i_mat) to mat1 and mat2 in portion (0.8 by default) */ template<typename Derived> void splitSparseMatrix(const SparseMatrix<Derived> &i_mat, SparseMatrix<Derived> &o_mat1,SparseMatrix<Derived> &o_mat2, double portion = 0.8) { int num = (int)(portion * (double)i_mat.cols()); o_mat1 = i_mat.leftCols(num); o_mat2 = i_mat.rightCols(i_mat.cols()-num); } template <typename Derived> Matrix<Derived, Dynamic, Dynamic> shuffleByIndexes(const Matrix<Derived, Dynamic, Dynamic>& mat, const std::vector<int>& indexes) { if (indexes.empty()) return mat; PermutationMatrix<Dynamic,Dynamic> perm(mat.cols()); for (int i = 0; i < perm.indices().size(); i++) { *(perm.indices().data()+i) = indexes[i]; } return mat * perm; } template <typename Derived> SparseMatrix<Derived> shuffleByIndexes(const SparseMatrix<Derived>& mat, const std::vector<int>& indexes) { if (indexes.empty()) return mat; PermutationMatrix<Dynamic,Dynamic> perm(mat.cols()); for (int i = 0; i < perm.indices().size(); i++) { *(perm.indices().data()+i) = indexes[i]; } return mat * perm; } template <class M> M randomShuffleMatrix(const M& mat, std::vector<int>& indexes) { indexes.clear(); indexes = vector<int>(mat.cols(),0); for (size_t i = 0; i < indexes.size();i++) indexes[i] = i; std::random_shuffle(indexes.begin(), indexes.end()); return eigentools::shuffleByIndexes(mat,indexes); } template <typename Derived> void randomStohasticMatrix(Matrix<Derived, Dynamic, Dynamic>& m, int rows, int cols, bool NormByRows = true) { srand(time(NULL)); Matrix<Derived, Dynamic, Dynamic> tmp; if (NormByRows) { tmp = (Matrix<Derived, Dynamic, Dynamic>::Random(rows, cols).array()+1).matrix()/2; } else { tmp = (Matrix<Derived, Dynamic, Dynamic>::Random(cols,rows).array()+1).matrix()/2; } Array<Derived, Dynamic, 1> c = tmp.rowwise().sum().array().pow(-1); tmp = (tmp.array().colwise() * c).matrix(); if (!NormByRows) m = tmp.transpose(); else m = tmp; } template <typename Derived> void makeStohastic(Matrix<Derived, Dynamic, Dynamic>& m, bool NormByRows = true) { srand(time(NULL)); if (NormByRows) { Array<Derived, Dynamic, 1> c = m.rowwise().sum().array(); c = (c.array() ==0).select(-1,c); m = m.array().colwise() / c; } else if (!NormByRows) { Array<Derived, Dynamic, 1> c = m.colwise().sum().array(); c = (c.array() ==0).select(-1,c); m = m.array().rowwise() / c.transpose(); } } template <typename Derived> void makeStohastic(const Matrix<Derived, Dynamic, Dynamic>& m, Matrix<Derived, Dynamic, Dynamic>& res, bool NormByRows = true) { srand(time(NULL)); if (NormByRows) { Array<Derived, Dynamic, 1> c = m.rowwise().sum().array(); c = (c.array() ==0).select(-1,c); res = m.array().colwise() / c; } else if (!NormByRows) { Array<Derived, Dynamic, 1> c = m.colwise().sum().array(); c = (c.array() ==0).select(-1,c); res = m.array().rowwise() / c.transpose(); } } template <typename Derived> ScalarType density(const Matrix<Derived,Dynamic,Dynamic>& i_mat, ScalarType i_precision = 0) { Matrix<Derived,Dynamic,Dynamic> a(i_mat.rows(),i_mat.cols()); a = (i_mat.array() > i_precision).select(1,i_mat); a = (i_mat.array() <= i_precision).select(0,a); return a.sum()/(i_mat.cols()*i_mat.rows()); } template <typename Derived> ScalarType density(const SparseMatrix<Derived>& i_mat) { return (ScalarType)i_mat.nonZeros()/(i_mat.cols()*i_mat.rows()); } template <typename Derived, typename T> void eigenVec2StlVecOfPair(const DenseBase<Derived> &i_mat, vector<std::pair<int,T> >& result) { if (i_mat.cols()==1) { result = vector<std::pair<int,T> >(i_mat.rows(),std::make_pair(0,(T)0)); for (int i = 0; i < i_mat.rows(); i++) result[i] = std::make_pair(i,(T)i_mat.coeff(i,0)); } else if (i_mat.rows()==1) { result = vector<std::pair<int,T> >(i_mat.cols(),std::make_pair(0,(T)0)); for (int i = 0; i < i_mat.cols(); i++) result[i] = std::make_pair(i,(T)i_mat.coeff(0,i)); } else { result = vector<std::pair<int,T> >(); } } template <typename Derived, typename T> void eigenVec2StlVec(const DenseBase<Derived> &i_mat, vector<T>& result) { if (i_mat.cols()==1) { result = vector<T>(i_mat.rows(),(T)0); for (int i = 0; i < i_mat.rows(); i++) result[i] = (T)i_mat.coeff(i,0); } else if (i_mat.rows()==1) { result = vector<T>(i_mat.cols(),(T)0); for (int i = 0; i < i_mat.cols(); i++) result[i] = i_mat.coeff(0,i); } else { result = vector<T>(); } } template <class M> void removeColumn(M &io_mat, int col) { int rows = io_mat.rows(); int cols = io_mat.cols(); if (col < 0 || col>=cols) return; io_mat.block(0,col,rows,cols-col-1) = io_mat.block(0,col+1,rows,cols-col-1); io_mat.conservativeResize(rows,cols-1); } template <class M> void removeRow(M &io_mat, int row) { int rows = io_mat.rows(); int cols = io_mat.cols(); if (row < 0 || row>=rows) return; io_mat.block(row,0,rows-row-1,cols) =io_mat.block(row+1,0,rows-row-1,cols); io_mat.conservativeResize(rows-1,cols); } template <typename Derived> void saveMatrix(const DenseBase<Derived> &i_mat, const std::string& filename) { std::ofstream oStream(filename); if (!oStream) return; oStream<<i_mat.rows()<<std::endl; oStream<<i_mat.cols()<<std::endl; oStream<<i_mat; oStream.close(); } /** *template function for loading from file matrix * ATTENTION: correspondence of scalar types in loading and saving matrix is obligation */ template <typename Derived> void loadMatrix(DenseBase<Derived> &i_mat, const std::string &filename) { typedef typename DenseBase<Derived>::Scalar Scalar; std::ifstream iStream(filename); if (!iStream) return; // std::cerr<<"Can't open file for writing " << filename << "\n"; int rows,cols; Scalar val; std::string line; int count = -1; char* pEnd; while( std::getline(iStream,line) ) { count++; if (count == 0) { rows = (int)strtof(line.c_str(),&pEnd); continue; } if (count == 1) { cols = (int)strtof(line.c_str(),&pEnd); i_mat.derived().resize(rows,cols); i_mat.setZero(); continue; } pEnd = (char*)line.c_str(); for (int i = 0; i < cols; i++) { val = (Scalar)strtod(pEnd,&pEnd); i_mat(count-2,i) = val; } } iStream.close(); } template<typename Derived> void saveSparseMatrix(SparseMatrix<Derived> &i_mat, const std::string &filename) { std::ofstream oStream(filename); if (!oStream) return; oStream<<i_mat.rows()<<std::endl; oStream<<i_mat.cols()<<std::endl; for (int k=0; k<i_mat.outerSize(); ++k) { int count = 0; std::string line; std::stringstream sstream(line); for (typename SparseMatrix<Derived>::InnerIterator it(i_mat,k); it; ++it) { sstream<<"\t"<<it.row()<<"\t"<<it.value(); count++; } oStream<<k<<"\t"<<count<<sstream.str(); oStream<<std::endl; } oStream.close(); } /** *template function for loading from file sparse matrix * ATTENTION: correspondence of scalar types in loading and saving matrix is obligation */ template<typename Derived> void loadSparseMatrix(SparseMatrix<Derived> &i_mat, const std::string &filename) { typedef typename SparseMatrix<Derived>::Scalar Scalar; std::ifstream iStream(filename); if (!iStream) return; int rows,cols,col,row; vector<Eigen::Triplet<Scalar> > t; std::string line; int count = -1,num; Scalar value; char* pEnd; while( std::getline(iStream,line) ) { count++; if (count == 0) { rows = (int)strtof(line.c_str(),&pEnd); continue; } if (count == 1) { cols = (int)strtof(line.c_str(),&pEnd); i_mat = SparseMatrix<Scalar>(rows,cols); if (rows == 0 || cols == 0) { return; } continue; } col = (int)strtof(line.c_str(),&pEnd); num = (int)strtof(pEnd, &pEnd); for (size_t i = 0; i < num; i++) { row = (int)strtof(pEnd, &pEnd); value = (Scalar)strtod(pEnd, &pEnd); t.push_back(Eigen::Triplet<Scalar>(row, col, value)); } } i_mat.setFromTriplets(t.begin(),t.end()); iStream.close(); } template<typename Derived> void concatenateMatrix(const DenseBase<Derived> &i_mat1, const DenseBase<Derived> &i_mat2, DenseBase<Derived>& res) { res.derived().resize(i_mat1.rows(),i_mat1.cols()+i_mat2.cols()); res.block(0,0,i_mat1.rows(),i_mat1.cols()) = i_mat1; res.block(0,i_mat1.cols(),i_mat2.rows(),i_mat2.cols()) = i_mat2; } template<typename Derived> void removeFirstNCols(const DenseBase<Derived> &i_mat, DenseBase<Derived> &o_mat, int N) { if (N < 0) { o_mat = i_mat; return; } if (N > i_mat.cols()) { o_mat = i_mat; return; } o_mat.derived().resize(i_mat.rows(),i_mat.cols()-N); o_mat = i_mat.block(0,N,i_mat.rows(),i_mat.cols()-N); } //template<typename Derived> //ScalarType cosineMeasure(const MatrixBase<Derived> &a, const MatrixBase<Derived> &b) template<typename Derived> void saveSparseMatrixBinary(SparseMatrix<Derived> &i_mat, const std::string &filename) { std::ofstream oStream(filename,ios::out|ios::binary); if (!oStream) return; saveSparseMatrixBinary(i_mat,oStream); oStream.close(); } template<typename Derived> void saveSparseMatrixBinary(SparseMatrix<Derived> &i_mat, std::ofstream& i_oStream) { if (!i_oStream) return; int num = i_mat.rows(); i_oStream.write((char*)& num,4); num =i_mat.cols(); i_oStream.write((char*)& num,4); int SizeOfScalarType = (int)sizeof(typename SparseMatrix<Derived>::Scalar); i_oStream.write((char*)& SizeOfScalarType,4); for (int k=0; k<i_mat.outerSize(); ++k) { i_oStream.write((char*)& k,4); for (typename SparseMatrix<Derived>::InnerIterator it(i_mat,k); it; ++it) { num = it.row(); i_oStream.write((char*)& num,4); i_oStream.write((char*)& it.value(),SizeOfScalarType); } num = -1; i_oStream.write((char*)& num,4); } } template<typename Derived> void loadSparseMatrixBinary(SparseMatrix<Derived> &o_mat, const std::string &filename) { std::ifstream iStream(filename,ios::in|ios::binary); if (!iStream) return; loadSparseMatrixBinary(o_mat,iStream); iStream.close(); } template<typename Derived> void loadSparseMatrixBinary(SparseMatrix<Derived> &o_mat, std::ifstream& i_iStream) { if (!i_iStream) return; typedef typename SparseMatrix<Derived>::Scalar Scalar; Scalar value; vector<Eigen::Triplet<Scalar> > t; int rows,cols, SizeOfScalarType, col,row; i_iStream.read((char*)& rows, 4); i_iStream.read((char*)& cols, 4); i_iStream.read((char*)& SizeOfScalarType, 4); if (SizeOfScalarType != (int)sizeof(Scalar)) { std::cerr<<"Sizes of data type stored in matreces are not equal"<<std::endl; } o_mat.derived().resize(rows,cols); while (1) { i_iStream.read((char*)& col, 4); while (1) { i_iStream.read((char*)& row, 4); if (row == -1) break; i_iStream.read((char*)& value, SizeOfScalarType); t.push_back(Eigen::Triplet<Scalar>(row,col,(Scalar)value)); } if (col == cols - 1) break; } o_mat.setFromTriplets(t.begin(),t.end()); } ScalarType cosineMeasure(DenseMat &a,DenseMat &b); } #endif // EIGEN_TOOLS
Java
import styled, { css as styledCss, keyframes } from 'styled-components' import type { TTestable } from '@/spec' import Img from '@/Img' import { theme } from '@/utils/themes' import css from '@/utils/css' const DURATION = '2.5s' const load = keyframes` 0% { top: 24px; } 70% { top: 10px; } 90% { top: 0; } 95% { top: 0; } 100% { top: 24px; } ` const liquid1 = keyframes` 0% { height: 0; opacity: 0; top: -5px; } 22% { height: 2.8125px; top: 3.75px; opacity: 1; } 25% { top: -2.5px; } 35% { height: 11.25px; top: -5px; } 55% { height: 3px; top: -1.25px; } 60% { height: 6px; opacity: 1; top: -3px; } 96% { height: 8.4375px; opacity: 0; top: 5px; } 100% { height: 0; opacity: 0; } ` const liquid2 = keyframes` 0% { height: 0; opacity: 0; top: -0.5rem; } 17.5% { height: 3px; top: 2px; opacity: 1; } 20% { top: -2.5px; } 25% { height: 15px; top: -6px; } 45% { height: 3px; top: -1px; } 60% { opacity: 1; height: 15px; top: -5px; } 96% { opacity: 0; height: 8px; top: 5px; } 100% { height: 0; opacity: 0; } ` const loadRule = styledCss` ${load} ${DURATION} infinite; ` const liquid1Rule = styledCss` ${liquid1} ${DURATION} infinite; ` const liquid2Rule = styledCss` ${liquid2} ${DURATION} infinite; ` export const Wrapper = styled.div.attrs(({ testid }: TTestable) => ({ 'data-test-id': testid, }))<TTestable>` text-align: center; position: relative; height: 28px; margin-bottom: 6px; cursor: pointer; ` export const Battery = styled.div` display: inline-block; position: relative; width: 16px; height: 26px; box-shadow: 0 0 0 2px #155e76; border-radius: 2px; &:before { content: ''; position: absolute; left: 5px; top: -4px; height: 3px; width: 6px; background: #155e76; border-radius: 2px; } ${Wrapper}:hover & { &:after { content: ''; position: absolute; top: 0; bottom: 0; left: 0; right: 0; border-right: 16px solid transparent; border-bottom: 22px solid rgba(255, 255, 255, 0.25); } } ` export const Liquid = styled.div` position: absolute; top: 23px; bottom: 0; left: 0; right: 0; width: 16px; background: ${theme('baseColor.green')}; ${Wrapper}:hover & { top: 0; animation: ${loadRule}; &:before { left: 0; animation: ${liquid2Rule}; content: ''; position: absolute; top: -5px; height: 11.25px; width: 14.625px; background: ${theme('baseColor.green')}; border-radius: 50%; opacity: 0; } &:after { right: 0; animation: ${liquid1Rule}; content: ''; position: absolute; top: -5px; height: 11.25px; width: 14.625px; background: ${theme('baseColor.green')}; border-radius: 50%; opacity: 0; } } ` export const MoneySign = styled(Img)` position: absolute; top: 6px; left: 3px; ${css.size(10)}; fill: #327faf; transition: opacity 0.25s; ${Wrapper}:hover & { fill: #ecbcb3; top: 8px; left: 2px; ${css.size(12)}; } transition: all 0.2s; `
Java
/* * Copyright (c) 2017 Antony Esik * * 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.ae.camunda.dispatcher.mapper.xml; import com.ae.camunda.dispatcher.api.mapper.TaskMapper; import com.ae.camunda.dispatcher.exception.CamundaMappingException; import org.eclipse.persistence.jaxb.JAXBContextFactory; import org.springframework.stereotype.Component; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import java.io.StringReader; import java.io.StringWriter; import java.util.Collections; /** * @author AEsik * Date 09.10.2017 */ @Component public class XmlTaskMapper implements TaskMapper { @Override public String map(Object task) { try { JAXBContext context = JAXBContextFactory.createContext(new Class[]{task.getClass()}, Collections.emptyMap()); StringWriter sw = new StringWriter(); context.createMarshaller().marshal(task, sw); return sw.toString(); } catch (JAXBException e) { throw new CamundaMappingException(e); } } @Override public Object map(String body, Class<?> clazz) { try { JAXBContext context = JAXBContextFactory.createContext(new Class[]{clazz}, Collections.emptyMap()); StringReader sr = new StringReader(body); return context.createUnmarshaller().unmarshal(sr); } catch (JAXBException e) { throw new CamundaMappingException(e); } } }
Java
/* Copyright 2022 The Vitess 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 physical import ( "strings" "vitess.io/vitess/go/mysql/collations" "vitess.io/vitess/go/sqltypes" vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc" "vitess.io/vitess/go/vt/sqlparser" "vitess.io/vitess/go/vt/vterrors" "vitess.io/vitess/go/vt/vtgate/evalengine" ) func (rp *Route) findSysInfoRoutingPredicatesGen4(predicates []sqlparser.Expr, reservedVars *sqlparser.ReservedVars) error { for _, pred := range predicates { isTableSchema, bvName, out, err := extractInfoSchemaRoutingPredicate(pred, reservedVars) if err != nil { return err } if out == nil { // we didn't find a predicate to use for routing, continue to look for next predicate continue } if isTableSchema { rp.SysTableTableSchema = append(rp.SysTableTableSchema, out) } else { if rp.SysTableTableName == nil { rp.SysTableTableName = map[string]evalengine.Expr{} } rp.SysTableTableName[bvName] = out } } return nil } func extractInfoSchemaRoutingPredicate(in sqlparser.Expr, reservedVars *sqlparser.ReservedVars) (bool, string, evalengine.Expr, error) { switch cmp := in.(type) { case *sqlparser.ComparisonExpr: if cmp.Operator == sqlparser.EqualOp { isSchemaName, col, other, replaceOther := findOtherComparator(cmp) if col != nil && shouldRewrite(other) { evalExpr, err := evalengine.Translate(other, &notImplementedSchemaInfoConverter{}) if err != nil { if strings.Contains(err.Error(), evalengine.ErrTranslateExprNotSupported) { // This just means we can't rewrite this particular expression, // not that we have to exit altogether return false, "", nil, nil } return false, "", nil, err } var name string if isSchemaName { name = sqltypes.BvSchemaName } else { name = reservedVars.ReserveColName(col.(*sqlparser.ColName)) } replaceOther(sqlparser.NewArgument(name)) return isSchemaName, name, evalExpr, nil } } } return false, "", nil, nil } func findOtherComparator(cmp *sqlparser.ComparisonExpr) (bool, sqlparser.Expr, sqlparser.Expr, func(arg sqlparser.Argument)) { if schema, table := isTableSchemaOrName(cmp.Left); schema || table { return schema, cmp.Left, cmp.Right, func(arg sqlparser.Argument) { cmp.Right = arg } } if schema, table := isTableSchemaOrName(cmp.Right); schema || table { return schema, cmp.Right, cmp.Left, func(arg sqlparser.Argument) { cmp.Left = arg } } return false, nil, nil, nil } func shouldRewrite(e sqlparser.Expr) bool { switch node := e.(type) { case *sqlparser.FuncExpr: // we should not rewrite database() calls against information_schema return !(node.Name.EqualString("database") || node.Name.EqualString("schema")) } return true } func isTableSchemaOrName(e sqlparser.Expr) (isTableSchema bool, isTableName bool) { col, ok := e.(*sqlparser.ColName) if !ok { return false, false } return isDbNameCol(col), isTableNameCol(col) } func isDbNameCol(col *sqlparser.ColName) bool { return col.Name.EqualString("table_schema") || col.Name.EqualString("constraint_schema") || col.Name.EqualString("schema_name") || col.Name.EqualString("routine_schema") } func isTableNameCol(col *sqlparser.ColName) bool { return col.Name.EqualString("table_name") } type notImplementedSchemaInfoConverter struct{} func (f *notImplementedSchemaInfoConverter) ColumnLookup(*sqlparser.ColName) (int, error) { return 0, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "Comparing table schema name with a column name not yet supported") } func (f *notImplementedSchemaInfoConverter) CollationForExpr(sqlparser.Expr) collations.ID { return collations.Unknown } func (f *notImplementedSchemaInfoConverter) DefaultCollation() collations.ID { return collations.Default() }
Java
"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_SWITCHES, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_OFF, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.script import Script from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS from .template_entity import TemplateEntity _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"] ON_ACTION = "turn_on" OFF_ACTION = "turn_off" SWITCH_SCHEMA = vol.Schema( { vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA, vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(ATTR_FRIENDLY_NAME): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) async def _async_create_entities(hass, config): """Create the Template switches.""" switches = [] for device, device_config in config[CONF_SWITCHES].items(): friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE) availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE) on_action = device_config[ON_ACTION] off_action = device_config[OFF_ACTION] unique_id = device_config.get(CONF_UNIQUE_ID) switches.append( SwitchTemplate( hass, device, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ) ) return switches async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template switches.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) async_add_entities(await _async_create_entities(hass, config)) class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity): """Representation of a Template switch.""" def __init__( self, hass, device_id, friendly_name, state_template, icon_template, entity_picture_template, availability_template, on_action, off_action, unique_id, ): """Initialize the Template switch.""" super().__init__( availability_template=availability_template, icon_template=icon_template, entity_picture_template=entity_picture_template, ) self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass ) self._name = friendly_name self._template = state_template domain = __name__.split(".")[-2] self._on_script = Script(hass, on_action, friendly_name, domain) self._off_script = Script(hass, off_action, friendly_name, domain) self._state = False self._unique_id = unique_id @callback def _update_state(self, result): super()._update_state(result) if isinstance(result, TemplateError): self._state = None return self._state = result.lower() in ("true", STATE_ON) async def async_added_to_hass(self): """Register callbacks.""" if self._template is None: # restore state after startup await super().async_added_to_hass() state = await self.async_get_last_state() if state: self._state = state.state == STATE_ON # no need to listen for events else: self.add_template_attribute( "_state", self._template, None, self._update_state ) await super().async_added_to_hass() @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of this switch.""" return self._unique_id @property def is_on(self): """Return true if device is on.""" return self._state @property def should_poll(self): """Return the polling state.""" return False async def async_turn_on(self, **kwargs): """Fire the on action.""" await self._on_script.async_run(context=self._context) if self._template is None: self._state = True self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Fire the off action.""" await self._off_script.async_run(context=self._context) if self._template is None: self._state = False self.async_write_ha_state() @property def assumed_state(self): """State is assumed, if no template given.""" return self._template is None
Java
package org.whale.ext.domain; import java.util.ArrayList; import java.util.List; import org.whale.system.annotation.jdbc.Column; import org.whale.system.annotation.jdbc.Id; import org.whale.system.annotation.jdbc.Table; import org.whale.system.annotation.jdbc.Validate; import org.whale.system.base.BaseEntry; import org.whale.system.common.util.PropertiesUtil; /** * 实体对象 * * @author wjs * 2014年9月10日-上午10:12:48 */ @Table(value="sys_domian", cnName="实体对象") public class Domain extends BaseEntry{ private static final long serialVersionUID = -23042834921L; @Id @Column(cnName="id") private Long id; @Validate(required=true) @Column(cnName="实体名") private String domainName; @Validate(required=true) @Column(cnName="中文名") private String domainCnName; @Validate(required=true) @Column(cnName="数据库", unique=true) private String domainSqlName; @Column(cnName="基础包路径") private String pkgName = "org.whale.system"; //树模型 private Integer treeModel; private String treeId; private String treePid; private String treeName; //模板类型 private Integer ftlType; //代码路径 private String codePath; private String author = PropertiesUtil.getValue("author", "wjs"); //主键 private Attr idAttr; private List<Attr> attrs; private List<Attr> listAttrs = new ArrayList<Attr>(); private List<Attr> formAttrs = new ArrayList<Attr>(); private List<Attr> queryAttrs = new ArrayList<Attr>(); public Long getId() { return id; } public String getDomainName() { return domainName; } public void setDomainName(String domainName) { this.domainName = domainName; } public String getDomainCnName() { return domainCnName; } public void setDomainCnName(String domainCnName) { this.domainCnName = domainCnName; } public String getDomainSqlName() { return domainSqlName; } public void setDomainSqlName(String domainSqlName) { this.domainSqlName = domainSqlName; } public String getPkgName() { return pkgName; } public void setPkgName(String pkgName) { this.pkgName = pkgName; } public Attr getIdAttr() { return idAttr; } public void setIdAttr(Attr idAttr) { this.idAttr = idAttr; } public List<Attr> getAttrs() { return attrs; } public void setAttrs(List<Attr> attrs) { this.attrs = attrs; } public List<Attr> getListAttrs() { return listAttrs; } public void setListAttrs(List<Attr> listAttrs) { this.listAttrs = listAttrs; } public List<Attr> getFormAttrs() { return formAttrs; } public void setFormAttrs(List<Attr> formAttrs) { this.formAttrs = formAttrs; } public List<Attr> getQueryAttrs() { return queryAttrs; } public void setQueryAttrs(List<Attr> queryAttrs) { this.queryAttrs = queryAttrs; } public void setId(Long id) { this.id = id; } public Integer getFtlType() { return ftlType; } public void setFtlType(Integer ftlType) { this.ftlType = ftlType; } public String getCodePath() { return codePath; } public void setCodePath(String codePath) { this.codePath = codePath; } public Integer getTreeModel() { return treeModel; } public void setTreeModel(Integer treeModel) { this.treeModel = treeModel; } public String getTreeId() { return treeId; } public void setTreeId(String treeId) { this.treeId = treeId; } public String getTreePid() { return treePid; } public void setTreePid(String treePid) { this.treePid = treePid; } public String getTreeName() { return treeName; } public void setTreeName(String treeName) { this.treeName = treeName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
Java
/* * syscall.cpp * * Created on: Jun 3, 2017 * Author: warlo */ #include "syscall.hpp" #include <diag\Trace.h> namespace os { #if 0 static void dispatch_syscall(void) naked_function; static void dispatch_syscall(void) { __asm__ __volatile__ ( " sub sp, sp, #16\n" /* Create a stack frame to hold 3 parms + lr */ " str r4, [sp, #0]\n" /* Move parameter 4 (if any) into position */ " str r5, [sp, #4]\n" /* Move parameter 5 (if any) into position */ " str r6, [sp, #8]\n" /* Move parameter 6 (if any) into position */ " str lr, [sp, #12]\n" /* Save lr in the stack frame */ " ldr ip, =g_stublookup\n" /* R12=The base of the stub lookup table */ " ldr ip, [ip, r0, lsl #2]\n" /* R12=The address of the stub for this syscall */ " blx ip\n" /* Call the stub (modifies lr) */ " ldr lr, [sp, #12]\n" /* Restore lr */ " add sp, sp, #16\n" /* Destroy the stack frame */ " mov r2, r0\n" /* R2=Save return value in R2 */ " mov r0, #3\n" /* R0=SYS_syscall_return */ " svc 0" /* Return from the syscall */ ); } #endif } #if 0 enum register_stack_t { /* Saved by hardware */ REG_R0, REG_R1, REG_R2, REG_R3, REG_R12, REG_LR, REG_PC, REG_xPSR }; #define RESERVED_STACK \ (8 * sizeof(uint32_t)) static void dispatch_syscall() __attribute((naked)); static void dispatch_syscall(uint32_t* caller) __attribute((naked)){ uint32_t svc_num = ((char *) caller[REG_PC])[-2]; } void syscall_init(uint8_t nbr, uintptr_t call){ assert(nbr < MAX_SYSCALLS); caller = call; } } template<uintptr_t FROM, uintptr_t TO> static inline void copy_stack(){ __asm volatile( "ldr r12, [sp, %0]\n" "str r12, [sp, %1]\n" : "i"(FROM), "i"(TO) ::"r12"); } __attribute((always_inline) )static inline void copy_memory(uintptr from, uintptr_t to) __attribute((always_inline) )static inline void copy_stack() { __asm__ __volatile__ ("push {r12 }sub sp, #(8*4)\n"); copy_stack<REG_R0+8, REG_R0>(); } #endif //extern "C" void SVC_Handler() __attribute((naked)) ; #if 0 extern "C" void SVC_Handler() { assert(0); } #endif
Java
# Asarum nipponicum var. nipponicum VARIETY #### Status ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
Java
# 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. """Federated CIFAR-10 classification library using TFF.""" import functools from typing import Callable, Optional from absl import logging import tensorflow as tf import tensorflow_federated as tff from fedopt_guide import training_loop from utils.datasets import cifar10_dataset from utils.models import resnet_models CIFAR_SHAPE = (32, 32, 3) NUM_CLASSES = 100 def run_federated( iterative_process_builder: Callable[..., tff.templates.IterativeProcess], client_epochs_per_round: int, client_batch_size: int, clients_per_round: int, client_datasets_random_seed: Optional[int] = None, crop_size: Optional[int] = 24, total_rounds: Optional[int] = 1500, experiment_name: Optional[str] = 'federated_cifar10', root_output_dir: Optional[str] = '/tmp/fed_opt', uniform_weighting: Optional[bool] = False, **kwargs): """Runs an iterative process on the CIFAR-10 classification task. This method will load and pre-process dataset and construct a model used for the task. It then uses `iterative_process_builder` to create an iterative process that it applies to the task, using `federated_research.utils.training_loop`. We assume that the iterative process has the following functional type signatures: * `initialize`: `( -> S@SERVER)` where `S` represents the server state. * `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S` represents the server state, `{B*}` represents the client datasets, and `T` represents a python `Mapping` object. The iterative process must also have a callable attribute `get_model_weights` that takes as input the state of the iterative process, and returns a `tff.learning.ModelWeights` object. Args: iterative_process_builder: A function that accepts a no-arg `model_fn`, and returns a `tff.templates.IterativeProcess`. The `model_fn` must return a `tff.learning.Model`. client_epochs_per_round: An integer representing the number of epochs of training performed per client in each training round. client_batch_size: An integer representing the batch size used on clients. clients_per_round: An integer representing the number of clients participating in each round. client_datasets_random_seed: An optional int used to seed which clients are sampled at each round. If `None`, no seed is used. crop_size: An optional integer representing the resulting size of input images after preprocessing. total_rounds: The number of federated training rounds. experiment_name: The name of the experiment being run. This will be appended to the `root_output_dir` for purposes of writing outputs. root_output_dir: The name of the root output directory for writing experiment outputs. uniform_weighting: Whether to weigh clients uniformly. If false, clients are weighted by the number of samples. **kwargs: Additional arguments configuring the training loop. For details on supported arguments, see `federated_research/utils/training_utils.py`. """ crop_shape = (crop_size, crop_size, 3) cifar_train, _ = cifar10_dataset.get_federated_datasets( train_client_epochs_per_round=client_epochs_per_round, train_client_batch_size=client_batch_size, crop_shape=crop_shape) _, cifar_test = cifar10_dataset.get_centralized_datasets( crop_shape=crop_shape) input_spec = cifar_train.create_tf_dataset_for_client( cifar_train.client_ids[0]).element_spec model_builder = functools.partial( resnet_models.create_resnet18, input_shape=crop_shape, num_classes=NUM_CLASSES) loss_builder = tf.keras.losses.SparseCategoricalCrossentropy metrics_builder = lambda: [tf.keras.metrics.SparseCategoricalAccuracy()] def tff_model_fn() -> tff.learning.Model: return tff.learning.from_keras_model( keras_model=model_builder(), input_spec=input_spec, loss=loss_builder(), metrics=metrics_builder()) if uniform_weighting: client_weight_fn = tff.learning.ClientWeighting.UNIFORM else: client_weight_fn = tff.learning.ClientWeighting.NUM_EXAMPLES training_process = iterative_process_builder(tff_model_fn, client_weight_fn) client_datasets_fn = functools.partial( tff.simulation.build_uniform_sampling_fn( dataset=cifar_train.client_ids, random_seed=client_datasets_random_seed), # pytype: disable=wrong-keyword-args # gen-stub-imports size=clients_per_round) evaluate_fn = tff.learning.build_federated_evaluation( tff_model_fn, use_experimental_simulation_loop=True) def validation_fn(model_weights, round_num): del round_num return evaluate_fn(model_weights, [cifar_test]) def test_fn(model_weights): return evaluate_fn(model_weights, [cifar_test]) logging.info('Training model:') logging.info(model_builder().summary()) training_loop.run( iterative_process=training_process, train_client_datasets_fn=client_datasets_fn, evaluation_fn=validation_fn, test_fn=test_fn, total_rounds=total_rounds, experiment_name=experiment_name, root_output_dir=root_output_dir, **kwargs)
Java
/* ========================================================================= * * Boarder * * http://boarder.mikuz.org/ * * ========================================================================= * * Copyright (C) 2013 Boarder * * * * 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 fi.mikuz.boarder.util; import org.acra.ACRA; import android.content.Context; import android.os.Looper; import android.util.Log; import android.widget.Toast; public abstract class ContextUtils { private static final String TAG = ContextUtils.class.getSimpleName(); public static void toast(Context context, String toast) { toast(context, toast, Toast.LENGTH_SHORT); } public static void toast(Context context, String toast, int duration) { String errLogMsg = "Unable to toast message: \"" + toast + "\""; if (Looper.myLooper() == null) { Exception e = new IllegalStateException("Not running in a looper"); Log.e(TAG, errLogMsg, e); ACRA.getErrorReporter().handleException(e); } else if (Looper.myLooper() != Looper.getMainLooper()) { Exception e = new IllegalStateException("Not running in the main looper"); Log.e(TAG, errLogMsg, e); ACRA.getErrorReporter().handleException(e); } else { try { Toast.makeText(context, toast, duration).show(); } catch (NullPointerException e) { Log.e(TAG, errLogMsg, e); } } } }
Java
#include <iostream> #include <iomanip> #include <cstdint> #include <typeinfo> #include "color/color.hpp" int main( int argc, char *argv[] ) { using namespace color; using namespace std; cout << "gray<std::uint8_t > is: " << typeid( trait::component< gray< std::uint8_t >::category_type >::instance_type ).name() << endl; cout << "gray<std::uint32_t> is: " << typeid( trait::component< gray< std::uint32_t >::category_type >::instance_type ).name() << endl; cout << "gray<float > is: " << typeid( trait::component< gray< float >::category_type >::instance_type ).name() << endl; cout << "gray<double > is: " << typeid( trait::component< gray< double >::category_type >::instance_type ).name() << endl; cout << "gray<long double > is: " << typeid( trait::component< gray< long double >::category_type >::instance_type ).name() << endl; return EXIT_SUCCESS; }
Java
# AUTOGENERATED FILE FROM balenalib/nanopi-neo-air-alpine:3.10-build ENV NODE_VERSION 14.16.1 ENV YARN_VERSION 1.22.4 # Install dependencies RUN apk add --no-cache libgcc libstdc++ libuv \ && apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://resin-packages.s3.amazonaws.com/node/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7hf-alpine.tar.gz" \ && echo "0d7d74264cbd457d1f54e4dcb6407a4b4b4602055d66e0a2cdec8bd635af8f59 node-v$NODE_VERSION-linux-armv7hf-alpine.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7hf-alpine.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7hf-alpine.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux 3.10 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.16.1, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && ln -f /bin/sh /bin/sh.real \ && ln -f /bin/sh-shim /bin/sh
Java
/* * Copyright 2017 StreamSets 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.streamsets.pipeline.kafka.impl; import com.streamsets.pipeline.api.Record; import com.streamsets.pipeline.api.Stage; import com.streamsets.pipeline.api.StageException; import com.streamsets.pipeline.config.DataFormat; import com.streamsets.pipeline.kafka.api.PartitionStrategy; import com.streamsets.pipeline.kafka.api.SdcKafkaProducer; import com.streamsets.pipeline.lib.kafka.KafkaErrors; import com.streamsets.pipeline.lib.kafka.exception.KafkaConnectionException; import kafka.javaapi.producer.Producer; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; public class KafkaProducer08 implements SdcKafkaProducer { private static final Logger LOG = LoggerFactory.getLogger(KafkaProducer08.class); private static final String METADATA_BROKER_LIST_KEY = "metadata.broker.list"; private static final String KEY_SERIALIZER_CLASS_KEY = "key.serializer.class"; private static final String PRODUCER_TYPE_KEY = "producer.type"; private static final String PRODUCER_TYPE_DEFAULT = "sync"; private static final String SERIALIZER_CLASS_KEY = "serializer.class"; private static final String REQUEST_REQUIRED_ACKS_KEY = "request.required.acks"; private static final String REQUEST_REQUIRED_ACKS_DEFAULT = "1"; private static final String DEFAULT_ENCODER_CLASS = "kafka.serializer.DefaultEncoder"; private static final String STRING_ENCODER_CLASS = "kafka.serializer.StringEncoder"; private static final String PARTITIONER_CLASS_KEY = "partitioner.class"; private static final String RANDOM_PARTITIONER_CLASS = "com.streamsets.pipeline.kafka.impl.RandomPartitioner"; private static final String ROUND_ROBIN_PARTITIONER_CLASS = "com.streamsets.pipeline.kafka.impl.RoundRobinPartitioner"; private static final String EXPRESSION_PARTITIONER_CLASS = "com.streamsets.pipeline.kafka.impl.ExpressionPartitioner"; /*Topic to readData from*/ /*Host on which the seed broker is running*/ private final String metadataBrokerList; private final Map<String, Object> kafkaProducerConfigs; private final DataFormat producerPayloadType; private final PartitionStrategy partitionStrategy; private List<KeyedMessage> messageList; private Producer producer; public KafkaProducer08( String metadataBrokerList, DataFormat producerPayloadType, PartitionStrategy partitionStrategy, Map<String, Object> kafkaProducerConfigs ) { this.metadataBrokerList = metadataBrokerList; this.producerPayloadType = producerPayloadType; this.partitionStrategy = partitionStrategy; this.messageList = new ArrayList<>(); this.kafkaProducerConfigs = kafkaProducerConfigs; } @Override public void init() throws StageException { Properties props = new Properties(); //metadata.broker.list props.put(METADATA_BROKER_LIST_KEY, metadataBrokerList); //producer.type props.put(PRODUCER_TYPE_KEY, PRODUCER_TYPE_DEFAULT); //key.serializer.class props.put(KEY_SERIALIZER_CLASS_KEY, STRING_ENCODER_CLASS); //partitioner.class configurePartitionStrategy(props, partitionStrategy); //serializer.class configureSerializer(props, producerPayloadType); //request.required.acks props.put(REQUEST_REQUIRED_ACKS_KEY, REQUEST_REQUIRED_ACKS_DEFAULT); addUserConfiguredProperties(props); ProducerConfig config = new ProducerConfig(props); producer = new Producer<>(config); } @Override public void destroy() { if(producer != null) { producer.close(); } } @Override public String getVersion() { return Kafka08Constants.KAFKA_VERSION; } @Override public void enqueueMessage(String topic, Object message, Object messageKey) { //Topic could be a record EL string. This is not a good place to evaluate expression //Hence get topic as parameter messageList.add(new KeyedMessage<>(topic, messageKey, message)); } @Override public void clearMessages() { messageList.clear(); } @Override public List<Record> write(Stage.Context context) throws StageException { try { producer.send(messageList); messageList.clear(); } catch (Exception e) { //Producer internally refreshes metadata and retries if there is any recoverable exception. //If retry fails, a FailedToSendMessageException is thrown. //In this case we want to fail pipeline. LOG.error(KafkaErrors.KAFKA_50.getMessage(), e.toString(), e); throw new KafkaConnectionException(KafkaErrors.KAFKA_50, e.toString(), e); } return Collections.emptyList(); } private void configureSerializer(Properties props, DataFormat producerPayloadType) { if(producerPayloadType == DataFormat.TEXT) { props.put(SERIALIZER_CLASS_KEY, DEFAULT_ENCODER_CLASS); } } private void configurePartitionStrategy(Properties props, PartitionStrategy partitionStrategy) { if (partitionStrategy == PartitionStrategy.RANDOM) { props.put(PARTITIONER_CLASS_KEY, RANDOM_PARTITIONER_CLASS); } else if (partitionStrategy == PartitionStrategy.ROUND_ROBIN) { props.put(PARTITIONER_CLASS_KEY, ROUND_ROBIN_PARTITIONER_CLASS); } else if (partitionStrategy == PartitionStrategy.EXPRESSION) { props.put(PARTITIONER_CLASS_KEY, EXPRESSION_PARTITIONER_CLASS); } else if (partitionStrategy == PartitionStrategy.DEFAULT) { //default partitioner class } } private void addUserConfiguredProperties(Properties props) { //The following options, if specified, are ignored : "metadata.broker.list", "producer.type", // "key.serializer.class", "partitioner.class", "serializer.class". if (kafkaProducerConfigs != null && !kafkaProducerConfigs.isEmpty()) { kafkaProducerConfigs.remove(METADATA_BROKER_LIST_KEY); kafkaProducerConfigs.remove(KEY_SERIALIZER_CLASS_KEY); kafkaProducerConfigs.remove(SERIALIZER_CLASS_KEY); for (Map.Entry<String, Object> producerConfig : kafkaProducerConfigs.entrySet()) { props.put(producerConfig.getKey(), producerConfig.getValue()); } } } }
Java
/* * Copyright 2014-2019 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.docdb.model.transform; import java.util.ArrayList; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.docdb.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * Event StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class EventStaxUnmarshaller implements Unmarshaller<Event, StaxUnmarshallerContext> { public Event unmarshall(StaxUnmarshallerContext context) throws Exception { Event event = new Event(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return event; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("SourceIdentifier", targetDepth)) { event.setSourceIdentifier(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("SourceType", targetDepth)) { event.setSourceType(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("Message", targetDepth)) { event.setMessage(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("EventCategories", targetDepth)) { event.withEventCategories(new ArrayList<String>()); continue; } if (context.testExpression("EventCategories/EventCategory", targetDepth)) { event.withEventCategories(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("Date", targetDepth)) { event.setDate(DateStaxUnmarshallerFactory.getInstance("iso8601").unmarshall(context)); continue; } if (context.testExpression("SourceArn", targetDepth)) { event.setSourceArn(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return event; } } } } private static EventStaxUnmarshaller instance; public static EventStaxUnmarshaller getInstance() { if (instance == null) instance = new EventStaxUnmarshaller(); return instance; } }
Java
package com.gentics.mesh.changelog.changes; import static com.gentics.mesh.core.data.relationship.GraphRelationships.SCHEMA_CONTAINER_VERSION_KEY_PROPERTY; import com.gentics.mesh.changelog.AbstractChange; import com.tinkerpop.blueprints.Direction; /** * Changelog entry which removed the schema version edges with properties */ public class ReplaceSchemaVersionEdges extends AbstractChange { @Override public String getUuid() { return "E737684330534623B768433053C623F2"; } @Override public String getName() { return "ReplaceSchemaVersionEdges"; } @Override public String getDescription() { return "Replaces edges from node content to schema versions with properties."; } @Override public void applyInTx() { replaceSingleEdge("NodeGraphFieldContainerImpl", Direction.OUT, "HAS_SCHEMA_CONTAINER_VERSION", SCHEMA_CONTAINER_VERSION_KEY_PROPERTY); } }
Java
package sl.hr_client; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
Java
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using System; #if Q8 using QuantumType = System.Byte; #elif Q16 using QuantumType = System.UInt16; #elif Q16HDRI using QuantumType = System.Single; #else #error Not implemented! #endif namespace ImageMagick { /// <summary> /// Class that represents a HSV color. /// </summary> public sealed class ColorHSV : ColorBase { /// <summary> /// Initializes a new instance of the <see cref="ColorHSV"/> class. /// </summary> /// <param name="hue">Hue component value of this color.</param> /// <param name="saturation">Saturation component value of this color.</param> /// <param name="value">Value component value of this color.</param> public ColorHSV(double hue, double saturation, double value) : base(new MagickColor(0, 0, 0)) { Hue = hue; Saturation = saturation; Value = value; } private ColorHSV(IMagickColor<QuantumType> color) : base(color) { Initialize(color.R, color.G, color.B); } /// <summary> /// Gets or sets the hue component value of this color. /// </summary> public double Hue { get; set; } /// <summary> /// Gets or sets the saturation component value of this color. /// </summary> public double Saturation { get; set; } /// <summary> /// Gets or sets the value component value of this color. /// </summary> public double Value { get; set; } /// <summary> /// Converts the specified <see cref="MagickColor"/> to an instance of this type. /// </summary> /// <param name="color">The color to use.</param> /// <returns>A <see cref="ColorHSV"/> instance.</returns> public static implicit operator ColorHSV?(MagickColor color) => FromMagickColor(color); /// <summary> /// Converts the specified <see cref="IMagickColor{QuantumType}"/> to an instance of this type. /// </summary> /// <param name="color">The color to use.</param> /// <returns>A <see cref="ColorHSV"/> instance.</returns> public static ColorHSV? FromMagickColor(IMagickColor<QuantumType> color) { if (color == null) return null; return new ColorHSV(color); } /// <summary> /// Performs a hue shift with the specified degrees. /// </summary> /// <param name="degrees">The degrees.</param> public void HueShift(double degrees) { Hue += degrees / 360.0; while (Hue >= 1.0) Hue -= 1.0; while (Hue < 0.0) Hue += 1.0; } /// <summary> /// Updates the color value in an inherited class. /// </summary> protected override void UpdateColor() { if (Math.Abs(Saturation) < double.Epsilon) { Color.R = Color.G = Color.B = Quantum.ScaleToQuantum(Value); return; } var h = 6.0 * (Hue - Math.Floor(Hue)); var f = h - Math.Floor(h); var p = Value * (1.0 - Saturation); var q = Value * (1.0 - (Saturation * f)); var t = Value * (1.0 - (Saturation * (1.0 - f))); switch ((int)h) { case 0: default: Color.R = Quantum.ScaleToQuantum(Value); Color.G = Quantum.ScaleToQuantum(t); Color.B = Quantum.ScaleToQuantum(p); break; case 1: Color.R = Quantum.ScaleToQuantum(q); Color.G = Quantum.ScaleToQuantum(Value); Color.B = Quantum.ScaleToQuantum(p); break; case 2: Color.R = Quantum.ScaleToQuantum(p); Color.G = Quantum.ScaleToQuantum(Value); Color.B = Quantum.ScaleToQuantum(t); break; case 3: Color.R = Quantum.ScaleToQuantum(p); Color.G = Quantum.ScaleToQuantum(q); Color.B = Quantum.ScaleToQuantum(Value); break; case 4: Color.R = Quantum.ScaleToQuantum(t); Color.G = Quantum.ScaleToQuantum(p); Color.B = Quantum.ScaleToQuantum(Value); break; case 5: Color.R = Quantum.ScaleToQuantum(Value); Color.G = Quantum.ScaleToQuantum(p); Color.B = Quantum.ScaleToQuantum(q); break; } } private void Initialize(double red, double green, double blue) { Hue = 0.0; Saturation = 0.0; Value = 0.0; var min = Math.Min(Math.Min(red, green), blue); var max = Math.Max(Math.Max(red, green), blue); if (Math.Abs(max) < double.Epsilon) return; var delta = max - min; Saturation = delta / max; Value = (1.0 / Quantum.Max) * max; if (Math.Abs(delta) < double.Epsilon) return; if (Math.Abs(red - max) < double.Epsilon) Hue = (green - blue) / delta; else if (Math.Abs(green - max) < double.Epsilon) Hue = 2.0 + ((blue - red) / delta); else Hue = 4.0 + ((red - green) / delta); Hue /= 6.0; if (Hue < 0.0) Hue += 1.0; } } }
Java
package cc.mallet.util; /** * Static utility methods for Strings */ final public class Strings { public static int commonPrefixIndex (String[] strings) { int prefixLen = strings[0].length(); for (int i = 1; i < strings.length; i++) { if (strings[i].length() < prefixLen) prefixLen = strings[i].length(); int j = 0; if (prefixLen == 0) return 0; while (j < prefixLen) { if (strings[i-1].charAt(j) != strings[i].charAt(j)) { prefixLen = j; break; } j++; } } return prefixLen; } public static String commonPrefix (String[] strings) { return strings[0].substring (0, commonPrefixIndex(strings)); } public static int count (String string, char ch) { int idx = -1; int count = 0; while ((idx = string.indexOf (ch, idx+1)) >= 0) { count++; }; return count; } public static double levenshteinDistance (String s, String t) { int n = s.length(); int m = t.length(); int d[][]; // matrix int i; // iterates through s int j; // iterates through t char s_i; // ith character of s char t_j; // jth character of t int cost; // cost if (n == 0) return 1.0; if (m == 0) return 1.0; d = new int[n+1][m+1]; for (i = 0; i <= n; i++) d[i][0] = i; for (j = 0; j <= m; j++) d[0][j] = j; for (i = 1; i <= n; i++) { s_i = s.charAt (i - 1); for (j = 1; j <= m; j++) { t_j = t.charAt (j - 1); cost = (s_i == t_j) ? 0 : 1; d[i][j] = minimum (d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost); } } int longer = (n > m) ? n : m; return (double)d[n][m] / longer; // Normalize to 0-1. } private static int minimum (int a, int b, int c) { int mi = a; if (b < mi) { mi = b; } if (c < mi) { mi = c; } return mi; } }
Java
package org.museautomation.core.step; import org.jetbrains.annotations.*; import org.museautomation.core.*; import org.museautomation.core.context.*; import org.museautomation.core.step.descriptor.*; import org.museautomation.core.steptask.*; import org.museautomation.core.values.*; import org.museautomation.core.values.descriptor.*; import java.util.*; /** * Executes the steps contained within a Macro. * * Note that this does NOT execute those steps within a separate variable scope, despite this class extending * ScopedGroup. It overrides #isCreateNewVariableScope to disable that behavior. That seems a bit strange, but * CallFunction builds on the basic function of CallMacroStep and it needs to be scoped. We need multiple-inheritance * to do this cleanly (yuck), but this will have to suffice. * * @see Macro * @author Christopher L Merrill (see LICENSE.txt for license details) */ @MuseTypeId("callmacro") @MuseStepName("Macro") @MuseInlineEditString("call macro {id}") @MuseStepIcon("glyph:FontAwesome:EXTERNAL_LINK") @MuseStepTypeGroup("Structure") @MuseStepLongDescription("The 'id' source is resolved to a string and used to find the macro in the project. The steps within the macro are then executed as children of the call-macro step, within the same variable scope as the parent. This means that steps within the macro have access to the same variables as the caller.") @MuseSubsourceDescriptor(displayName = "Macro name", description = "The name (resource id) of the macro to call", type = SubsourceDescriptor.Type.Named, name = CallMacroStep.ID_PARAM) public class CallMacroStep extends ScopedGroup { @SuppressWarnings("unused") // called via reflection public CallMacroStep(StepConfiguration config, MuseProject project) { super(config, project); _config = config; _project = project; } @Override protected StepExecutionContext createStepExecutionContextForChildren(StepExecutionContext context) throws MuseExecutionError { String id = getStepsId(context); ContainsStep resource = _project.getResourceStorage().getResource(id, ContainsStep.class); if (resource == null) throw new StepExecutionError("unable to locate project resource, id=" + id); StepConfiguration step = resource.getStep(); List<StepConfiguration> steps; if (step.getChildren() != null && step.getChildren().size() > 0) steps = step.getChildren(); else { steps = new ArrayList<>(); steps.add(step); } context.getStepLocator().loadSteps(steps); context.raiseEvent(DynamicStepLoadingEventType.create(_config, steps)); return new ListOfStepsExecutionContext(context.getParent(), steps, isCreateNewVariableScope(), this); } /** * Get the id of the project resource that contains the steps that should be run. */ @NotNull @SuppressWarnings("WeakerAccess") protected String getStepsId(StepExecutionContext context) throws MuseExecutionError { MuseValueSource id_source = getValueSource(_config, ID_PARAM, true, context.getProject()); return BaseValueSource.getValue(id_source, context, false, String.class); } @Override protected boolean isCreateNewVariableScope() { return false; } protected MuseProject _project; private StepConfiguration _config; public final static String ID_PARAM = "id"; public final static String TYPE_ID = CallMacroStep.class.getAnnotation(MuseTypeId.class).value(); }
Java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.diff.impl.patch.formove; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diff.impl.patch.FilePatch; import com.intellij.openapi.diff.impl.patch.TextFilePatch; import com.intellij.openapi.diff.impl.patch.apply.ApplyFilePatchBase; import com.intellij.openapi.diff.impl.patch.apply.ApplyFilePatchFactory; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.fileTypes.ex.FileTypeChooser; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.patch.RelativePathCalculator; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.*; public class PathsVerifier { // in private final Project myProject; private final VirtualFile myBaseDirectory; private final List<FilePatch> myPatches; // temp private final Map<VirtualFile, MovedFileData> myMovedFiles; private final List<FilePath> myBeforePaths; private final List<VirtualFile> myCreatedDirectories; // out private final List<PatchAndFile> myTextPatches; private final List<PatchAndFile> myBinaryPatches; @NotNull private final List<VirtualFile> myWritableFiles; private final ProjectLevelVcsManager myVcsManager; private final List<FilePatch> mySkipped; private DelayedPrecheckContext myDelayedPrecheckContext; private final List<FilePath> myAddedPaths; private final List<FilePath> myDeletedPaths; private boolean myIgnoreContentRootsCheck; public PathsVerifier(@NotNull Project project, @NotNull VirtualFile baseDirectory, @NotNull List<FilePatch> patches) { myProject = project; myBaseDirectory = baseDirectory; myPatches = patches; myMovedFiles = new HashMap<>(); myBeforePaths = new ArrayList<>(); myCreatedDirectories = new ArrayList<>(); myTextPatches = new ArrayList<>(); myBinaryPatches = new ArrayList<>(); myWritableFiles = new ArrayList<>(); myVcsManager = ProjectLevelVcsManager.getInstance(myProject); mySkipped = new ArrayList<>(); myAddedPaths = new ArrayList<>(); myDeletedPaths = new ArrayList<>(); } // those to be moved to CL: target + created dirs public List<FilePath> getDirectlyAffected() { final List<FilePath> affected = new ArrayList<>(); addAllFilePath(myCreatedDirectories, affected); addAllFilePath(myWritableFiles, affected); affected.addAll(myBeforePaths); return affected; } // old parents of moved files public List<VirtualFile> getAllAffected() { final List<VirtualFile> affected = new ArrayList<>(); affected.addAll(myCreatedDirectories); affected.addAll(myWritableFiles); // after files' parent for (VirtualFile file : myMovedFiles.keySet()) { final VirtualFile parent = file.getParent(); if (parent != null) { affected.add(parent); } } // before.. for (FilePath path : myBeforePaths) { final FilePath parent = path.getParentPath(); if (parent != null) { affected.add(parent.getVirtualFile()); } } return affected; } private static void addAllFilePath(final Collection<VirtualFile> files, final Collection<FilePath> paths) { for (VirtualFile file : files) { paths.add(VcsUtil.getFilePath(file)); } } @CalledInAwt public List<FilePatch> nonWriteActionPreCheck() { List<FilePatch> failedToApply = ContainerUtil.newArrayList(); myDelayedPrecheckContext = new DelayedPrecheckContext(myProject); for (FilePatch patch : myPatches) { final CheckPath checker = getChecker(patch); if (!checker.canBeApplied(myDelayedPrecheckContext)) { revert(checker.getErrorMessage()); failedToApply.add(patch); } } final Collection<FilePatch> skipped = myDelayedPrecheckContext.doDelayed(); mySkipped.addAll(skipped); myPatches.removeAll(skipped); myPatches.removeAll(failedToApply); return failedToApply; } public List<FilePatch> getSkipped() { return mySkipped; } public List<FilePatch> execute() { List<FilePatch> failedPatches = ContainerUtil.newArrayList(); try { final List<CheckPath> checkers = new ArrayList<>(myPatches.size()); for (FilePatch patch : myPatches) { final CheckPath checker = getChecker(patch); checkers.add(checker); } for (CheckPath checker : checkers) { if (!checker.check()) { failedPatches.add(checker.getPatch()); revert(checker.getErrorMessage()); } } } catch (IOException e) { revert(e.getMessage()); } myPatches.removeAll(failedPatches); return failedPatches; } private CheckPath getChecker(final FilePatch patch) { final String beforeFileName = patch.getBeforeName(); final String afterFileName = patch.getAfterName(); if (beforeFileName == null || patch.isNewFile()) { return new CheckAdded(patch); } else if (afterFileName == null || patch.isDeletedFile()) { return new CheckDeleted(patch); } else if (!beforeFileName.equals(afterFileName)) { return new CheckMoved(patch); } else { return new CheckModified(patch); } } public Collection<FilePath> getToBeAdded() { return myAddedPaths; } public Collection<FilePath> getToBeDeleted() { return myDeletedPaths; } @NotNull public Collection<FilePatch> filterBadFileTypePatches() { List<PatchAndFile> failedTextPatches = ContainerUtil.findAll(myTextPatches, textPatch -> !isFileTypeOk(textPatch.getFile())); myTextPatches.removeAll(failedTextPatches); return ContainerUtil.map(failedTextPatches, patchInfo -> patchInfo.getApplyPatch().getPatch()); } private boolean isFileTypeOk(@NotNull VirtualFile file) { if (file.isDirectory()) { PatchApplier .showError(myProject, "Cannot apply content for " + file.getPresentableName() + " file from patch because it is directory."); return false; } FileType fileType = file.getFileType(); if (fileType == FileTypes.UNKNOWN) { fileType = FileTypeChooser.associateFileType(file.getName()); if (fileType == null) { PatchApplier .showError(myProject, "Cannot apply content for " + file.getPresentableName() + " file from patch because its type not defined."); return false; } } if (fileType.isBinary()) { PatchApplier.showError(myProject, "Cannot apply file " + file.getPresentableName() + " from patch because it is binary."); return false; } return true; } private class CheckModified extends CheckDeleted { private CheckModified(final FilePatch path) { super(path); } } private class CheckDeleted extends CheckPath { protected CheckDeleted(final FilePatch path) { super(path); } @Override protected boolean precheck(final VirtualFile beforeFile, final VirtualFile afterFile, DelayedPrecheckContext context) { if (beforeFile == null) { context.addSkip(getMappedFilePath(myBeforeName), myPatch); } return true; } @Override protected boolean check() { final VirtualFile beforeFile = getMappedFile(myBeforeName); if (! checkExistsAndValid(beforeFile, myBeforeName)) { return false; } addPatch(myPatch, beforeFile); FilePath filePath = VcsUtil.getFilePath(beforeFile.getParent(), beforeFile.getName(), beforeFile.isDirectory()); if (myPatch.isDeletedFile() || myPatch.getAfterName() == null) { myDeletedPaths.add(filePath); } myBeforePaths.add(filePath); return true; } } private class CheckAdded extends CheckPath { private CheckAdded(final FilePatch path) { super(path); } @Override protected boolean precheck(final VirtualFile beforeFile, final VirtualFile afterFile, DelayedPrecheckContext context) { if (afterFile != null) { context.addOverrideExisting(myPatch, VcsUtil.getFilePath(afterFile)); } return true; } @Override public boolean check() throws IOException { final String[] pieces = RelativePathCalculator.split(myAfterName); final VirtualFile parent = makeSureParentPathExists(pieces); if (parent == null) { setErrorMessage(fileNotFoundMessage(myAfterName)); return false; } String name = pieces[pieces.length - 1]; File afterFile = new File(parent.getPath(), name); //if user already accepted overwriting, we shouldn't have created a new one final VirtualFile file = myDelayedPrecheckContext.getOverridenPaths().contains(VcsUtil.getFilePath(afterFile)) ? parent.findChild(name) : createFile(parent, name); if (file == null) { setErrorMessage(fileNotFoundMessage(myAfterName)); return false; } myAddedPaths.add(VcsUtil.getFilePath(file)); if (! checkExistsAndValid(file, myAfterName)) { return false; } addPatch(myPatch, file); return true; } } private class CheckMoved extends CheckPath { private CheckMoved(final FilePatch path) { super(path); } // before exists; after does not exist @Override protected boolean precheck(final VirtualFile beforeFile, final VirtualFile afterFile, final DelayedPrecheckContext context) { if (beforeFile == null) { setErrorMessage(fileNotFoundMessage(myBeforeName)); } else if (afterFile != null) { setErrorMessage(fileAlreadyExists(afterFile.getPath())); } return beforeFile != null && afterFile == null; } @Override public boolean check() throws IOException { final String[] pieces = RelativePathCalculator.split(myAfterName); final VirtualFile afterFileParent = makeSureParentPathExists(pieces); if (afterFileParent == null) { setErrorMessage(fileNotFoundMessage(myAfterName)); return false; } final VirtualFile beforeFile = getMappedFile(myBeforeName); if (! checkExistsAndValid(beforeFile, myBeforeName)) { return false; } assert beforeFile != null; // if beforeFile is null then checkExist returned false; myMovedFiles.put(beforeFile, new MovedFileData(afterFileParent, beforeFile, myPatch.getAfterFileName())); addPatch(myPatch, beforeFile); return true; } } private abstract class CheckPath { protected final String myBeforeName; protected final String myAfterName; protected final FilePatch myPatch; private String myErrorMessage; CheckPath(final FilePatch path) { myPatch = path; myBeforeName = path.getBeforeName(); myAfterName = path.getAfterName(); } public String getErrorMessage() { return myErrorMessage; } public void setErrorMessage(final String errorMessage) { myErrorMessage = errorMessage; } public boolean canBeApplied(DelayedPrecheckContext context) { final VirtualFile beforeFile = getMappedFile(myBeforeName); final VirtualFile afterFile = getMappedFile(myAfterName); return precheck(beforeFile, afterFile, context); } protected abstract boolean precheck(final VirtualFile beforeFile, final VirtualFile afterFile, DelayedPrecheckContext context); protected abstract boolean check() throws IOException; protected boolean checkExistsAndValid(final VirtualFile file, final String name) { if (file == null) { setErrorMessage(fileNotFoundMessage(name)); return false; } return checkModificationValid(file, name); } protected boolean checkModificationValid(final VirtualFile file, final String name) { if (ApplicationManager.getApplication().isUnitTestMode() && myIgnoreContentRootsCheck) return true; // security check to avoid overwriting system files with a patch if (file == null || !inContent(file) || myVcsManager.getVcsRootFor(file) == null) { setErrorMessage("File to patch found outside content root: " + name); return false; } return true; } @Nullable protected VirtualFile getMappedFile(String path) { return PathMerger.getFile(myBaseDirectory, path); } protected FilePath getMappedFilePath(String path) { return PathMerger.getFile(VcsUtil.getFilePath(myBaseDirectory), path); } private boolean inContent(VirtualFile file) { return myVcsManager.isFileInContent(file); } public FilePatch getPatch() { return myPatch; } } private void addPatch(final FilePatch patch, final VirtualFile file) { if (patch instanceof TextFilePatch) { myTextPatches.add(new PatchAndFile(file, ApplyFilePatchFactory.create((TextFilePatch)patch))); } else { myBinaryPatches.add(new PatchAndFile(file, ApplyFilePatchFactory.createGeneral(patch))); } myWritableFiles.add(file); } private static String fileNotFoundMessage(final String path) { return VcsBundle.message("cannot.find.file.to.patch", path); } private static String fileAlreadyExists(final String path) { return VcsBundle.message("cannot.apply.file.already.exists", path); } private void revert(final String errorMessage) { PatchApplier.showError(myProject, errorMessage); // move back /*for (MovedFileData movedFile : myMovedFiles) { try { final VirtualFile current = movedFile.getCurrent(); final VirtualFile newParent = current.getParent(); final VirtualFile file; if (! Comparing.equal(newParent, movedFile.getOldParent())) { file = moveFile(current, movedFile.getOldParent()); } else { file = current; } if (! Comparing.equal(current.getName(), movedFile.getOldName())) { file.rename(PatchApplier.class, movedFile.getOldName()); } } catch (IOException e) { // ignore: revert as much as possible } } // go back ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { for (int i = myCreatedDirectories.size() - 1; i >= 0; -- i) { final VirtualFile file = myCreatedDirectories.get(i); try { file.delete(PatchApplier.class); } catch (IOException e) { // ignore } } } }); myBinaryPatches.clear(); myTextPatches.clear(); myWritableFiles.clear();*/ } private static VirtualFile createFile(final VirtualFile parent, final String name) throws IOException { return parent.createChildData(PatchApplier.class, name); /*final Ref<IOException> ioExceptionRef = new Ref<IOException>(); final Ref<VirtualFile> result = new Ref<VirtualFile>(); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { result.set(parent.createChildData(PatchApplier.class, name)); } catch (IOException e) { ioExceptionRef.set(e); } } }); if (! ioExceptionRef.isNull()) { throw ioExceptionRef.get(); } return result.get();*/ } private static VirtualFile moveFile(final VirtualFile file, final VirtualFile newParent) throws IOException { file.move(FilePatch.class, newParent); return file; /*final Ref<IOException> ioExceptionRef = new Ref<IOException>(); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { file.move(FilePatch.class, newParent); } catch (IOException e) { ioExceptionRef.set(e); } } }); if (! ioExceptionRef.isNull()) { throw ioExceptionRef.get(); } return file;*/ } @Nullable private VirtualFile makeSureParentPathExists(final String[] pieces) throws IOException { VirtualFile child = myBaseDirectory; final int size = pieces.length - 1; for (int i = 0; i < size; i++) { final String piece = pieces[i]; if (StringUtil.isEmptyOrSpaces(piece)) { continue; } if ("..".equals(piece)) { child = child.getParent(); continue; } VirtualFile nextChild = child.findChild(piece); if (nextChild == null) { nextChild = VfsUtil.createDirectories(child.getPath() + '/' + piece); myCreatedDirectories.add(nextChild); } child = nextChild; } return child; } public List<PatchAndFile> getTextPatches() { return myTextPatches; } public List<PatchAndFile> getBinaryPatches() { return myBinaryPatches; } @NotNull public List<VirtualFile> getWritableFiles() { return myWritableFiles; } public void doMoveIfNeeded(final VirtualFile file) throws IOException { final MovedFileData movedFile = myMovedFiles.get(file); if (movedFile != null) { myBeforePaths.add(VcsUtil.getFilePath(file)); ApplicationManager.getApplication().runWriteAction(new ThrowableComputable<VirtualFile, IOException>() { @Override public VirtualFile compute() throws IOException { return movedFile.doMove(); } }); } } private static class MovedFileData { private final VirtualFile myNewParent; private final VirtualFile myCurrent; private final String myNewName; private MovedFileData(@NotNull final VirtualFile newParent, @NotNull final VirtualFile current, @NotNull final String newName) { myNewParent = newParent; myCurrent = current; myNewName = newName; } public VirtualFile getCurrent() { return myCurrent; } public VirtualFile getNewParent() { return myNewParent; } public String getNewName() { return myNewName; } public VirtualFile doMove() throws IOException { final VirtualFile oldParent = myCurrent.getParent(); boolean needRename = !Comparing.equal(myCurrent.getName(), myNewName); boolean needMove = !myNewParent.equals(oldParent); if (needRename) { if (needMove) { File oldParentFile = VfsUtilCore.virtualToIoFile(oldParent); File targetAfterRenameFile = new File(oldParentFile, myNewName); if (targetAfterRenameFile.exists() && myCurrent.exists()) { // if there is a conflict during first rename we have to rename to third name, then move, then rename to final target performRenameWithConflicts(oldParentFile); return myCurrent; } } myCurrent.rename(PatchApplier.class, myNewName); } if (needMove) { myCurrent.move(PatchApplier.class, myNewParent); } return myCurrent; } private void performRenameWithConflicts(@NotNull File oldParent) throws IOException { File tmpFileWithUniqueName = FileUtil.createTempFile(oldParent, "tempFileToMove", null, false); File newParentFile = VfsUtilCore.virtualToIoFile(myNewParent); File destFile = new File(newParentFile, tmpFileWithUniqueName.getName()); while (destFile.exists()) { destFile = new File(newParentFile, FileUtil.createTempFile(oldParent, FileUtil.getNameWithoutExtension(destFile.getName()), null, false) .getName()); } myCurrent.rename(PatchApplier.class, destFile.getName()); myCurrent.move(PatchApplier.class, myNewParent); myCurrent.rename(PatchApplier.class, myNewName); } } private static class DelayedPrecheckContext { private final Map<FilePath, FilePatch> mySkipDeleted; private final Map<FilePath, FilePatch> myOverrideExisting; private final List<FilePath> myOverridenPaths; private final Project myProject; private DelayedPrecheckContext(final Project project) { myProject = project; myOverrideExisting = new HashMap<>(); mySkipDeleted = new HashMap<>(); myOverridenPaths = new LinkedList<>(); } public void addSkip(final FilePath path, final FilePatch filePatch) { mySkipDeleted.put(path, filePatch); } public void addOverrideExisting(final FilePatch patch, final FilePath filePath) { if (! myOverrideExisting.containsKey(filePath)) { myOverrideExisting.put(filePath, patch); } } // returns those to be skipped public Collection<FilePatch> doDelayed() { final List<FilePatch> result = new LinkedList<>(); if (! myOverrideExisting.isEmpty()) { final String title = "Overwrite Existing Files"; List<FilePath> files = new ArrayList<>(myOverrideExisting.keySet()); Collection<FilePath> selected = AbstractVcsHelper.getInstance(myProject).selectFilePathsToProcess( files, title, "\nThe following files should be created by patch, but they already exist.\nDo you want to overwrite them?\n", title, "The following file should be created by patch, but it already exists.\nDo you want to overwrite it?\n{0}", VcsShowConfirmationOption.STATIC_SHOW_CONFIRMATION, "Overwrite", "Cancel"); if (selected != null) { for (FilePath path : selected) { myOverrideExisting.remove(path); } } result.addAll(myOverrideExisting.values()); if (selected != null) { myOverridenPaths.addAll(selected); } } result.addAll(mySkipDeleted.values()); return result; } public List<FilePath> getOverridenPaths() { return myOverridenPaths; } public Collection<FilePath> getAlreadyDeletedPaths() { return mySkipDeleted.keySet(); } } public void setIgnoreContentRootsCheck(boolean ignoreContentRootsCheck) { myIgnoreContentRootsCheck = ignoreContentRootsCheck; } public static class PatchAndFile { private final VirtualFile myFile; private final ApplyFilePatchBase<?> myPatch; public PatchAndFile(VirtualFile file, ApplyFilePatchBase<?> patch) { myFile = file; myPatch = patch; } public VirtualFile getFile() { return myFile; } public ApplyFilePatchBase<?> getApplyPatch() { return myPatch; } } }
Java
f- == fő
Java
package com.therabbitmage.android.beacon.network; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URISyntaxException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.message.BasicHeader; import android.net.Uri; import android.util.Log; import com.therabbitmage.android.beacon.entities.google.urlshortener.Url; public final class URLShortenerAPI { private static final String TAG = URLShortenerAPI.class.getSimpleName(); private static final String BASE_URL = "https://www.googleapis.com/urlshortener/v1/url"; public static NetworkResponse urlShorten(String url) throws IOException, URISyntaxException{ android.net.Uri.Builder uriBuilder = Uri.parse(BASE_URL).buildUpon(); String uri = uriBuilder.build().toString(); Header[] headers = new Header[1]; headers[0] = new BasicHeader(ApacheNetworkUtils.HEADER_CONTENT_TYPE, ApacheNetworkUtils.TYPE_JSON); ApacheNetworkUtils.getAndroidInstance(ApacheNetworkUtils.sUserAgent, false); HttpResponse response = ApacheNetworkUtils.post( uri, ApacheNetworkUtils.getDefaultApacheHeaders(), new Url(url).toJson()); ApacheNetworkUtils.toStringResponseHeaders(response.getAllHeaders()); ApacheNetworkUtils.toStringStatusLine(response.getStatusLine()); HttpEntity entity = response.getEntity(); NetworkResponse networkResponse = new NetworkResponse(); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ networkResponse.setError(0); BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuilder stringBuilder = new StringBuilder(); String output = new String(); while((output = br.readLine()) != null){ stringBuilder.append(output); } br.close(); Log.i(TAG, "Body: " + stringBuilder.toString()); networkResponse.setUrl(Url.fromJson(stringBuilder.toString())); } else { networkResponse.setError(1); } return networkResponse; } }
Java
#include "common/common/version.h" std::string VersionInfo::version() { return fmt::format("{}/{}", GIT_SHA.substr(0, 6), #ifdef NDEBUG "RELEASE" #else "DEBUG" #endif ); }
Java
/** * Copyright (c) 2015 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 com.github.jmnarloch.spring.jaxrs.client.support; import org.junit.Before; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import javax.ws.rs.ext.Provider; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; /** * Tests the {@link JaxRsClientProxyFactorySupport} class. * * @author Jakub Narloch */ public class JaxRsClientProxyFactorySupportTest { /** * The instance of the tested class. */ private JaxRsClientProxyFactorySupport instance; /** * Sets up the test environment. * * @throws Exception if any error occurs */ @Before public void setUp() throws Exception { instance = new MockJaxRsClientProxyFactorySupport(); } @Test public void shouldRetrieveProviders() { // given final List<JaxRsClientConfigurer> configurers = Arrays.asList( mock(JaxRsClientConfigurer.class), mock(JaxRsClientConfigurer.class) ); for(JaxRsClientConfigurer conf : configurers) { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { ((ProviderRegistry)invocation.getArguments()[0]).addProvider(SimpleProvider.class); return null; } }).when(conf).registerProviders(any(ProviderRegistry.class)); } instance.setConfigurers(configurers); // when Class<?>[] providers = instance.getProviders(); // then assertNotNull(providers); assertEquals(2, providers.length); } private static class MockJaxRsClientProxyFactorySupport extends JaxRsClientProxyFactorySupport { @Override public <T> T createClientProxy(Class<T> serviceClass, String serviceUrl) { return null; } } /** * A simple provider class used for testing. * * @author Jakub Narloch */ @Provider private static class SimpleProvider { } }
Java
#!/bin/bash #crosscontaminate in=<file,file,...> out=<file,file,...> usage(){ echo " Written by Brian Bushnell Last modified February 17, 2015 Description: Generates synthetic cross-contaminated files from clean files. Intended for use with synthetic reads generated by SynthMDA or RandomReads. Usage: crosscontaminate.sh in=<file,file,...> out=<file,file,...> Parameters and their defaults: Input parameters: in=<file,file,...> Clean input reads. innamefile=<file> A file containing the names of input files, one name per line. interleaved=auto (int) t/f overrides interleaved autodetection. qin=auto Input quality offset: 33 (Sanger), 64, or auto. reads=-1 If positive, quit after processing X reads or pairs. Processing Parameters: minsinks=1 Min contamination destinations from one source. maxsinks=8 Max contamination destinations from one source. minprob=0.000005 Min allowed contamination rate (geometric distribution). maxprob=0.025 Max allowed contamination rate. Output parameters: out=<file,file,...> Contaminated output reads. outnamefile=<file> A file containing the names of output files, one name per line. overwrite=t (ow) Grant permission to overwrite files. #showspeed=t (ss) 'f' suppresses display of processing speed. ziplevel=2 (zl) Compression level; 1 (min) through 9 (max). threads=auto (t) Set number of threads to use; default is number of logical processors. qout=auto Output quality offset: 33 (Sanger), 64, or auto. shuffle=f Shuffle contents of output files. shufflethreads=3 Use this many threads for shuffling (requires more memory). Java Parameters: -Xmx This will be passed to Java to set memory usage, overriding the program's automatic memory detection. -Xmx20g will specify 20 gigs of RAM, and -Xmx200m will specify 200 megs. The max is typically 85% of physical memory. There is a changelog at docs/changelog_crosscontaminate.txt Please contact Brian Bushnell at bbushnell@lbl.gov if you encounter any problems. " } pushd . > /dev/null DIR="${BASH_SOURCE[0]}" while [ -h "$DIR" ]; do cd "$(dirname "$DIR")" DIR="$(readlink "$(basename "$DIR")")" done cd "$(dirname "$DIR")" DIR="$(pwd)/" popd > /dev/null #DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/" CP="$DIR""current/" z="-Xmx4g" z2="-Xms4g" EA="-ea" set=0 if [ -z "$1" ] || [[ $1 == -h ]] || [[ $1 == --help ]]; then usage exit fi calcXmx () { source "$DIR""/calcmem.sh" parseXmx "$@" if [[ $set == 1 ]]; then return fi freeRam 4000m 42 z="-Xmx${RAM}m" } calcXmx "$@" crosscontaminate() { #module unload oracle-jdk #module load oracle-jdk/1.7_64bit #module load pigz local CMD="java $EA $z -cp $CP jgi.CrossContaminate $@" echo $CMD >&2 eval $CMD } crosscontaminate "$@"
Java
# Stylonychia dupla Dumas SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
/* Copyright (c) 2012 Marco Amadei. 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 net.ucanaccess.test; import java.sql.Connection; import com.healthmarketscience.jackcess.Database.FileFormat; public class PasswordTest extends UcanaccessTestBase { public PasswordTest() { super(); } public PasswordTest(FileFormat accVer) { super(accVer); } public String getAccessPath() { return "net/ucanaccess/test/resources/pwd.mdb"; } protected void setUp() throws Exception {} public void testPassword() throws Exception { Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); Connection ucanaccessConnection = null; try { ucanaccessConnection = getUcanaccessConnection(); } catch (Exception e) { } assertNull(ucanaccessConnection); super.setPassword("ucanaccess"); //url will be try { ucanaccessConnection = getUcanaccessConnection(); } catch (Exception e) { e.printStackTrace(); } assertNotNull(ucanaccessConnection); } }
Java
# Parmularia novomexicana B. de Lesd. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Parmularia novomexicana B. de Lesd. ### Remarks null
Java
<?php /*! * @mainpage Configuration * * @section intro Introduction * * You can create file <b>application/config.php</b> for configuration. * * @section intro Configuration items * * @subsection encryptor Encrypt * For NpFactory::getEncryptor, $_CONFIG['encryptor'] * @param mode encrypt mode, support aes, 3des; default aes * @param password password, length limit: min 7, max 32 for aes and 16 for 3des * @param timeout seconds for expire time, default 0 (forever) * * @subsection database Database * For NpFactory::getDatabase, $_CONFIG['database'] * @param type database type for PDO, default mysql * @param host host or ip address for connect, default localhost * @param port port for connect, default 3306 * @param user username for connect, default root * @param passwd password for connect, default empty * @param dbname database name for connect, default mysql * @param charset charset for connect, default utf8 * @param persistent persistent for connect, default true * * For NpFactory::getExtraDatabase, $_CONFIG's key is 'database-' append extra name. * * @subsection cache Key-Value Cache * For NpFactory::getCache, $_CONFIG['cache'] * @param type cache type, support memcache,memcached,redis; default memcache * @param host host or ip address for connect, default localhost * @param port port for connect, default 11211 * @param prefix prefix append for keys, default empty * @param timeout seconds for expire time, default 0 (forever) * * For NpFactory::getExtraCache, $_CONFIG's key is 'cache-' append extra name. * * @subsection system Environment * For Framework environment, $_CONFIG['system'] * @param quiet error reporting level switch, true is E_ERROR | E_PARSE, flase is E_ALL ^ E_NOTICE, default false * @param timeZone date's default time zone, default UTC */ //! The class for configs class NpConfig { private static $configs; private static function load() { if(!defined('NP_CONF_PATH')) define('NP_CONF_PATH', NP_APP_PATH); $_CONFIG=array(); // encryptor $config=array(); $config['mode'] = 'aes'; // as: aes(32), 3des(16) $config['password'] = 'b5ee4d5b4f59451431081b0246c57c7b'; $config['timeout'] = 0; // seconds $_CONFIG['encryptor']=$config; // database $config=array(); $config['type'] = 'mysql'; $config['host'] = 'localhost'; $config['port'] = 3306; $config['user'] = 'root'; $config['passwd'] = ''; $config['dbname'] = 'mysql'; $config['charset'] = 'utf8'; $config['persistent'] = true; $_CONFIG['database']=$config; // cache $config=array(); $config['type'] = 'memcache'; $config['host'] = 'localhost'; $config['port'] = 11211; $config['prefix'] = ''; $config['timeout'] = 0; // seconds $_CONFIG['cache']=$config; // system $config=array(); $config['quiet'] = false; $config['timeZone'] = 'UTC'; $_CONFIG['system']=$config; // load application config @include(NP_CONF_PATH.'config.php'); // apply values to setting if($_CONFIG['system']['quiet']===true) error_reporting(E_ERROR | E_PARSE); else error_reporting(E_ALL ^ E_NOTICE); date_default_timezone_set($_CONFIG['system']['timeZone']); self::$configs=$_CONFIG; } //! Get a config item object public static function get($key) { if(self::$configs===null) self::load(); if(!isset(self::$configs[$key])) throw new Exception('Not found config item:'.$key); return self::$configs[$key]; } } ?>
Java
/* $Header: /cvs/maptools/cvsroot/libtiff/contrib/pds/tif_pdsdirread.c,v 1.2 2003/11/17 15:09:39 dron Exp $ */ /* * Copyright (c) 1988-1996 Sam Leffler * Copyright (c) 1991-1996 Silicon Graphics, Inc. * Copyright (c( 1996 USAF Phillips Laboratory * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * These routines written by Conrad J. Poelman on a single late-night of * March 20-21, 1996. * * The entire purpose of this file is to provide a single external function, * TIFFReadPrivateDataSubDirectory(). This function is intended for use in reading a * private subdirectory from a TIFF file into a private structure. The * actual writing of data into the structure is handled by the setFieldFn(), * which is passed to TIFFReadPrivateDataSubDirectory() as a parameter. The idea is to * enable any application wishing to store private subdirectories to do so * easily using this function, without modifying the TIFF library. * * The astute observer will notice that only two functions are at all different * from the original tif_dirread.c file: TIFFReadPrivateDataSubDirectory() and * TIFFFetchNormalSubTag(). All the other stuff that makes this file so huge * is only necessary because all of those functions are declared static in * tif_dirread.c, so we have to totally duplicate them in order to use them. * * Oh, also note the bug fix in TIFFFetchFloat(). * */ #include "tiffiop.h" #define IGNORE 0 /* tag placeholder used below */ #if HAVE_IEEEFP #define TIFFCvtIEEEFloatToNative(tif, n, fp) #define TIFFCvtIEEEDoubleToNative(tif, n, dp) #else extern void TIFFCvtIEEEFloatToNative(TIFF*, uint32, float*); extern void TIFFCvtIEEEDoubleToNative(TIFF*, uint32, double*); #endif static void EstimateStripByteCounts(TIFF*, TIFFDirEntry*, uint16); static void MissingRequired(TIFF*, const char*); static int CheckDirCount(TIFF*, TIFFDirEntry*, uint32); static tsize_t TIFFFetchData(TIFF*, TIFFDirEntry*, char*); static tsize_t TIFFFetchString(TIFF*, TIFFDirEntry*, char*); static float TIFFFetchRational(TIFF*, TIFFDirEntry*); static int TIFFFetchNormalSubTag(TIFF*, TIFFDirEntry*, const TIFFFieldInfo*, int (*getFieldFn)(TIFF *tif,ttag_t tag,...)); static int TIFFFetchPerSampleShorts(TIFF*, TIFFDirEntry*, int*); static int TIFFFetchPerSampleAnys(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchShortArray(TIFF*, TIFFDirEntry*, uint16*); static int TIFFFetchStripThing(TIFF*, TIFFDirEntry*, long, uint32**); static int TIFFFetchExtraSamples(TIFF*, TIFFDirEntry*); static int TIFFFetchRefBlackWhite(TIFF*, TIFFDirEntry*); static float TIFFFetchFloat(TIFF*, TIFFDirEntry*); static int TIFFFetchFloatArray(TIFF*, TIFFDirEntry*, float*); static int TIFFFetchDoubleArray(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchAnyArray(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchShortPair(TIFF*, TIFFDirEntry*); #if STRIPCHOP_SUPPORT static void ChopUpSingleUncompressedStrip(TIFF*); #endif static char * CheckMalloc(TIFF* tif, tsize_t n, const char* what) { char *cp = (char*)_TIFFmalloc(n); if (cp == NULL) TIFFError(tif->tif_name, "No space %s", what); return (cp); } /* Just as was done with TIFFWritePrivateDataSubDirectory(), here we implement TIFFReadPrivateDataSubDirectory() which takes an offset into the TIFF file, a TIFFFieldInfo structure specifying the types of the various tags, and a function to use to set individual tags when they are encountered. The data is read from the file, translated using the TIFF library's built-in machine-independent conversion functions, and filled into private subdirectory structure. This code was written by copying the original TIFFReadDirectory() function from tif_dirread.c and paring it down to what is needed for this. It is the caller's responsibility to allocate and initialize the internal structure that setFieldFn() will be writing into. If this function is being called more than once before closing the file, the caller also must be careful to free data in the structure before re-initializing. It is also the caller's responsibility to verify the presence of any required fields after reading the directory in. */ int TIFFReadPrivateDataSubDirectory(TIFF* tif, toff_t pdir_offset, TIFFFieldInfo *field_info, int (*setFieldFn)(TIFF *tif, ttag_t tag, ...)) { register TIFFDirEntry* dp; register int n; register TIFFDirectory* td; TIFFDirEntry* dir; int iv; long v; double dv; const TIFFFieldInfo* fip; int fix; uint16 dircount; uint32 nextdiroff; char* cp; int diroutoforderwarning = 0; /* Skipped part about checking for directories or compression data. */ if (!isMapped(tif)) { if (!SeekOK(tif, pdir_offset)) { TIFFError(tif->tif_name, "Seek error accessing TIFF private subdirectory"); return (0); } if (!ReadOK(tif, &dircount, sizeof (uint16))) { TIFFError(tif->tif_name, "Can not read TIFF private subdirectory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)CheckMalloc(tif, dircount * sizeof (TIFFDirEntry), "to read TIFF private subdirectory"); if (dir == NULL) return (0); if (!ReadOK(tif, dir, dircount*sizeof (TIFFDirEntry))) { TIFFError(tif->tif_name, "Can not read TIFF private subdirectory"); goto bad; } /* * Read offset to next directory for sequential scans. */ (void) ReadOK(tif, &nextdiroff, sizeof (uint32)); } else { toff_t off = pdir_offset; if (off + sizeof (short) > tif->tif_size) { TIFFError(tif->tif_name, "Can not read TIFF private subdirectory count"); return (0); } else _TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16)); off += sizeof (uint16); if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)CheckMalloc(tif, dircount * sizeof (TIFFDirEntry), "to read TIFF private subdirectory"); if (dir == NULL) return (0); if (off + dircount*sizeof (TIFFDirEntry) > tif->tif_size) { TIFFError(tif->tif_name, "Can not read TIFF private subdirectory"); goto bad; } else _TIFFmemcpy(dir, tif->tif_base + off, dircount*sizeof (TIFFDirEntry)); off += dircount* sizeof (TIFFDirEntry); if (off + sizeof (uint32) < tif->tif_size) _TIFFmemcpy(&nextdiroff, tif->tif_base+off, sizeof (uint32)); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextdiroff); /* * Setup default value and then make a pass over * the fields to check type and tag information, * and to extract info required to size data * structures. A second pass is made afterwards * to read in everthing not taken in the first pass. */ td = &tif->tif_dir; for (fip = field_info, dp = dir, n = dircount; n > 0; n--, dp++) { if (tif->tif_flags & TIFF_SWAB) { TIFFSwabArrayOfShort(&dp->tdir_tag, 2); TIFFSwabArrayOfLong(&dp->tdir_count, 2); } /* * Find the field information entry for this tag. */ /* * Silicon Beach (at least) writes unordered * directory tags (violating the spec). Handle * it here, but be obnoxious (maybe they'll fix it?). */ if (dp->tdir_tag < fip->field_tag) { if (!diroutoforderwarning) { TIFFWarning(tif->tif_name, "invalid TIFF private subdirectory; tags are not sorted in ascending order"); diroutoforderwarning = 1; } fip = field_info; /* O(n^2) */ } while (fip->field_tag && fip->field_tag < dp->tdir_tag) fip++; if (!fip->field_tag || fip->field_tag != dp->tdir_tag) { TIFFWarning(tif->tif_name, "unknown field with tag %d (0x%x) in private subdirectory ignored", dp->tdir_tag, dp->tdir_tag); dp->tdir_tag = IGNORE; fip = field_info;/* restart search */ continue; } /* * Null out old tags that we ignore. */ /* Not implemented yet, since FIELD_IGNORE is specific to the main directories. Could pass this in too... */ if (0 /* && fip->field_bit == FIELD_IGNORE */) { ignore: dp->tdir_tag = IGNORE; continue; } /* * Check data type. */ while (dp->tdir_type != (u_short)fip->field_type) { if (fip->field_type == TIFF_ANY) /* wildcard */ break; fip++; if (!fip->field_tag || fip->field_tag != dp->tdir_tag) { TIFFWarning(tif->tif_name, "wrong data type %d for \"%s\"; tag ignored", dp->tdir_type, fip[-1].field_name); goto ignore; } } /* * Check count if known in advance. */ if (fip->field_readcount != TIFF_VARIABLE) { uint32 expected = (fip->field_readcount == TIFF_SPP) ? (uint32) td->td_samplesperpixel : (uint32) fip->field_readcount; if (!CheckDirCount(tif, dp, expected)) goto ignore; } /* Now read in and process data from field. */ if (!TIFFFetchNormalSubTag(tif, dp, fip, setFieldFn)) goto bad; } if (dir) _TIFFfree(dir); return (1); bad: if (dir) _TIFFfree(dir); return (0); } static void EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount) { register TIFFDirEntry *dp; register TIFFDirectory *td = &tif->tif_dir; uint16 i; if (td->td_stripbytecount) _TIFFfree(td->td_stripbytecount); td->td_stripbytecount = (uint32*) CheckMalloc(tif, td->td_nstrips * sizeof (uint32), "for \"StripByteCounts\" array"); if (td->td_compression != COMPRESSION_NONE) { uint32 space = (uint32)(sizeof (TIFFHeader) + sizeof (uint16) + (dircount * sizeof (TIFFDirEntry)) + sizeof (uint32)); toff_t filesize = TIFFGetFileSize(tif); uint16 n; /* calculate amount of space used by indirect values */ for (dp = dir, n = dircount; n > 0; n--, dp++) { uint32 cc = dp->tdir_count*TIFFDataWidth(dp->tdir_type); if (cc > sizeof (uint32)) space += cc; } space = (filesize - space) / td->td_samplesperpixel; for (i = 0; i < td->td_nstrips; i++) td->td_stripbytecount[i] = space; /* * This gross hack handles the case were the offset to * the last strip is past the place where we think the strip * should begin. Since a strip of data must be contiguous, * it's safe to assume that we've overestimated the amount * of data in the strip and trim this number back accordingly. */ i--; if (td->td_stripoffset[i] + td->td_stripbytecount[i] > filesize) td->td_stripbytecount[i] = filesize - td->td_stripoffset[i]; } else { uint32 rowbytes = TIFFScanlineSize(tif); uint32 rowsperstrip = td->td_imagelength / td->td_nstrips; for (i = 0; i < td->td_nstrips; i++) td->td_stripbytecount[i] = rowbytes*rowsperstrip; } TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS); if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP)) td->td_rowsperstrip = td->td_imagelength; } static void MissingRequired(TIFF* tif, const char* tagname) { TIFFError(tif->tif_name, "TIFF directory is missing required \"%s\" field", tagname); } /* * Check the count field of a directory * entry against a known value. The caller * is expected to skip/ignore the tag if * there is a mismatch. */ static int CheckDirCount(TIFF* tif, TIFFDirEntry* dir, uint32 count) { if (count != dir->tdir_count) { TIFFWarning(tif->tif_name, "incorrect count for field \"%s\" (%lu, expecting %lu); tag ignored", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, dir->tdir_count, count); return (0); } return (1); } /* * Fetch a contiguous directory item. */ static tsize_t TIFFFetchData(TIFF* tif, TIFFDirEntry* dir, char* cp) { int w = TIFFDataWidth(dir->tdir_type); tsize_t cc = dir->tdir_count * w; if (!isMapped(tif)) { if (!SeekOK(tif, dir->tdir_offset)) goto bad; if (!ReadOK(tif, cp, cc)) goto bad; } else { if (dir->tdir_offset + cc > tif->tif_size) goto bad; _TIFFmemcpy(cp, tif->tif_base + dir->tdir_offset, cc); } if (tif->tif_flags & TIFF_SWAB) { switch (dir->tdir_type) { case TIFF_SHORT: case TIFF_SSHORT: TIFFSwabArrayOfShort((uint16*) cp, dir->tdir_count); break; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: TIFFSwabArrayOfLong((uint32*) cp, dir->tdir_count); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: TIFFSwabArrayOfLong((uint32*) cp, 2*dir->tdir_count); break; case TIFF_DOUBLE: TIFFSwabArrayOfDouble((double*) cp, dir->tdir_count); break; } } return (cc); bad: TIFFError(tif->tif_name, "Error fetching data for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return ((tsize_t) 0); } /* * Fetch an ASCII item from the file. */ static tsize_t TIFFFetchString(TIFF* tif, TIFFDirEntry* dir, char* cp) { if (dir->tdir_count <= 4) { uint32 l = dir->tdir_offset; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&l); _TIFFmemcpy(cp, &l, dir->tdir_count); return (1); } return (TIFFFetchData(tif, dir, cp)); } /* * Convert numerator+denominator to float. */ static int cvtRational(TIFF* tif, TIFFDirEntry* dir, uint32 num, uint32 denom, float* rv) { if (denom == 0) { TIFFError(tif->tif_name, "%s: Rational with zero denominator (num = %lu)", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, num); return (0); } else { if (dir->tdir_type == TIFF_RATIONAL) *rv = ((float)num / (float)denom); else *rv = ((float)(int32)num / (float)(int32)denom); return (1); } } /* * Fetch a rational item from the file * at offset off and return the value * as a floating point number. */ static float TIFFFetchRational(TIFF* tif, TIFFDirEntry* dir) { uint32 l[2]; float v; return (!TIFFFetchData(tif, dir, (char *)l) || !cvtRational(tif, dir, l[0], l[1], &v) ? 1.0f : v); } /* * Fetch a single floating point value * from the offset field and return it * as a native float. */ static float TIFFFetchFloat(TIFF* tif, TIFFDirEntry* dir) { /* This appears to be a flagrant bug in the TIFF library, yet I actually don't understand how it could have ever worked the old way. Look at the comments in my new code and you'll understand. */ #if (0) float v = (float) TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset); TIFFCvtIEEEFloatToNative(tif, 1, &v); #else float v; /* This is a little bit tricky - if we just cast the uint32 to a float, C will perform a numerical conversion, which is not what we want. We want to take the actual bit pattern in the uint32 and interpret it as a float. Thus we cast a uint32 * into a float * and then dereference to get v. */ uint32 l = (uint32) TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset); v = * (float *) &l; TIFFCvtIEEEFloatToNative(tif, 1, &v); #endif return (v); } /* * Fetch an array of BYTE or SBYTE values. */ static int TIFFFetchByteArray(TIFF* tif, TIFFDirEntry* dir, uint16* v) { if (dir->tdir_count <= 4) { /* * Extract data from offset field. */ if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset & 0xff; case 3: v[2] = (dir->tdir_offset >> 8) & 0xff; case 2: v[1] = (dir->tdir_offset >> 16) & 0xff; case 1: v[0] = dir->tdir_offset >> 24; } } else { switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset >> 24; case 3: v[2] = (dir->tdir_offset >> 16) & 0xff; case 2: v[1] = (dir->tdir_offset >> 8) & 0xff; case 1: v[0] = dir->tdir_offset & 0xff; } } return (1); } else return (TIFFFetchData(tif, dir, (char*) v) != 0); /* XXX */ } /* * Fetch an array of SHORT or SSHORT values. */ static int TIFFFetchShortArray(TIFF* tif, TIFFDirEntry* dir, uint16* v) { if (dir->tdir_count <= 2) { if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { switch (dir->tdir_count) { case 2: v[1] = dir->tdir_offset & 0xffff; case 1: v[0] = dir->tdir_offset >> 16; } } else { switch (dir->tdir_count) { case 2: v[1] = dir->tdir_offset >> 16; case 1: v[0] = dir->tdir_offset & 0xffff; } } return (1); } else return (TIFFFetchData(tif, dir, (char *)v) != 0); } /* * Fetch a pair of SHORT or BYTE values. */ static int TIFFFetchShortPair(TIFF* tif, TIFFDirEntry* dir) { uint16 v[2]; int ok = 0; switch (dir->tdir_type) { case TIFF_SHORT: case TIFF_SSHORT: ok = TIFFFetchShortArray(tif, dir, v); break; case TIFF_BYTE: case TIFF_SBYTE: ok = TIFFFetchByteArray(tif, dir, v); break; } if (ok) TIFFSetField(tif, dir->tdir_tag, v[0], v[1]); return (ok); } /* * Fetch an array of LONG or SLONG values. */ static int TIFFFetchLongArray(TIFF* tif, TIFFDirEntry* dir, uint32* v) { if (dir->tdir_count == 1) { v[0] = dir->tdir_offset; return (1); } else return (TIFFFetchData(tif, dir, (char*) v) != 0); } /* * Fetch an array of RATIONAL or SRATIONAL values. */ static int TIFFFetchRationalArray(TIFF* tif, TIFFDirEntry* dir, float* v) { int ok = 0; uint32* l; l = (uint32*)CheckMalloc(tif, dir->tdir_count*TIFFDataWidth(dir->tdir_type), "to fetch array of rationals"); if (l) { if (TIFFFetchData(tif, dir, (char *)l)) { uint32 i; for (i = 0; i < dir->tdir_count; i++) { ok = cvtRational(tif, dir, l[2*i+0], l[2*i+1], &v[i]); if (!ok) break; } } _TIFFfree((char *)l); } return (ok); } /* * Fetch an array of FLOAT values. */ static int TIFFFetchFloatArray(TIFF* tif, TIFFDirEntry* dir, float* v) { if (dir->tdir_count == 1) { v[0] = *(float*) &dir->tdir_offset; TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); return (1); } else if (TIFFFetchData(tif, dir, (char*) v)) { TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); return (1); } else return (0); } /* * Fetch an array of DOUBLE values. */ static int TIFFFetchDoubleArray(TIFF* tif, TIFFDirEntry* dir, double* v) { if (TIFFFetchData(tif, dir, (char*) v)) { TIFFCvtIEEEDoubleToNative(tif, dir->tdir_count, v); return (1); } else return (0); } /* * Fetch an array of ANY values. The actual values are * returned as doubles which should be able hold all the * types. Yes, there really should be an tany_t to avoid * this potential non-portability ... Note in particular * that we assume that the double return value vector is * large enough to read in any fundamental type. We use * that vector as a buffer to read in the base type vector * and then convert it in place to double (from end * to front of course). */ static int TIFFFetchAnyArray(TIFF* tif, TIFFDirEntry* dir, double* v) { int i; switch (dir->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: if (!TIFFFetchByteArray(tif, dir, (uint16*) v)) return (0); if (dir->tdir_type == TIFF_BYTE) { uint16* vp = (uint16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int16* vp = (int16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_SHORT: case TIFF_SSHORT: if (!TIFFFetchShortArray(tif, dir, (uint16*) v)) return (0); if (dir->tdir_type == TIFF_SHORT) { uint16* vp = (uint16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int16* vp = (int16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_LONG: case TIFF_SLONG: if (!TIFFFetchLongArray(tif, dir, (uint32*) v)) return (0); if (dir->tdir_type == TIFF_LONG) { uint32* vp = (uint32*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int32* vp = (int32*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: if (!TIFFFetchRationalArray(tif, dir, (float*) v)) return (0); { float* vp = (float*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_FLOAT: if (!TIFFFetchFloatArray(tif, dir, (float*) v)) return (0); { float* vp = (float*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_DOUBLE: return (TIFFFetchDoubleArray(tif, dir, (double*) v)); default: /* TIFF_NOTYPE */ /* TIFF_ASCII */ /* TIFF_UNDEFINED */ TIFFError(tif->tif_name, "Cannot read TIFF_ANY type %d for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return (0); } return (1); } /* * Fetch a tag that is not handled by special case code. */ /* The standard function TIFFFetchNormalTag() could definitely be replaced with a simple call to this function, just adding TIFFSetField() as the last argument. */ static int TIFFFetchNormalSubTag(TIFF* tif, TIFFDirEntry* dp, const TIFFFieldInfo* fip, int (*setFieldFn)(TIFF *tif, ttag_t tag, ...)) { static char mesg[] = "to fetch tag value"; int ok = 0; if (dp->tdir_count > 1) { /* array of values */ char* cp = NULL; switch (dp->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: /* NB: always expand BYTE values to shorts */ cp = CheckMalloc(tif, dp->tdir_count * sizeof (uint16), mesg); ok = cp && TIFFFetchByteArray(tif, dp, (uint16*) cp); break; case TIFF_SHORT: case TIFF_SSHORT: cp = CheckMalloc(tif, dp->tdir_count * sizeof (uint16), mesg); ok = cp && TIFFFetchShortArray(tif, dp, (uint16*) cp); break; case TIFF_LONG: case TIFF_SLONG: cp = CheckMalloc(tif, dp->tdir_count * sizeof (uint32), mesg); ok = cp && TIFFFetchLongArray(tif, dp, (uint32*) cp); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: cp = CheckMalloc(tif, dp->tdir_count * sizeof (float), mesg); ok = cp && TIFFFetchRationalArray(tif, dp, (float*) cp); break; case TIFF_FLOAT: cp = CheckMalloc(tif, dp->tdir_count * sizeof (float), mesg); ok = cp && TIFFFetchFloatArray(tif, dp, (float*) cp); break; case TIFF_DOUBLE: cp = CheckMalloc(tif, dp->tdir_count * sizeof (double), mesg); ok = cp && TIFFFetchDoubleArray(tif, dp, (double*) cp); break; case TIFF_ASCII: case TIFF_UNDEFINED: /* bit of a cheat... */ /* * Some vendors write strings w/o the trailing * NULL byte, so always append one just in case. */ cp = CheckMalloc(tif, dp->tdir_count+1, mesg); if (ok = (cp && TIFFFetchString(tif, dp, cp))) cp[dp->tdir_count] = '\0'; /* XXX */ break; } if (ok) { ok = (fip->field_passcount ? (*setFieldFn)(tif, dp->tdir_tag, dp->tdir_count, cp) : (*setFieldFn)(tif, dp->tdir_tag, cp)); } if (cp != NULL) _TIFFfree(cp); } else if (CheckDirCount(tif, dp, 1)) { /* singleton value */ switch (dp->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: /* * If the tag is also acceptable as a LONG or SLONG * then (*setFieldFn) will expect an uint32 parameter * passed to it (through varargs). Thus, for machines * where sizeof (int) != sizeof (uint32) we must do * a careful check here. It's hard to say if this * is worth optimizing. * * NB: We use TIFFFieldWithTag here knowing that * it returns us the first entry in the table * for the tag and that that entry is for the * widest potential data type the tag may have. */ { TIFFDataType type = fip->field_type; if (type != TIFF_LONG && type != TIFF_SLONG) { uint16 v = (uint16) TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); ok = (fip->field_passcount ? (*setFieldFn)(tif, dp->tdir_tag, 1, &v) : (*setFieldFn)(tif, dp->tdir_tag, v)); break; } } /* fall thru... */ case TIFF_LONG: case TIFF_SLONG: { uint32 v32 = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); ok = (fip->field_passcount ? (*setFieldFn)(tif, dp->tdir_tag, 1, &v32) : (*setFieldFn)(tif, dp->tdir_tag, v32)); } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float v = (dp->tdir_type == TIFF_FLOAT ? TIFFFetchFloat(tif, dp) : TIFFFetchRational(tif, dp)); ok = (fip->field_passcount ? (*setFieldFn)(tif, dp->tdir_tag, 1, &v) : (*setFieldFn)(tif, dp->tdir_tag, v)); } break; case TIFF_DOUBLE: { double v; ok = (TIFFFetchDoubleArray(tif, dp, &v) && (fip->field_passcount ? (*setFieldFn)(tif, dp->tdir_tag, 1, &v) : (*setFieldFn)(tif, dp->tdir_tag, v)) ); } break; case TIFF_ASCII: case TIFF_UNDEFINED: /* bit of a cheat... */ { char c[2]; if (ok = (TIFFFetchString(tif, dp, c) != 0)) { c[1] = '\0'; /* XXX paranoid */ ok = (*setFieldFn)(tif, dp->tdir_tag, c); } } break; } } return (ok); } /* Everything after this is exactly duplicated from the standard tif_dirread.c file, necessitated by the fact that they are declared static there so we can't call them! */ #define NITEMS(x) (sizeof (x) / sizeof (x[0])) /* * Fetch samples/pixel short values for * the specified tag and verify that * all values are the same. */ static int TIFFFetchPerSampleShorts(TIFF* tif, TIFFDirEntry* dir, int* pl) { int samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { uint16 buf[10]; uint16* v = buf; if (samples > NITEMS(buf)) v = (uint16*) _TIFFmalloc(samples * sizeof (uint16)); if (TIFFFetchShortArray(tif, dir, v)) { int i; for (i = 1; i < samples; i++) if (v[i] != v[0]) { TIFFError(tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v != buf) _TIFFfree((char*) v); } return (status); } /* * Fetch samples/pixel ANY values for * the specified tag and verify that * all values are the same. */ static int TIFFFetchPerSampleAnys(TIFF* tif, TIFFDirEntry* dir, double* pl) { int samples = (int) tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { double buf[10]; double* v = buf; if (samples > NITEMS(buf)) v = (double*) _TIFFmalloc(samples * sizeof (double)); if (TIFFFetchAnyArray(tif, dir, v)) { int i; for (i = 1; i < samples; i++) if (v[i] != v[0]) { TIFFError(tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v != buf) _TIFFfree(v); } return (status); } #undef NITEMS /* * Fetch a set of offsets or lengths. * While this routine says "strips", * in fact it's also used for tiles. */ static int TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, long nstrips, uint32** lpp) { register uint32* lp; int status; if (!CheckDirCount(tif, dir, (uint32) nstrips)) return (0); /* * Allocate space for strip information. */ if (*lpp == NULL && (*lpp = (uint32 *)CheckMalloc(tif, nstrips * sizeof (uint32), "for strip array")) == NULL) return (0); lp = *lpp; if (dir->tdir_type == (int)TIFF_SHORT) { /* * Handle uint16->uint32 expansion. */ uint16* dp = (uint16*) CheckMalloc(tif, dir->tdir_count* sizeof (uint16), "to fetch strip tag"); if (dp == NULL) return (0); if (status = TIFFFetchShortArray(tif, dir, dp)) { register uint16* wp = dp; while (nstrips-- > 0) *lp++ = *wp++; } _TIFFfree((char*) dp); } else status = TIFFFetchLongArray(tif, dir, lp); return (status); } #define NITEMS(x) (sizeof (x) / sizeof (x[0])) /* * Fetch and set the ExtraSamples tag. */ static int TIFFFetchExtraSamples(TIFF* tif, TIFFDirEntry* dir) { uint16 buf[10]; uint16* v = buf; int status; if (dir->tdir_count > NITEMS(buf)) v = (uint16*) _TIFFmalloc(dir->tdir_count * sizeof (uint16)); if (dir->tdir_type == TIFF_BYTE) status = TIFFFetchByteArray(tif, dir, v); else status = TIFFFetchShortArray(tif, dir, v); if (status) status = TIFFSetField(tif, dir->tdir_tag, dir->tdir_count, v); if (v != buf) _TIFFfree((char*) v); return (status); } #undef NITEMS #ifdef COLORIMETRY_SUPPORT /* * Fetch and set the RefBlackWhite tag. */ static int TIFFFetchRefBlackWhite(TIFF* tif, TIFFDirEntry* dir) { static char mesg[] = "for \"ReferenceBlackWhite\" array"; char* cp; int ok; if (dir->tdir_type == TIFF_RATIONAL) return (1/*TIFFFetchNormalTag(tif, dir) just so linker won't complain - this part of the code is never used anyway */); /* * Handle LONG's for backward compatibility. */ cp = CheckMalloc(tif, dir->tdir_count * sizeof (uint32), mesg); if (ok = (cp && TIFFFetchLongArray(tif, dir, (uint32*) cp))) { float* fp = (float*) CheckMalloc(tif, dir->tdir_count * sizeof (float), mesg); if (ok = (fp != NULL)) { uint32 i; for (i = 0; i < dir->tdir_count; i++) fp[i] = (float)((uint32*) cp)[i]; ok = TIFFSetField(tif, dir->tdir_tag, fp); _TIFFfree((char*) fp); } } if (cp) _TIFFfree(cp); return (ok); } #endif #if STRIPCHOP_SUPPORT /* * Replace a single strip (tile) of uncompressed data by * multiple strips (tiles), each approximately 8Kbytes. * This is useful for dealing with large images or * for dealing with machines with a limited amount * memory. */ static void ChopUpSingleUncompressedStrip(TIFF* tif) { register TIFFDirectory *td = &tif->tif_dir; uint32 bytecount = td->td_stripbytecount[0]; uint32 offset = td->td_stripoffset[0]; tsize_t rowbytes = TIFFVTileSize(tif, 1), stripbytes; tstrip_t strip, nstrips, rowsperstrip; uint32* newcounts; uint32* newoffsets; /* * Make the rows hold at least one * scanline, but fill 8k if possible. */ if (rowbytes > 8192) { stripbytes = rowbytes; rowsperstrip = 1; } else { rowsperstrip = 8192 / rowbytes; stripbytes = rowbytes * rowsperstrip; } /* never increase the number of strips in an image */ if (rowsperstrip >= td->td_rowsperstrip) return; nstrips = (tstrip_t) TIFFhowmany(bytecount, stripbytes); newcounts = (uint32*) CheckMalloc(tif, nstrips * sizeof (uint32), "for chopped \"StripByteCounts\" array"); newoffsets = (uint32*) CheckMalloc(tif, nstrips * sizeof (uint32), "for chopped \"StripOffsets\" array"); if (newcounts == NULL || newoffsets == NULL) { /* * Unable to allocate new strip information, give * up and use the original one strip information. */ if (newcounts != NULL) _TIFFfree(newcounts); if (newoffsets != NULL) _TIFFfree(newoffsets); return; } /* * Fill the strip information arrays with * new bytecounts and offsets that reflect * the broken-up format. */ for (strip = 0; strip < nstrips; strip++) { if (stripbytes > bytecount) stripbytes = bytecount; newcounts[strip] = stripbytes; newoffsets[strip] = offset; offset += stripbytes; bytecount -= stripbytes; } /* * Replace old single strip info with multi-strip info. */ td->td_stripsperimage = td->td_nstrips = nstrips; TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip); _TIFFfree(td->td_stripbytecount); _TIFFfree(td->td_stripoffset); td->td_stripbytecount = newcounts; td->td_stripoffset = newoffsets; } #endif /* STRIPCHOP_SUPPORT */
Java
/* * Copyright 2017-2019 University of Hildesheim, Software Systems Engineering * * 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 net.ssehub.kernel_haven.code_model; import java.io.File; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.ssehub.kernel_haven.SetUpException; import net.ssehub.kernel_haven.config.DefaultSettings; import net.ssehub.kernel_haven.provider.AbstractCache; import net.ssehub.kernel_haven.provider.AbstractProvider; import net.ssehub.kernel_haven.util.null_checks.NonNull; /** * The provider for the code model. This class serves as an intermediate between the analysis and the code model * extractor. * * @author Adam */ public class CodeModelProvider extends AbstractProvider<SourceFile<?>> { @Override protected long getTimeout() { return config.getValue(DefaultSettings.CODE_PROVIDER_TIMEOUT); } @Override protected @NonNull List<@NonNull File> getTargets() throws SetUpException { List<@NonNull File> result = new LinkedList<>(); Pattern pattern = config.getValue(DefaultSettings.CODE_EXTRACTOR_FILE_REGEX); for (String relativeStr : config.getValue(DefaultSettings.CODE_EXTRACTOR_FILES)) { File relativeFile = new File(relativeStr); File absoluteFile = new File(config.getValue(DefaultSettings.SOURCE_TREE), relativeFile.getPath()); if (absoluteFile.isFile()) { result.add(relativeFile); } else if (absoluteFile.isDirectory()) { readFilesFromDirectory(absoluteFile, pattern, result); } else { throw new SetUpException("Non-existing file specified in code.extractor.files: " + relativeFile.getPath()); } } return result; } /** * Finds all files in the given directory (recursively) that match the given * pattern. The files that match are added to filesToParse. * * @param directory * The directory to search in. * @param pattern * The pattern to check against. * @param result * The list to add the found files to. */ private void readFilesFromDirectory(File directory, Pattern pattern, List<File> result) { for (File file : directory.listFiles()) { if (file.isDirectory()) { readFilesFromDirectory(file, pattern, result); } else { Matcher m = pattern.matcher(file.getName()); if (m.matches()) { result.add(config.getValue(DefaultSettings.SOURCE_TREE).toPath() .relativize(file.toPath()).toFile()); } } } } @Override protected @NonNull AbstractCache<SourceFile<?>> createCache() { return new JsonCodeModelCache(config.getValue(DefaultSettings.CACHE_DIR), config.getValue(DefaultSettings.CODE_PROVIDER_CACHE_COMPRESS)); } @Override public boolean readCache() { return config.getValue(DefaultSettings.CODE_PROVIDER_CACHE_READ); } @Override public boolean writeCache() { return config.getValue(DefaultSettings.CODE_PROVIDER_CACHE_WRITE); } @Override public int getNumberOfThreads() { return config.getValue(DefaultSettings.CODE_EXTRACTOR_THREADS); } }
Java
/* * Copyright 2005-2008 The Kuali Foundation * * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.edl.impl; public class TestConfigProcessor extends TestEDLModelCompent { }
Java
package org.apache.hadoop.hive.kafka.camus; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.MapWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.UTF8; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Map; /** * The key for the mapreduce job to pull kafka. Contains offsets and the * checksum. */ public class KafkaKey implements WritableComparable<KafkaKey>, IKafkaKey { public static final Text SERVER = new Text("server"); public static final Text SERVICE = new Text("service"); public static KafkaKey DUMMY_KEY = new KafkaKey(); private String leaderId = ""; private int partition = 0; private long beginOffset = 0; private long offset = 0; private long checksum = 0; private String topic = ""; private long time = 0; private String server = ""; private String service = ""; private MapWritable partitionMap = new MapWritable(); /** * dummy empty constructor */ public KafkaKey() { this("dummy", "0", 0, 0, 0, 0); } public KafkaKey(KafkaKey other) { this.partition = other.partition; this.beginOffset = other.beginOffset; this.offset = other.offset; this.checksum = other.checksum; this.topic = other.topic; this.time = other.time; this.server = other.server; this.service = other.service; this.partitionMap = new MapWritable(other.partitionMap); } public KafkaKey(String topic, String leaderId, int partition) { this.set(topic, leaderId, partition, 0, 0, 0); } public KafkaKey(String topic, String leaderId, int partition, long beginOffset, long offset) { this.set(topic, leaderId, partition, beginOffset, offset, 0); } public KafkaKey(String topic, String leaderId, int partition, long beginOffset, long offset, long checksum) { this.set(topic, leaderId, partition, beginOffset, offset, checksum); } public void set(String topic, String leaderId, int partition, long beginOffset, long offset, long checksum) { this.leaderId = leaderId; this.partition = partition; this.beginOffset = beginOffset; this.offset = offset; this.checksum = checksum; this.topic = topic; this.time = System.currentTimeMillis(); // if event can't be decoded, // this time will be used for // debugging. } public void clear() { leaderId = ""; partition = 0; beginOffset = 0; offset = 0; checksum = 0; topic = ""; time = 0; server = ""; service = ""; partitionMap = new MapWritable(); } public String getServer() { return partitionMap.get(SERVER).toString(); } public void setServer(String newServer) { partitionMap.put(SERVER, new Text(newServer)); } public String getService() { return partitionMap.get(SERVICE).toString(); } public void setService(String newService) { partitionMap.put(SERVICE, new Text(newService)); } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public String getTopic() { return topic; } public String getLeaderId() { return leaderId; } public int getPartition() { return this.partition; } public long getBeginOffset() { return this.beginOffset; } public void setOffset(long offset) { this.offset = offset; } public long getOffset() { return this.offset; } public long getChecksum() { return this.checksum; } @Override public long getMessageSize() { Text key = new Text("message.size"); if (this.partitionMap.containsKey(key)) return ((LongWritable) this.partitionMap.get(key)).get(); else return 1024; //default estimated size } public void setMessageSize(long messageSize) { Text key = new Text("message.size"); put(key, new LongWritable(messageSize)); } public void put(Writable key, Writable value) { this.partitionMap.put(key, value); } public void addAllPartitionMap(MapWritable partitionMap) { this.partitionMap.putAll(partitionMap); } public MapWritable getPartitionMap() { return partitionMap; } @Override public void readFields(DataInput in) throws IOException { this.leaderId = UTF8.readString(in); this.partition = in.readInt(); this.beginOffset = in.readLong(); this.offset = in.readLong(); this.checksum = in.readLong(); this.topic = in.readUTF(); this.time = in.readLong(); this.server = in.readUTF(); // left for legacy this.service = in.readUTF(); // left for legacy this.partitionMap = new MapWritable(); try { this.partitionMap.readFields(in); } catch (IOException e) { this.setServer(this.server); this.setService(this.service); } } @Override public void write(DataOutput out) throws IOException { UTF8.writeString(out, this.leaderId); out.writeInt(this.partition); out.writeLong(this.beginOffset); out.writeLong(this.offset); out.writeLong(this.checksum); out.writeUTF(this.topic); out.writeLong(this.time); out.writeUTF(this.server); // left for legacy out.writeUTF(this.service); // left for legacy this.partitionMap.write(out); } @Override public int compareTo(KafkaKey o) { if (partition != o.partition) { return partition = o.partition; } else { if (offset > o.offset) { return 1; } else if (offset < o.offset) { return -1; } else { if (checksum > o.checksum) { return 1; } else if (checksum < o.checksum) { return -1; } else { return 0; } } } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("topic="); builder.append(topic); builder.append(" partition="); builder.append(partition); builder.append("leaderId="); builder.append(leaderId); builder.append(" server="); builder.append(server); builder.append(" service="); builder.append(service); builder.append(" beginOffset="); builder.append(beginOffset); builder.append(" offset="); builder.append(offset); builder.append(" msgSize="); builder.append(getMessageSize()); builder.append(" server="); builder.append(server); builder.append(" checksum="); builder.append(checksum); builder.append(" time="); builder.append(time); for (Map.Entry<Writable, Writable> e : partitionMap.entrySet()) { builder.append(" " + e.getKey() + "="); builder.append(e.getValue().toString()); } return builder.toString(); } }
Java
/* * Copyright 2011 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.google.jstestdriver.output; /** * Escapes and formats a filename. * * @author Cory Smith (corbinrsmith@gmail.com) */ public class FileNameFormatter { public String format(String path, String format) { String escaped = path .replace('/', 'a') .replace('\\', 'a') .replace(">", "a") .replace(":", "a") .replace(":", "a") .replace(";", "a") .replace("+", "a") .replace(",", "a") .replace("<", "a") .replace("?", "a") .replace("*", "a") .replace(" ", "a"); return String.format(format, escaped.length() > 200 ? escaped.substring(0, 200) : escaped); } }
Java
/** * Copyright 2014 Google Inc. * Copyright 2014 Andreas Schildbach * * 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.bitcoin.wallet; import com.google.bitcoin.crypto.*; import com.google.bitcoin.store.UnreadableWalletException; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import org.bitcoinj.wallet.Protos; import org.spongycastle.crypto.params.KeyParameter; import javax.annotation.Nullable; import java.io.UnsupportedEncodingException; import java.security.SecureRandom; import java.util.List; import static com.google.bitcoin.core.Utils.HEX; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * Holds the seed bytes for the BIP32 deterministic wallet algorithm, inside a * {@link com.google.bitcoin.wallet.DeterministicKeyChain}. The purpose of this wrapper is to simplify the encryption * code. */ public class DeterministicSeed implements EncryptableItem { // It would take more than 10^12 years to brute-force a 128 bit seed using $1B worth of computing equipment. public static final int DEFAULT_SEED_ENTROPY_BITS = 128; public static final int MAX_SEED_ENTROPY_BITS = 512; @Nullable private final byte[] seed; @Nullable private List<String> mnemonicCode; @Nullable private EncryptedData encryptedMnemonicCode; private final long creationTimeSeconds; public DeterministicSeed(String mnemonicCode, String passphrase, long creationTimeSeconds) throws UnreadableWalletException { this(decodeMnemonicCode(mnemonicCode), passphrase, creationTimeSeconds); } public DeterministicSeed(byte[] seed, List<String> mnemonic, long creationTimeSeconds) { this.seed = checkNotNull(seed); this.mnemonicCode = checkNotNull(mnemonic); this.encryptedMnemonicCode = null; this.creationTimeSeconds = creationTimeSeconds; } public DeterministicSeed(EncryptedData encryptedMnemonic, long creationTimeSeconds) { this.seed = null; this.mnemonicCode = null; this.encryptedMnemonicCode = checkNotNull(encryptedMnemonic); this.creationTimeSeconds = creationTimeSeconds; } /** * Constructs a seed from a BIP 39 mnemonic code. See {@link com.google.bitcoin.crypto.MnemonicCode} for more * details on this scheme. * @param mnemonicCode A list of words. * @param passphrase A user supplied passphrase, or an empty string if there is no passphrase * @param creationTimeSeconds When the seed was originally created, UNIX time. */ public DeterministicSeed(List<String> mnemonicCode, String passphrase, long creationTimeSeconds) { this(MnemonicCode.toSeed(mnemonicCode, passphrase), mnemonicCode, creationTimeSeconds); } /** * Constructs a seed from a BIP 39 mnemonic code. See {@link com.google.bitcoin.crypto.MnemonicCode} for more * details on this scheme. * @param random Entropy source * @param bits number of bits, must be divisible by 32 * @param passphrase A user supplied passphrase, or an empty string if there is no passphrase * @param creationTimeSeconds When the seed was originally created, UNIX time. */ public DeterministicSeed(SecureRandom random, int bits, String passphrase, long creationTimeSeconds) { this(getEntropy(random, bits), passphrase, creationTimeSeconds); } /** * Constructs a seed from a BIP 39 mnemonic code. See {@link com.google.bitcoin.crypto.MnemonicCode} for more * details on this scheme. * @param entropy entropy bits, length must be divisible by 32 * @param passphrase A user supplied passphrase, or an empty string if there is no passphrase * @param creationTimeSeconds When the seed was originally created, UNIX time. */ public DeterministicSeed(byte[] entropy, String passphrase, long creationTimeSeconds) { Preconditions.checkArgument(entropy.length % 4 == 0, "entropy size in bits not divisible by 32"); Preconditions.checkArgument(entropy.length * 8 >= DEFAULT_SEED_ENTROPY_BITS, "entropy size too small"); try { this.mnemonicCode = MnemonicCode.INSTANCE.toMnemonic(entropy); } catch (MnemonicException.MnemonicLengthException e) { // cannot happen throw new RuntimeException(e); } this.seed = MnemonicCode.toSeed(mnemonicCode, passphrase); this.encryptedMnemonicCode = null; this.creationTimeSeconds = creationTimeSeconds; } private static byte[] getEntropy(SecureRandom random, int bits) { Preconditions.checkArgument(bits <= MAX_SEED_ENTROPY_BITS, "requested entropy size too large"); byte[] seed = new byte[bits / 8]; random.nextBytes(seed); return seed; } @Override public boolean isEncrypted() { checkState(mnemonicCode != null || encryptedMnemonicCode != null); return encryptedMnemonicCode != null; } @Override public String toString() { if (isEncrypted()) return "DeterministicSeed [encrypted]"; else return "DeterministicSeed " + toHexString() + ((mnemonicCode != null) ? " " + Joiner.on(" ").join(mnemonicCode) : ""); } /** Returns the seed as hex or null if encrypted. */ @Nullable public String toHexString() { if (seed != null) return HEX.encode(seed); else return null; } @Nullable @Override public byte[] getSecretBytes() { return getMnemonicAsBytes(); } @Nullable public byte[] getSeedBytes() { return seed; } @Nullable @Override public EncryptedData getEncryptedData() { return encryptedMnemonicCode; } @Override public Protos.Wallet.EncryptionType getEncryptionType() { return Protos.Wallet.EncryptionType.ENCRYPTED_SCRYPT_AES; } @Override public long getCreationTimeSeconds() { return creationTimeSeconds; } public DeterministicSeed encrypt(KeyCrypter keyCrypter, KeyParameter aesKey) { checkState(encryptedMnemonicCode == null, "Trying to encrypt seed twice"); checkState(mnemonicCode != null, "Mnemonic missing so cannot encrypt"); EncryptedData mnemonic = keyCrypter.encrypt(getMnemonicAsBytes(), aesKey); return new DeterministicSeed(mnemonic, creationTimeSeconds); } private byte[] getMnemonicAsBytes() { return Joiner.on(" ").join(mnemonicCode).getBytes(Charsets.UTF_8); } public DeterministicSeed decrypt(KeyCrypter crypter, String passphrase, KeyParameter aesKey) { checkState(isEncrypted()); checkNotNull(encryptedMnemonicCode); List<String> mnemonic = null; try { mnemonic = decodeMnemonicCode(crypter.decrypt(encryptedMnemonicCode, aesKey)); } catch (UnreadableWalletException e) { // TODO what is the best way to handle this exception? throw new RuntimeException(e); } return new DeterministicSeed(mnemonic, passphrase, creationTimeSeconds); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DeterministicSeed seed = (DeterministicSeed) o; if (creationTimeSeconds != seed.creationTimeSeconds) return false; if (encryptedMnemonicCode != null) { if (seed.encryptedMnemonicCode == null) return false; if (!encryptedMnemonicCode.equals(seed.encryptedMnemonicCode)) return false; } else { if (!mnemonicCode.equals(seed.mnemonicCode)) return false; } return true; } @Override public int hashCode() { int result = encryptedMnemonicCode != null ? encryptedMnemonicCode.hashCode() : mnemonicCode.hashCode(); result = 31 * result + (int) (creationTimeSeconds ^ (creationTimeSeconds >>> 32)); return result; } /** * Check if our mnemonic is a valid mnemonic phrase for our word list. * Does nothing if we are encrypted. * * @throws com.google.bitcoin.crypto.MnemonicException if check fails */ public void check() throws MnemonicException { if (mnemonicCode != null) MnemonicCode.INSTANCE.check(mnemonicCode); } byte[] getEntropyBytes() throws MnemonicException { return MnemonicCode.INSTANCE.toEntropy(mnemonicCode); } /** Get the mnemonic code, or null if unknown. */ @Nullable public List<String> getMnemonicCode() { return mnemonicCode; } private static List<String> decodeMnemonicCode(byte[] mnemonicCode) throws UnreadableWalletException { try { return Splitter.on(" ").splitToList(new String(mnemonicCode, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new UnreadableWalletException(e.toString()); } } private static List<String> decodeMnemonicCode(String mnemonicCode) { return Splitter.on(" ").splitToList(mnemonicCode); } }
Java
package com.datawizards.dmg.service import com.datawizards.dmg.repository.{AvroSchemaRegistryRepository, AvroSchemaRegistryRepositoryImpl} class AvroSchemaRegistryServiceImpl(url: String) extends AvroSchemaRegistryService { override protected val repository: AvroSchemaRegistryRepository = new AvroSchemaRegistryRepositoryImpl(url) override protected val hdfsService: HDFSService = HDFSServiceImpl }
Java
/* * Copyright (c) 2016-present, RxJava Contributors. * * 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.reactivex.rxjava3.internal.operators.flowable; import static org.junit.Assert.*; import java.util.*; import java.util.concurrent.ExecutionException; import org.junit.Test; import org.reactivestreams.*; import io.reactivex.rxjava3.core.*; import io.reactivex.rxjava3.functions.*; import io.reactivex.rxjava3.internal.subscriptions.BooleanSubscription; import io.reactivex.rxjava3.schedulers.Schedulers; import io.reactivex.rxjava3.subscribers.*; import io.reactivex.rxjava3.testsupport.*; public class FlowableMaterializeTest extends RxJavaTest { @Test public void materialize1() { // null will cause onError to be triggered before "three" can be // returned final TestAsyncErrorObservable o1 = new TestAsyncErrorObservable("one", "two", null, "three"); TestNotificationSubscriber observer = new TestNotificationSubscriber(); Flowable<Notification<String>> m = Flowable.unsafeCreate(o1).materialize(); m.subscribe(observer); try { o1.t.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } assertFalse(observer.onError); assertTrue(observer.onComplete); assertEquals(3, observer.notifications.size()); assertTrue(observer.notifications.get(0).isOnNext()); assertEquals("one", observer.notifications.get(0).getValue()); assertTrue(observer.notifications.get(1).isOnNext()); assertEquals("two", observer.notifications.get(1).getValue()); assertTrue(observer.notifications.get(2).isOnError()); assertEquals(NullPointerException.class, observer.notifications.get(2).getError().getClass()); } @Test public void materialize2() { final TestAsyncErrorObservable o1 = new TestAsyncErrorObservable("one", "two", "three"); TestNotificationSubscriber subscriber = new TestNotificationSubscriber(); Flowable<Notification<String>> m = Flowable.unsafeCreate(o1).materialize(); m.subscribe(subscriber); try { o1.t.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } assertFalse(subscriber.onError); assertTrue(subscriber.onComplete); assertEquals(4, subscriber.notifications.size()); assertTrue(subscriber.notifications.get(0).isOnNext()); assertEquals("one", subscriber.notifications.get(0).getValue()); assertTrue(subscriber.notifications.get(1).isOnNext()); assertEquals("two", subscriber.notifications.get(1).getValue()); assertTrue(subscriber.notifications.get(2).isOnNext()); assertEquals("three", subscriber.notifications.get(2).getValue()); assertTrue(subscriber.notifications.get(3).isOnComplete()); } @Test public void multipleSubscribes() throws InterruptedException, ExecutionException { final TestAsyncErrorObservable o = new TestAsyncErrorObservable("one", "two", null, "three"); Flowable<Notification<String>> m = Flowable.unsafeCreate(o).materialize(); assertEquals(3, m.toList().toFuture().get().size()); assertEquals(3, m.toList().toFuture().get().size()); } @Test public void backpressureOnEmptyStream() { TestSubscriber<Notification<Integer>> ts = new TestSubscriber<>(0L); Flowable.<Integer> empty().materialize().subscribe(ts); ts.assertNoValues(); ts.request(1); ts.assertValueCount(1); assertTrue(ts.values().get(0).isOnComplete()); ts.assertComplete(); } @Test public void backpressureNoError() { TestSubscriber<Notification<Integer>> ts = new TestSubscriber<>(0L); Flowable.just(1, 2, 3).materialize().subscribe(ts); ts.assertNoValues(); ts.request(1); ts.assertValueCount(1); ts.request(2); ts.assertValueCount(3); ts.request(1); ts.assertValueCount(4); ts.assertComplete(); } @Test public void backpressureNoErrorAsync() throws InterruptedException { TestSubscriber<Notification<Integer>> ts = new TestSubscriber<>(0L); Flowable.just(1, 2, 3) .materialize() .subscribeOn(Schedulers.computation()) .subscribe(ts); Thread.sleep(100); ts.assertNoValues(); ts.request(1); Thread.sleep(100); ts.assertValueCount(1); ts.request(2); Thread.sleep(100); ts.assertValueCount(3); ts.request(1); Thread.sleep(100); ts.assertValueCount(4); ts.assertComplete(); } @Test public void backpressureWithError() { TestSubscriber<Notification<Integer>> ts = new TestSubscriber<>(0L); Flowable.<Integer> error(new IllegalArgumentException()).materialize().subscribe(ts); ts.assertNoValues(); ts.request(1); ts.assertValueCount(1); ts.assertComplete(); } @Test public void backpressureWithEmissionThenError() { TestSubscriber<Notification<Integer>> ts = new TestSubscriber<>(0L); IllegalArgumentException ex = new IllegalArgumentException(); Flowable.fromIterable(Arrays.asList(1)).concatWith(Flowable.<Integer> error(ex)).materialize() .subscribe(ts); ts.assertNoValues(); ts.request(1); ts.assertValueCount(1); assertTrue(ts.values().get(0).isOnNext()); ts.request(1); ts.assertValueCount(2); assertTrue(ts.values().get(1).isOnError()); assertEquals(ex, ts.values().get(1).getError()); ts.assertComplete(); } @Test public void withCompletionCausingError() { TestSubscriberEx<Notification<Integer>> ts = new TestSubscriberEx<>(); final RuntimeException ex = new RuntimeException("boo"); Flowable.<Integer>empty().materialize().doOnNext(new Consumer<Object>() { @Override public void accept(Object t) { throw ex; } }).subscribe(ts); ts.assertError(ex); ts.assertNoValues(); ts.assertTerminated(); } @Test public void unsubscribeJustBeforeCompletionNotificationShouldPreventThatNotificationArriving() { TestSubscriber<Notification<Integer>> ts = new TestSubscriber<>(0L); Flowable.<Integer>empty().materialize() .subscribe(ts); ts.assertNoValues(); ts.cancel(); ts.request(1); ts.assertNoValues(); } private static class TestNotificationSubscriber extends DefaultSubscriber<Notification<String>> { boolean onComplete; boolean onError; List<Notification<String>> notifications = new Vector<>(); @Override public void onComplete() { this.onComplete = true; } @Override public void onError(Throwable e) { this.onError = true; } @Override public void onNext(Notification<String> value) { this.notifications.add(value); } } private static class TestAsyncErrorObservable implements Publisher<String> { String[] valuesToReturn; TestAsyncErrorObservable(String... values) { valuesToReturn = values; } volatile Thread t; @Override public void subscribe(final Subscriber<? super String> subscriber) { subscriber.onSubscribe(new BooleanSubscription()); t = new Thread(new Runnable() { @Override public void run() { for (String s : valuesToReturn) { if (s == null) { System.out.println("throwing exception"); try { Thread.sleep(100); } catch (Throwable e) { } subscriber.onError(new NullPointerException()); return; } else { subscriber.onNext(s); } } System.out.println("subscription complete"); subscriber.onComplete(); } }); t.start(); } } @Test public void backpressure() { TestSubscriber<Notification<Integer>> ts = Flowable.range(1, 5).materialize().test(0); ts.assertEmpty(); ts.request(5); ts.assertValueCount(5) .assertNoErrors() .assertNotComplete(); ts.request(1); ts.assertValueCount(6) .assertNoErrors() .assertComplete(); } @Test public void dispose() { TestHelper.checkDisposed(Flowable.just(1).materialize()); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Notification<Object>>>() { @Override public Flowable<Notification<Object>> apply(Flowable<Object> f) throws Exception { return f.materialize(); } }); } @Test public void badSource() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Object>, Object>() { @Override public Object apply(Flowable<Object> f) throws Exception { return f.materialize(); } }, false, null, null, Notification.createOnComplete()); } @Test public void badRequest() { TestHelper.assertBadRequestReported(Flowable.just(1).materialize()); } }
Java
package net.unicon.cas.addons.serviceregistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; /** * <code>BeanFactoryPostProcessor</code> to remove 2 quartz beans responsible for reloading the default services registry's registered services. * <p/> * Useful in cases where other facilities are responsible for reloading in-memory services cache, for example on-demand reloading * of JSON services registry, etc. * <p/> * This bean just needs to be declared in CAS' application context and upon bootstrap Spring will call back into it and * 2 scheduling quartz beans dedicated for services registry reloading thread will be removed from the final application context * effectively disabling the default reloading behavior. * * @author Dmitriy Kopylenko * @author Unicon, inc. * @since 1.8 */ public class RegisteredServicesReloadDisablingBeanFactoryPostProcessor implements BeanFactoryPostProcessor { private static final String JOB_DETAIL_BEAN_NAME = "serviceRegistryReloaderJobDetail"; private static final String JOB_TRIGGER_BEAN_NAME = "periodicServiceRegistryReloaderTrigger"; private static final Logger logger = LoggerFactory.getLogger(RegisteredServicesReloadDisablingBeanFactoryPostProcessor.class); public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { logger.debug("Removing [{}] bean definition from the application context...", JOB_DETAIL_BEAN_NAME); BeanDefinitionRegistry.class.cast(beanFactory).removeBeanDefinition(JOB_DETAIL_BEAN_NAME); logger.debug("Removing [{}] bean definition from the application context...", JOB_TRIGGER_BEAN_NAME); BeanDefinitionRegistry.class.cast(beanFactory).removeBeanDefinition(JOB_TRIGGER_BEAN_NAME); } }
Java
package dhg.util import scala.collection.generic.CanBuildFrom object Pattern { object UInt { val IntRE = """^(-?\d+)$""".r def unapply(v: String): Option[Int] = v match { case IntRE(s) => Some(s.toInt) case _ => None } } // implicit def int2unapplyInt(objA: Int.type) = UInt object UDouble { val DoubleRE = """^(-?\d+\.?\d*|-?\d*\.?\d+)$""".r def unapply(v: String): Option[Double] = v match { case DoubleRE(s) => Some(s.toDouble) case _ => None } } // implicit def double2unapplyDouble(objA: Double.type) = UDouble object UBoolean { val booleanRE = """([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])""".r def unapply(v: String): Option[Boolean] = v match { case booleanRE(s) => Some(s.toBoolean) case _ => None } } object UMap { def unapplySeq[A, B](m: Map[A, B]): Option[Seq[(A, B)]] = Some(m.toIndexedSeq) } object USet { def unapplySeq[A](s: Set[A]): Option[Seq[A]] = Some(s.toIndexedSeq) } object -> { def unapply[A, B](pair: (A, B)): Option[(A, B)] = { Some(pair) } } object Range { val RangeRE = """^(\d+)-(\d+)$""".r def unapply(s: String): Option[Seq[Int]] = Some( s.replaceAll("\\s+", "").split(",").flatMap { case UInt(i) => i to i case RangeRE(UInt(b), UInt(e)) if b <= e => b to e }) } class Range(max: Int) { val OpenRangeRE = """^(\d+)-$""".r def unapply(s: String): Option[Seq[Int]] = Some( s.replaceAll("\\s+", "").split(",").flatMap { case OpenRangeRE(UInt(b)) => b to max case Range(r) => r }) } def makeRangeString(seq: Seq[Int]): String = { assert(seq.nonEmpty, "cannot make empty sequence into a range string") assert(seq.exists(_ >= 0), s"negative numbers are not permitted: $seq") (-2 +: seq).sliding(2).foldLeft(Vector[Vector[Int]]()) { case ((z :+ c), Seq(a, b)) => if (a != b - 1) (z :+ c) :+ Vector(b) else (z :+ (c :+ b)) case (z, Seq(a, b)) => z :+ Vector(b) } .map { case Seq(x) => x.toString case s => s.head + "-" + s.last }.mkString(",") } object Iterable { def unapplySeq[T](s: Iterable[T]): Option[Seq[T]] = Some(s.toIndexedSeq) } }
Java
# Omphalia epichysium (Pers.) P. Kumm., 1871 SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Führ. Pilzk. (Zwickau) 107 (1871) #### Original name Agaricus epichysium Pers., 1794 ### Remarks null
Java
# Achillea lereschei Sch.Bip. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
using ClassLibrary; using Pokemon_IMIE.Model; using Pokemon_IMIE.usercontrols; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236 namespace Pokemon_IMIE.usercontrols { public sealed partial class PokemonStatus : BaseUserControl { private Model.Pokemon pokemon; public Model.Pokemon Pokemon { get { return pokemon; } set { pokemon = value; base.OnPropertyChanged("Pokemon"); } } public PokemonStatus() { this.InitializeComponent(); base.DataContext = this; } } }
Java
#coding=utf-8 from django.db import models from django.contrib.auth.models import User class Activity(models.Model): owner = models.ForeignKey(User, null=False) text = models.CharField(max_length=20, unique=True) class Dessert(models.Model): activity = models.ForeignKey(Activity, null=False) description = models.TextField() photo = models.ImageField()
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Day57-vlvibesSwitch</title> <script src="https://aframe.io/releases/0.2.0/aframe.min.js"></script> <script src="https://rawgit.com/ngokevin/aframe-text-component/master/dist/aframe-text-component.min.js"></script> <script src="https://code.jquery.com/jquery-2.1.1.js"></script> </head> <body> <a-scene> <!-- camera --> <a-entity id="camera" rotation="0 0 0" position="0 0 0"> <a-camera> <a-entity cursor="maxDistance:10000" position="0 0 -1" color="pink" geometry="primitive:ring; color:pink; radiusInner:.005; radiusOuter:.01"></a-entity> </a-camera> </a-entity> <!--divs and baloon--> <a-entity id="titleName"></a-entity> <a-entity id="sphereA"> <a-sphere id="sphere1" visable="true" material="src:url(http://www.headsub.com/attachment/uq23A3T8/Templates/Textures/Football.png)" radius="1"></a-sphere> <a-animation attribute="position" from="0 -20 -2" to="0 0 -2"></a-animation> </a-entity> <!-- light --> <a-entity><a-entity id="light" light="color:#F5F5F5; intensity:2" position="-1 3 2"></a-entity></a-entity> <!-- sounds --> <a-entity id="vibes" geometry="primitive: plane" material="color: pink" position="-10 0 0" sound="src: vibes.mp3; autoplay: false"></a-entity> <a-entity id="mainMenu" position="-4.5 3.5 -8"><a-plane material="src:url(https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcT5l4ULXmIyLZDMgJ2-iUnWSINwaxERpLFlqwBtnEFekiYlwnyn)"></a-plane></a-entity> <a-sky color="#333"></a-sky> </a-scene> <script> $(document).ready(function(){ document.querySelector('#sphere1').addEventListener('click', function () { // text add $("a-scene").append('<a-entity><a-entity material="color:#F16785" scale="5 5 5" text="text:Lay ut"></a-entity><a-animation begin="500" attribute="position" from="20 0 -10" to=".15 0 -10"></a-animation></a-entity>'); $("a-scene").append('<a-entity><a-entity material="color:#F16785" scale="5 5 5" text="text:Virtual"></a-entity><a-animation begin="500" attribute="position" from="-20 0 -10" to="-10.5 0 -10"></a-animation></a-entity>'); // welcome slide in and slide out $("a-scene").append('<a-entity><a-entity material="color:#F16785" scale="1 1 1" text="text:Welcome to"></a-entity><a-animation begin="1100" attribute="position" from="-20 3 -10" to="-4 3 -10"></a-animation><a-animation begin="2000" attribute="position" from="-4 3 -10" to="-40 3 -10"></a-animation><a-animation begin="6050" attribute="position" from="-43 3 -10" to="-8 3 -10 -10"></a-animation></a-entity>'); // animated spotlight $("a-scene").append('<a-entity><a-entity id="spotLight" light="color:#F5F5F5; type:spot; intensity:1.8; angle:10"></a-entity><a-animation id="durAnimation" attribute="position" dur="5000" from="-25 -2 2" to="25 -1 4" repeat="indefinite"></a-animation></a-entity>'); // remove original sphere $(this).hide(1,function(){$(this).remove();}); // create new sphere $("a-scene").append('<a-entity id="sphereB" camera"><a-sphere position="0 0 -2" id="sphere1" material="src:url(http://www.headsub.com/attachment/uq23A3T8/Templates/Textures/Football.png)" radius="1"></a-sphere><a-animation attribute="position" from=0 0 -4" to="0 4 -8"></a-animation><a-animation begin="1410" attribute="rotation" dur="5000" fill="forwards" to="0 0 -360"></a-animation><a-animation attribute="position" begin="1710" from="0 4 -8" to="2 5 -8"></a-animation><a-animation attribute="position" begin="2500" from="2 5 -8" to="3.5 3.2 -8"></a-animation><a-animation attribute="position" begin="3400" from="3.5 3.2 -8" to="6.58 3.2 -8"></a-animation><a-animation attribute="position" begin="4500" from="6.58 3.2 -8" to="6.58 .9 -8"></a-animation></a-entity>'); // sphere slammer $("a-scene").append('<a-entity id="sphereRod"><a-cylinder></a-cylinder height="5"><a-animation begin="3800" attribute="position" from="6.58 20 -10" to="6.58 3.5 -10"></a-animation><a-animation begin="4500" attribute="position" from="6.58 3.5 -10" to="6.58 20 -10"></a-animation></a-entity>') // welcome slammer $("a-scene").append('<a-entity id="welcomeRod"><a-cylinder></a-cylinder height="5" rotation="0 0 180"><a-animation begin="6000" attribute="position" from="-41 3 -10" to="-10 3 -10 -10"></a-animation><a-animation begin="7500" attribute="position" from="-10 3 -10" to="-100 3 -10"></a-animation></a-entity>') }); document.querySelector('#mainMenu').addEventListener('toggle', function(){ $('a-scene').append('<a-entity id="lightSwitch"><a-plane material="src:url(https://d13yacurqjgara.cloudfront.net/users/63537/screenshots/1069396/toggle.gif)" position="-5.5 -3.5 -8"></a-plane></a-entity>') $('a-scene').append('<a-entity id="sphereMenu"><a-plane material="src:url(https://cdn2.iconfinder.com/data/icons/windows-8-metro-style/128/switch.png)" position="-5.5 3.5 -8"></a-plane></a-entity>') $('a-scene').append('<a-entity id="fogSwitch"><a-plane material="src:url(https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQaw2r7ErK7CnwqssEY1ulDL6s0gZe7raDCUaovxK4WMSkDrwubiF2M7w)" position="-5.5 -7 -8"></a-plane></a-entity>') $('a-scene').append('<a-entity id=spotLightSpeed><a-plane material="src:url(https://cdn0.iconfinder.com/data/icons/astronomy-1/500/speed-512.png)" position="-5.5 -9.5 -8"></a-plane></a-entity>'); $('a-scene').append('<a-entity id="cameraSwitch"><a-plane material="src:url()" position="-5.5 -12 -8"></a-plane></a-entity>'); $('a-scene')append('<a-entity id="vibesSwitch"><a-plane material="src:url()" position="-5.5 -14.5 -8"></a-plane></a-entity>') }) document.querySelector('#sphereMenu').addEventListener('click', function () { $('a-scene').append('<a-entity id="MENU"><a-plane height="2" width="10" position="2 5 -7"></a-plane></a-entity>') $('a-scene').append('<a-plane id="futbol" height="1.5" width="1.5" position="-1.5 5 -6.8" material="src:url(http://www.headsub.com/attachment/uq23A3T8/Templates/Textures/Football.png)"></a-plane>') $('a-scene').append('<a-entity id="bask"><a-plane id="basketball" height="1.5" width="1.5" position=".5 5 -6.8" material="src:url(http://www.robinwood.com/Catalog/FreeStuff/Textures/TextureDownloads/Balls/BasketballColor.jpg)"></a-plane></a-entity>'); }); document.querySelector('#bask').addEventListener('toggle', function () { $('#sphere1').attr('material', 'src:url(http://www.robinwood.com/Catalog/FreeStuff/Textures/TextureDownloads/Balls/BasketballColor.jpg)'); }); document.querySelector('#lightSwitch').addEventListener('click', function () { $('#light').attr('light','color:#555555; intensity:5'); }); document.querySelector('#fogSwitch').addEventListener('click', function () { $('#light').attr('light','color:#555555; intensity:5'); }); document.querySelector('#spotLightSpeed').addEventListener('click', function () { $('#durAnimation').attr('dur','3000'); }); document.querySelector('#cameraSwitch').addEventListener('click', function () { $('#camera').attr('position','5 0 0'); $('#camera').attr('rotation','20 0 0'); }); document.querySelector('#vibesSwitch').addEventListener('click', function(){ $('#vibes').attr('autoplay', 'true'); }) }); </script> </body> </html>
Java
var angularjs = angular.module('articleDetailModule', ['courseTagServiceModule', 'ngCookies', 'ngVideo']); angularjs.controller('ArticleDetailController', ['$rootScope', '$scope', '$http', '$stateParams', '$state', '$location', 'CourseTagService', '$sce', '$cookies', '$httpParamSerializer', 'video', '$route', function($rootScope, $scope, $http, $stateParams, $state, $location, courseTagSrv, $sce, $cookies, $httpParamSerializer, video, $route) { if ($stateParams.courseId === undefined) { $state.go('home'); } var token = $location.search().token; if (token !== undefined) { console.log('set token on cookie'); $cookies.put('access_token', token); } $scope.showShare = false; $scope.shareImg = "img/share_400_400_2.png"; $scope.courseUrl = $location.absUrl(); console.log('location=', $scope.courseUrl); var util = new DomainNameUtil($location); $scope.originUrl = window.location.href; console.log('get access token:', $cookies.get('access_token')); $scope.favoriteCls = 'fontawesome-heart-empty'; $scope.favoriteText = '收藏'; $http.get(util.getBackendServiceUrl() + '/course/proposal/' + $stateParams.courseId, { headers: { 'access_token': $cookies.get('access_token') } }). success(function(e) { console.log('get course ', e); $scope.course = e; $rootScope.title = e.name; var $body = $('body'); var $iframe = $('<iframe src="/favicon.ico"></iframe>'); $iframe.on('load', function() { setTimeout(function() { $iframe.off('load').remove(); }, 0); }).appendTo($body); $scope.course.videoUrl = $sce.trustAsResourceUrl($scope.course.videoUrl); document.getElementById('article_content').innerHTML = $scope.course.content; // video.addSource('mp4',$scope.course.videoUrl); setFavoriteDom(); configJSAPI(); }).error(function(e) { }); $http.get(util.getBackendServiceUrl() + '/course/proposal/query?number=3&ignore_course_id=' + $stateParams.courseId) .success(function(e) { console.log('get related courses ', e); $scope.relatedCourses = e; }).error(function(e) { }); courseTagSrv.getCourseTags().then(function(e) { $scope.courseTags = e; }); $scope.background = function(course) { return { 'background-image': 'url(' + course.titleImageUrl + ')', 'background-size': '100%' }; } $scope.goToCourseTag = function(tag, $event) { console.log('go to course tag'); $state.go('course_tags', { courseTagId: tag.id, courseName: tag.name }); $event.stopPropagation(); } $scope.share = function() { console.log('share'); $scope.showShare = true; // var ret = recordShareFavorite('SHARE'); // ret.success(function(e){ // }); } $scope.favorite = function() { console.log('favorite'); if ($cookies.get('access_token') === undefined) { var redirect = encodeURI($scope.courseUrl).replace('#', '%23'); console.log('redirect=', encodeURI($scope.courseUrl).replace('#', '%23')); window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxfe34c2ab5b5c5813&redirect_uri=http%3a%2f%2fwww.imzao.com%2feducation%2fzaozao%2fwechat%2flogin&response_type=code&scope=snsapi_userinfo&state=WECHAT_SERVICE-' + redirect + '#wechat_redirect'; return; } var promise = recordShareFavorite('FAVORITE'); promise.success(function(e) { console.log('favorite success ', e); $scope.course.favorited = !$scope.course.favorited; setFavoriteDom(); }).error(function(e) { console.log('share failed'); }); } function setFavoriteDom() { if ($scope.course.favorited === true) { $scope.favoriteCls = 'fontawesome-heart'; $scope.favoriteText = '已收藏'; } else { $scope.favoriteCls = 'fontawesome-heart-empty'; $scope.favoriteText = '收藏'; } } $scope.hideShare = function() { $scope.showShare = false; } $scope.showPlayButton = true; $scope.showVideo = false; $scope.playVideo = function(e) { console.log('course video,', $("#course_video")); $("#course_video")[0].play(); } document.getElementById('course_video').addEventListener('webkitendfullscreen', function(e) { // handle end full screen console.log('webkitendfullscreen'); $scope.showVideo = false; $scope.showPlayButton = true; $scope.$apply(); }); document.getElementById('course_video').addEventListener('webkitenterfullscreen', function(e) { // handle end full screen console.log('webkitenterfullscreen'); $scope.showVideo = true; $scope.$apply(); }); // $scope.videoEnded = function(e) { // console.log('video ended '); // $scope.showPlayButton = true; // } // $scope.videoPaused = function(e) { // console.log('video paused '); // $scope.showPlayButton = true; // } function configJSAPI() { console.log('js api config:', $scope.courseUrl); $http.get(util.getBackendServiceUrl() + '/wechat/jsapi?url=' + $scope.courseUrl.split('#')[0].replace('&', '%26')) .success(function(e) { console.log(e); var signature = e; wx.config({ debug: false, appId: e.appid, timestamp: e.timestamp, nonceStr: e.noncestr, signature: e.signature, jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage'] }); wx.ready(function() { console.log('wx ready'); }); wx.error(function(res) { console.log('wx error'); }); wx.onMenuShareTimeline({ title: $scope.course.name, link: $scope.courseUrl, imgUrl: encodeURI($scope.course.titleImageUrl), success: function() { console.log('share success'); scope.showShare = false; recordShareFavorite('SHARE'); }, cancel: function() { console.log('cancel share'); scope.showShare = false; } }); var shareDesc = ''; console.log('share desc:', $scope.course.introduction); if ($scope.course.introduction !== null && $scope.course.introduction !== 'undefined') { shareDesc = $scope.course.introduction; } wx.onMenuShareAppMessage({ title: $scope.course.name, // 分享标题 desc: shareDesc, // 分享描述 link: $scope.courseUrl, // 分享链接 imgUrl: encodeURI($scope.course.titleImageUrl), // 分享图标 // 分享类型,music、video或link,不填默认为link // 如果type是music或video,则要提供数据链接,默认为空 success: function(res) { // 用户确认分享后执行的回调函数 console.log('share success'); recordShareFavorite('SHARE'); scope.showShare = false; }, cancel: function(res) { // 用户取消分享后执行的回调函数 console.log('cancel share'); scope.showShare = false; }, fail: function(res) { } }); }).error(function(e) { }); } function recordShareFavorite(activity) { var link = util.getBackendServiceUrl() + '/course/interactive'; var req = { method: 'POST', url: link, headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 'access_token': $cookies.get('access_token') //'Content-Type': 'multipart/form-data; charset=utf-8;' }, data: $httpParamSerializer({ course_id: $scope.course.id, flag: activity }) }; return $http(req); } } ]); angularjs.directive('videoLoader', function() { return function(scope, element, attrs) { scope.$watch(attrs.videoLoader, function() { console.log('element:', element); $("#course_video").bind('ended', function() { console.log('video ended.'); // element.removeAttr('controls'); scope.showPlayButton = true; scope.showVideo = false; scope.$apply(); // $(this).unbind('ended'); // if (!this.hasPlayed) { // return; // } }); $("#course_video").bind('pause', function() { console.log('video paused.'); scope.showPlayButton = false; scope.showVideo = true; // element.attr('controls',true); scope.$apply(); // $(this).unbind('paused'); // if (!this.hasPlayed) { // return; // } }); $("#course_video").bind('play', function() { console.log('video played.'); scope.showPlayButton = false; scope.showVideo = true; // element.attr('controls',true); scope.$apply(); // $(this).unbind('played'); // if (!this.hasPlayed) { // return; // } }); $("#course_video").bind('webkitfullscreenchange mozfullscreenchange fullscreenchange', function(event) { console.log('full screen ', event); var state = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement; if (state !== undefined) { scope.showVideo = true; } else { scope.showVideo = false; } scope.$apply(); }); }); } });
Java
import time from tsm.common.app import exception import requests import json from requests.packages.urllib3.util.retry import Retry from requests.adapters import HTTPAdapter KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1" class KangRouterClient: pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers" def __init__(self,apiKey,licenseId): self.headers = {"content-type": "application/json", "Authorization": apiKey} self.params = {"licenseId" : licenseId } retries = Retry(total=5, backoff_factor=0.75) self.session = requests.Session() self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT, HTTPAdapter(max_retries=retries)) def validateReply(self,req): if req.status_code >= 400 and req.status_code <= 500: try: j = req.json() except ValueError: raise exception.InternalError(req.text,req.status_code) raise exception.jsonToException(req.json()) def create(self,problem,**kwargs): path = self.pathbase payload=json.dumps(problem) params = self.params.copy() params.update(kwargs) req = self.session.post(path, params=params, headers=self.headers, data=payload) self.validateReply(req) return req.text def delete(self,solverId): path = "{base}/{solverId}".format(base=self.pathbase, solverId=str(solverId)) req = self.session.delete(path, params=self.params, headers=self.headers) self.validateReply(req) return True def stop(self,solverId): path = "{base}/{solverId}/stop".format(base=self.pathbase, solverId=str(solverId)) req = self.session.put(path, params=self.params, headers=self.headers) self.validateReply(req) return True def getStatus(self,solverId): path = "{base}/{solverId}/status".format(base=self.pathbase, solverId=str(solverId)) req = self.session.get(path, params=self.params, headers=self.headers) self.validateReply(req) return req.json() def getSolution(self,solverId): path = "{base}/{solverId}/solution".format(base=self.pathbase, solverId=str(solverId)) req = self.session.get(path, params=self.params, headers=self.headers) self.validateReply(req) return req.json() # polling def createAndWait(self,problem,cancel,**kwargs): solverId = self.create(problem,**kwargs) timeout = 300 while not cancel() and timeout>0: status = self.getStatus(solverId) if status["execStatus"] =="invalid": raise exception.solverError(json.dumps(status["errors"])) if status["execStatus"] =="completed": return self.getSolution(solverId) time.sleep(1) timeout -= 1 if timeout == 0: raise exception.InternalError("Timed out waiting for solver") raise exception.UserCancelled()
Java
/* Copyright 2008, 2009, 2010 by the Oxford University Computing Laboratory This file is part of HermiT. HermiT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. HermiT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with HermiT. If not, see <http://www.gnu.org/licenses/>. */ package org.semanticweb.HermiT.datatypes.owlreal; import java.math.BigDecimal; import java.math.BigInteger; public enum NumberRange { NOTHING, INTEGER, DECIMAL, RATIONAL, REAL; public boolean isDense() { return ordinal() >= DECIMAL.ordinal(); } public static NumberRange intersection(NumberRange it1, NumberRange it2) { int minOrdinal = Math.min(it1.ordinal(), it2.ordinal()); return values()[minOrdinal]; } public static NumberRange union(NumberRange it1, NumberRange it2) { int maxOrdinal = Math.max(it1.ordinal(), it2.ordinal()); return values()[maxOrdinal]; } public static boolean isSubsetOf(NumberRange subset, NumberRange superset) { return subset.ordinal() <= superset.ordinal(); } public static NumberRange getMostSpecificRange(Number n) { if (n instanceof Integer || n instanceof Long || n instanceof BigInteger) return INTEGER; else if (n instanceof BigDecimal) return DECIMAL; else if (n instanceof BigRational) return RATIONAL; else throw new IllegalArgumentException(); } }
Java
/* * Copyright 2017-2022 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.lookoutequipment.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.lookoutequipment.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CreateDatasetResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateDatasetResultJsonUnmarshaller implements Unmarshaller<CreateDatasetResult, JsonUnmarshallerContext> { public CreateDatasetResult unmarshall(JsonUnmarshallerContext context) throws Exception { CreateDatasetResult createDatasetResult = new CreateDatasetResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return createDatasetResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("DatasetName", targetDepth)) { context.nextToken(); createDatasetResult.setDatasetName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("DatasetArn", targetDepth)) { context.nextToken(); createDatasetResult.setDatasetArn(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Status", targetDepth)) { context.nextToken(); createDatasetResult.setStatus(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return createDatasetResult; } private static CreateDatasetResultJsonUnmarshaller instance; public static CreateDatasetResultJsonUnmarshaller getInstance() { if (instance == null) instance = new CreateDatasetResultJsonUnmarshaller(); return instance; } }
Java
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Recipe.cs" company="Dapr Labs"> // Copyright 2014, Dapr Labs Pty. Ltd. // </copyright> // <summary> // Describes a recipe. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ForkTip.Models { using System; using System.Collections.Generic; /// <summary> /// Describes a recipe. /// </summary> [Serializable] public class Recipe { /// <summary> /// Gets or sets the id. /// </summary> public Guid Id { get; set; } /// <summary> /// Gets or sets the name. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the creator's name. /// </summary> public string Author { get; set; } /// <summary> /// Gets or sets the description. /// </summary> public string Description { get; set; } /// <summary> /// Gets or sets the ingredients. /// </summary> public List<string> Ingredients { get; set; } /// <summary> /// Gets or sets the directions. /// </summary> public List<string> Directions { get; set; } } }
Java
package com.designpattern.structural.facade; public class Facade { SystemOne system1 = new SystemOne(); SystemTwo system2 = new SystemTwo(); SystemThree system3 = new SystemThree(); SystemFour system4 = new SystemFour(); public void facadeFunction1() { System.out.println("---- facade function 1"); system1.methodOne(); system3.methodThree(); system4.methodFour(); System.out.println("---- facade function 1 end"); } public void facadeFunction2() { System.out.println("---- facade function 2"); system2.methodTwo(); system3.methodThree(); System.out.println("---- facade function 2 end"); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_92) on Wed Jul 27 21:27:29 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>PythonParserConstants (PMD Python 5.5.1 API)</title> <meta name="date" content="2016-07-27"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="PythonParserConstants (PMD Python 5.5.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/PythonParserConstants.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserTokenManager.html" title="class in net.sourceforge.pmd.lang.python.ast"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html" target="_top">Frames</a></li> <li><a href="PythonParserConstants.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">net.sourceforge.pmd.lang.python.ast</div> <h2 title="Interface PythonParserConstants" class="title">Interface PythonParserConstants</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserTokenManager.html" title="class in net.sourceforge.pmd.lang.python.ast">PythonParserTokenManager</a></dd> </dl> <hr> <br> <pre>public interface <span class="typeNameLabel">PythonParserConstants</span></pre> <div class="block">Token literal values and constants. Generated by org.javacc.parser.OtherFilesGen#start()</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#AND">AND</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#AND_BOOL">AND_BOOL</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#ANDEQ">ANDEQ</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#AS">AS</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#ASSERT">ASSERT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#AT">AT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#BINNUMBER">BINNUMBER</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#BREAK">BREAK</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#CLASS">CLASS</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#COLON">COLON</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#COMMA">COMMA</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#COMPLEX">COMPLEX</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#CONTINUATION">CONTINUATION</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#CONTINUE">CONTINUE</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#DECNUMBER">DECNUMBER</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#DEF">DEF</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#DEFAULT">DEFAULT</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#DEL">DEL</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#DIGIT">DIGIT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#DIVIDE">DIVIDE</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#DIVIDEEQ">DIVIDEEQ</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#DOT">DOT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#ELIF">ELIF</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#ELSE">ELSE</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#EOF">EOF</a></span></code> <div class="block">End of File.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#EQEQUAL">EQEQUAL</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#EQGREATER">EQGREATER</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#EQLESS">EQLESS</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#EQUAL">EQUAL</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#EXCEPT">EXCEPT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#EXEC">EXEC</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#EXPONENT">EXPONENT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#FINALLY">FINALLY</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#FLOAT">FLOAT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#FLOORDIVIDE">FLOORDIVIDE</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#FLOORDIVIDEEQ">FLOORDIVIDEEQ</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#FOR">FOR</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#FROM">FROM</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#GLOBAL">GLOBAL</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#GREATER">GREATER</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#HEXNUMBER">HEXNUMBER</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IF">IF</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IMPORT">IMPORT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN">IN</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_BSTRING11">IN_BSTRING11</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_BSTRING13">IN_BSTRING13</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_BSTRING1NLC">IN_BSTRING1NLC</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_BSTRING21">IN_BSTRING21</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_BSTRING23">IN_BSTRING23</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_BSTRING2NLC">IN_BSTRING2NLC</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_STRING11">IN_STRING11</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_STRING13">IN_STRING13</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_STRING1NLC">IN_STRING1NLC</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_STRING21">IN_STRING21</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_STRING23">IN_STRING23</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_STRING2NLC">IN_STRING2NLC</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_USTRING11">IN_USTRING11</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_USTRING13">IN_USTRING13</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_USTRING1NLC">IN_USTRING1NLC</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_USTRING21">IN_USTRING21</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_USTRING23">IN_USTRING23</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IN_USTRING2NLC">IN_USTRING2NLC</a></span></code> <div class="block">Lexical state.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#IS">IS</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#LAMBDA">LAMBDA</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#LBRACE">LBRACE</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#LBRACKET">LBRACKET</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#LESS">LESS</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#LESSGREATER">LESSGREATER</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#LETTER">LETTER</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#LPAREN">LPAREN</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#LSHIFT">LSHIFT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#LSHIFTEQ">LSHIFTEQ</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#MINUS">MINUS</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#MINUSEQ">MINUSEQ</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#MODULO">MODULO</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#MODULOEQ">MODULOEQ</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#MULTIPLY">MULTIPLY</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#MULTIPLYEQ">MULTIPLYEQ</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#NAME">NAME</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#NEWLINE">NEWLINE</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#NOT">NOT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#NOT_BOOL">NOT_BOOL</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#NOTEQUAL">NOTEQUAL</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#OCTNUMBER">OCTNUMBER</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#OR">OR</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#OR_BOOL">OR_BOOL</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#OREQ">OREQ</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#PASS">PASS</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#PLUS">PLUS</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#PLUSEQ">PLUSEQ</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#POWER">POWER</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#POWEREQ">POWEREQ</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#PRINT">PRINT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#RAISE">RAISE</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#RBRACE">RBRACE</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#RBRACKET">RBRACKET</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#RETURN">RETURN</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#RPAREN">RPAREN</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#RSHIFT">RSHIFT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#RSHIFTEQ">RSHIFTEQ</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#SEMICOLON">SEMICOLON</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#SINGLE_BSTRING">SINGLE_BSTRING</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#SINGLE_BSTRING2">SINGLE_BSTRING2</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#SINGLE_STRING">SINGLE_STRING</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#SINGLE_STRING2">SINGLE_STRING2</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#SINGLE_USTRING">SINGLE_USTRING</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#SINGLE_USTRING2">SINGLE_USTRING2</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#SPACE">SPACE</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#tokenImage">tokenImage</a></span></code> <div class="block">Literal token values.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#TRAILING_COMMENT">TRAILING_COMMENT</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#TRIPLE_BSTRING">TRIPLE_BSTRING</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#TRIPLE_BSTRING2">TRIPLE_BSTRING2</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#TRIPLE_STRING">TRIPLE_STRING</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#TRIPLE_STRING2">TRIPLE_STRING2</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#TRIPLE_USTRING">TRIPLE_USTRING</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#TRIPLE_USTRING2">TRIPLE_USTRING2</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#TRY">TRY</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#WHILE">WHILE</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#WITH">WITH</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#XOR">XOR</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#XOREQ">XOREQ</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html#YIELD">YIELD</a></span></code> <div class="block">RegularExpression Id.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="EOF"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>EOF</h4> <pre>static final&nbsp;int EOF</pre> <div class="block">End of File.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.EOF">Constant Field Values</a></dd> </dl> </li> </ul> <a name="SPACE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>SPACE</h4> <pre>static final&nbsp;int SPACE</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.SPACE">Constant Field Values</a></dd> </dl> </li> </ul> <a name="CONTINUATION"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>CONTINUATION</h4> <pre>static final&nbsp;int CONTINUATION</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.CONTINUATION">Constant Field Values</a></dd> </dl> </li> </ul> <a name="NEWLINE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>NEWLINE</h4> <pre>static final&nbsp;int NEWLINE</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.NEWLINE">Constant Field Values</a></dd> </dl> </li> </ul> <a name="TRAILING_COMMENT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TRAILING_COMMENT</h4> <pre>static final&nbsp;int TRAILING_COMMENT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.TRAILING_COMMENT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="LPAREN"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>LPAREN</h4> <pre>static final&nbsp;int LPAREN</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.LPAREN">Constant Field Values</a></dd> </dl> </li> </ul> <a name="RPAREN"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>RPAREN</h4> <pre>static final&nbsp;int RPAREN</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.RPAREN">Constant Field Values</a></dd> </dl> </li> </ul> <a name="LBRACE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>LBRACE</h4> <pre>static final&nbsp;int LBRACE</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.LBRACE">Constant Field Values</a></dd> </dl> </li> </ul> <a name="RBRACE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>RBRACE</h4> <pre>static final&nbsp;int RBRACE</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.RBRACE">Constant Field Values</a></dd> </dl> </li> </ul> <a name="LBRACKET"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>LBRACKET</h4> <pre>static final&nbsp;int LBRACKET</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.LBRACKET">Constant Field Values</a></dd> </dl> </li> </ul> <a name="RBRACKET"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>RBRACKET</h4> <pre>static final&nbsp;int RBRACKET</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.RBRACKET">Constant Field Values</a></dd> </dl> </li> </ul> <a name="SEMICOLON"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>SEMICOLON</h4> <pre>static final&nbsp;int SEMICOLON</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.SEMICOLON">Constant Field Values</a></dd> </dl> </li> </ul> <a name="COMMA"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COMMA</h4> <pre>static final&nbsp;int COMMA</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.COMMA">Constant Field Values</a></dd> </dl> </li> </ul> <a name="DOT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>DOT</h4> <pre>static final&nbsp;int DOT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.DOT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="COLON"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COLON</h4> <pre>static final&nbsp;int COLON</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.COLON">Constant Field Values</a></dd> </dl> </li> </ul> <a name="PLUS"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>PLUS</h4> <pre>static final&nbsp;int PLUS</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.PLUS">Constant Field Values</a></dd> </dl> </li> </ul> <a name="MINUS"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>MINUS</h4> <pre>static final&nbsp;int MINUS</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.MINUS">Constant Field Values</a></dd> </dl> </li> </ul> <a name="MULTIPLY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>MULTIPLY</h4> <pre>static final&nbsp;int MULTIPLY</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.MULTIPLY">Constant Field Values</a></dd> </dl> </li> </ul> <a name="DIVIDE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>DIVIDE</h4> <pre>static final&nbsp;int DIVIDE</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.DIVIDE">Constant Field Values</a></dd> </dl> </li> </ul> <a name="FLOORDIVIDE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>FLOORDIVIDE</h4> <pre>static final&nbsp;int FLOORDIVIDE</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.FLOORDIVIDE">Constant Field Values</a></dd> </dl> </li> </ul> <a name="POWER"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>POWER</h4> <pre>static final&nbsp;int POWER</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.POWER">Constant Field Values</a></dd> </dl> </li> </ul> <a name="LSHIFT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>LSHIFT</h4> <pre>static final&nbsp;int LSHIFT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.LSHIFT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="RSHIFT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>RSHIFT</h4> <pre>static final&nbsp;int RSHIFT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.RSHIFT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="MODULO"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>MODULO</h4> <pre>static final&nbsp;int MODULO</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.MODULO">Constant Field Values</a></dd> </dl> </li> </ul> <a name="NOT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>NOT</h4> <pre>static final&nbsp;int NOT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.NOT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="XOR"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>XOR</h4> <pre>static final&nbsp;int XOR</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.XOR">Constant Field Values</a></dd> </dl> </li> </ul> <a name="OR"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>OR</h4> <pre>static final&nbsp;int OR</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.OR">Constant Field Values</a></dd> </dl> </li> </ul> <a name="AND"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>AND</h4> <pre>static final&nbsp;int AND</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.AND">Constant Field Values</a></dd> </dl> </li> </ul> <a name="EQUAL"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>EQUAL</h4> <pre>static final&nbsp;int EQUAL</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.EQUAL">Constant Field Values</a></dd> </dl> </li> </ul> <a name="GREATER"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>GREATER</h4> <pre>static final&nbsp;int GREATER</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.GREATER">Constant Field Values</a></dd> </dl> </li> </ul> <a name="LESS"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>LESS</h4> <pre>static final&nbsp;int LESS</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.LESS">Constant Field Values</a></dd> </dl> </li> </ul> <a name="EQEQUAL"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>EQEQUAL</h4> <pre>static final&nbsp;int EQEQUAL</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.EQEQUAL">Constant Field Values</a></dd> </dl> </li> </ul> <a name="EQLESS"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>EQLESS</h4> <pre>static final&nbsp;int EQLESS</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.EQLESS">Constant Field Values</a></dd> </dl> </li> </ul> <a name="EQGREATER"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>EQGREATER</h4> <pre>static final&nbsp;int EQGREATER</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.EQGREATER">Constant Field Values</a></dd> </dl> </li> </ul> <a name="LESSGREATER"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>LESSGREATER</h4> <pre>static final&nbsp;int LESSGREATER</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.LESSGREATER">Constant Field Values</a></dd> </dl> </li> </ul> <a name="NOTEQUAL"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>NOTEQUAL</h4> <pre>static final&nbsp;int NOTEQUAL</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.NOTEQUAL">Constant Field Values</a></dd> </dl> </li> </ul> <a name="PLUSEQ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>PLUSEQ</h4> <pre>static final&nbsp;int PLUSEQ</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.PLUSEQ">Constant Field Values</a></dd> </dl> </li> </ul> <a name="MINUSEQ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>MINUSEQ</h4> <pre>static final&nbsp;int MINUSEQ</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.MINUSEQ">Constant Field Values</a></dd> </dl> </li> </ul> <a name="MULTIPLYEQ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>MULTIPLYEQ</h4> <pre>static final&nbsp;int MULTIPLYEQ</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.MULTIPLYEQ">Constant Field Values</a></dd> </dl> </li> </ul> <a name="DIVIDEEQ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>DIVIDEEQ</h4> <pre>static final&nbsp;int DIVIDEEQ</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.DIVIDEEQ">Constant Field Values</a></dd> </dl> </li> </ul> <a name="FLOORDIVIDEEQ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>FLOORDIVIDEEQ</h4> <pre>static final&nbsp;int FLOORDIVIDEEQ</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.FLOORDIVIDEEQ">Constant Field Values</a></dd> </dl> </li> </ul> <a name="MODULOEQ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>MODULOEQ</h4> <pre>static final&nbsp;int MODULOEQ</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.MODULOEQ">Constant Field Values</a></dd> </dl> </li> </ul> <a name="ANDEQ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ANDEQ</h4> <pre>static final&nbsp;int ANDEQ</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.ANDEQ">Constant Field Values</a></dd> </dl> </li> </ul> <a name="OREQ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>OREQ</h4> <pre>static final&nbsp;int OREQ</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.OREQ">Constant Field Values</a></dd> </dl> </li> </ul> <a name="XOREQ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>XOREQ</h4> <pre>static final&nbsp;int XOREQ</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.XOREQ">Constant Field Values</a></dd> </dl> </li> </ul> <a name="LSHIFTEQ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>LSHIFTEQ</h4> <pre>static final&nbsp;int LSHIFTEQ</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.LSHIFTEQ">Constant Field Values</a></dd> </dl> </li> </ul> <a name="RSHIFTEQ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>RSHIFTEQ</h4> <pre>static final&nbsp;int RSHIFTEQ</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.RSHIFTEQ">Constant Field Values</a></dd> </dl> </li> </ul> <a name="POWEREQ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>POWEREQ</h4> <pre>static final&nbsp;int POWEREQ</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.POWEREQ">Constant Field Values</a></dd> </dl> </li> </ul> <a name="OR_BOOL"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>OR_BOOL</h4> <pre>static final&nbsp;int OR_BOOL</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.OR_BOOL">Constant Field Values</a></dd> </dl> </li> </ul> <a name="AND_BOOL"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>AND_BOOL</h4> <pre>static final&nbsp;int AND_BOOL</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.AND_BOOL">Constant Field Values</a></dd> </dl> </li> </ul> <a name="NOT_BOOL"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>NOT_BOOL</h4> <pre>static final&nbsp;int NOT_BOOL</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.NOT_BOOL">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IS"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IS</h4> <pre>static final&nbsp;int IS</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IS">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN</h4> <pre>static final&nbsp;int IN</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN">Constant Field Values</a></dd> </dl> </li> </ul> <a name="LAMBDA"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>LAMBDA</h4> <pre>static final&nbsp;int LAMBDA</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.LAMBDA">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IF"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IF</h4> <pre>static final&nbsp;int IF</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IF">Constant Field Values</a></dd> </dl> </li> </ul> <a name="ELSE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ELSE</h4> <pre>static final&nbsp;int ELSE</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.ELSE">Constant Field Values</a></dd> </dl> </li> </ul> <a name="ELIF"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ELIF</h4> <pre>static final&nbsp;int ELIF</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.ELIF">Constant Field Values</a></dd> </dl> </li> </ul> <a name="WHILE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>WHILE</h4> <pre>static final&nbsp;int WHILE</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.WHILE">Constant Field Values</a></dd> </dl> </li> </ul> <a name="FOR"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>FOR</h4> <pre>static final&nbsp;int FOR</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.FOR">Constant Field Values</a></dd> </dl> </li> </ul> <a name="TRY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TRY</h4> <pre>static final&nbsp;int TRY</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.TRY">Constant Field Values</a></dd> </dl> </li> </ul> <a name="EXCEPT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>EXCEPT</h4> <pre>static final&nbsp;int EXCEPT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.EXCEPT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="DEF"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>DEF</h4> <pre>static final&nbsp;int DEF</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.DEF">Constant Field Values</a></dd> </dl> </li> </ul> <a name="CLASS"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>CLASS</h4> <pre>static final&nbsp;int CLASS</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.CLASS">Constant Field Values</a></dd> </dl> </li> </ul> <a name="FINALLY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>FINALLY</h4> <pre>static final&nbsp;int FINALLY</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.FINALLY">Constant Field Values</a></dd> </dl> </li> </ul> <a name="PRINT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>PRINT</h4> <pre>static final&nbsp;int PRINT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.PRINT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="PASS"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>PASS</h4> <pre>static final&nbsp;int PASS</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.PASS">Constant Field Values</a></dd> </dl> </li> </ul> <a name="BREAK"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>BREAK</h4> <pre>static final&nbsp;int BREAK</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.BREAK">Constant Field Values</a></dd> </dl> </li> </ul> <a name="CONTINUE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>CONTINUE</h4> <pre>static final&nbsp;int CONTINUE</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.CONTINUE">Constant Field Values</a></dd> </dl> </li> </ul> <a name="RETURN"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>RETURN</h4> <pre>static final&nbsp;int RETURN</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.RETURN">Constant Field Values</a></dd> </dl> </li> </ul> <a name="YIELD"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>YIELD</h4> <pre>static final&nbsp;int YIELD</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.YIELD">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IMPORT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IMPORT</h4> <pre>static final&nbsp;int IMPORT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IMPORT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="FROM"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>FROM</h4> <pre>static final&nbsp;int FROM</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.FROM">Constant Field Values</a></dd> </dl> </li> </ul> <a name="DEL"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>DEL</h4> <pre>static final&nbsp;int DEL</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.DEL">Constant Field Values</a></dd> </dl> </li> </ul> <a name="RAISE"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>RAISE</h4> <pre>static final&nbsp;int RAISE</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.RAISE">Constant Field Values</a></dd> </dl> </li> </ul> <a name="GLOBAL"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>GLOBAL</h4> <pre>static final&nbsp;int GLOBAL</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.GLOBAL">Constant Field Values</a></dd> </dl> </li> </ul> <a name="EXEC"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>EXEC</h4> <pre>static final&nbsp;int EXEC</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.EXEC">Constant Field Values</a></dd> </dl> </li> </ul> <a name="ASSERT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ASSERT</h4> <pre>static final&nbsp;int ASSERT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.ASSERT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="AS"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>AS</h4> <pre>static final&nbsp;int AS</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.AS">Constant Field Values</a></dd> </dl> </li> </ul> <a name="WITH"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>WITH</h4> <pre>static final&nbsp;int WITH</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.WITH">Constant Field Values</a></dd> </dl> </li> </ul> <a name="AT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>AT</h4> <pre>static final&nbsp;int AT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.AT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="NAME"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>NAME</h4> <pre>static final&nbsp;int NAME</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.NAME">Constant Field Values</a></dd> </dl> </li> </ul> <a name="LETTER"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>LETTER</h4> <pre>static final&nbsp;int LETTER</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.LETTER">Constant Field Values</a></dd> </dl> </li> </ul> <a name="DECNUMBER"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>DECNUMBER</h4> <pre>static final&nbsp;int DECNUMBER</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.DECNUMBER">Constant Field Values</a></dd> </dl> </li> </ul> <a name="HEXNUMBER"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>HEXNUMBER</h4> <pre>static final&nbsp;int HEXNUMBER</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.HEXNUMBER">Constant Field Values</a></dd> </dl> </li> </ul> <a name="OCTNUMBER"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>OCTNUMBER</h4> <pre>static final&nbsp;int OCTNUMBER</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.OCTNUMBER">Constant Field Values</a></dd> </dl> </li> </ul> <a name="BINNUMBER"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>BINNUMBER</h4> <pre>static final&nbsp;int BINNUMBER</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.BINNUMBER">Constant Field Values</a></dd> </dl> </li> </ul> <a name="FLOAT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>FLOAT</h4> <pre>static final&nbsp;int FLOAT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.FLOAT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="COMPLEX"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>COMPLEX</h4> <pre>static final&nbsp;int COMPLEX</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.COMPLEX">Constant Field Values</a></dd> </dl> </li> </ul> <a name="EXPONENT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>EXPONENT</h4> <pre>static final&nbsp;int EXPONENT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.EXPONENT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="DIGIT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>DIGIT</h4> <pre>static final&nbsp;int DIGIT</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.DIGIT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="SINGLE_STRING"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>SINGLE_STRING</h4> <pre>static final&nbsp;int SINGLE_STRING</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.SINGLE_STRING">Constant Field Values</a></dd> </dl> </li> </ul> <a name="SINGLE_STRING2"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>SINGLE_STRING2</h4> <pre>static final&nbsp;int SINGLE_STRING2</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.SINGLE_STRING2">Constant Field Values</a></dd> </dl> </li> </ul> <a name="TRIPLE_STRING"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TRIPLE_STRING</h4> <pre>static final&nbsp;int TRIPLE_STRING</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.TRIPLE_STRING">Constant Field Values</a></dd> </dl> </li> </ul> <a name="TRIPLE_STRING2"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TRIPLE_STRING2</h4> <pre>static final&nbsp;int TRIPLE_STRING2</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.TRIPLE_STRING2">Constant Field Values</a></dd> </dl> </li> </ul> <a name="SINGLE_BSTRING"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>SINGLE_BSTRING</h4> <pre>static final&nbsp;int SINGLE_BSTRING</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.SINGLE_BSTRING">Constant Field Values</a></dd> </dl> </li> </ul> <a name="SINGLE_BSTRING2"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>SINGLE_BSTRING2</h4> <pre>static final&nbsp;int SINGLE_BSTRING2</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.SINGLE_BSTRING2">Constant Field Values</a></dd> </dl> </li> </ul> <a name="TRIPLE_BSTRING"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TRIPLE_BSTRING</h4> <pre>static final&nbsp;int TRIPLE_BSTRING</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.TRIPLE_BSTRING">Constant Field Values</a></dd> </dl> </li> </ul> <a name="TRIPLE_BSTRING2"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TRIPLE_BSTRING2</h4> <pre>static final&nbsp;int TRIPLE_BSTRING2</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.TRIPLE_BSTRING2">Constant Field Values</a></dd> </dl> </li> </ul> <a name="SINGLE_USTRING"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>SINGLE_USTRING</h4> <pre>static final&nbsp;int SINGLE_USTRING</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.SINGLE_USTRING">Constant Field Values</a></dd> </dl> </li> </ul> <a name="SINGLE_USTRING2"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>SINGLE_USTRING2</h4> <pre>static final&nbsp;int SINGLE_USTRING2</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.SINGLE_USTRING2">Constant Field Values</a></dd> </dl> </li> </ul> <a name="TRIPLE_USTRING"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TRIPLE_USTRING</h4> <pre>static final&nbsp;int TRIPLE_USTRING</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.TRIPLE_USTRING">Constant Field Values</a></dd> </dl> </li> </ul> <a name="TRIPLE_USTRING2"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TRIPLE_USTRING2</h4> <pre>static final&nbsp;int TRIPLE_USTRING2</pre> <div class="block">RegularExpression Id.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.TRIPLE_USTRING2">Constant Field Values</a></dd> </dl> </li> </ul> <a name="DEFAULT"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>DEFAULT</h4> <pre>static final&nbsp;int DEFAULT</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.DEFAULT">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_STRING11"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_STRING11</h4> <pre>static final&nbsp;int IN_STRING11</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_STRING11">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_STRING21"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_STRING21</h4> <pre>static final&nbsp;int IN_STRING21</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_STRING21">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_STRING13"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_STRING13</h4> <pre>static final&nbsp;int IN_STRING13</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_STRING13">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_STRING23"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_STRING23</h4> <pre>static final&nbsp;int IN_STRING23</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_STRING23">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_BSTRING11"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_BSTRING11</h4> <pre>static final&nbsp;int IN_BSTRING11</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_BSTRING11">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_BSTRING21"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_BSTRING21</h4> <pre>static final&nbsp;int IN_BSTRING21</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_BSTRING21">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_BSTRING13"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_BSTRING13</h4> <pre>static final&nbsp;int IN_BSTRING13</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_BSTRING13">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_BSTRING23"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_BSTRING23</h4> <pre>static final&nbsp;int IN_BSTRING23</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_BSTRING23">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_USTRING11"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_USTRING11</h4> <pre>static final&nbsp;int IN_USTRING11</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_USTRING11">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_USTRING21"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_USTRING21</h4> <pre>static final&nbsp;int IN_USTRING21</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_USTRING21">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_USTRING13"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_USTRING13</h4> <pre>static final&nbsp;int IN_USTRING13</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_USTRING13">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_USTRING23"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_USTRING23</h4> <pre>static final&nbsp;int IN_USTRING23</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_USTRING23">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_STRING1NLC"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_STRING1NLC</h4> <pre>static final&nbsp;int IN_STRING1NLC</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_STRING1NLC">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_STRING2NLC"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_STRING2NLC</h4> <pre>static final&nbsp;int IN_STRING2NLC</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_STRING2NLC">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_USTRING1NLC"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_USTRING1NLC</h4> <pre>static final&nbsp;int IN_USTRING1NLC</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_USTRING1NLC">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_USTRING2NLC"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_USTRING2NLC</h4> <pre>static final&nbsp;int IN_USTRING2NLC</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_USTRING2NLC">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_BSTRING1NLC"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_BSTRING1NLC</h4> <pre>static final&nbsp;int IN_BSTRING1NLC</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_BSTRING1NLC">Constant Field Values</a></dd> </dl> </li> </ul> <a name="IN_BSTRING2NLC"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IN_BSTRING2NLC</h4> <pre>static final&nbsp;int IN_BSTRING2NLC</pre> <div class="block">Lexical state.</div> <dl> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../../../constant-values.html#net.sourceforge.pmd.lang.python.ast.PythonParserConstants.IN_BSTRING2NLC">Constant Field Values</a></dd> </dl> </li> </ul> <a name="tokenImage"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>tokenImage</h4> <pre>static final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[] tokenImage</pre> <div class="block">Literal token values.</div> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/PythonParserConstants.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../../net/sourceforge/pmd/lang/python/ast/PythonParserTokenManager.html" title="class in net.sourceforge.pmd.lang.python.ast"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sourceforge/pmd/lang/python/ast/PythonParserConstants.html" target="_top">Frames</a></li> <li><a href="PythonParserConstants.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2002&#x2013;2016 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All rights reserved.</small></p> </body> </html>
Java
<?php namespace Slime; use Illuminate\Database\Eloquent\Model; class Persona extends Model { protected $table = "Persona"; protected $fillable = ['nombre','apellido','Cargo_id']; }
Java
/* * Copyright (C) 2013 @JamesMontemagno http://www.montemagno.com http://www.refractored.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. */ using System; using System.Collections.Generic; using Android.Content; using Android.Content.Res; using Android.Graphics; using Android.Runtime; using Android.Util; using Android.Widget; using MyCompany.Visitors.Client.Droid; namespace com.refractored.controls { public class RobotoTextView : TextView { private const int RobotoThin = 0; private const int RobotoThinItalic = 1; private const int RobotoLight = 2; private const int RobotoLightItalic = 3; private const int RobotoRegular = 4; private const int RobotoItalic = 5; private const int RobotoMedium = 6; private const int RobotoMediumItalic = 7; private const int RobotoBold = 8; private const int RobotoBoldItalic = 9; private const int RobotoBlack = 10; private const int RobotoBlackItalic = 11; private const int RobotoCondensed = 12; private const int RobotoCondensedItalic = 13; private const int RobotoCondensedBold = 14; private const int RobotoCondensedBoldItalic = 15; private TypefaceStyle m_Style = TypefaceStyle.Normal; private static readonly Dictionary<int, Typeface> Typefaces = new Dictionary<int, Typeface>(16); public RobotoTextView(Context context) : base(context) { } protected RobotoTextView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } public RobotoTextView(Context context, IAttributeSet attrs) : base(context, attrs) { this.Initialize(context, attrs); } public RobotoTextView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { this.Initialize(context, attrs); } private void Initialize(Context context, IAttributeSet attrs) { try { TypedArray values = context.ObtainStyledAttributes(attrs, Resource.Styleable.RobotoTextView); int typefaceValue = values.GetInt(Resource.Styleable.RobotoTextView_typeface, 4); values.Recycle(); var font = this.ObtainTypeface(context, typefaceValue); this.SetTypeface(font, this.m_Style); } catch (Exception) { } } private Typeface ObtainTypeface(Context context, int typefaceValue) { try { Typeface typeface = null; if (Typefaces.ContainsKey(typefaceValue)) typeface = Typefaces[typefaceValue]; if (typeface == null) { typeface = this.CreateTypeface(context, typefaceValue); Typefaces.Add(typefaceValue, typeface); } return typeface; } catch (Exception ex) { } return null; } private Typeface CreateTypeface(Context context, int typefaceValue) { try { Typeface typeface; switch (typefaceValue) { case RobotoThin: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Thin.ttf"); break; case RobotoThinItalic: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-ThinItalic.ttf"); m_Style = TypefaceStyle.Italic; break; case RobotoLight: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Light.ttf"); break; case RobotoLightItalic: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-LightItalic.ttf"); m_Style = TypefaceStyle.Italic; break; case RobotoRegular: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Regular.ttf"); break; case RobotoItalic: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Italic.ttf"); m_Style = TypefaceStyle.Italic; break; case RobotoMedium: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Medium.ttf"); break; case RobotoMediumItalic: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-MediumItalic.ttf"); m_Style = TypefaceStyle.Italic; break; case RobotoBold: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Bold.ttf"); m_Style = TypefaceStyle.Bold; break; case RobotoBoldItalic: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-BoldItalic.ttf"); m_Style = TypefaceStyle.BoldItalic; break; case RobotoBlack: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Black.ttf"); break; case RobotoBlackItalic: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-BlackItalic.ttf"); m_Style = TypefaceStyle.Italic; break; case RobotoCondensed: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-Condensed.ttf"); break; case RobotoCondensedItalic: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-CondensedItalic.ttf"); m_Style = TypefaceStyle.Italic; break; case RobotoCondensedBold: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-BoldCondensed.ttf"); m_Style = TypefaceStyle.Bold; break; case RobotoCondensedBoldItalic: typeface = Typeface.CreateFromAsset(context.Assets, "fonts/Roboto-BoldCondensedItalic.ttf"); m_Style = TypefaceStyle.BoldItalic; break; default: throw new ArgumentException("Unknown typeface attribute value " + typefaceValue); } return typeface; } catch (Exception) { } return null; } } }
Java