text
stringlengths 7
1.01M
|
|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* This package is based on the work done by Timothy Gerard Endres
* (time@ice.com) to whom the Ant project is very grateful for his great code.
*/
package org.apache.tools.tar;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Locale;
import org.apache.tools.zip.ZipEncoding;
/**
* This class represents an entry in a Tar archive. It consists
* of the entry's header, as well as the entry's File. Entries
* can be instantiated in one of three ways, depending on how
* they are to be used.
* <p>
* TarEntries that are created from the header bytes read from
* an archive are instantiated with the TarEntry(byte[])
* constructor. These entries will be used when extracting from
* or listing the contents of an archive. These entries have their
* header filled in using the header bytes. They also set the File
* to null, since they reference an archive entry not a file.
* </p>
* <p>
* TarEntries that are created from Files that are to be written
* into an archive are instantiated with the TarEntry(File)
* constructor. These entries have their header filled in using
* the File's information. They also keep a reference to the File
* for convenience when writing entries.
* </p>
* <p>
* Finally, TarEntries can be constructed from nothing but a name.
* This allows the programmer to construct the entry by hand, for
* instance when only an InputStream is available for writing to
* the archive, and the header information is constructed from
* other information. In this case the header fields are set to
* defaults and the File is set to null.
* </p>
* The C structure for a Tar Entry's header is:
* <pre>
* struct header {
* char name[NAMSIZ];
* char mode[8];
* char uid[8];
* char gid[8];
* char size[12];
* char mtime[12];
* char chksum[8];
* char linkflag;
* char linkname[NAMSIZ];
* char magic[8];
* char uname[TUNMLEN];
* char gname[TGNMLEN];
* char devmajor[8];
* char devminor[8];
* } header;
* All unused bytes are set to null.
* New-style GNU tar files are slightly different from the above.
* For values of size larger than 077777777777L (11 7s)
* or uid and gid larger than 07777777L (7 7s)
* the sign bit of the first byte is set, and the rest of the
* field is the binary representation of the number.
* See TarUtils.parseOctalOrBinary.
* </pre>
* The C structure for a old GNU Tar Entry's header is:
* <pre>
* struct oldgnu_header {
* char unused_pad1[345]; // TarConstants.PAD1LEN_GNU - offset 0
* char atime[12]; // TarConstants.ATIMELEN_GNU - offset 345
* char ctime[12]; // TarConstants.CTIMELEN_GNU - offset 357
* char offset[12]; // TarConstants.OFFSETLEN_GNU - offset 369
* char longnames[4]; // TarConstants.LONGNAMESLEN_GNU - offset 381
* char unused_pad2; // TarConstants.PAD2LEN_GNU - offset 385
* struct sparse sp[4]; // TarConstants.SPARSELEN_GNU - offset 386
* char isextended; // TarConstants.ISEXTENDEDLEN_GNU - offset 482
* char realsize[12]; // TarConstants.REALSIZELEN_GNU - offset 483
* char unused_pad[17]; // TarConstants.PAD3LEN_GNU - offset 495
* };
* </pre>
* Whereas, "struct sparse" is:
* <pre>
* struct sparse {
* char offset[12]; // offset 0
* char numbytes[12]; // offset 12
* };
* </pre>
*/
public class TarEntry implements TarConstants {
/** The entry's name. */
private String name;
/** The entry's permission mode. */
private int mode;
/** The entry's user id. */
private long userId;
/** The entry's group id. */
private long groupId;
/** The entry's size. */
private long size;
/** The entry's modification time. */
private long modTime;
/** The entry's link flag. */
private byte linkFlag;
/** The entry's link name. */
private String linkName;
/** The entry's magic tag. */
private String magic;
/** The version of the format */
private String version;
/** The entry's user name. */
private String userName;
/** The entry's group name. */
private String groupName;
/** The entry's major device number. */
private int devMajor;
/** The entry's minor device number. */
private int devMinor;
/** If an extension sparse header follows. */
private boolean isExtended;
/** The entry's real size in case of a sparse file. */
private long realSize;
/** The entry's file reference */
private File file;
/** Maximum length of a user's name in the tar file */
public static final int MAX_NAMELEN = 31;
/** Default permissions bits for directories */
public static final int DEFAULT_DIR_MODE = 040755;
/** Default permissions bits for files */
public static final int DEFAULT_FILE_MODE = 0100644;
/** Convert millis to seconds */
public static final int MILLIS_PER_SECOND = 1000;
/**
* Construct an empty entry and prepares the header values.
*/
private TarEntry() {
this.magic = MAGIC_POSIX;
this.version = VERSION_POSIX;
this.name = "";
this.linkName = "";
String user = System.getProperty("user.name", "");
if (user.length() > MAX_NAMELEN) {
user = user.substring(0, MAX_NAMELEN);
}
this.userId = 0;
this.groupId = 0;
this.userName = user;
this.groupName = "";
this.file = null;
}
/**
* Construct an entry with only a name. This allows the programmer
* to construct the entry's header "by hand". File is set to null.
*
* @param name the entry name
*/
public TarEntry(String name) {
this(name, false);
}
/**
* Construct an entry with only a name. This allows the programmer
* to construct the entry's header "by hand". File is set to null.
*
* @param name the entry name
* @param preserveLeadingSlashes whether to allow leading slashes
* in the name.
*/
public TarEntry(String name, boolean preserveLeadingSlashes) {
this();
name = normalizeFileName(name, preserveLeadingSlashes);
boolean isDir = name.endsWith("/");
this.devMajor = 0;
this.devMinor = 0;
this.name = name;
this.mode = isDir ? DEFAULT_DIR_MODE : DEFAULT_FILE_MODE;
this.linkFlag = isDir ? LF_DIR : LF_NORMAL;
this.userId = 0;
this.groupId = 0;
this.size = 0;
this.modTime = (new Date()).getTime() / MILLIS_PER_SECOND;
this.linkName = "";
this.userName = "";
this.groupName = "";
}
/**
* Construct an entry with a name and a link flag.
*
* @param name the entry name
* @param linkFlag the entry link flag.
*/
public TarEntry(String name, byte linkFlag) {
this(name);
this.linkFlag = linkFlag;
if (linkFlag == LF_GNUTYPE_LONGNAME) {
magic = GNU_TMAGIC;
version = VERSION_GNU_SPACE;
}
}
/**
* Construct an entry for a file. File is set to file, and the
* header is constructed from information from the file.
* The name is set from the normalized file path.
*
* @param file The file that the entry represents.
*/
public TarEntry(File file) {
this(file, file.getPath());
}
/**
* Construct an entry for a file. File is set to file, and the
* header is constructed from information from the file.
*
* @param file The file that the entry represents.
* @param fileName the name to be used for the entry.
*/
public TarEntry(File file, String fileName) {
this();
String normalizedName = normalizeFileName(fileName, false);
this.file = file;
this.linkName = "";
if (file.isDirectory()) {
this.mode = DEFAULT_DIR_MODE;
this.linkFlag = LF_DIR;
int nameLength = normalizedName.length();
if (nameLength == 0 || normalizedName.charAt(nameLength - 1) != '/') {
this.name = normalizedName + "/";
} else {
this.name = normalizedName;
}
this.size = 0;
} else {
this.mode = DEFAULT_FILE_MODE;
this.linkFlag = LF_NORMAL;
this.size = file.length();
this.name = normalizedName;
}
this.modTime = file.lastModified() / MILLIS_PER_SECOND;
this.devMajor = 0;
this.devMinor = 0;
}
/**
* Construct an entry from an archive's header bytes. File is set
* to null.
*
* @param headerBuf The header bytes from a tar archive entry.
* @throws IllegalArgumentException if any of the numeric fields have an invalid format
*/
public TarEntry(byte[] headerBuf) {
this();
parseTarHeader(headerBuf);
}
/**
* Construct an entry from an archive's header bytes. File is set
* to null.
*
* @param headerBuf The header bytes from a tar archive entry.
* @param encoding encoding to use for file names
* @throws IllegalArgumentException if any of the numeric fields have an invalid format
* @throws IOException if an error occurs during reading the archive
*/
public TarEntry(byte[] headerBuf, ZipEncoding encoding)
throws IOException {
this();
parseTarHeader(headerBuf, encoding);
}
/**
* Determine if the two entries are equal. Equality is determined
* by the header names being equal.
*
* @param it Entry to be checked for equality.
* @return True if the entries are equal.
*/
public boolean equals(TarEntry it) {
return it != null && getName().equals(it.getName());
}
/**
* Determine if the two entries are equal. Equality is determined
* by the header names being equal.
*
* @param it Entry to be checked for equality.
* @return True if the entries are equal.
*/
@Override
public boolean equals(Object it) {
return it != null && getClass() == it.getClass() && equals((TarEntry) it);
}
/**
* Hashcodes are based on entry names.
*
* @return the entry hashcode
*/
@Override
public int hashCode() {
return getName().hashCode();
}
/**
* Determine if the given entry is a descendant of this entry.
* Descendancy is determined by the name of the descendant
* starting with this entry's name.
*
* @param desc Entry to be checked as a descendant of this.
* @return True if entry is a descendant of this.
*/
public boolean isDescendent(TarEntry desc) {
return desc.getName().startsWith(getName());
}
/**
* Get this entry's name.
*
* @return This entry's name.
*/
public String getName() {
return name;
}
/**
* Set this entry's name.
*
* @param name This entry's new name.
*/
public void setName(String name) {
this.name = normalizeFileName(name, false);
}
/**
* Set the mode for this entry
*
* @param mode the mode for this entry
*/
public void setMode(int mode) {
this.mode = mode;
}
/**
* Get this entry's link name.
*
* @return This entry's link name.
*/
public String getLinkName() {
return linkName;
}
/**
* Set this entry's link name.
*
* @param link the link name to use.
*/
public void setLinkName(String link) {
this.linkName = link;
}
/**
* Get this entry's user id.
*
* @return This entry's user id.
* @deprecated use #getLongUserId instead as user ids can be
* bigger than {@link Integer#MAX_VALUE}
*/
@Deprecated
public int getUserId() {
return (int) userId;
}
/**
* Set this entry's user id.
*
* @param userId This entry's new user id.
*/
public void setUserId(int userId) {
setUserId((long) userId);
}
/**
* Get this entry's user id.
*
* @return This entry's user id.
* @since 1.9.5
*/
public long getLongUserId() {
return userId;
}
/**
* Set this entry's user id.
*
* @param userId This entry's new user id.
* @since 1.9.5
*/
public void setUserId(long userId) {
this.userId = userId;
}
/**
* Get this entry's group id.
*
* @return This entry's group id.
* @deprecated use #getLongGroupId instead as group ids can be
* bigger than {@link Integer#MAX_VALUE}
*/
@Deprecated
public int getGroupId() {
return (int) groupId;
}
/**
* Set this entry's group id.
*
* @param groupId This entry's new group id.
*/
public void setGroupId(int groupId) {
setGroupId((long) groupId);
}
/**
* Get this entry's group id.
*
* @return This entry's group id.
* @since 1.9.5
*/
public long getLongGroupId() {
return groupId;
}
/**
* Set this entry's group id.
*
* @param groupId This entry's new group id.
* @since 1.9.5
*/
public void setGroupId(long groupId) {
this.groupId = groupId;
}
/**
* Get this entry's user name.
*
* @return This entry's user name.
*/
public String getUserName() {
return userName;
}
/**
* Set this entry's user name.
*
* @param userName This entry's new user name.
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* Get this entry's group name.
*
* @return This entry's group name.
*/
public String getGroupName() {
return groupName;
}
/**
* Set this entry's group name.
*
* @param groupName This entry's new group name.
*/
public void setGroupName(String groupName) {
this.groupName = groupName;
}
/**
* Convenience method to set this entry's group and user ids.
*
* @param userId This entry's new user id.
* @param groupId This entry's new group id.
*/
public void setIds(int userId, int groupId) {
setUserId(userId);
setGroupId(groupId);
}
/**
* Convenience method to set this entry's group and user names.
*
* @param userName This entry's new user name.
* @param groupName This entry's new group name.
*/
public void setNames(String userName, String groupName) {
setUserName(userName);
setGroupName(groupName);
}
/**
* Set this entry's modification time. The parameter passed
* to this method is in "Java time".
*
* @param time This entry's new modification time.
*/
public void setModTime(long time) {
modTime = time / MILLIS_PER_SECOND;
}
/**
* Set this entry's modification time.
*
* @param time This entry's new modification time.
*/
public void setModTime(Date time) {
modTime = time.getTime() / MILLIS_PER_SECOND;
}
/**
* Set this entry's modification time.
*
* @return time This entry's new modification time.
*/
public Date getModTime() {
return new Date(modTime * MILLIS_PER_SECOND);
}
/**
* Get this entry's file.
*
* @return This entry's file.
*/
public File getFile() {
return file;
}
/**
* Get this entry's mode.
*
* @return This entry's mode.
*/
public int getMode() {
return mode;
}
/**
* Get this entry's file size.
*
* @return This entry's file size.
*/
public long getSize() {
return size;
}
/**
* Set this entry's file size.
*
* @param size This entry's new file size.
* @throws IllegalArgumentException if the size is < 0.
*/
public void setSize(long size) {
if (size < 0) {
throw new IllegalArgumentException("Size is out of range: " + size);
}
this.size = size;
}
/**
* Get this entry's major device number.
*
* @return This entry's major device number.
*/
public int getDevMajor() {
return devMajor;
}
/**
* Set this entry's major device number.
*
* @param devNo This entry's major device number.
* @throws IllegalArgumentException if the devNo is < 0.
*/
public void setDevMajor(int devNo) {
if (devNo < 0) {
throw new IllegalArgumentException("Major device number is out of "
+ "range: " + devNo);
}
this.devMajor = devNo;
}
/**
* Get this entry's minor device number.
*
* @return This entry's minor device number.
*/
public int getDevMinor() {
return devMinor;
}
/**
* Set this entry's minor device number.
*
* @param devNo This entry's minor device number.
* @throws IllegalArgumentException if the devNo is < 0.
*/
public void setDevMinor(int devNo) {
if (devNo < 0) {
throw new IllegalArgumentException("Minor device number is out of "
+ "range: " + devNo);
}
this.devMinor = devNo;
}
/**
* Indicates in case of a sparse file if an extension sparse header
* follows.
*
* @return true if an extension sparse header follows.
*/
public boolean isExtended() {
return isExtended;
}
/**
* Get this entry's real file size in case of a sparse file.
*
* @return This entry's real file size.
*/
public long getRealSize() {
return realSize;
}
/**
* Indicate if this entry is a GNU sparse block.
*
* @return true if this is a sparse extension provided by GNU tar
*/
public boolean isGNUSparse() {
return linkFlag == LF_GNUTYPE_SPARSE;
}
/**
* Indicate if this entry is a GNU long linkname block
*
* @return true if this is a long name extension provided by GNU tar
*/
public boolean isGNULongLinkEntry() {
return linkFlag == LF_GNUTYPE_LONGLINK;
}
/**
* Indicate if this entry is a GNU long name block
*
* @return true if this is a long name extension provided by GNU tar
*/
public boolean isGNULongNameEntry() {
return linkFlag == LF_GNUTYPE_LONGNAME;
}
/**
* Check if this is a Pax header.
*
* @return {@code true} if this is a Pax header.
*/
public boolean isPaxHeader() {
return linkFlag == LF_PAX_EXTENDED_HEADER_LC
|| linkFlag == LF_PAX_EXTENDED_HEADER_UC;
}
/**
* Check if this is a Pax header.
*
* @return {@code true} if this is a Pax header.
*/
public boolean isGlobalPaxHeader() {
return linkFlag == LF_PAX_GLOBAL_EXTENDED_HEADER;
}
/**
* Return whether or not this entry represents a directory.
*
* @return True if this entry is a directory.
*/
public boolean isDirectory() {
if (file != null) {
return file.isDirectory();
}
return linkFlag == LF_DIR || getName().endsWith("/");
}
/**
* Check if this is a "normal file".
* @return <i>true</i> if it is a 'normal' file
*/
public boolean isFile() {
return file != null ? file.isFile()
: linkFlag == LF_OLDNORM || linkFlag == LF_NORMAL || !getName().endsWith("/");
}
/**
* Check if this is a symbolic link entry.
* @return <i>true</i> if it is a symlink
*/
public boolean isSymbolicLink() {
return linkFlag == LF_SYMLINK;
}
/**
* Check if this is a link entry.
* @return <i>true</i> if it is a link
*/
public boolean isLink() {
return linkFlag == LF_LINK;
}
/**
* Check if this is a character device entry.
* @return <i>true</i> if it is a character device entry
*/
public boolean isCharacterDevice() {
return linkFlag == LF_CHR;
}
/**
* @return <i>true</i> if this is a block device entry.
*/
public boolean isBlockDevice() {
return linkFlag == LF_BLK;
}
/**
* @return <i>true</i> if this is a FIFO (pipe) entry.
*/
public boolean isFIFO() {
return linkFlag == LF_FIFO;
}
/**
* If this entry represents a file, and the file is a directory, return
* an array of TarEntries for this entry's children.
*
* @return An array of TarEntry's for this entry's children.
*/
public TarEntry[] getDirectoryEntries() {
if (file == null || !file.isDirectory()) {
return new TarEntry[0];
}
String[] list = file.list();
TarEntry[] result = new TarEntry[list.length];
for (int i = 0; i < list.length; ++i) {
result[i] = new TarEntry(new File(file, list[i]));
}
return result;
}
/**
* Write an entry's header information to a header buffer.
*
* <p>This method does not use the star/GNU tar/BSD tar extensions.</p>
*
* @param outbuf The tar entry header buffer to fill in.
*/
public void writeEntryHeader(byte[] outbuf) {
try {
writeEntryHeader(outbuf, TarUtils.DEFAULT_ENCODING, false);
} catch (IOException ex) {
try {
writeEntryHeader(outbuf, TarUtils.FALLBACK_ENCODING, false);
} catch (IOException ex2) {
// impossible
throw new RuntimeException(ex2); //NOSONAR
}
}
}
/**
* Write an entry's header information to a header buffer.
*
* @param outbuf The tar entry header buffer to fill in.
* @param encoding encoding to use when writing the file name.
* @param starMode whether to use the star/GNU tar/BSD tar
* extension for numeric fields if their value doesn't fit in the
* maximum size of standard tar archives
* @throws IOException if an error occurs while writing the archive
*/
public void writeEntryHeader(byte[] outbuf, ZipEncoding encoding,
boolean starMode) throws IOException {
int offset = 0;
offset = TarUtils.formatNameBytes(name, outbuf, offset, NAMELEN,
encoding);
offset = writeEntryHeaderField(mode, outbuf, offset, MODELEN, starMode);
offset = writeEntryHeaderField(userId, outbuf, offset, UIDLEN,
starMode);
offset = writeEntryHeaderField(groupId, outbuf, offset, GIDLEN,
starMode);
offset = writeEntryHeaderField(size, outbuf, offset, SIZELEN, starMode);
offset = writeEntryHeaderField(modTime, outbuf, offset, MODTIMELEN,
starMode);
int csOffset = offset;
for (int c = 0; c < CHKSUMLEN; ++c) {
outbuf[offset++] = (byte) ' ';
}
outbuf[offset++] = linkFlag;
offset = TarUtils.formatNameBytes(linkName, outbuf, offset, NAMELEN,
encoding);
offset = TarUtils.formatNameBytes(magic, outbuf, offset, PURE_MAGICLEN);
offset = TarUtils.formatNameBytes(version, outbuf, offset, VERSIONLEN);
offset = TarUtils.formatNameBytes(userName, outbuf, offset, UNAMELEN,
encoding);
offset = TarUtils.formatNameBytes(groupName, outbuf, offset, GNAMELEN,
encoding);
offset = writeEntryHeaderField(devMajor, outbuf, offset, DEVLEN,
starMode);
offset = writeEntryHeaderField(devMinor, outbuf, offset, DEVLEN,
starMode);
while (offset < outbuf.length) {
outbuf[offset++] = 0;
}
long chk = TarUtils.computeCheckSum(outbuf);
TarUtils.formatCheckSumOctalBytes(chk, outbuf, csOffset, CHKSUMLEN);
}
private int writeEntryHeaderField(long value, byte[] outbuf, int offset,
int length, boolean starMode) {
if (!starMode && (value < 0
|| value >= (1L << (3 * (length - 1))))) {
// value doesn't fit into field when written as octal
// number, will be written to PAX header or causes an
// error
return TarUtils.formatLongOctalBytes(0, outbuf, offset, length);
}
return TarUtils.formatLongOctalOrBinaryBytes(value, outbuf, offset,
length);
}
/**
* Parse an entry's header information from a header buffer.
*
* @param header The tar entry header buffer to get information from.
* @throws IllegalArgumentException if any of the numeric fields have an invalid format
*/
public void parseTarHeader(byte[] header) {
try {
parseTarHeader(header, TarUtils.DEFAULT_ENCODING);
} catch (IOException ex) {
try {
parseTarHeader(header, TarUtils.DEFAULT_ENCODING, true);
} catch (IOException ex2) {
// not really possible
throw new RuntimeException(ex2); //NOSONAR
}
}
}
/**
* Parse an entry's header information from a header buffer.
*
* @param header The tar entry header buffer to get information from.
* @param encoding encoding to use for file names
* @throws IllegalArgumentException if any of the numeric fields
* have an invalid format
* @throws IOException if an error occurs while reading the archive
*/
public void parseTarHeader(byte[] header, ZipEncoding encoding)
throws IOException {
parseTarHeader(header, encoding, false);
}
private void parseTarHeader(byte[] header, ZipEncoding encoding,
final boolean oldStyle)
throws IOException {
int offset = 0;
name = oldStyle ? TarUtils.parseName(header, offset, NAMELEN)
: TarUtils.parseName(header, offset, NAMELEN, encoding);
offset += NAMELEN;
mode = (int) TarUtils.parseOctalOrBinary(header, offset, MODELEN);
offset += MODELEN;
userId = (int) TarUtils.parseOctalOrBinary(header, offset, UIDLEN);
offset += UIDLEN;
groupId = (int) TarUtils.parseOctalOrBinary(header, offset, GIDLEN);
offset += GIDLEN;
size = TarUtils.parseOctalOrBinary(header, offset, SIZELEN);
offset += SIZELEN;
modTime = TarUtils.parseOctalOrBinary(header, offset, MODTIMELEN);
offset += MODTIMELEN;
offset += CHKSUMLEN;
linkFlag = header[offset++];
linkName = oldStyle ? TarUtils.parseName(header, offset, NAMELEN)
: TarUtils.parseName(header, offset, NAMELEN, encoding);
offset += NAMELEN;
magic = TarUtils.parseName(header, offset, PURE_MAGICLEN);
offset += PURE_MAGICLEN;
version = TarUtils.parseName(header, offset, VERSIONLEN);
offset += VERSIONLEN;
userName = oldStyle ? TarUtils.parseName(header, offset, UNAMELEN)
: TarUtils.parseName(header, offset, UNAMELEN, encoding);
offset += UNAMELEN;
groupName = oldStyle ? TarUtils.parseName(header, offset, GNAMELEN)
: TarUtils.parseName(header, offset, GNAMELEN, encoding);
offset += GNAMELEN;
devMajor = (int) TarUtils.parseOctalOrBinary(header, offset, DEVLEN);
offset += DEVLEN;
devMinor = (int) TarUtils.parseOctalOrBinary(header, offset, DEVLEN);
offset += DEVLEN;
int type = evaluateType(header);
switch (type) {
case FORMAT_OLDGNU: {
offset += ATIMELEN_GNU;
offset += CTIMELEN_GNU;
offset += OFFSETLEN_GNU;
offset += LONGNAMESLEN_GNU;
offset += PAD2LEN_GNU;
offset += SPARSELEN_GNU;
isExtended = TarUtils.parseBoolean(header, offset);
offset += ISEXTENDEDLEN_GNU;
realSize = TarUtils.parseOctal(header, offset, REALSIZELEN_GNU);
offset += REALSIZELEN_GNU;
break;
}
case FORMAT_POSIX:
default: {
String prefix = oldStyle ? TarUtils.parseName(header, offset, PREFIXLEN)
: TarUtils.parseName(header, offset, PREFIXLEN, encoding);
// SunOS tar -E does not add / to directory names, so fix
// up to be consistent
if (isDirectory() && !name.endsWith("/")) {
name += "/";
}
if (!prefix.isEmpty()) {
name = prefix + "/" + name;
}
}
}
}
/**
* Strips Windows' drive letter as well as any leading slashes,
* turns path separators into forward slashes.
*/
private static String normalizeFileName(String fileName,
boolean preserveLeadingSlashes) {
String osname = System.getProperty("os.name").toLowerCase(Locale.ENGLISH);
if (osname != null) {
// Strip off drive letters!
// REVIEW Would a better check be "(File.separator == '\')"?
if (osname.startsWith("windows")) {
if (fileName.length() > 2) {
char ch1 = fileName.charAt(0);
char ch2 = fileName.charAt(1);
if (ch2 == ':'
&& ((ch1 >= 'a' && ch1 <= 'z')
|| (ch1 >= 'A' && ch1 <= 'Z'))) {
fileName = fileName.substring(2);
}
}
} else if (osname.contains("netware")) {
int colon = fileName.indexOf(':');
if (colon != -1) {
fileName = fileName.substring(colon + 1);
}
}
}
fileName = fileName.replace(File.separatorChar, '/');
// No absolute pathnames
// Windows (and Posix?) paths can start with "\\NetworkDrive\",
// so we loop on starting /'s.
while (!preserveLeadingSlashes && fileName.startsWith("/")) {
fileName = fileName.substring(1);
}
return fileName;
}
/**
* Evaluate an entry's header format from a header buffer.
*
* @param header The tar entry header buffer to evaluate the format for.
* @return format type
*/
private int evaluateType(byte[] header) {
if (matchAsciiBuffer(GNU_TMAGIC, header, MAGIC_OFFSET, PURE_MAGICLEN)) {
return FORMAT_OLDGNU;
}
if (matchAsciiBuffer(MAGIC_POSIX, header, MAGIC_OFFSET, PURE_MAGICLEN)) {
return FORMAT_POSIX;
}
return 0;
}
/**
* Check if buffer contents matches Ascii String.
*
* @param expected String
* @param buffer byte[]
* @param offset int
* @param length int
* @return {@code true} if buffer is the same as the expected string
*/
private static boolean matchAsciiBuffer(String expected, byte[] buffer,
int offset, int length) {
byte[] buffer1;
try {
buffer1 = expected.getBytes("ASCII");
} catch (UnsupportedEncodingException e) {
// Should not happen
throw new RuntimeException(e); //NOSONAR
}
return isEqual(buffer1, 0, buffer1.length, buffer, offset, length,
false);
}
/**
* Compare byte buffers, optionally ignoring trailing nulls
*
* @param buffer1 byte[]
* @param offset1 int
* @param length1 int
* @param buffer2 byte[]
* @param offset2 int
* @param length2 int
* @param ignoreTrailingNulls boolean
* @return {@code true} if buffer1 and buffer2 have same contents, having regard to trailing nulls
*/
private static boolean isEqual(
final byte[] buffer1, final int offset1, final int length1,
final byte[] buffer2, final int offset2, final int length2,
boolean ignoreTrailingNulls) {
int minLen = (length1 < length2) ? length1 : length2;
for (int i = 0; i < minLen; i++) {
if (buffer1[offset1 + i] != buffer2[offset2 + i]) {
return false;
}
}
if (length1 == length2) {
return true;
}
if (ignoreTrailingNulls) {
if (length1 > length2) {
for (int i = length2; i < length1; i++) {
if (buffer1[offset1 + i] != 0) {
return false;
}
}
} else {
for (int i = length1; i < length2; i++) {
if (buffer2[offset2 + i] != 0) {
return false;
}
}
}
return true;
}
return false;
}
}
|
package com.thinkgem.jeesite.modules.weixin.wxpay.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import org.apache.log4j.Logger;
public class HttpUtil {
public static Logger logger = Logger.getLogger(HttpUtil.class);
/**
* java.net实现 HTTP POST方法提交
*
* @param url
* @param paramContent
* @return
*/
public static StringBuffer submitPost(String url, String paramContent) {
StringBuffer responseMessage = null;
java.net.URLConnection connection = null;
java.net.URL reqUrl = null;
OutputStreamWriter reqOut = null;
InputStream in = null;
BufferedReader br = null;
String param = paramContent;
try {
//System.out.println("url=" + url + "?" + paramContent + "\n");
//System.out.println("===========post method start=========");
logger.debug("url=" + url + "?" + paramContent);
logger.debug("===========post method start=========");
responseMessage = new StringBuffer();
reqUrl = new java.net.URL(url);
connection = reqUrl.openConnection();
connection.setDoOutput(true);
reqOut = new OutputStreamWriter(connection.getOutputStream());
reqOut.write(param);
reqOut.flush();
int charCount = -1;
in = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(in, "utf-8"));//GBK
while ((charCount = br.read()) != -1) {
responseMessage.append((char) charCount);
}
//System.out.println(responseMessage);
//System.out.println("===========post method end=========");
logger.debug(responseMessage);
logger.debug("===========post method end=========");
} catch (Exception ex) {
//System.out.println("url=" + url + "?" + paramContent + "\n e=" + ex);
logger.error("请求异常 url=" + url + "?" + paramContent + " e=" + ex);
} finally {
try {
in.close();
reqOut.close();
} catch (Exception e) {
//System.out.println("paramContent=" + paramContent + "|err=" + e);
logger.error("请求异常 url=" + url + "?" + paramContent + " e=" + e);
}
}
return responseMessage;
}
/**
* java.net实现 HTTP或HTTPs GET方法提交
*
* @param strUrl
* 提交的地址及参数
* @return 返回的response信息
*/
public static StringBuffer submitGet(String strUrl) {
URLConnection connection = null;
BufferedReader reader = null;
StringBuffer responseMessage = null;
try {
logger.debug("send getmethod=" + strUrl);
//System.out.println("send getmethod=" + strUrl);
responseMessage = new StringBuffer();
URL url = new URL(strUrl);
connection = url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(false);
// 取得输入流,并使用Reader读取
reader = new BufferedReader(new InputStreamReader(connection
.getInputStream(), "utf-8"));
//System.out.println("============Contents of get request===============");
logger.debug("============Contents of get request===============");
int charCount = -1;
while ((charCount = reader.read()) != -1) {
responseMessage.append((char) charCount);
}
logger.debug(responseMessage);
//System.out.println(responseMessage);
//System.out.println("============Contents of get request ends==========");
logger.debug("============Contents of get request ends===============");
} catch (Exception e) {
//System.out.println("getmethod is err=" + e);
logger.error("getmethod is err=" + e);
} finally {
try {
reader.close();
} catch (Exception e) {
logger.error("getmethod is err=" + e);
}
}
return responseMessage;
}
}
|
/*
* 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.ignite.ml.optimization.updatecalculators;
import org.apache.ignite.ml.math.Matrix;
import org.apache.ignite.ml.math.Vector;
import org.apache.ignite.ml.math.VectorUtils;
import org.apache.ignite.ml.math.functions.IgniteDifferentiableVectorToDoubleFunction;
import org.apache.ignite.ml.math.functions.IgniteFunction;
import org.apache.ignite.ml.math.util.MatrixUtil;
import org.apache.ignite.ml.optimization.SmoothParametrized;
/**
* Class encapsulating RProp algorithm.
* <p>
* See <a href="https://paginas.fe.up.pt/~ee02162/dissertacao/RPROP%20paper.pdf">RProp</a>.</p>
*/
public class RPropUpdateCalculator implements ParameterUpdateCalculator<SmoothParametrized, RPropParameterUpdate> {
/**
* Default initial update.
*/
private static double DFLT_INIT_UPDATE = 0.1;
/**
* Default acceleration rate.
*/
private static double DFLT_ACCELERATION_RATE = 1.2;
/**
* Default deacceleration rate.
*/
private static double DFLT_DEACCELERATION_RATE = 0.5;
/**
* Initial update.
*/
private final double initUpdate;
/**
* Acceleration rate.
*/
private final double accelerationRate;
/**
* Deacceleration rate.
*/
private final double deaccelerationRate;
/**
* Maximal value for update.
*/
private final static double UPDATE_MAX = 50.0;
/**
* Minimal value for update.
*/
private final static double UPDATE_MIN = 1E-6;
/**
* Loss function.
*/
protected IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss;
/**
* Construct RPropUpdateCalculator.
*
* @param initUpdate Initial update.
* @param accelerationRate Acceleration rate.
* @param deaccelerationRate Deacceleration rate.
*/
public RPropUpdateCalculator(double initUpdate, double accelerationRate, double deaccelerationRate) {
this.initUpdate = initUpdate;
this.accelerationRate = accelerationRate;
this.deaccelerationRate = deaccelerationRate;
}
/**
* Construct RPropUpdateCalculator with default parameters.
*/
public RPropUpdateCalculator() {
this(DFLT_INIT_UPDATE, DFLT_ACCELERATION_RATE, DFLT_DEACCELERATION_RATE);
}
/** {@inheritDoc} */
@Override public RPropParameterUpdate calculateNewUpdate(SmoothParametrized mdl, RPropParameterUpdate updaterParams,
int iteration, Matrix inputs, Matrix groundTruth) {
Vector gradient = mdl.differentiateByParameters(loss, inputs, groundTruth);
Vector prevGradient = updaterParams.prevIterationGradient();
Vector derSigns;
if (prevGradient != null)
derSigns = VectorUtils.zipWith(prevGradient, gradient, (x, y) -> Math.signum(x * y));
else
derSigns = gradient.like(gradient.size()).assign(1.0);
Vector newDeltas = updaterParams.deltas().copy().map(derSigns, (prevDelta, sign) -> {
if (sign > 0)
return Math.min(prevDelta * accelerationRate, UPDATE_MAX);
else if (sign < 0)
return Math.max(prevDelta * deaccelerationRate, UPDATE_MIN);
else
return prevDelta;
});
Vector newPrevIterationUpdates = MatrixUtil.zipWith(gradient, updaterParams.deltas(), (der, delta, i) -> {
if (derSigns.getX(i) >= 0)
return -Math.signum(der) * delta;
return updaterParams.prevIterationUpdates().getX(i);
});
Vector updatesMask = MatrixUtil.zipWith(derSigns, updaterParams.prevIterationUpdates(), (sign, upd, i) -> {
if (sign < 0)
gradient.setX(i, 0.0);
if (sign >= 0)
return 1.0;
else
return -1.0;
});
return new RPropParameterUpdate(newPrevIterationUpdates, gradient.copy(), newDeltas, updatesMask);
}
/** {@inheritDoc} */
@Override public RPropParameterUpdate init(SmoothParametrized mdl,
IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss) {
this.loss = loss;
return new RPropParameterUpdate(mdl.parametersCount(), initUpdate);
}
/** {@inheritDoc} */
@Override public <M1 extends SmoothParametrized> M1 update(M1 obj, RPropParameterUpdate update) {
Vector updatesToAdd = VectorUtils.elementWiseTimes(update.updatesMask().copy(), update.prevIterationUpdates());
return (M1)obj.setParameters(obj.parameters().plus(updatesToAdd));
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Gabriel Harris-Rouquette
*
* 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.
*/
package com.afterkraft.kraftrpg.bundled.skills;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Effect;
import org.bukkit.FireworkEffect;
import org.bukkit.FireworkEffect.Type;
import org.bukkit.Location;
import org.bukkit.entity.Projectile;
import org.bukkit.potion.PotionEffect;
import org.bukkit.scheduler.BukkitRunnable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.afterkraft.kraftrpg.api.RPGPlugin;
import com.afterkraft.kraftrpg.api.effects.EffectType;
import com.afterkraft.kraftrpg.api.effects.common.ProjectileShotEffect;
import com.afterkraft.kraftrpg.api.entity.Insentient;
import com.afterkraft.kraftrpg.api.entity.SkillCaster;
import com.afterkraft.kraftrpg.api.skills.SkillSetting;
import com.afterkraft.kraftrpg.api.skills.SkillType;
import com.afterkraft.kraftrpg.api.skills.common.ArrowSkill;
import com.afterkraft.kraftrpg.bundled.utils.FireworksUtil;
/**
* An ArrowSkill that attempts to teleport the shooter wherever the arrow lands. This is a clear
* example of utilizing the provided common skills in KraftRPG-API to minimize writing extra
* listeners and boilerplate code. These type of skills should be easy to read and easily
* understood.
*
* Our objective with this skill is to hook when the SkillCaster shoots an Arrow (from {@link
* ArrowSkill}, spawn a visual firework effect that trails the arrow, and finally, teleport the
* shooter to the arrows landed location. For all intents and purposes, this should be a clear
* example of how an {@link ArrowSkill} should be written. Extra listeners should not be required.
*
* Methods that are not needed to be overridden are: {@link #useSkill(SkillCaster)}.
*
* It is possible to apply customized settings for SkillCasters to designate, such as new skill
* arguments; however, it should be noted that normally these skills are single use.
*/
public class SkillEnderArrow extends ArrowSkill {
/**
* Creates the skill.
*
* @param plugin The RPGPlugin implementation
*/
public SkillEnderArrow(RPGPlugin plugin) {
super(plugin, "EnderArrow");
// We always have a description for when skills are listed
setDescription("Shooting an enchanted arrow that teleports the shooter to the landing "
+ "location.");
// Since this is a teleporting skill, we should note it
setSkillTypes(SkillType.TELEPORTING, SkillType.UNINTERRUPTIBLE, SkillType.UNSILENCABLE);
// Setting our default values. Remember, we can't fetch any configured values unless they
// are written as defaults as well. KraftRPG WILL yell and scream if a skill is
// attempting to fetch a skill setting without having noted the defaults before hand.
// NOTE: We do not need to set the custom skill setting for "max-uses" as KraftRPG-API's
// ArrowSkill does that for us.
// This is specifically when the arrow is shot.
setDefault(SkillSetting.APPLY_TEXT, "You shoot a mystical arrow bending time and space...");
// Yet again, another setting. For when the player is teleported.
setDefault(SkillSetting.EXPIRE_TEXT, "Your arrow has moved you to your location");
}
// Since we want to apply our own custom ProjectileShotEffect, we need to override this
// method and fetch any necessary configuration settings.
@Override
public void addImbueEffect(SkillCaster caster, int maxUses) {
// We need to actually get the configured settings. In this case, we're getting the
// configured application text, expiration text, and maximum shots text.
String applyText = this.plugin.getSkillConfigManager()
.getUsedStringSetting(caster, this, SkillSetting.APPLY_TEXT);
String expireText = this.plugin.getSkillConfigManager()
.getUsedStringSetting(caster, this, SkillSetting.EXPIRE_TEXT);
// We now construct our new effect for the caster
EnderArrowShotEffect effect = new EnderArrowShotEffect(this, caster, maxUses, applyText,
expireText);
// Add the effect to our caster
caster.addEffect(effect);
}
// This projectile effect is an extension to avoid having to write all the internal stuff to
// implement an IEffect. We can further customize a few things accordingly.
class EnderArrowShotEffect extends ProjectileShotEffect {
// We want to store the runnable that we'll use to shoot fireworks on our arrows. We also
// don't want to use the actual objects because we don't need to.
private Map<UUID, Integer> projectileFireworkMap = new HashMap<UUID, Integer>();
public EnderArrowShotEffect(SkillEnderArrow skill, Insentient applier, int shots,
String applyText,
String expireText) {
// We want to keep our effect uniquely named to avoid confusion with other effects.
super(skill, applier, "EnderArrowShot",
ImmutableSet.<PotionEffect>of(), false,
// We can apply a Jump Boos effect type to avoid fall damage if damage is taken
// immediately upon teleporting. We also might apply an expirable effect
// afterwards that grants the shooter some sort of safe-fall for a few seconds
// after teleportation.
ImmutableList.of(EffectType.JUMP_BOOST),
applyText,
expireText, shots);
}
@Override
public boolean applyToProjectile(Projectile projectile) {
// We must call the super to reduce the uses of this effect, otherwise we risk
// allowing the caster to shoot unlimited Imbued shots!
if (!super.applyToProjectile(projectile)) {
return false;
}
// We construct our new runnable
BukkitRunnable runnable = new EnderArrowShotRunnable(projectile);
// Get our task id
int id = runnable.runTaskTimer(SkillEnderArrow.this.plugin, 0, 2).getTaskId();
// And store it into our map for retrieval later.
this.projectileFireworkMap.put(projectile.getUniqueId(), id);
return true;
}
@Override
public void onProjectileLand(Projectile projectile, Location location) {
// We can get our shooter from the getApplier() method.
Insentient applier = getApplier();
// Cancel the repeating task from our map
int id = this.projectileFireworkMap.remove(projectile.getUniqueId());
Bukkit.getScheduler().cancelTask(id);
applier.teleport(location, true);
}
}
// We have our runnable to play a firework effect. We can probably delegate this out to the
// FireworksUtil at some point, but for now, let's keep as much in this skill class as possible.
class EnderArrowShotRunnable extends BukkitRunnable {
private Projectile arrow;
private EnderArrowShotRunnable(Projectile arrow) {
this.arrow = arrow;
}
@Override
public void run() {
// We don't want to do anything if the arrow is invalid or on the ground. Just some
// validation.
if (this.arrow.isValid() && !this.arrow.isOnGround()) {
// We need our desired FireworkEffect
FireworkEffect effect = FireworkEffect.builder()
.withFlicker()
.withColor(Color.BLACK)
.withFade(Color.GRAY)
.with(Type.BALL)
.build();
// Get the utility to spawn the firework
FireworksUtil.playFireworkEffect(this.arrow.getLocation(), effect);
// Just some added particles for show
this.arrow.getWorld().playEffect(this.arrow.getLocation(),
Effect.ENDER_SIGNAL, 0);
}
}
}
}
|
import cc.refectorie.proj.relation.protobuf.DocumentProtos.Relation;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
class RelationReader {
public static void main(String[] args) throws Exception {
String filePath = args[0];
String destPath= args[1];
FileInputStream input = new FileInputStream(filePath);
int i = 100000;
FileOutputStream output;
Relation rel;
System.out.println("Begin processing.");
while (input.available()>0){
rel = Relation.parseDelimitedFrom(input);
System.out.println(rel.getSourceGuid() + " " +rel.getDestGuid() );
output = new FileOutputStream(destPath+i+".pb");
i++;
rel.writeTo(output);
output.close();
}
input.close();
System.out.println("Done processing.");
}
}
|
/*
* 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.accumulo.test;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import org.apache.accumulo.core.cli.ClientOpts;
import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.MutationsRejectedException;
import org.apache.accumulo.core.client.TableExistsException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.security.SecurityErrorCode;
import org.apache.accumulo.core.clientImpl.ClientContext;
import org.apache.accumulo.core.conf.ClientProperty;
import org.apache.accumulo.core.conf.DefaultConfiguration;
import org.apache.accumulo.core.crypto.CryptoServiceFactory;
import org.apache.accumulo.core.data.ConstraintViolationSummary;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.TabletId;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.file.FileOperations;
import org.apache.accumulo.core.file.FileSKVWriter;
import org.apache.accumulo.core.file.rfile.RFile;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.ColumnVisibility;
import org.apache.accumulo.core.util.FastFormat;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.Text;
import com.beust.jcommander.Parameter;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
public class TestIngest {
public static final Authorizations AUTHS = new Authorizations("L1", "L2", "G1", "GROUP2");
public static class IngestParams {
public Properties clientProps = new Properties();
public String tableName = "test_ingest";
public boolean createTable = false;
public int numsplits = 1;
public int startRow = 0;
public int rows = 100000;
public int cols = 1;
public Integer random = null;
public int dataSize = 1000;
public boolean delete = false;
public long timestamp = -1;
public String outputFile = null;
public int stride;
public String columnFamily = "colf";
public ColumnVisibility columnVisibility = new ColumnVisibility();
public IngestParams(Properties props) {
clientProps = props;
}
public IngestParams(Properties props, String table) {
this(props);
tableName = table;
}
public IngestParams(Properties props, String table, int rows) {
this(props, table);
this.rows = rows;
}
}
public static class Opts extends ClientOpts {
@Parameter(names = "--table", description = "table to use")
String tableName = "test_ingest";
@Parameter(names = "--createTable")
boolean createTable = false;
@Parameter(names = "--splits",
description = "the number of splits to use when creating the table")
int numsplits = 1;
@Parameter(names = "--start", description = "the starting row number")
int startRow = 0;
@Parameter(names = "--rows", description = "the number of rows to ingest")
int rows = 100000;
@Parameter(names = "--cols", description = "the number of columns to ingest per row")
int cols = 1;
@Parameter(names = "--random", description = "insert random rows and use"
+ " the given number to seed the psuedo-random number generator")
Integer random = null;
@Parameter(names = "--size", description = "the size of the value to ingest")
int dataSize = 1000;
@Parameter(names = "--delete", description = "delete values instead of inserting them")
boolean delete = false;
@Parameter(names = {"-ts", "--timestamp"}, description = "timestamp to use for all values")
long timestamp = -1;
@Parameter(names = "--rfile", description = "generate data into a file that can be imported")
String outputFile = null;
@Parameter(names = "--stride", description = "the difference between successive row ids")
int stride;
@Parameter(names = {"-cf", "--columnFamily"},
description = "place columns in this column family")
String columnFamily = "colf";
@Parameter(names = {"-cv", "--columnVisibility"},
description = "place columns in this column family", converter = VisibilityConverter.class)
ColumnVisibility columnVisibility = new ColumnVisibility();
protected void populateIngestPrams(IngestParams params) {
params.createTable = createTable;
params.numsplits = numsplits;
params.startRow = startRow;
params.rows = rows;
params.cols = cols;
params.random = random;
params.dataSize = dataSize;
params.delete = delete;
params.timestamp = timestamp;
params.outputFile = outputFile;
params.stride = stride;
params.columnFamily = columnFamily;
params.columnVisibility = columnVisibility;
}
public IngestParams getIngestPrams() {
IngestParams params = new IngestParams(getClientProps(), tableName);
populateIngestPrams(params);
return params;
}
}
public static void createTable(AccumuloClient client, IngestParams params)
throws AccumuloException, AccumuloSecurityException, TableExistsException {
if (params.createTable) {
TreeSet<Text> splits =
getSplitPoints(params.startRow, params.startRow + params.rows, params.numsplits);
if (!client.tableOperations().exists(params.tableName)) {
client.tableOperations().create(params.tableName);
}
try {
client.tableOperations().addSplits(params.tableName, splits);
} catch (TableNotFoundException ex) {
// unlikely
throw new RuntimeException(ex);
}
}
}
public static TreeSet<Text> getSplitPoints(long start, long end, long numsplits) {
long splitSize = (end - start) / numsplits;
long pos = start + splitSize;
TreeSet<Text> splits = new TreeSet<>();
while (pos < end) {
splits.add(new Text(String.format("row_%010d", pos)));
pos += splitSize;
}
return splits;
}
public static byte[][] generateValues(int dataSize) {
byte[][] bytevals = new byte[10][];
byte[] letters = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
for (int i = 0; i < 10; i++) {
bytevals[i] = new byte[dataSize];
for (int j = 0; j < dataSize; j++) {
bytevals[i][j] = letters[i];
}
}
return bytevals;
}
private static byte[] ROW_PREFIX = "row_".getBytes(UTF_8);
private static byte[] COL_PREFIX = "col_".getBytes(UTF_8);
public static Text generateRow(int rowid, int startRow) {
return new Text(FastFormat.toZeroPaddedString(rowid + startRow, 10, 10, ROW_PREFIX));
}
public static byte[] genRandomValue(Random random, byte[] dest, int seed, int row, int col) {
random.setSeed((row ^ seed) ^ col);
random.nextBytes(dest);
toPrintableChars(dest);
return dest;
}
public static void toPrintableChars(byte[] dest) {
// transform to printable chars
for (int i = 0; i < dest.length; i++) {
dest[i] = (byte) (((0xff & dest[i]) % 92) + ' ');
}
}
public static void main(String[] args) throws Exception {
Opts opts = new Opts();
opts.parseArgs(TestIngest.class.getSimpleName(), args);
try (AccumuloClient client = Accumulo.newClient().from(opts.getClientProps()).build()) {
ingest(client, opts.getIngestPrams());
}
}
@SuppressFBWarnings(value = "PREDICTABLE_RANDOM",
justification = "predictable random is okay for testing")
public static void ingest(AccumuloClient accumuloClient, FileSystem fs, IngestParams params)
throws IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException,
MutationsRejectedException, TableExistsException {
long stopTime;
byte[][] bytevals = generateValues(params.dataSize);
byte[] randomValue = new byte[params.dataSize];
Random random = new Random();
long bytesWritten = 0;
createTable(accumuloClient, params);
BatchWriter bw = null;
FileSKVWriter writer = null;
if (params.outputFile != null) {
ClientContext cc = (ClientContext) accumuloClient;
writer = FileOperations.getInstance().newWriterBuilder()
.forFile(params.outputFile + "." + RFile.EXTENSION, fs, cc.getHadoopConf(),
CryptoServiceFactory.newDefaultInstance())
.withTableConfiguration(DefaultConfiguration.getInstance()).build();
writer.startDefaultLocalityGroup();
} else {
bw = accumuloClient.createBatchWriter(params.tableName);
String principal = ClientProperty.AUTH_PRINCIPAL.getValue(params.clientProps);
accumuloClient.securityOperations().changeUserAuthorizations(principal, AUTHS);
}
Text labBA = new Text(params.columnVisibility.getExpression());
long startTime = System.currentTimeMillis();
for (int i = 0; i < params.rows; i++) {
int rowid;
if (params.stride > 0) {
rowid = ((i % params.stride) * (params.rows / params.stride)) + (i / params.stride);
} else {
rowid = i;
}
Text row = generateRow(rowid, params.startRow);
Mutation m = new Mutation(row);
for (int j = 0; j < params.cols; j++) {
Text colf = new Text(params.columnFamily);
Text colq = new Text(FastFormat.toZeroPaddedString(j, 7, 10, COL_PREFIX));
if (writer != null) {
Key key = new Key(row, colf, colq, labBA);
if (params.timestamp >= 0) {
key.setTimestamp(params.timestamp);
} else {
key.setTimestamp(startTime);
}
if (params.delete) {
key.setDeleted(true);
} else {
key.setDeleted(false);
}
bytesWritten += key.getSize();
if (params.delete) {
writer.append(key, new Value(new byte[0]));
} else {
byte[] value;
if (params.random != null) {
value =
genRandomValue(random, randomValue, params.random, rowid + params.startRow, j);
} else {
value = bytevals[j % bytevals.length];
}
Value v = new Value(value);
writer.append(key, v);
bytesWritten += v.getSize();
}
} else {
Key key = new Key(row, colf, colq, labBA);
bytesWritten += key.getSize();
if (params.delete) {
if (params.timestamp >= 0) {
m.putDelete(colf, colq, params.columnVisibility, params.timestamp);
} else {
m.putDelete(colf, colq, params.columnVisibility);
}
} else {
byte[] value;
if (params.random != null) {
value =
genRandomValue(random, randomValue, params.random, rowid + params.startRow, j);
} else {
value = bytevals[j % bytevals.length];
}
bytesWritten += value.length;
if (params.timestamp >= 0) {
m.put(colf, colq, params.columnVisibility, params.timestamp, new Value(value, true));
} else {
m.put(colf, colq, params.columnVisibility, new Value(value, true));
}
}
}
}
if (bw != null) {
bw.addMutation(m);
}
}
if (writer != null) {
writer.close();
} else if (bw != null) {
try {
bw.close();
} catch (MutationsRejectedException e) {
if (!e.getSecurityErrorCodes().isEmpty()) {
for (Entry<TabletId,Set<SecurityErrorCode>> entry : e.getSecurityErrorCodes()
.entrySet()) {
System.err.println("ERROR : Not authorized to write to : " + entry.getKey() + " due to "
+ entry.getValue());
}
}
if (!e.getConstraintViolationSummaries().isEmpty()) {
for (ConstraintViolationSummary cvs : e.getConstraintViolationSummaries()) {
System.err.println("ERROR : Constraint violates : " + cvs);
}
}
throw e;
}
}
stopTime = System.currentTimeMillis();
int totalValues = params.rows * params.cols;
double elapsed = (stopTime - startTime) / 1000.0;
System.out.printf(
"%,12d records written | %,8d records/sec | %,12d bytes written"
+ " | %,8d bytes/sec | %6.3f secs %n",
totalValues, (int) (totalValues / elapsed), bytesWritten, (int) (bytesWritten / elapsed),
elapsed);
}
public static void ingest(AccumuloClient c, IngestParams params)
throws MutationsRejectedException, IOException, AccumuloException, AccumuloSecurityException,
TableNotFoundException, TableExistsException {
ClientContext cc = (ClientContext) c;
ingest(c, FileSystem.get(cc.getHadoopConf()), params);
}
}
|
package com.book.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import com.book.domain.Lend;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@Repository
public class LendDao {
private JdbcTemplate jdbcTemplate;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
private final static String BOOK_RETURN_SQL_ONE="UPDATE lend_list SET back_date = ? WHERE book_id = ? AND back_date is NULL";
private final static String BOOK_RETURN_SQL_TWO="UPDATE book_info SET state = 1 WHERE book_id = ? ";
private final static String BOOK_LEND_SQL_ONE="INSERT INTO lend_list (book_id,reader_id,lend_date) VALUES ( ? , ? , ? )";
private final static String BOOK_LEND_SQL_TWO="UPDATE book_info SET state = 0 WHERE book_id = ? ";
private final static String LEND_LIST_SQL="SELECT * FROM lend_list";
private final static String MY_LEND_LIST_SQL="SELECT * FROM lend_list WHERE reader_id = ? ";
public int bookReturnOne(long bookId){
return jdbcTemplate.update(BOOK_RETURN_SQL_ONE,new Object[]{df.format(new Date()),bookId});
}
public int bookReturnTwo(long bookId){
return jdbcTemplate.update(BOOK_RETURN_SQL_TWO,new Object[]{bookId});
}
public int bookLendOne(long bookId,int readerId){
return jdbcTemplate.update(BOOK_LEND_SQL_ONE,new Object[]{bookId,readerId,df.format(new Date())});
}
public int bookLendTwo(long bookId){
return jdbcTemplate.update(BOOK_LEND_SQL_TWO,new Object[]{bookId});
}
public ArrayList<Lend> lendList(){
final ArrayList<Lend> list=new ArrayList<Lend>();
jdbcTemplate.query(LEND_LIST_SQL, new RowCallbackHandler() {
public void processRow(ResultSet resultSet) throws SQLException {
resultSet.beforeFirst();
while (resultSet.next()){
Lend lend=new Lend();
lend.setBackDate(resultSet.getDate("back_date"));
lend.setBookId(resultSet.getLong("book_id"));
lend.setLendDate(resultSet.getDate("lend_date"));
lend.setReaderId(resultSet.getInt("reader_id"));
lend.setSernum(resultSet.getLong("sernum"));
list.add(lend);
}
}
});
return list;
}
public ArrayList<Lend> myLendList(int readerId){
final ArrayList<Lend> list=new ArrayList<Lend>();
jdbcTemplate.query(MY_LEND_LIST_SQL, new Object[]{readerId},new RowCallbackHandler() {
public void processRow(ResultSet resultSet) throws SQLException {
resultSet.beforeFirst();
while (resultSet.next()){
Lend lend=new Lend();
lend.setBackDate(resultSet.getDate("back_date"));
lend.setBookId(resultSet.getLong("book_id"));
lend.setLendDate(resultSet.getDate("lend_date"));
lend.setReaderId(resultSet.getInt("reader_id"));
lend.setSernum(resultSet.getLong("sernum"));
list.add(lend);
}
}
});
return list;
}
}
|
package com.github.houbb.segment.support.segment.impl;
import com.github.houbb.heaven.support.instance.impl.Instances;
import com.github.houbb.segment.api.ISegment;
/**
* 分词实现工具类
* @author binbin.hou
* @since 0.0.7
*/
public final class Segments {
private Segments(){}
/**
* 默认实现
* @return 结果
* @since 0.0.7
*/
public static ISegment defaults() {
return Instances.singleton(Segment.class);
}
/**
* 快速分词模式
* @return 快速分词
* @since 0.0.7
*/
public static ISegment fast() {
return Instances.singleton(FastSegment.class);
}
/**
* 精确分词模式
* @return 精确分词
* @since 0.0.7
*/
public static ISegment precise() {
return Instances.singleton(PreciseSegment.class);
}
}
|
/*
* 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.nemo.common.ir.vertex.transform;
import org.apache.nemo.common.Pair;
import org.apache.nemo.common.ir.OutputCollector;
import org.apache.nemo.common.ir.vertex.utility.runtimepass.MessageAggregatorVertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@link Transform} that aggregates statistics generated by the {@link MessageGeneratorTransform}.
*
* @param <K> input key type.
* @param <V> input value type.
* @param <O> output type.
*/
public final class MessageAggregatorTransform<K, V, O> extends NoWatermarkEmitTransform<Pair<K, V>, O> {
private static final Logger LOG = LoggerFactory.getLogger(MessageAggregatorTransform.class.getName());
private transient O state;
private transient OutputCollector<O> outputCollector;
private final MessageAggregatorVertex.InitialStateSupplier<O> initialStateSupplier;
private final MessageAggregatorVertex.MessageAggregatorFunction<K, V, O> aggregator;
/**
* Default constructor.
* @param initialStateSupplier to use.
* @param aggregator to use.
*/
public MessageAggregatorTransform(final MessageAggregatorVertex.InitialStateSupplier<O> initialStateSupplier,
final MessageAggregatorVertex.MessageAggregatorFunction<K, V, O> aggregator) {
this.initialStateSupplier = initialStateSupplier;
this.aggregator = aggregator;
}
@Override
public void prepare(final Context context, final OutputCollector<O> oc) {
this.state = initialStateSupplier.get();
this.outputCollector = oc;
}
@Override
public void onData(final Pair<K, V> element) {
state = aggregator.apply(element, state);
}
@Override
public void close() {
outputCollector.emit(state);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(MessageAggregatorTransform.class);
sb.append(":");
sb.append(super.toString());
return sb.toString();
}
}
|
package DAO;
import Engine.Conexao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import Modelos.cliente;
public class Editar {
cliente objCli = new cliente();
public boolean Atualizar(cliente objCli) throws SQLException
{
Conexao conexao = new Conexao();
int registros;
try(PreparedStatement pstmt = conexao.getConnection().prepareStatement("UPDATE cliente set nome = ?, telefone = ?, ENDERECO = ? where id = ?"))
{
pstmt.setString(1, objCli.getNome().trim());
pstmt.setString(3, objCli.getEndereco().trim());
pstmt.setString(2, objCli.getTelefone().trim());
String ids = "" + objCli.getId();
pstmt.setString(4, ids);
registros = pstmt.executeUpdate();
}
if(registros == 1)
{
return true;
}
else
{
return false;
}
}
}
|
package com.kailash.tutorial.swing.ch30.gui;
import com.kailash.tutorial.swing.ch30.model.Person;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
public class TablePanel extends JPanel {
PersonTableListener personTableListener;
private final JTable table;
private final PersonTableModel tableModel;
private final JPopupMenu popup;
public TablePanel() {
tableModel = new PersonTableModel();
table = new JTable();
table.setModel(tableModel);
popup = new JPopupMenu();
JMenuItem removeItem = new JMenuItem("Delete row");
popup.add(removeItem);
table.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int row = table.rowAtPoint(e.getPoint());
table.getSelectionModel().setSelectionInterval(row, row);
if (e.getButton() == MouseEvent.BUTTON3) {
popup.show(table, e.getX(), e.getY());
}
}
});
removeItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (personTableListener != null) {
personTableListener.rowDeleted(row);
tableModel.fireTableRowsDeleted(row, row);
}
}
});
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
}
public void setData(List<Person> db) {
tableModel.setData(db);
}
public void refresh() {
tableModel.fireTableDataChanged();
}
public void setPersonTableListener(PersonTableListener personTableListener) {
this.personTableListener = personTableListener;
}
}
|
package com.tudou;
import com.tudou.common.util.A;
import com.tudou.common.util.LogUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class WebPlatformApplication extends SpringBootServletInitializer{
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(WebPlatformApplication.class);
}
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(WebPlatformApplication.class, args);
if (LogUtil.ROOT_LOG.isDebugEnabled()) {
String[] activeProfiles = ctx.getEnvironment().getActiveProfiles();
if (A.isNotEmpty(activeProfiles)) {
LogUtil.ROOT_LOG.debug("current profile : ({})", A.toStr(activeProfiles));
}
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.implementation;
import com.azure.core.annotation.BodyParam;
import com.azure.core.annotation.Delete;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.Put;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.management.polling.PollResult;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.polling.PollerFlux;
import com.azure.core.util.polling.SyncPoller;
import com.azure.resourcemanager.network.fluent.InboundNatRulesClient;
import com.azure.resourcemanager.network.fluent.models.InboundNatRuleInner;
import com.azure.resourcemanager.network.models.InboundNatRuleListResult;
import java.nio.ByteBuffer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in InboundNatRulesClient. */
public final class InboundNatRulesClientImpl implements InboundNatRulesClient {
private final ClientLogger logger = new ClientLogger(InboundNatRulesClientImpl.class);
/** The proxy service used to perform REST calls. */
private final InboundNatRulesService service;
/** The service client containing this operation class. */
private final NetworkManagementClientImpl client;
/**
* Initializes an instance of InboundNatRulesClientImpl.
*
* @param client the instance of the service client containing this operation class.
*/
InboundNatRulesClientImpl(NetworkManagementClientImpl client) {
this.service =
RestProxy.create(InboundNatRulesService.class, client.getHttpPipeline(), client.getSerializerAdapter());
this.client = client;
}
/**
* The interface defining all the services for NetworkManagementClientInboundNatRules to be used by the proxy
* service to perform REST calls.
*/
@Host("{$host}")
@ServiceInterface(name = "NetworkManagementCli")
private interface InboundNatRulesService {
@Headers({"Content-Type: application/json"})
@Get(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network"
+ "/loadBalancers/{loadBalancerName}/inboundNatRules")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<InboundNatRuleListResult>> list(
@HostParam("$host") String endpoint,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("loadBalancerName") String loadBalancerName,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
@HeaderParam("Accept") String accept,
Context context);
@Headers({"Content-Type: application/json"})
@Delete(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network"
+ "/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}")
@ExpectedResponses({200, 202, 204})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<Flux<ByteBuffer>>> delete(
@HostParam("$host") String endpoint,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("loadBalancerName") String loadBalancerName,
@PathParam("inboundNatRuleName") String inboundNatRuleName,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
@HeaderParam("Accept") String accept,
Context context);
@Headers({"Content-Type: application/json"})
@Get(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network"
+ "/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<InboundNatRuleInner>> get(
@HostParam("$host") String endpoint,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("loadBalancerName") String loadBalancerName,
@PathParam("inboundNatRuleName") String inboundNatRuleName,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
@QueryParam("$expand") String expand,
@HeaderParam("Accept") String accept,
Context context);
@Headers({"Content-Type: application/json"})
@Put(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network"
+ "/loadBalancers/{loadBalancerName}/inboundNatRules/{inboundNatRuleName}")
@ExpectedResponses({200, 201})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<Flux<ByteBuffer>>> createOrUpdate(
@HostParam("$host") String endpoint,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("loadBalancerName") String loadBalancerName,
@PathParam("inboundNatRuleName") String inboundNatRuleName,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
@BodyParam("application/json") InboundNatRuleInner inboundNatRuleParameters,
@HeaderParam("Accept") String accept,
Context context);
@Headers({"Content-Type: application/json"})
@Get("{nextLink}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<InboundNatRuleListResult>> listNext(
@PathParam(value = "nextLink", encoded = true) String nextLink,
@HostParam("$host") String endpoint,
@HeaderParam("Accept") String accept,
Context context);
}
/**
* Gets all the inbound nat rules in a load balancer.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the inbound nat rules in a load balancer.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<InboundNatRuleInner>> listSinglePageAsync(
String resourceGroupName, String loadBalancerName) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (loadBalancerName == null) {
return Mono
.error(new IllegalArgumentException("Parameter loadBalancerName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-07-01";
final String accept = "application/json";
return FluxUtil
.withContext(
context ->
service
.list(
this.client.getEndpoint(),
resourceGroupName,
loadBalancerName,
apiVersion,
this.client.getSubscriptionId(),
accept,
context))
.<PagedResponse<InboundNatRuleInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Gets all the inbound nat rules in a load balancer.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the inbound nat rules in a load balancer.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<InboundNatRuleInner>> listSinglePageAsync(
String resourceGroupName, String loadBalancerName, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (loadBalancerName == null) {
return Mono
.error(new IllegalArgumentException("Parameter loadBalancerName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-07-01";
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.list(
this.client.getEndpoint(),
resourceGroupName,
loadBalancerName,
apiVersion,
this.client.getSubscriptionId(),
accept,
context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
/**
* Gets all the inbound nat rules in a load balancer.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the inbound nat rules in a load balancer.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<InboundNatRuleInner> listAsync(String resourceGroupName, String loadBalancerName) {
return new PagedFlux<>(
() -> listSinglePageAsync(resourceGroupName, loadBalancerName),
nextLink -> listNextSinglePageAsync(nextLink));
}
/**
* Gets all the inbound nat rules in a load balancer.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the inbound nat rules in a load balancer.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedFlux<InboundNatRuleInner> listAsync(
String resourceGroupName, String loadBalancerName, Context context) {
return new PagedFlux<>(
() -> listSinglePageAsync(resourceGroupName, loadBalancerName, context),
nextLink -> listNextSinglePageAsync(nextLink, context));
}
/**
* Gets all the inbound nat rules in a load balancer.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the inbound nat rules in a load balancer.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<InboundNatRuleInner> list(String resourceGroupName, String loadBalancerName) {
return new PagedIterable<>(listAsync(resourceGroupName, loadBalancerName));
}
/**
* Gets all the inbound nat rules in a load balancer.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the inbound nat rules in a load balancer.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<InboundNatRuleInner> list(String resourceGroupName, String loadBalancerName, Context context) {
return new PagedIterable<>(listAsync(resourceGroupName, loadBalancerName, context));
}
/**
* Deletes the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Flux<ByteBuffer>>> deleteWithResponseAsync(
String resourceGroupName, String loadBalancerName, String inboundNatRuleName) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (loadBalancerName == null) {
return Mono
.error(new IllegalArgumentException("Parameter loadBalancerName is required and cannot be null."));
}
if (inboundNatRuleName == null) {
return Mono
.error(new IllegalArgumentException("Parameter inboundNatRuleName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-07-01";
final String accept = "application/json";
return FluxUtil
.withContext(
context ->
service
.delete(
this.client.getEndpoint(),
resourceGroupName,
loadBalancerName,
inboundNatRuleName,
apiVersion,
this.client.getSubscriptionId(),
accept,
context))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Deletes the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<Flux<ByteBuffer>>> deleteWithResponseAsync(
String resourceGroupName, String loadBalancerName, String inboundNatRuleName, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (loadBalancerName == null) {
return Mono
.error(new IllegalArgumentException("Parameter loadBalancerName is required and cannot be null."));
}
if (inboundNatRuleName == null) {
return Mono
.error(new IllegalArgumentException("Parameter inboundNatRuleName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-07-01";
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.delete(
this.client.getEndpoint(),
resourceGroupName,
loadBalancerName,
inboundNatRuleName,
apiVersion,
this.client.getSubscriptionId(),
accept,
context);
}
/**
* Deletes the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PollerFlux<PollResult<Void>, Void> beginDeleteAsync(
String resourceGroupName, String loadBalancerName, String inboundNatRuleName) {
Mono<Response<Flux<ByteBuffer>>> mono =
deleteWithResponseAsync(resourceGroupName, loadBalancerName, inboundNatRuleName);
return this
.client
.<Void, Void>getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, Context.NONE);
}
/**
* Deletes the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private PollerFlux<PollResult<Void>, Void> beginDeleteAsync(
String resourceGroupName, String loadBalancerName, String inboundNatRuleName, Context context) {
context = this.client.mergeContext(context);
Mono<Response<Flux<ByteBuffer>>> mono =
deleteWithResponseAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, context);
return this
.client
.<Void, Void>getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, context);
}
/**
* Deletes the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public SyncPoller<PollResult<Void>, Void> beginDelete(
String resourceGroupName, String loadBalancerName, String inboundNatRuleName) {
return beginDeleteAsync(resourceGroupName, loadBalancerName, inboundNatRuleName).getSyncPoller();
}
/**
* Deletes the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public SyncPoller<PollResult<Void>, Void> beginDelete(
String resourceGroupName, String loadBalancerName, String inboundNatRuleName, Context context) {
return beginDeleteAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, context).getSyncPoller();
}
/**
* Deletes the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteAsync(String resourceGroupName, String loadBalancerName, String inboundNatRuleName) {
return beginDeleteAsync(resourceGroupName, loadBalancerName, inboundNatRuleName)
.last()
.flatMap(this.client::getLroFinalResultOrError);
}
/**
* Deletes the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Void> deleteAsync(
String resourceGroupName, String loadBalancerName, String inboundNatRuleName, Context context) {
return beginDeleteAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, context)
.last()
.flatMap(this.client::getLroFinalResultOrError);
}
/**
* Deletes the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void delete(String resourceGroupName, String loadBalancerName, String inboundNatRuleName) {
deleteAsync(resourceGroupName, loadBalancerName, inboundNatRuleName).block();
}
/**
* Deletes the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void delete(String resourceGroupName, String loadBalancerName, String inboundNatRuleName, Context context) {
deleteAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, context).block();
}
/**
* Gets the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param expand Expands referenced resources.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified load balancer inbound nat rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<InboundNatRuleInner>> getWithResponseAsync(
String resourceGroupName, String loadBalancerName, String inboundNatRuleName, String expand) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (loadBalancerName == null) {
return Mono
.error(new IllegalArgumentException("Parameter loadBalancerName is required and cannot be null."));
}
if (inboundNatRuleName == null) {
return Mono
.error(new IllegalArgumentException("Parameter inboundNatRuleName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-07-01";
final String accept = "application/json";
return FluxUtil
.withContext(
context ->
service
.get(
this.client.getEndpoint(),
resourceGroupName,
loadBalancerName,
inboundNatRuleName,
apiVersion,
this.client.getSubscriptionId(),
expand,
accept,
context))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Gets the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param expand Expands referenced resources.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified load balancer inbound nat rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<InboundNatRuleInner>> getWithResponseAsync(
String resourceGroupName, String loadBalancerName, String inboundNatRuleName, String expand, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (loadBalancerName == null) {
return Mono
.error(new IllegalArgumentException("Parameter loadBalancerName is required and cannot be null."));
}
if (inboundNatRuleName == null) {
return Mono
.error(new IllegalArgumentException("Parameter inboundNatRuleName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2020-07-01";
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.get(
this.client.getEndpoint(),
resourceGroupName,
loadBalancerName,
inboundNatRuleName,
apiVersion,
this.client.getSubscriptionId(),
expand,
accept,
context);
}
/**
* Gets the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param expand Expands referenced resources.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified load balancer inbound nat rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<InboundNatRuleInner> getAsync(
String resourceGroupName, String loadBalancerName, String inboundNatRuleName, String expand) {
return getWithResponseAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, expand)
.flatMap(
(Response<InboundNatRuleInner> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
});
}
/**
* Gets the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified load balancer inbound nat rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<InboundNatRuleInner> getAsync(
String resourceGroupName, String loadBalancerName, String inboundNatRuleName) {
final String expand = null;
return getWithResponseAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, expand)
.flatMap(
(Response<InboundNatRuleInner> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
});
}
/**
* Gets the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified load balancer inbound nat rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public InboundNatRuleInner get(String resourceGroupName, String loadBalancerName, String inboundNatRuleName) {
final String expand = null;
return getAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, expand).block();
}
/**
* Gets the specified load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param expand Expands referenced resources.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified load balancer inbound nat rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<InboundNatRuleInner> getWithResponse(
String resourceGroupName, String loadBalancerName, String inboundNatRuleName, String expand, Context context) {
return getWithResponseAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, expand, context).block();
}
/**
* Creates or updates a load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param inboundNatRuleParameters Inbound NAT rule of the load balancer.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return inbound NAT rule of the load balancer.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponseAsync(
String resourceGroupName,
String loadBalancerName,
String inboundNatRuleName,
InboundNatRuleInner inboundNatRuleParameters) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (loadBalancerName == null) {
return Mono
.error(new IllegalArgumentException("Parameter loadBalancerName is required and cannot be null."));
}
if (inboundNatRuleName == null) {
return Mono
.error(new IllegalArgumentException("Parameter inboundNatRuleName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
if (inboundNatRuleParameters == null) {
return Mono
.error(
new IllegalArgumentException("Parameter inboundNatRuleParameters is required and cannot be null."));
} else {
inboundNatRuleParameters.validate();
}
final String apiVersion = "2020-07-01";
final String accept = "application/json";
return FluxUtil
.withContext(
context ->
service
.createOrUpdate(
this.client.getEndpoint(),
resourceGroupName,
loadBalancerName,
inboundNatRuleName,
apiVersion,
this.client.getSubscriptionId(),
inboundNatRuleParameters,
accept,
context))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Creates or updates a load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param inboundNatRuleParameters Inbound NAT rule of the load balancer.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return inbound NAT rule of the load balancer.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponseAsync(
String resourceGroupName,
String loadBalancerName,
String inboundNatRuleName,
InboundNatRuleInner inboundNatRuleParameters,
Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (loadBalancerName == null) {
return Mono
.error(new IllegalArgumentException("Parameter loadBalancerName is required and cannot be null."));
}
if (inboundNatRuleName == null) {
return Mono
.error(new IllegalArgumentException("Parameter inboundNatRuleName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
if (inboundNatRuleParameters == null) {
return Mono
.error(
new IllegalArgumentException("Parameter inboundNatRuleParameters is required and cannot be null."));
} else {
inboundNatRuleParameters.validate();
}
final String apiVersion = "2020-07-01";
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.createOrUpdate(
this.client.getEndpoint(),
resourceGroupName,
loadBalancerName,
inboundNatRuleName,
apiVersion,
this.client.getSubscriptionId(),
inboundNatRuleParameters,
accept,
context);
}
/**
* Creates or updates a load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param inboundNatRuleParameters Inbound NAT rule of the load balancer.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return inbound NAT rule of the load balancer.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PollerFlux<PollResult<InboundNatRuleInner>, InboundNatRuleInner> beginCreateOrUpdateAsync(
String resourceGroupName,
String loadBalancerName,
String inboundNatRuleName,
InboundNatRuleInner inboundNatRuleParameters) {
Mono<Response<Flux<ByteBuffer>>> mono =
createOrUpdateWithResponseAsync(
resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters);
return this
.client
.<InboundNatRuleInner, InboundNatRuleInner>getLroResult(
mono,
this.client.getHttpPipeline(),
InboundNatRuleInner.class,
InboundNatRuleInner.class,
Context.NONE);
}
/**
* Creates or updates a load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param inboundNatRuleParameters Inbound NAT rule of the load balancer.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return inbound NAT rule of the load balancer.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private PollerFlux<PollResult<InboundNatRuleInner>, InboundNatRuleInner> beginCreateOrUpdateAsync(
String resourceGroupName,
String loadBalancerName,
String inboundNatRuleName,
InboundNatRuleInner inboundNatRuleParameters,
Context context) {
context = this.client.mergeContext(context);
Mono<Response<Flux<ByteBuffer>>> mono =
createOrUpdateWithResponseAsync(
resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters, context);
return this
.client
.<InboundNatRuleInner, InboundNatRuleInner>getLroResult(
mono, this.client.getHttpPipeline(), InboundNatRuleInner.class, InboundNatRuleInner.class, context);
}
/**
* Creates or updates a load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param inboundNatRuleParameters Inbound NAT rule of the load balancer.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return inbound NAT rule of the load balancer.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public SyncPoller<PollResult<InboundNatRuleInner>, InboundNatRuleInner> beginCreateOrUpdate(
String resourceGroupName,
String loadBalancerName,
String inboundNatRuleName,
InboundNatRuleInner inboundNatRuleParameters) {
return beginCreateOrUpdateAsync(
resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters)
.getSyncPoller();
}
/**
* Creates or updates a load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param inboundNatRuleParameters Inbound NAT rule of the load balancer.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return inbound NAT rule of the load balancer.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public SyncPoller<PollResult<InboundNatRuleInner>, InboundNatRuleInner> beginCreateOrUpdate(
String resourceGroupName,
String loadBalancerName,
String inboundNatRuleName,
InboundNatRuleInner inboundNatRuleParameters,
Context context) {
return beginCreateOrUpdateAsync(
resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters, context)
.getSyncPoller();
}
/**
* Creates or updates a load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param inboundNatRuleParameters Inbound NAT rule of the load balancer.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return inbound NAT rule of the load balancer.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<InboundNatRuleInner> createOrUpdateAsync(
String resourceGroupName,
String loadBalancerName,
String inboundNatRuleName,
InboundNatRuleInner inboundNatRuleParameters) {
return beginCreateOrUpdateAsync(
resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters)
.last()
.flatMap(this.client::getLroFinalResultOrError);
}
/**
* Creates or updates a load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param inboundNatRuleParameters Inbound NAT rule of the load balancer.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return inbound NAT rule of the load balancer.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<InboundNatRuleInner> createOrUpdateAsync(
String resourceGroupName,
String loadBalancerName,
String inboundNatRuleName,
InboundNatRuleInner inboundNatRuleParameters,
Context context) {
return beginCreateOrUpdateAsync(
resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters, context)
.last()
.flatMap(this.client::getLroFinalResultOrError);
}
/**
* Creates or updates a load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param inboundNatRuleParameters Inbound NAT rule of the load balancer.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return inbound NAT rule of the load balancer.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public InboundNatRuleInner createOrUpdate(
String resourceGroupName,
String loadBalancerName,
String inboundNatRuleName,
InboundNatRuleInner inboundNatRuleParameters) {
return createOrUpdateAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters)
.block();
}
/**
* Creates or updates a load balancer inbound nat rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param inboundNatRuleName The name of the inbound nat rule.
* @param inboundNatRuleParameters Inbound NAT rule of the load balancer.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return inbound NAT rule of the load balancer.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public InboundNatRuleInner createOrUpdate(
String resourceGroupName,
String loadBalancerName,
String inboundNatRuleName,
InboundNatRuleInner inboundNatRuleParameters,
Context context) {
return createOrUpdateAsync(
resourceGroupName, loadBalancerName, inboundNatRuleName, inboundNatRuleParameters, context)
.block();
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListInboundNatRule API service call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<InboundNatRuleInner>> listNextSinglePageAsync(String nextLink) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
final String accept = "application/json";
return FluxUtil
.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context))
.<PagedResponse<InboundNatRuleInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListInboundNatRule API service call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<InboundNatRuleInner>> listNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.listNext(nextLink, this.client.getEndpoint(), accept, context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
}
|
/*
* Copyright (c) 2008-2012, Hazel Bilisim Ltd. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jmx;
import com.hazelcast.core.ILock;
/**
* MBean for Locks
*
* @author Marco Ferrante, DISI - University of Genoa
*/
@JMXDescription("A distributed Lock")
public class LockMBean extends AbstractMBean<ILock> {
public LockMBean(ILock lock, ManagementService managementService) {
super(lock, managementService);
}
@Override
public ObjectNameSpec getNameSpec() {
return getParentName().getNested("Lock", getName());
}
@JMXAttribute("String")
@JMXDescription("toString() result")
public String getName() {
return getManagedObject().toString();
}
@JMXAttribute("LockObject")
@JMXDescription("The object locked")
public String getLockObject() {
Object obj = getManagedObject().getLockObject();
if (obj != null) {
return obj.toString();
}
return null;
}
}
|
/*
* 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.sling.pipes;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.resource.Resource;
import javax.jcr.query.Query;
import java.util.Iterator;
/**
* generates output based on an xpath query (no input is considered)
*/
public class XPathPipe extends BasePipe {
public static final String RESOURCE_TYPE = "slingPipes/xpath";
public XPathPipe(Plumber plumber, Resource resource) throws Exception {
super(plumber, resource);
}
@Override
public Iterator<Resource> getOutput() {
String query = getExpr();
if (StringUtils.isNotBlank(query)){
return resource.getResourceResolver().findResources(query, Query.XPATH);
}
return EMPTY_ITERATOR;
}
}
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* The core Vulkan 1.1 functionality.
*
* <p>Vulkan Version 1.1 <em>promoted</em> a number of key extensions into the core API:</p>
*
* <ul>
* <li>{@link KHR16bitStorage KHR_16bit_storage}</li>
* <li>{@link KHRBindMemory2 KHR_bind_memory2}</li>
* <li>{@link KHRDedicatedAllocation KHR_dedicated_allocation}</li>
* <li>{@link KHRDescriptorUpdateTemplate KHR_descriptor_update_template}</li>
* <li>{@link KHRDeviceGroup KHR_device_group}</li>
* <li>{@link KHRDeviceGroupCreation KHR_device_group_creation}</li>
* <li>{@link KHRExternalMemory KHR_external_memory}</li>
* <li>{@link KHRExternalMemoryCapabilities KHR_external_memory_capabilities}</li>
* <li>{@link KHRExternalSemaphore KHR_external_semaphore}</li>
* <li>{@link KHRExternalSemaphoreCapabilities KHR_external_semaphore_capabilities}</li>
* <li>{@link KHRExternalFence KHR_external_fence}</li>
* <li>{@link KHRExternalFenceCapabilities KHR_external_fence_capabilities}</li>
* <li>{@link KHRGetMemoryRequirements2 KHR_get_memory_requirements2}</li>
* <li>{@link KHRGetPhysicalDeviceProperties2 KHR_get_physical_device_properties2}</li>
* <li>{@link KHRMaintenance1 KHR_maintenance1}</li>
* <li>{@link KHRMaintenance2 KHR_maintenance2}</li>
* <li>{@link KHRMaintenance3 KHR_maintenance3}</li>
* <li>{@link KHRMultiview KHR_multiview}</li>
* <li>{@link KHRRelaxedBlockLayout KHR_relaxed_block_layout}</li>
* <li>{@link KHRSamplerYcbcrConversion KHR_sampler_ycbcr_conversion}</li>
* <li>{@link KHRShaderDrawParameters KHR_shader_draw_parameters}</li>
* <li>{@link KHRStorageBufferStorageClass KHR_storage_buffer_storage_class}</li>
* <li>{@link KHRVariablePointers KHR_variable_pointers}</li>
* </ul>
*
* <p>The only changes to the functionality added by these extensions were to {@code VK_KHR_shader_draw_parameters}, which had a
* <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-features-shaderDrawParameters">feature bit</a>
* added to determine support in the core API, and
* <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-features-variablePointersStorageBuffer">{@code variablePointersStorageBuffer}</a>
* from {@code VK_KHR_variable_pointers} was made optional.</p>
*
* <p>Additionally, Vulkan 1.1 added support for {@link VkPhysicalDeviceSubgroupProperties subgroup operations},
* {@link VkPhysicalDeviceProtectedMemoryFeatures protected memory}, and a new command to {@link VK11#vkEnumerateInstanceVersion enumerate the
* instance version}.</p>
*/
public class VK11 extends VK10 {
/** Extends {@code VkStructureType}. */
public static final int VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES = 1000094000;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO = 1000157000,
VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO = 1000157001;
/** Extends {@code VkImageCreateFlagBits}. */
public static final int VK_IMAGE_CREATE_ALIAS_BIT = 0x400;
/** Extends {@code VkStructureType}. */
public static final int VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES = 1000083000;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS}</li>
* <li>{@link #VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS = 1000127000,
VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO = 1000127001;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DEVICE_GROUP_RENDER_PASS_BEGIN_INFO STRUCTURE_TYPE_DEVICE_GROUP_RENDER_PASS_BEGIN_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DEVICE_GROUP_COMMAND_BUFFER_BEGIN_INFO STRUCTURE_TYPE_DEVICE_GROUP_COMMAND_BUFFER_BEGIN_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DEVICE_GROUP_BIND_SPARSE_INFO STRUCTURE_TYPE_DEVICE_GROUP_BIND_SPARSE_INFO}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO = 1000060000,
VK_STRUCTURE_TYPE_DEVICE_GROUP_RENDER_PASS_BEGIN_INFO = 1000060003,
VK_STRUCTURE_TYPE_DEVICE_GROUP_COMMAND_BUFFER_BEGIN_INFO = 1000060004,
VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO = 1000060005,
VK_STRUCTURE_TYPE_DEVICE_GROUP_BIND_SPARSE_INFO = 1000060006;
/**
* Extends {@code VkPipelineCreateFlagBits}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_PIPELINE_CREATE_VIEW_INDEX_FROM_DEVICE_INDEX_BIT PIPELINE_CREATE_VIEW_INDEX_FROM_DEVICE_INDEX_BIT}</li>
* <li>{@link #VK_PIPELINE_CREATE_DISPATCH_BASE_BIT PIPELINE_CREATE_DISPATCH_BASE_BIT}</li>
* <li>{@link #VK_PIPELINE_CREATE_DISPATCH_BASE PIPELINE_CREATE_DISPATCH_BASE}</li>
* </ul>
*/
public static final int
VK_PIPELINE_CREATE_VIEW_INDEX_FROM_DEVICE_INDEX_BIT = 0x8,
VK_PIPELINE_CREATE_DISPATCH_BASE_BIT = 0x10,
VK_PIPELINE_CREATE_DISPATCH_BASE = 0x10;
/** Extends {@code VkDependencyFlagBits}. */
public static final int VK_DEPENDENCY_DEVICE_GROUP_BIT = 0x4;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_DEVICE_GROUP_INFO STRUCTURE_TYPE_BIND_BUFFER_MEMORY_DEVICE_GROUP_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_DEVICE_GROUP_INFO STRUCTURE_TYPE_BIND_IMAGE_MEMORY_DEVICE_GROUP_INFO}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_DEVICE_GROUP_INFO = 1000060013,
VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_DEVICE_GROUP_INFO = 1000060014;
/** Extends {@code VkImageCreateFlagBits}. */
public static final int VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT = 0x40;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES = 1000070000,
VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO = 1000070001;
/** Extends {@code VkMemoryHeapFlagBits}. */
public static final int VK_MEMORY_HEAP_MULTI_INSTANCE_BIT = 0x2;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2 STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2}</li>
* <li>{@link #VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2 STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2}</li>
* <li>{@link #VK_STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2 STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2}</li>
* <li>{@link #VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2 STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}</li>
* <li>{@link #VK_STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2 STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2 = 1000146000,
VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2 = 1000146001,
VK_STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2 = 1000146002,
VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2 = 1000146003,
VK_STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2 = 1000146004;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2 STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}</li>
* <li>{@link #VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2 STRUCTURE_TYPE_FORMAT_PROPERTIES_2}</li>
* <li>{@link #VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2 STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2 STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2}</li>
* <li>{@link #VK_STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2 STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2 STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2}</li>
* <li>{@link #VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2 STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SPARSE_IMAGE_FORMAT_INFO_2 STRUCTURE_TYPE_PHYSICAL_DEVICE_SPARSE_IMAGE_FORMAT_INFO_2}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 = 1000059000,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2 = 1000059001,
VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2 = 1000059002,
VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2 = 1000059003,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2 = 1000059004,
VK_STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2 = 1000059005,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2 = 1000059006,
VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2 = 1000059007,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SPARSE_IMAGE_FORMAT_INFO_2 = 1000059008;
/** Extends {@code VkResult}. */
public static final int VK_ERROR_OUT_OF_POOL_MEMORY = -1000069000;
/**
* Extends {@code VkFormatFeatureFlagBits}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_FORMAT_FEATURE_TRANSFER_SRC_BIT FORMAT_FEATURE_TRANSFER_SRC_BIT}</li>
* <li>{@link #VK_FORMAT_FEATURE_TRANSFER_DST_BIT FORMAT_FEATURE_TRANSFER_DST_BIT}</li>
* </ul>
*/
public static final int
VK_FORMAT_FEATURE_TRANSFER_SRC_BIT = 0x4000,
VK_FORMAT_FEATURE_TRANSFER_DST_BIT = 0x8000;
/** Extends {@code VkImageCreateFlagBits}. */
public static final int VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT = 0x20;
/**
* Extends {@code VkImageCreateFlagBits}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT}</li>
* <li>{@link #VK_IMAGE_CREATE_EXTENDED_USAGE_BIT IMAGE_CREATE_EXTENDED_USAGE_BIT}</li>
* </ul>
*/
public static final int
VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT = 0x80,
VK_IMAGE_CREATE_EXTENDED_USAGE_BIT = 0x100;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES}</li>
* <li>{@link #VK_STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO STRUCTURE_TYPE_PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES = 1000117000,
VK_STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO = 1000117001,
VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO = 1000117002,
VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO = 1000117003;
/**
* Extends {@code VkImageLayout}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL}</li>
* <li>{@link #VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL}</li>
* </ul>
*/
public static final int
VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL = 1000117000,
VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL = 1000117001;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO = 1000053000,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES = 1000053001,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES = 1000053002;
/** Extends {@code VkDependencyFlagBits}. */
public static final int VK_DEPENDENCY_VIEW_LOCAL_BIT = 0x2;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES = 1000120000,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES = 1000120000;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_PROTECTED_SUBMIT_INFO STRUCTURE_TYPE_PROTECTED_SUBMIT_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2 STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_PROTECTED_SUBMIT_INFO = 1000145000,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES = 1000145001,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES = 1000145002,
VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2 = 1000145003;
/** Extends {@code VkQueueFlagBits}. */
public static final int VK_QUEUE_PROTECTED_BIT = 0x10;
/** Extends {@code VkDeviceQueueCreateFlagBits}. */
public static final int VK_DEVICE_QUEUE_CREATE_PROTECTED_BIT = 0x1;
/** Extends {@code VkMemoryPropertyFlagBits}. */
public static final int VK_MEMORY_PROPERTY_PROTECTED_BIT = 0x20;
/** Extends {@code VkBufferCreateFlagBits}. */
public static final int VK_BUFFER_CREATE_PROTECTED_BIT = 0x8;
/** Extends {@code VkImageCreateFlagBits}. */
public static final int VK_IMAGE_CREATE_PROTECTED_BIT = 0x800;
/** Extends {@code VkCommandPoolCreateFlagBits}. */
public static final int VK_COMMAND_POOL_CREATE_PROTECTED_BIT = 0x4;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES}</li>
* <li>{@link #VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_IMAGE_FORMAT_PROPERTIES STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_IMAGE_FORMAT_PROPERTIES}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO = 1000156000,
VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO = 1000156001,
VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO = 1000156002,
VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO = 1000156003,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES = 1000156004,
VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_IMAGE_FORMAT_PROPERTIES = 1000156005;
/** Extends {@code VkObjectType}. */
public static final int VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION = 1000156000;
/**
* Extends {@code VkFormat}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_FORMAT_G8B8G8R8_422_UNORM FORMAT_G8B8G8R8_422_UNORM}</li>
* <li>{@link #VK_FORMAT_B8G8R8G8_422_UNORM FORMAT_B8G8R8G8_422_UNORM}</li>
* <li>{@link #VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM FORMAT_G8_B8_R8_3PLANE_420_UNORM}</li>
* <li>{@link #VK_FORMAT_G8_B8R8_2PLANE_420_UNORM FORMAT_G8_B8R8_2PLANE_420_UNORM}</li>
* <li>{@link #VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM FORMAT_G8_B8_R8_3PLANE_422_UNORM}</li>
* <li>{@link #VK_FORMAT_G8_B8R8_2PLANE_422_UNORM FORMAT_G8_B8R8_2PLANE_422_UNORM}</li>
* <li>{@link #VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM FORMAT_G8_B8_R8_3PLANE_444_UNORM}</li>
* <li>{@link #VK_FORMAT_R10X6_UNORM_PACK16 FORMAT_R10X6_UNORM_PACK16}</li>
* <li>{@link #VK_FORMAT_R10X6G10X6_UNORM_2PACK16 FORMAT_R10X6G10X6_UNORM_2PACK16}</li>
* <li>{@link #VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16 FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16}</li>
* <li>{@link #VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16 FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16}</li>
* <li>{@link #VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16 FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16}</li>
* <li>{@link #VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16 FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16}</li>
* <li>{@link #VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16 FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16}</li>
* <li>{@link #VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16 FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16}</li>
* <li>{@link #VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16 FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16}</li>
* <li>{@link #VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16 FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16}</li>
* <li>{@link #VK_FORMAT_R12X4_UNORM_PACK16 FORMAT_R12X4_UNORM_PACK16}</li>
* <li>{@link #VK_FORMAT_R12X4G12X4_UNORM_2PACK16 FORMAT_R12X4G12X4_UNORM_2PACK16}</li>
* <li>{@link #VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16 FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16}</li>
* <li>{@link #VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16 FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16}</li>
* <li>{@link #VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16 FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16}</li>
* <li>{@link #VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16 FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16}</li>
* <li>{@link #VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16 FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16}</li>
* <li>{@link #VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16 FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16}</li>
* <li>{@link #VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16 FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16}</li>
* <li>{@link #VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16 FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16}</li>
* <li>{@link #VK_FORMAT_G16B16G16R16_422_UNORM FORMAT_G16B16G16R16_422_UNORM}</li>
* <li>{@link #VK_FORMAT_B16G16R16G16_422_UNORM FORMAT_B16G16R16G16_422_UNORM}</li>
* <li>{@link #VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM FORMAT_G16_B16_R16_3PLANE_420_UNORM}</li>
* <li>{@link #VK_FORMAT_G16_B16R16_2PLANE_420_UNORM FORMAT_G16_B16R16_2PLANE_420_UNORM}</li>
* <li>{@link #VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM FORMAT_G16_B16_R16_3PLANE_422_UNORM}</li>
* <li>{@link #VK_FORMAT_G16_B16R16_2PLANE_422_UNORM FORMAT_G16_B16R16_2PLANE_422_UNORM}</li>
* <li>{@link #VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM FORMAT_G16_B16_R16_3PLANE_444_UNORM}</li>
* </ul>
*/
public static final int
VK_FORMAT_G8B8G8R8_422_UNORM = 1000156000,
VK_FORMAT_B8G8R8G8_422_UNORM = 1000156001,
VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM = 1000156002,
VK_FORMAT_G8_B8R8_2PLANE_420_UNORM = 1000156003,
VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM = 1000156004,
VK_FORMAT_G8_B8R8_2PLANE_422_UNORM = 1000156005,
VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM = 1000156006,
VK_FORMAT_R10X6_UNORM_PACK16 = 1000156007,
VK_FORMAT_R10X6G10X6_UNORM_2PACK16 = 1000156008,
VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16 = 1000156009,
VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16 = 1000156010,
VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16 = 1000156011,
VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16 = 1000156012,
VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16 = 1000156013,
VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16 = 1000156014,
VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16 = 1000156015,
VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16 = 1000156016,
VK_FORMAT_R12X4_UNORM_PACK16 = 1000156017,
VK_FORMAT_R12X4G12X4_UNORM_2PACK16 = 1000156018,
VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16 = 1000156019,
VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16 = 1000156020,
VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16 = 1000156021,
VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16 = 1000156022,
VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16 = 1000156023,
VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16 = 1000156024,
VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16 = 1000156025,
VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16 = 1000156026,
VK_FORMAT_G16B16G16R16_422_UNORM = 1000156027,
VK_FORMAT_B16G16R16G16_422_UNORM = 1000156028,
VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM = 1000156029,
VK_FORMAT_G16_B16R16_2PLANE_420_UNORM = 1000156030,
VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM = 1000156031,
VK_FORMAT_G16_B16R16_2PLANE_422_UNORM = 1000156032,
VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM = 1000156033;
/**
* Extends {@code VkImageAspectFlagBits}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_IMAGE_ASPECT_PLANE_0_BIT IMAGE_ASPECT_PLANE_0_BIT}</li>
* <li>{@link #VK_IMAGE_ASPECT_PLANE_1_BIT IMAGE_ASPECT_PLANE_1_BIT}</li>
* <li>{@link #VK_IMAGE_ASPECT_PLANE_2_BIT IMAGE_ASPECT_PLANE_2_BIT}</li>
* </ul>
*/
public static final int
VK_IMAGE_ASPECT_PLANE_0_BIT = 0x10,
VK_IMAGE_ASPECT_PLANE_1_BIT = 0x20,
VK_IMAGE_ASPECT_PLANE_2_BIT = 0x40;
/** Extends {@code VkImageCreateFlagBits}. */
public static final int VK_IMAGE_CREATE_DISJOINT_BIT = 0x200;
/**
* Extends {@code VkFormatFeatureFlagBits}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT}</li>
* <li>{@link #VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT}</li>
* <li>{@link #VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT}</li>
* <li>{@link #VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT}</li>
* <li>{@link #VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT}</li>
* <li>{@link #VK_FORMAT_FEATURE_DISJOINT_BIT FORMAT_FEATURE_DISJOINT_BIT}</li>
* <li>{@link #VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT}</li>
* </ul>
*/
public static final int
VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT = 0x20000,
VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT = 0x40000,
VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT = 0x80000,
VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT = 0x100000,
VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT = 0x200000,
VK_FORMAT_FEATURE_DISJOINT_BIT = 0x400000,
VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT = 0x800000;
/** Extends {@code VkStructureType}. */
public static final int VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO = 1000085000;
/** Extends {@code VkObjectType}. */
public static final int VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE = 1000085000;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO = 1000071000,
VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES = 1000071001,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO = 1000071002,
VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES = 1000071003,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES = 1000071004;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO = 1000072000,
VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO = 1000072001,
VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO = 1000072002;
/** Extends {@code VkResult}. */
public static final int VK_ERROR_INVALID_EXTERNAL_HANDLE = -1000072003;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_FENCE_INFO STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_FENCE_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_EXTERNAL_FENCE_PROPERTIES STRUCTURE_TYPE_EXTERNAL_FENCE_PROPERTIES}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_FENCE_INFO = 1000112000,
VK_STRUCTURE_TYPE_EXTERNAL_FENCE_PROPERTIES = 1000112001;
/** Extends {@code VkStructureType}. */
public static final int VK_STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO = 1000113000;
/** Extends {@code VkStructureType}. */
public static final int VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO = 1000077000;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO}</li>
* <li>{@link #VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO = 1000076000,
VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES = 1000076001;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES}</li>
* <li>{@link #VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES = 1000168000,
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT = 1000168001;
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES}</li>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES = 1000063000,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES = 1000063000;
/**
* VkSubgroupFeatureFlagBits - Bitmask describing what group operations are supported with subgroup scope
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_SUBGROUP_FEATURE_BASIC_BIT SUBGROUP_FEATURE_BASIC_BIT} specifies the device will accept SPIR-V shader modules containing the {@code GroupNonUniform} capability.</li>
* <li>{@link #VK_SUBGROUP_FEATURE_VOTE_BIT SUBGROUP_FEATURE_VOTE_BIT} specifies the device will accept SPIR-V shader modules containing the {@code GroupNonUniformVote} capability.</li>
* <li>{@link #VK_SUBGROUP_FEATURE_ARITHMETIC_BIT SUBGROUP_FEATURE_ARITHMETIC_BIT} specifies the device will accept SPIR-V shader modules containing the {@code GroupNonUniformArithmetic} capability.</li>
* <li>{@link #VK_SUBGROUP_FEATURE_BALLOT_BIT SUBGROUP_FEATURE_BALLOT_BIT} specifies the device will accept SPIR-V shader modules containing the {@code GroupNonUniformBallot} capability.</li>
* <li>{@link #VK_SUBGROUP_FEATURE_SHUFFLE_BIT SUBGROUP_FEATURE_SHUFFLE_BIT} specifies the device will accept SPIR-V shader modules containing the {@code GroupNonUniformShuffle} capability.</li>
* <li>{@link #VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT} specifies the device will accept SPIR-V shader modules containing the {@code GroupNonUniformShuffleRelative} capability.</li>
* <li>{@link #VK_SUBGROUP_FEATURE_CLUSTERED_BIT SUBGROUP_FEATURE_CLUSTERED_BIT} specifies the device will accept SPIR-V shader modules containing the {@code GroupNonUniformClustered} capability.</li>
* <li>{@link #VK_SUBGROUP_FEATURE_QUAD_BIT SUBGROUP_FEATURE_QUAD_BIT} specifies the device will accept SPIR-V shader modules containing the {@code GroupNonUniformQuad} capability.</li>
* <li>{@link NVShaderSubgroupPartitioned#VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV SUBGROUP_FEATURE_PARTITIONED_BIT_NV} specifies the device will accept SPIR-V shader modules containing the {@code GroupNonUniformPartitionedNV} capability.</li>
* </ul>
*/
public static final int
VK_SUBGROUP_FEATURE_BASIC_BIT = 0x1,
VK_SUBGROUP_FEATURE_VOTE_BIT = 0x2,
VK_SUBGROUP_FEATURE_ARITHMETIC_BIT = 0x4,
VK_SUBGROUP_FEATURE_BALLOT_BIT = 0x8,
VK_SUBGROUP_FEATURE_SHUFFLE_BIT = 0x10,
VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT = 0x20,
VK_SUBGROUP_FEATURE_CLUSTERED_BIT = 0x40,
VK_SUBGROUP_FEATURE_QUAD_BIT = 0x80;
/**
* VkPeerMemoryFeatureFlagBits - Bitmask specifying supported peer memory features
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT PEER_MEMORY_FEATURE_COPY_SRC_BIT} specifies that the memory <b>can</b> be accessed as the source of any {@code vkCmdCopy*} command.</li>
* <li>{@link #VK_PEER_MEMORY_FEATURE_COPY_DST_BIT PEER_MEMORY_FEATURE_COPY_DST_BIT} specifies that the memory <b>can</b> be accessed as the destination of any {@code vkCmdCopy*} command.</li>
* <li>{@link #VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT PEER_MEMORY_FEATURE_GENERIC_SRC_BIT} specifies that the memory <b>can</b> be read as any memory access type.</li>
* <li>{@link #VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT PEER_MEMORY_FEATURE_GENERIC_DST_BIT} specifies that the memory <b>can</b> be written as any memory access type. Shader atomics are considered to be writes.</li>
* </ul>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>The peer memory features of a memory heap also apply to any accesses that <b>may</b> be performed during <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#synchronization-image-layout-transitions">image layout transitions</a>.</p>
* </div>
*
* <p>{@link #VK_PEER_MEMORY_FEATURE_COPY_DST_BIT PEER_MEMORY_FEATURE_COPY_DST_BIT} <b>must</b> be supported for all host local heaps and for at least one device-local memory heap.</p>
*
* <p>If a device does not support a peer memory feature, it is still valid to use a resource that includes both local and peer memory bindings with the corresponding access type as long as only the local bindings are actually accessed. For example, an application doing split-frame rendering would use framebuffer attachments that include both local and peer memory bindings, but would scissor the rendering to only update local memory.</p>
*/
public static final int
VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT = 0x1,
VK_PEER_MEMORY_FEATURE_COPY_DST_BIT = 0x2,
VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT = 0x4,
VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT = 0x8;
/**
* VkMemoryAllocateFlagBits - Bitmask specifying flags for a device memory allocation
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT MEMORY_ALLOCATE_DEVICE_MASK_BIT} specifies that memory will be allocated for the devices in {@link VkMemoryAllocateFlagsInfo}{@code ::deviceMask}.</li>
* <li>{@link VK12#VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT} specifies that the memory <b>can</b> be attached to a buffer object created with the {@link VK12#VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT} bit set in {@code usage}, and that the memory handle <b>can</b> be used to retrieve an opaque address via {@link VK12#vkGetDeviceMemoryOpaqueCaptureAddress GetDeviceMemoryOpaqueCaptureAddress}.</li>
* <li>{@link VK12#VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT MEMORY_ALLOCATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT} specifies that the memory’s address <b>can</b> be saved and reused on a subsequent run (e.g. for trace capture and replay), see {@link VkBufferOpaqueCaptureAddressCreateInfo} for more detail.</li>
* </ul>
*/
public static final int VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT = 0x1;
/**
* VkPointClippingBehavior - Enum specifying the point clipping behavior
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES} specifies that the primitive is discarded if the vertex lies outside any clip plane, including the planes bounding the view volume.</li>
* <li>{@link #VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY} specifies that the primitive is discarded only if the vertex lies outside any user clip plane.</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkPhysicalDevicePointClippingProperties}, {@link VkPhysicalDeviceVulkan11Properties}</p>
*/
public static final int
VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES = 0,
VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY = 1;
/**
* VkTessellationDomainOrigin - Enum describing tessellation domain origin
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT} specifies that the origin of the domain space is in the upper left corner, as shown in figure <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#img-tessellation-topology-ul">Domain parameterization for tessellation primitive modes (upper-left origin)</a>.</li>
* <li>{@link #VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT} specifies that the origin of the domain space is in the lower left corner, as shown in figure <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#img-tessellation-topology-ll">Domain parameterization for tessellation primitive modes (lower-left origin)</a>.</li>
* </ul>
*
* <p>This enum affects how the {@code VertexOrderCw} and {@code VertexOrderCcw} tessellation execution modes are interpreted, since the winding is defined relative to the orientation of the domain.</p>
*
* <h5>See Also</h5>
*
* <p>{@link VkPipelineTessellationDomainOriginStateCreateInfo}</p>
*/
public static final int
VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT = 0,
VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT = 1;
/**
* VkSamplerYcbcrModelConversion - Color model component of a color space
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY} specifies that the input values to the conversion are unmodified.</li>
* <li>{@link #VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY} specifies no model conversion but the inputs are range expanded as for Y′C<sub>B</sub>C<sub>R</sub>.</li>
* <li>{@link #VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709 SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709} specifies the color model conversion from Y′C<sub>B</sub>C<sub>R</sub> to R′G′B′ defined in BT.709 and described in the “BT.709 Y’C<sub>B</sub>C<sub>R</sub> conversion” section of the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#data-format">Khronos Data Format Specification</a>.</li>
* <li>{@link #VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601 SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601} specifies the color model conversion from Y′C<sub>B</sub>C<sub>R</sub> to R′G′B′ defined in BT.601 and described in the “BT.601 Y’C<sub>B</sub>C<sub>R</sub> conversion” section of the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#data-format">Khronos Data Format Specification</a>.</li>
* <li>{@link #VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020 SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020} specifies the color model conversion from Y′C<sub>B</sub>C<sub>R</sub> to R′G′B′ defined in BT.2020 and described in the “BT.2020 Y’C<sub>B</sub>C<sub>R</sub> conversion” section of the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#data-format">Khronos Data Format Specification</a>.</li>
* </ul>
*
* <p>In the {@code VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_*} color models, for the input to the sampler Y′C<sub>B</sub>C<sub>R</sub> range expansion and model conversion:</p>
*
* <ul>
* <li>the Y (Y′ luma) component corresponds to the G component of an RGB image.</li>
* <li>the CB (C<sub>B</sub> or “U” blue color difference) component corresponds to the B component of an RGB image.</li>
* <li>the CR (C<sub>R</sub> or “V” red color difference) component corresponds to the R component of an RGB image.</li>
* <li>the alpha component, if present, is not modified by color model conversion.</li>
* </ul>
*
* <p>These rules reflect the mapping of components after the component swizzle operation (controlled by {@link VkSamplerYcbcrConversionCreateInfo}{@code ::components}).</p>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>For example, an “{@code YUVA}” 32-bit format comprising four 8-bit components can be implemented as {@link VK10#VK_FORMAT_R8G8B8A8_UNORM FORMAT_R8G8B8A8_UNORM} with a component mapping:</p>
*
* <ul>
* <li>{@code components.a} = {@link VK10#VK_COMPONENT_SWIZZLE_IDENTITY COMPONENT_SWIZZLE_IDENTITY}</li>
* <li>{@code components.r} = {@link VK10#VK_COMPONENT_SWIZZLE_B COMPONENT_SWIZZLE_B}</li>
* <li>{@code components.g} = {@link VK10#VK_COMPONENT_SWIZZLE_R COMPONENT_SWIZZLE_R}</li>
* <li>{@code components.b} = {@link VK10#VK_COMPONENT_SWIZZLE_G COMPONENT_SWIZZLE_G}</li>
* </ul>
* </div>
*
* <h5>See Also</h5>
*
* <p>{@link VkSamplerYcbcrConversionCreateInfo}</p>
*/
public static final int
VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY = 0,
VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY = 1,
VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709 = 2,
VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601 = 3,
VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020 = 4;
/**
* VkSamplerYcbcrRange - Range of encoded values in a color space
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_SAMPLER_YCBCR_RANGE_ITU_FULL SAMPLER_YCBCR_RANGE_ITU_FULL} specifies that the full range of the encoded values are valid and interpreted according to the ITU “full range” quantization rules.</li>
* <li>{@link #VK_SAMPLER_YCBCR_RANGE_ITU_NARROW SAMPLER_YCBCR_RANGE_ITU_NARROW} specifies that headroom and foot room are reserved in the numerical range of encoded values, and the remaining values are expanded according to the ITU “narrow range” quantization rules.</li>
* </ul>
*
* <p>The formulae for these conversions is described in the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#textures-sampler-YCbCr-conversion-rangeexpand">Sampler Y′C<sub>B</sub>C<sub>R</sub> Range Expansion</a> section of the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#textures">Image Operations</a> chapter.</p>
*
* <p>No range modification takes place if {@code ycbcrModel} is {@link #VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY}; the {@code ycbcrRange} field of {@link VkSamplerYcbcrConversionCreateInfo} is ignored in this case.</p>
*
* <h5>See Also</h5>
*
* <p>{@link VkSamplerYcbcrConversionCreateInfo}</p>
*/
public static final int
VK_SAMPLER_YCBCR_RANGE_ITU_FULL = 0,
VK_SAMPLER_YCBCR_RANGE_ITU_NARROW = 1;
/**
* VkChromaLocation - Position of downsampled chroma samples
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_CHROMA_LOCATION_COSITED_EVEN CHROMA_LOCATION_COSITED_EVEN} specifies that downsampled chroma samples are aligned with luma samples with even coordinates.</li>
* <li>{@link #VK_CHROMA_LOCATION_MIDPOINT CHROMA_LOCATION_MIDPOINT} specifies that downsampled chroma samples are located half way between each even luma sample and the nearest higher odd luma sample.</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkSamplerYcbcrConversionCreateInfo}</p>
*/
public static final int
VK_CHROMA_LOCATION_COSITED_EVEN = 0,
VK_CHROMA_LOCATION_MIDPOINT = 1;
/**
* VkDescriptorUpdateTemplateType - Indicates the valid usage of the descriptor update template
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET} specifies that the descriptor update template will be used for descriptor set updates only.</li>
* <li>{@link KHRPushDescriptor#VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR} specifies that the descriptor update template will be used for push descriptor updates only.</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkDescriptorUpdateTemplateCreateInfo}</p>
*/
public static final int VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET = 0;
/**
* VkExternalMemoryHandleTypeFlagBits - Bit specifying external memory handle types
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT} specifies a POSIX file descriptor handle that has only limited valid usage outside of Vulkan and other compatible APIs. It <b>must</b> be compatible with the POSIX system calls {@code dup}, {@code dup2}, {@code close}, and the non-standard system call {@code dup3}. Additionally, it <b>must</b> be transportable over a socket using an {@code SCM_RIGHTS} control message. It owns a reference to the underlying memory resource represented by its Vulkan memory object.</li>
* <li>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT} specifies an NT handle that has only limited valid usage outside of Vulkan and other compatible APIs. It <b>must</b> be compatible with the functions {@code DuplicateHandle}, {@code CloseHandle}, {@code CompareObjectHandles}, {@code GetHandleInformation}, and {@code SetHandleInformation}. It owns a reference to the underlying memory resource represented by its Vulkan memory object.</li>
* <li>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT} specifies a global share handle that has only limited valid usage outside of Vulkan and other compatible APIs. It is not compatible with any native APIs. It does not own a reference to the underlying memory resource represented by its Vulkan memory object, and will therefore become invalid when all Vulkan memory objects associated with it are destroyed.</li>
* <li>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT} specifies an NT handle returned by {@code IDXGIResource1}{@code ::CreateSharedHandle} referring to a Direct3D 10 or 11 texture resource. It owns a reference to the memory used by the Direct3D resource.</li>
* <li>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT} specifies a global share handle returned by {@code IDXGIResource}{@code ::GetSharedHandle} referring to a Direct3D 10 or 11 texture resource. It does not own a reference to the underlying Direct3D resource, and will therefore become invalid when all Vulkan memory objects and Direct3D resources associated with it are destroyed.</li>
* <li>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT} specifies an NT handle returned by {@code ID3D12Device}{@code ::CreateSharedHandle} referring to a Direct3D 12 heap resource. It owns a reference to the resources used by the Direct3D heap.</li>
* <li>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT} specifies an NT handle returned by {@code ID3D12Device}{@code ::CreateSharedHandle} referring to a Direct3D 12 committed resource. It owns a reference to the memory used by the Direct3D resource.</li>
* <li>{@link EXTExternalMemoryHost#VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT} specifies a host pointer returned by a host memory allocation command. It does not own a reference to the underlying memory resource, and will therefore become invalid if the host memory is freed.</li>
* <li>{@link EXTExternalMemoryHost#VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT} specifies a host pointer to <em>host mapped foreign memory</em>. It does not own a reference to the underlying memory resource, and will therefore become invalid if the foreign memory is unmapped or otherwise becomes no longer available.</li>
* <li>{@link EXTExternalMemoryDmaBuf#VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT} is a file descriptor for a Linux dma_buf. It owns a reference to the underlying memory resource represented by its Vulkan memory object.</li>
* <li>{@link NVExternalMemoryRdma#VK_EXTERNAL_MEMORY_HANDLE_TYPE_RDMA_ADDRESS_BIT_NV EXTERNAL_MEMORY_HANDLE_TYPE_RDMA_ADDRESS_BIT_NV} is a handle to an allocation accessible by remote devices. It owns a reference to the underlying memory resource represented by its Vulkan memory object.</li>
* </ul>
*
* <p>Some external memory handle types can only be shared within the same underlying physical device and/or the same driver version, as defined in the following table:</p>
*
* <h6>External memory handle types compatibility</h6>
*
* <table class="lwjgl">
* <tbody>
* <tr><td>Handle type</td><td>{@link VkPhysicalDeviceIDProperties}{@code ::driverUUID}</td><td>{@link VkPhysicalDeviceIDProperties}{@code ::deviceUUID}</td></tr>
* <tr><td>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link EXTExternalMemoryHost#VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT}</td><td>No restriction</td><td>No restriction</td></tr>
* <tr><td>{@link EXTExternalMemoryHost#VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT}</td><td>No restriction</td><td>No restriction</td></tr>
* <tr><td>{@link EXTExternalMemoryDmaBuf#VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT}</td><td>No restriction</td><td>No restriction</td></tr>
* <tr><td>{@link NVExternalMemoryRdma#VK_EXTERNAL_MEMORY_HANDLE_TYPE_RDMA_ADDRESS_BIT_NV EXTERNAL_MEMORY_HANDLE_TYPE_RDMA_ADDRESS_BIT_NV}</td><td>No restriction</td><td>No restriction</td></tr>
* </tbody>
* </table>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>The above table does not restrict the drivers and devices with which {@link EXTExternalMemoryHost#VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT} and {@link EXTExternalMemoryHost#VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT} <b>may</b> be shared, as these handle types inherently mean memory that does not come from the same device, as they import memory from the host or a foreign device, respectively.</p>
* </div>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>Even though the above table does not restrict the drivers and devices with which {@link EXTExternalMemoryDmaBuf#VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT} <b>may</b> be shared, query mechanisms exist in the Vulkan API that prevent the import of incompatible dma-bufs (such as {@link KHRExternalMemoryFd#vkGetMemoryFdPropertiesKHR GetMemoryFdPropertiesKHR}) and that prevent incompatible usage of dma-bufs (such as {@link VkPhysicalDeviceExternalBufferInfo} and {@link VkPhysicalDeviceExternalImageFormatInfo}).</p>
* </div>
*
* <h5>See Also</h5>
*
* <p>{@link VkImportMemoryFdInfoKHR}, {@link VkImportMemoryHostPointerInfoEXT}, {@link VkImportMemoryWin32HandleInfoKHR}, {@link VkMemoryGetFdInfoKHR}, {@link VkMemoryGetRemoteAddressInfoNV}, {@link VkMemoryGetWin32HandleInfoKHR}, {@link VkPhysicalDeviceExternalBufferInfo}, {@link VkPhysicalDeviceExternalImageFormatInfo}, {@link KHRExternalMemoryFd#vkGetMemoryFdPropertiesKHR GetMemoryFdPropertiesKHR}, {@link EXTExternalMemoryHost#vkGetMemoryHostPointerPropertiesEXT GetMemoryHostPointerPropertiesEXT}, {@link KHRExternalMemoryWin32#vkGetMemoryWin32HandlePropertiesKHR GetMemoryWin32HandlePropertiesKHR}</p>
*/
public static final int
VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT = 0x1,
VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT = 0x2,
VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT = 0x4,
VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT = 0x8,
VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT = 0x10,
VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT = 0x20,
VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT = 0x40;
/**
* VkExternalMemoryFeatureFlagBits - Bitmask specifying features of an external memory handle type
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT} specifies that images or buffers created with the specified parameters and handle type <b>must</b> use the mechanisms defined by {@link VkMemoryDedicatedRequirements} and {@link VkMemoryDedicatedAllocateInfo} to create (or import) a dedicated allocation for the image or buffer.</li>
* <li>{@link #VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT} specifies that handles of this type <b>can</b> be exported from Vulkan memory objects.</li>
* <li>{@link #VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT} specifies that handles of this type <b>can</b> be imported as Vulkan memory objects.</li>
* </ul>
*
* <p>Because their semantics in external APIs roughly align with that of an image or buffer with a dedicated allocation in Vulkan, implementations are <b>required</b> to report {@link #VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT} for the following external handle types:</p>
*
* <ul>
* <li>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT}</li>
* <li>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT}</li>
* <li>{@link #VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT}</li>
* </ul>
*
* <p>Implementations <b>must</b> not report {@link #VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT} for images or buffers with external handle type {@link EXTExternalMemoryHost#VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT}, or {@link EXTExternalMemoryHost#VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT}.</p>
*/
public static final int
VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT = 0x1,
VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT = 0x2,
VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT = 0x4;
/**
* VkExternalFenceHandleTypeFlagBits - Bitmask of valid external fence handle types
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT} specifies a POSIX file descriptor handle that has only limited valid usage outside of Vulkan and other compatible APIs. It <b>must</b> be compatible with the POSIX system calls {@code dup}, {@code dup2}, {@code close}, and the non-standard system call {@code dup3}. Additionally, it <b>must</b> be transportable over a socket using an {@code SCM_RIGHTS} control message. It owns a reference to the underlying synchronization primitive represented by its Vulkan fence object.</li>
* <li>{@link #VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT} specifies an NT handle that has only limited valid usage outside of Vulkan and other compatible APIs. It <b>must</b> be compatible with the functions {@code DuplicateHandle}, {@code CloseHandle}, {@code CompareObjectHandles}, {@code GetHandleInformation}, and {@code SetHandleInformation}. It owns a reference to the underlying synchronization primitive represented by its Vulkan fence object.</li>
* <li>{@link #VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT} specifies a global share handle that has only limited valid usage outside of Vulkan and other compatible APIs. It is not compatible with any native APIs. It does not own a reference to the underlying synchronization primitive represented by its Vulkan fence object, and will therefore become invalid when all Vulkan fence objects associated with it are destroyed.</li>
* <li>{@link #VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT} specifies a POSIX file descriptor handle to a Linux Sync File or Android Fence. It can be used with any native API accepting a valid sync file or fence as input. It owns a reference to the underlying synchronization primitive associated with the file descriptor. Implementations which support importing this handle type <b>must</b> accept any type of sync or fence FD supported by the native system they are running on.</li>
* </ul>
*
* <p>Some external fence handle types can only be shared within the same underlying physical device and/or the same driver version, as defined in the following table:</p>
*
* <h6>External fence handle types compatibility</h6>
*
* <table class="lwjgl">
* <tbody>
* <tr><td>Handle type</td><td>{@link VkPhysicalDeviceIDProperties}{@code ::driverUUID}</td><td>{@link VkPhysicalDeviceIDProperties}{@code ::deviceUUID}</td></tr>
* <tr><td>{@link #VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT}</td><td>No restriction</td><td>No restriction</td></tr>
* </tbody>
* </table>
*
* <h5>See Also</h5>
*
* <p>{@link VkFenceGetFdInfoKHR}, {@link VkFenceGetWin32HandleInfoKHR}, {@link VkImportFenceFdInfoKHR}, {@link VkImportFenceWin32HandleInfoKHR}, {@link VkPhysicalDeviceExternalFenceInfo}</p>
*/
public static final int
VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT = 0x1,
VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT = 0x2,
VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT = 0x4,
VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT = 0x8;
/**
* VkExternalFenceFeatureFlagBits - Bitfield describing features of an external fence handle type
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT} specifies handles of this type <b>can</b> be exported from Vulkan fence objects.</li>
* <li>{@link #VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT} specifies handles of this type <b>can</b> be imported to Vulkan fence objects.</li>
* </ul>
*/
public static final int
VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT = 0x1,
VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT = 0x2;
/**
* VkFenceImportFlagBits - Bitmask specifying additional parameters of fence payload import
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_FENCE_IMPORT_TEMPORARY_BIT FENCE_IMPORT_TEMPORARY_BIT} specifies that the fence payload will be imported only temporarily, as described in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#synchronization-fences-importing">Importing Fence Payloads</a>, regardless of the permanence of {@code handleType}.</li>
* </ul>
*/
public static final int VK_FENCE_IMPORT_TEMPORARY_BIT = 0x1;
/**
* VkSemaphoreImportFlagBits - Bitmask specifying additional parameters of semaphore payload import
*
* <h5>Description</h5>
*
* <p>These bits have the following meanings:</p>
*
* <ul>
* <li>{@link #VK_SEMAPHORE_IMPORT_TEMPORARY_BIT SEMAPHORE_IMPORT_TEMPORARY_BIT} specifies that the semaphore payload will be imported only temporarily, as described in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#synchronization-semaphores-importing">Importing Semaphore Payloads</a>, regardless of the permanence of {@code handleType}.</li>
* </ul>
*/
public static final int VK_SEMAPHORE_IMPORT_TEMPORARY_BIT = 0x1;
/**
* VkExternalSemaphoreHandleTypeFlagBits - Bitmask of valid external semaphore handle types
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT} specifies a POSIX file descriptor handle that has only limited valid usage outside of Vulkan and other compatible APIs. It <b>must</b> be compatible with the POSIX system calls {@code dup}, {@code dup2}, {@code close}, and the non-standard system call {@code dup3}. Additionally, it <b>must</b> be transportable over a socket using an {@code SCM_RIGHTS} control message. It owns a reference to the underlying synchronization primitive represented by its Vulkan semaphore object.</li>
* <li>{@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT} specifies an NT handle that has only limited valid usage outside of Vulkan and other compatible APIs. It <b>must</b> be compatible with the functions {@code DuplicateHandle}, {@code CloseHandle}, {@code CompareObjectHandles}, {@code GetHandleInformation}, and {@code SetHandleInformation}. It owns a reference to the underlying synchronization primitive represented by its Vulkan semaphore object.</li>
* <li>{@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT} specifies a global share handle that has only limited valid usage outside of Vulkan and other compatible APIs. It is not compatible with any native APIs. It does not own a reference to the underlying synchronization primitive represented by its Vulkan semaphore object, and will therefore become invalid when all Vulkan semaphore objects associated with it are destroyed.</li>
* <li>{@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT} specifies an NT handle returned by {@code ID3D12Device}{@code ::CreateSharedHandle} referring to a Direct3D 12 fence, or {@code ID3D11Device5}{@code ::CreateFence} referring to a Direct3D 11 fence. It owns a reference to the underlying synchronization primitive associated with the Direct3D fence.</li>
* <li>{@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE_BIT} is an alias of {@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT} with the same meaning. It is provided for convenience and code clarity when interacting with D3D11 fences.</li>
* <li>{@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT} specifies a POSIX file descriptor handle to a Linux Sync File or Android Fence object. It can be used with any native API accepting a valid sync file or fence as input. It owns a reference to the underlying synchronization primitive associated with the file descriptor. Implementations which support importing this handle type <b>must</b> accept any type of sync or fence FD supported by the native system they are running on.</li>
* </ul>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>Handles of type {@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT} generated by the implementation may represent either Linux Sync Files or Android Fences at the implementation’s discretion. Applications <b>should</b> only use operations defined for both types of file descriptors, unless they know via means external to Vulkan the type of the file descriptor, or are prepared to deal with the system-defined operation failures resulting from using the wrong type.</p>
* </div>
*
* <p>Some external semaphore handle types can only be shared within the same underlying physical device and/or the same driver version, as defined in the following table:</p>
*
* <h6>External semaphore handle types compatibility</h6>
*
* <table class="lwjgl">
* <tbody>
* <tr><td>Handle type</td><td>{@link VkPhysicalDeviceIDProperties}{@code ::driverUUID}</td><td>{@link VkPhysicalDeviceIDProperties}{@code ::deviceUUID}</td></tr>
* <tr><td>{@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT}</td><td>Must match</td><td>Must match</td></tr>
* <tr><td>{@link #VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT}</td><td>No restriction</td><td>No restriction</td></tr>
* </tbody>
* </table>
*
* <h5>See Also</h5>
*
* <p>{@link VkImportSemaphoreFdInfoKHR}, {@link VkImportSemaphoreWin32HandleInfoKHR}, {@link VkPhysicalDeviceExternalSemaphoreInfo}, {@link VkSemaphoreGetFdInfoKHR}, {@link VkSemaphoreGetWin32HandleInfoKHR}</p>
*/
public static final int
VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT = 0x1,
VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT = 0x2,
VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT = 0x4,
VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT = 0x8,
VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE_BIT = 0x8,
VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT = 0x10;
/**
* VkExternalSemaphoreFeatureFlagBits - Bitfield describing features of an external semaphore handle type
*
* <h5>Description</h5>
*
* <ul>
* <li>{@link #VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT} specifies that handles of this type <b>can</b> be exported from Vulkan semaphore objects.</li>
* <li>{@link #VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT} specifies that handles of this type <b>can</b> be imported as Vulkan semaphore objects.</li>
* </ul>
*/
public static final int
VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT = 0x1,
VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT = 0x2;
/** The API version number for Vulkan 1.1. */
public static final int VK_API_VERSION_1_1 = VK_MAKE_VERSION(1, 1, 0);
protected VK11() {
throw new UnsupportedOperationException();
}
// --- [ vkEnumerateInstanceVersion ] ---
/** Unsafe version of: {@link #vkEnumerateInstanceVersion EnumerateInstanceVersion} */
public static int nvkEnumerateInstanceVersion(long pApiVersion) {
long __functionAddress = VK.getGlobalCommands().vkEnumerateInstanceVersion;
if (CHECKS) {
check(__functionAddress);
}
return callPI(pApiVersion, __functionAddress);
}
/**
* Query instance-level version before instance creation.
*
* <h5>C Specification</h5>
*
* <p>To query the version of instance-level functionality supported by the implementation, call:</p>
*
* <pre><code>
* VkResult vkEnumerateInstanceVersion(
* uint32_t* pApiVersion);</code></pre>
*
* <h5>Description</h5>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>The intended behaviour of {@link #vkEnumerateInstanceVersion EnumerateInstanceVersion} is that an implementation <b>should</b> not need to perform memory allocations and <b>should</b> unconditionally return {@link VK10#VK_SUCCESS SUCCESS}. The loader, and any enabled layers, <b>may</b> return {@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY} in the case of a failed memory allocation.</p>
* </div>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code pApiVersion} <b>must</b> be a valid pointer to a {@code uint32_t} value</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* </ul></dd>
* </dl>
*
* @param pApiVersion a pointer to a {@code uint32_t}, which is the version of Vulkan supported by instance-level functionality, encoded as described in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#extendingvulkan-coreversions-versionnumbers">Version Numbers</a>.
*/
@NativeType("VkResult")
public static int vkEnumerateInstanceVersion(@NativeType("uint32_t *") IntBuffer pApiVersion) {
if (CHECKS) {
check(pApiVersion, 1);
}
return nvkEnumerateInstanceVersion(memAddress(pApiVersion));
}
// --- [ vkBindBufferMemory2 ] ---
/**
* Unsafe version of: {@link #vkBindBufferMemory2 BindBufferMemory2}
*
* @param bindInfoCount the number of elements in {@code pBindInfos}.
*/
public static int nvkBindBufferMemory2(VkDevice device, int bindInfoCount, long pBindInfos) {
long __functionAddress = device.getCapabilities().vkBindBufferMemory2;
if (CHECKS) {
check(__functionAddress);
}
return callPPI(device.address(), bindInfoCount, pBindInfos, __functionAddress);
}
/**
* Bind device memory to buffer objects.
*
* <h5>C Specification</h5>
*
* <p>To attach memory to buffer objects for one or more buffers at a time, call:</p>
*
* <pre><code>
* VkResult vkBindBufferMemory2(
* VkDevice device,
* uint32_t bindInfoCount,
* const VkBindBufferMemoryInfo* pBindInfos);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* VkResult vkBindBufferMemory2KHR(
* VkDevice device,
* uint32_t bindInfoCount,
* const VkBindBufferMemoryInfo* pBindInfos);</code></pre>
*
* <h5>Description</h5>
*
* <p>On some implementations, it <b>may</b> be more efficient to batch memory bindings into a single command.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pBindInfos} <b>must</b> be a valid pointer to an array of {@code bindInfoCount} valid {@link VkBindBufferMemoryInfo} structures</li>
* <li>{@code bindInfoCount} <b>must</b> be greater than 0</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* <li>{@link KHRBufferDeviceAddress#VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkBindBufferMemoryInfo}</p>
*
* @param device the logical device that owns the buffers and memory.
* @param pBindInfos a pointer to an array of {@code bindInfoCount} {@link VkBindBufferMemoryInfo} structures describing buffers and memory to bind.
*/
@NativeType("VkResult")
public static int vkBindBufferMemory2(VkDevice device, @NativeType("VkBindBufferMemoryInfo const *") VkBindBufferMemoryInfo.Buffer pBindInfos) {
return nvkBindBufferMemory2(device, pBindInfos.remaining(), pBindInfos.address());
}
// --- [ vkBindImageMemory2 ] ---
/**
* Unsafe version of: {@link #vkBindImageMemory2 BindImageMemory2}
*
* @param bindInfoCount the number of elements in {@code pBindInfos}.
*/
public static int nvkBindImageMemory2(VkDevice device, int bindInfoCount, long pBindInfos) {
long __functionAddress = device.getCapabilities().vkBindImageMemory2;
if (CHECKS) {
check(__functionAddress);
}
return callPPI(device.address(), bindInfoCount, pBindInfos, __functionAddress);
}
/**
* Bind device memory to image objects.
*
* <h5>C Specification</h5>
*
* <p>To attach memory to image objects for one or more images at a time, call:</p>
*
* <pre><code>
* VkResult vkBindImageMemory2(
* VkDevice device,
* uint32_t bindInfoCount,
* const VkBindImageMemoryInfo* pBindInfos);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* VkResult vkBindImageMemory2KHR(
* VkDevice device,
* uint32_t bindInfoCount,
* const VkBindImageMemoryInfo* pBindInfos);</code></pre>
*
* <h5>Description</h5>
*
* <p>On some implementations, it <b>may</b> be more efficient to batch memory bindings into a single command.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>If any {@link VkBindImageMemoryInfo}{@code ::image} was created with {@link #VK_IMAGE_CREATE_DISJOINT_BIT IMAGE_CREATE_DISJOINT_BIT} then all planes of {@link VkBindImageMemoryInfo}{@code ::image} <b>must</b> be bound individually in separate {@code pBindInfos}</li>
* <li>{@code pBindInfos} <b>must</b> not refer to the same image subresource more than once</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pBindInfos} <b>must</b> be a valid pointer to an array of {@code bindInfoCount} valid {@link VkBindImageMemoryInfo} structures</li>
* <li>{@code bindInfoCount} <b>must</b> be greater than 0</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkBindImageMemoryInfo}</p>
*
* @param device the logical device that owns the images and memory.
* @param pBindInfos a pointer to an array of {@link VkBindImageMemoryInfo} structures, describing images and memory to bind.
*/
@NativeType("VkResult")
public static int vkBindImageMemory2(VkDevice device, @NativeType("VkBindImageMemoryInfo const *") VkBindImageMemoryInfo.Buffer pBindInfos) {
return nvkBindImageMemory2(device, pBindInfos.remaining(), pBindInfos.address());
}
// --- [ vkGetDeviceGroupPeerMemoryFeatures ] ---
/** Unsafe version of: {@link #vkGetDeviceGroupPeerMemoryFeatures GetDeviceGroupPeerMemoryFeatures} */
public static void nvkGetDeviceGroupPeerMemoryFeatures(VkDevice device, int heapIndex, int localDeviceIndex, int remoteDeviceIndex, long pPeerMemoryFeatures) {
long __functionAddress = device.getCapabilities().vkGetDeviceGroupPeerMemoryFeatures;
if (CHECKS) {
check(__functionAddress);
}
callPPV(device.address(), heapIndex, localDeviceIndex, remoteDeviceIndex, pPeerMemoryFeatures, __functionAddress);
}
/**
* Query supported peer memory features of a device.
*
* <h5>C Specification</h5>
*
* <p><em>Peer memory</em> is memory that is allocated for a given physical device and then bound to a resource and accessed by a different physical device, in a logical device that represents multiple physical devices. Some ways of reading and writing peer memory <b>may</b> not be supported by a device.</p>
*
* <p>To determine how peer memory <b>can</b> be accessed, call:</p>
*
* <pre><code>
* void vkGetDeviceGroupPeerMemoryFeatures(
* VkDevice device,
* uint32_t heapIndex,
* uint32_t localDeviceIndex,
* uint32_t remoteDeviceIndex,
* VkPeerMemoryFeatureFlags* pPeerMemoryFeatures);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetDeviceGroupPeerMemoryFeaturesKHR(
* VkDevice device,
* uint32_t heapIndex,
* uint32_t localDeviceIndex,
* uint32_t remoteDeviceIndex,
* VkPeerMemoryFeatureFlags* pPeerMemoryFeatures);</code></pre>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code heapIndex} <b>must</b> be less than {@code memoryHeapCount}</li>
* <li>{@code localDeviceIndex} <b>must</b> be a valid device index</li>
* <li>{@code remoteDeviceIndex} <b>must</b> be a valid device index</li>
* <li>{@code localDeviceIndex} <b>must</b> not equal {@code remoteDeviceIndex}</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pPeerMemoryFeatures} <b>must</b> be a valid pointer to a {@code VkPeerMemoryFeatureFlags} value</li>
* </ul>
*
* @param device the logical device that owns the memory.
* @param heapIndex the index of the memory heap from which the memory is allocated.
* @param localDeviceIndex the device index of the physical device that performs the memory access.
* @param remoteDeviceIndex the device index of the physical device that the memory is allocated for.
* @param pPeerMemoryFeatures a pointer to a {@code VkPeerMemoryFeatureFlags} bitmask indicating which types of memory accesses are supported for the combination of heap, local, and remote devices.
*/
public static void vkGetDeviceGroupPeerMemoryFeatures(VkDevice device, @NativeType("uint32_t") int heapIndex, @NativeType("uint32_t") int localDeviceIndex, @NativeType("uint32_t") int remoteDeviceIndex, @NativeType("VkPeerMemoryFeatureFlags *") IntBuffer pPeerMemoryFeatures) {
if (CHECKS) {
check(pPeerMemoryFeatures, 1);
}
nvkGetDeviceGroupPeerMemoryFeatures(device, heapIndex, localDeviceIndex, remoteDeviceIndex, memAddress(pPeerMemoryFeatures));
}
// --- [ vkCmdSetDeviceMask ] ---
/**
* Modify device mask of a command buffer.
*
* <h5>C Specification</h5>
*
* <p>To update the current device mask of a command buffer, call:</p>
*
* <pre><code>
* void vkCmdSetDeviceMask(
* VkCommandBuffer commandBuffer,
* uint32_t deviceMask);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkCmdSetDeviceMaskKHR(
* VkCommandBuffer commandBuffer,
* uint32_t deviceMask);</code></pre>
*
* <h5>Description</h5>
*
* <p>{@code deviceMask} is used to filter out subsequent commands from executing on all physical devices whose bit indices are not set in the mask, except commands beginning a render pass instance, commands transitioning to the next subpass in the render pass instance, and commands ending a render pass instance, which always execute on the set of physical devices whose bit indices are included in the {@code deviceMask} member of the {@link VkDeviceGroupRenderPassBeginInfo} structure passed to the command beginning the corresponding render pass instance.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code deviceMask} <b>must</b> be a valid device mask value</li>
* <li>{@code deviceMask} <b>must</b> not be zero</li>
* <li>{@code deviceMask} <b>must</b> not include any set bits that were not in the {@link VkDeviceGroupCommandBufferBeginInfo}{@code ::deviceMask} value when the command buffer began recording</li>
* <li>If {@code vkCmdSetDeviceMask} is called inside a render pass instance, {@code deviceMask} <b>must</b> not include any set bits that were not in the {@link VkDeviceGroupRenderPassBeginInfo}{@code ::deviceMask} value when the render pass instance began recording</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li>
* <li>{@code commandBuffer} <b>must</b> be in the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#commandbuffers-lifecycle">recording state</a></li>
* <li>The {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> support graphics, compute, or transfer operations</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code commandBuffer} <b>must</b> be externally synchronized</li>
* <li>Host access to the {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Command Properties</h5>
*
* <table class="lwjgl">
* <thead><tr><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkQueueFlagBits">Supported Queue Types</a></th></tr></thead>
* <tbody><tr><td>Primary Secondary</td><td>Both</td><td>Graphics Compute Transfer</td></tr></tbody>
* </table>
*
* @param commandBuffer command buffer whose current device mask is modified.
* @param deviceMask the new value of the current device mask.
*/
public static void vkCmdSetDeviceMask(VkCommandBuffer commandBuffer, @NativeType("uint32_t") int deviceMask) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdSetDeviceMask;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), deviceMask, __functionAddress);
}
// --- [ vkCmdDispatchBase ] ---
/**
* Dispatch compute work items with non-zero base values for the workgroup IDs.
*
* <h5>C Specification</h5>
*
* <p>To record a dispatch using non-zero base values for the components of {@code WorkgroupId}, call:</p>
*
* <pre><code>
* void vkCmdDispatchBase(
* VkCommandBuffer commandBuffer,
* uint32_t baseGroupX,
* uint32_t baseGroupY,
* uint32_t baseGroupZ,
* uint32_t groupCountX,
* uint32_t groupCountY,
* uint32_t groupCountZ);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkCmdDispatchBaseKHR(
* VkCommandBuffer commandBuffer,
* uint32_t baseGroupX,
* uint32_t baseGroupY,
* uint32_t baseGroupZ,
* uint32_t groupCountX,
* uint32_t groupCountY,
* uint32_t groupCountZ);</code></pre>
*
* <h5>Description</h5>
*
* <p>When the command is executed, a global workgroup consisting of <code>groupCountX × groupCountY × groupCountZ</code> local workgroups is assembled, with {@code WorkgroupId} values ranging from <code>[baseGroup*, baseGroup* + groupCount*)</code> in each component. {@link VK10#vkCmdDispatch CmdDispatch} is equivalent to {@code vkCmdDispatchBase(0,0,0,groupCountX,groupCountY,groupCountZ)}.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>If a {@code VkSampler} created with {@code magFilter} or {@code minFilter} equal to {@link VK10#VK_FILTER_LINEAR FILTER_LINEAR} and {@code compareEnable} equal to {@link VK10#VK_FALSE FALSE} is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features">format features</a> <b>must</b> contain {@link VK10#VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT}</li>
* <li>If a {@code VkSampler} created with {@code mipmapMode} equal to {@link VK10#VK_SAMPLER_MIPMAP_MODE_LINEAR SAMPLER_MIPMAP_MODE_LINEAR} and {@code compareEnable} equal to {@link VK10#VK_FALSE FALSE} is used to sample a {@code VkImageView} as a result of this command, then the image view’s <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features">format features</a> <b>must</b> contain {@link VK10#VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT}</li>
* <li>If a {@code VkImageView} is accessed using atomic operations as a result of this command, then the image view’s <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features">format features</a> <b>must</b> contain {@link VK10#VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT}</li>
* <li>If a {@code VkImageView} is sampled with {@link EXTFilterCubic#VK_FILTER_CUBIC_EXT FILTER_CUBIC_EXT} as a result of this command, then the image view’s <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#resources-image-view-format-features">format features</a> <b>must</b> contain {@link EXTFilterCubic#VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT}</li>
* <li>Any {@code VkImageView} being sampled with {@link EXTFilterCubic#VK_FILTER_CUBIC_EXT FILTER_CUBIC_EXT} as a result of this command <b>must</b> have a {@code VkImageViewType} and format that supports cubic filtering, as specified by {@link VkFilterCubicImageViewImageFormatPropertiesEXT}{@code ::filterCubic} returned by {@code vkGetPhysicalDeviceImageFormatProperties2}</li>
* <li>Any {@code VkImageView} being sampled with {@link EXTFilterCubic#VK_FILTER_CUBIC_EXT FILTER_CUBIC_EXT} with a reduction mode of either {@link VK12#VK_SAMPLER_REDUCTION_MODE_MIN SAMPLER_REDUCTION_MODE_MIN} or {@link VK12#VK_SAMPLER_REDUCTION_MODE_MAX SAMPLER_REDUCTION_MODE_MAX} as a result of this command <b>must</b> have a {@code VkImageViewType} and format that supports cubic filtering together with minmax filtering, as specified by {@link VkFilterCubicImageViewImageFormatPropertiesEXT}{@code ::filterCubicMinmax} returned by {@code vkGetPhysicalDeviceImageFormatProperties2}</li>
* <li>Any {@code VkImage} created with a {@link VkImageCreateInfo}{@code ::flags} containing {@link NVCornerSampledImage#VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV IMAGE_CREATE_CORNER_SAMPLED_BIT_NV} sampled as a result of this command <b>must</b> only be sampled using a {@code VkSamplerAddressMode} of {@link VK10#VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE}</li>
* <li>Any {@code VkImageView} or {@code VkBufferView} being written as a storage image or storage texel buffer where the image format field of the {@code OpTypeImage} is {@code Unknown} <b>must</b> have image format features that support {@link KHRFormatFeatureFlags2#VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT_KHR FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT_KHR}</li>
* <li>Any {@code VkImageView} or {@code VkBufferView} being read as a storage image or storage texel buffer where the image format field of the {@code OpTypeImage} is {@code Unknown} <b>must</b> have image format features that support {@link KHRFormatFeatureFlags2#VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT_KHR FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT_KHR}</li>
* <li>For each set <em>n</em> that is statically used by the {@code VkPipeline} bound to the pipeline bind point used by this command, a descriptor set <b>must</b> have been bound to <em>n</em> at the same pipeline bind point, with a {@code VkPipelineLayout} that is compatible for set <em>n</em>, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline}, as described in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#descriptorsets-compatibility">Pipeline Layout Compatibility</a></li>
* <li>If the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-maintenance4">{@code maintenance4}</a> feature is not enabled, then for each push constant that is statically used by the {@code VkPipeline} bound to the pipeline bind point used by this command, a push constant value <b>must</b> have been set for the same pipeline bind point, with a {@code VkPipelineLayout} that is compatible for push constants, with the {@code VkPipelineLayout} used to create the current {@code VkPipeline}, as described in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#descriptorsets-compatibility">Pipeline Layout Compatibility</a></li>
* <li>Descriptors in each bound descriptor set, specified via {@code vkCmdBindDescriptorSets}, <b>must</b> be valid if they are statically used by the {@code VkPipeline} bound to the pipeline bind point used by this command</li>
* <li>A valid pipeline <b>must</b> be bound to the pipeline bind point used by this command</li>
* <li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command requires any dynamic state, that state <b>must</b> have been set or inherited (if the {@link NVInheritedViewportScissor VK_NV_inherited_viewport_scissor} extension is enabled) for {@code commandBuffer}, and done so after any previously bound pipeline with the corresponding state not specified as dynamic</li>
* <li>There <b>must</b> not have been any calls to dynamic state setting commands for any state not specified as dynamic in the {@code VkPipeline} object bound to the pipeline bind point used by this command, since that pipeline was bound</li>
* <li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} object that uses unnormalized coordinates, that sampler <b>must</b> not be used to sample from any {@code VkImage} with a {@code VkImageView} of the type {@link VK10#VK_IMAGE_VIEW_TYPE_3D IMAGE_VIEW_TYPE_3D}, {@link VK10#VK_IMAGE_VIEW_TYPE_CUBE IMAGE_VIEW_TYPE_CUBE}, {@link VK10#VK_IMAGE_VIEW_TYPE_1D_ARRAY IMAGE_VIEW_TYPE_1D_ARRAY}, {@link VK10#VK_IMAGE_VIEW_TYPE_2D_ARRAY IMAGE_VIEW_TYPE_2D_ARRAY} or {@link VK10#VK_IMAGE_VIEW_TYPE_CUBE_ARRAY IMAGE_VIEW_TYPE_CUBE_ARRAY}, in any shader stage</li>
* <li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} object that uses unnormalized coordinates, that sampler <b>must</b> not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions with {@code ImplicitLod}, {@code Dref} or {@code Proj} in their name, in any shader stage</li>
* <li>If the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a {@code VkSampler} object that uses unnormalized coordinates, that sampler <b>must</b> not be used with any of the SPIR-V {@code OpImageSample*} or {@code OpImageSparseSample*} instructions that includes a LOD bias or any offset values, in any shader stage</li>
* <li>If the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-robustBufferAccess">robust buffer access</a> feature is not enabled, and if the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a uniform buffer, it <b>must</b> not access values outside of the range of the buffer as specified in the descriptor set bound to the same pipeline bind point</li>
* <li>If the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-robustBufferAccess">robust buffer access</a> feature is not enabled, and if the {@code VkPipeline} object bound to the pipeline bind point used by this command accesses a storage buffer, it <b>must</b> not access values outside of the range of the buffer as specified in the descriptor set bound to the same pipeline bind point</li>
* <li>If {@code commandBuffer} is an unprotected command buffer, any resource accessed by the {@code VkPipeline} object bound to the pipeline bind point used by this command <b>must</b> not be a protected resource</li>
* <li>If a {@code VkImageView} is accessed using {@code OpImageWrite} as a result of this command, then the {@code Type} of the {@code Texel} operand of that instruction <b>must</b> have at least as many components as the image view’s format</li>
* <li>If a {@code VkBufferView} is accessed using {@code OpImageWrite} as a result of this command, then the {@code Type} of the {@code Texel} operand of that instruction <b>must</b> have at least as many components as the buffer view’s format</li>
* <li>If a {@code VkImageView} with a {@code VkFormat} that has a 64-bit component width is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 64</li>
* <li>If a {@code VkImageView} with a {@code VkFormat} that has a component width less than 64-bit is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 32</li>
* <li>If a {@code VkBufferView} with a {@code VkFormat} that has a 64-bit component width is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 64</li>
* <li>If a {@code VkBufferView} with a {@code VkFormat} that has a component width less than 64-bit is accessed as a result of this command, the {@code SampledType} of the {@code OpTypeImage} operand of that instruction <b>must</b> have a {@code Width} of 32</li>
* <li>If the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-sparseImageInt64Atomics">{@code sparseImageInt64Atomics}</a> feature is not enabled, {@code VkImage} objects created with the {@link VK10#VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT IMAGE_CREATE_SPARSE_RESIDENCY_BIT} flag <b>must</b> not be accessed by atomic instructions through an {@code OpTypeImage} with a {@code SampledType} with a {@code Width} of 64 by this command</li>
* <li>If the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-sparseImageInt64Atomics">{@code sparseImageInt64Atomics}</a> feature is not enabled, {@code VkBuffer} objects created with the {@link VK10#VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT BUFFER_CREATE_SPARSE_RESIDENCY_BIT} flag <b>must</b> not be accessed by atomic instructions through an {@code OpTypeImage} with a {@code SampledType} with a {@code Width} of 64 by this command</li>
* </ul>
*
* <ul>
* <li>If {@code commandBuffer} is a protected command buffer, any resource written to by the {@code VkPipeline} object bound to the pipeline bind point used by this command <b>must</b> not be an unprotected resource</li>
* <li>If {@code commandBuffer} is a protected command buffer, pipeline stages other than the framebuffer-space and compute stages in the {@code VkPipeline} object bound to the pipeline bind point used by this command <b>must</b> not write to any resource</li>
* <li>If any of the shader stages of the {@code VkPipeline} bound to the pipeline bind point used by this command uses the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#spirvenv-capabilities-table-RayQueryKHR">RayQueryKHR</a> capability, then {@code commandBuffer} <b>must</b> not be a protected command buffer</li>
* <li>{@code baseGroupX} <b>must</b> be less than {@link VkPhysicalDeviceLimits}{@code ::maxComputeWorkGroupCount}[0]</li>
* <li>{@code baseGroupY} <b>must</b> be less than {@link VkPhysicalDeviceLimits}{@code ::maxComputeWorkGroupCount}[1]</li>
* <li>{@code baseGroupZ} <b>must</b> be less than {@link VkPhysicalDeviceLimits}{@code ::maxComputeWorkGroupCount}[2]</li>
* <li>{@code groupCountX} <b>must</b> be less than or equal to {@link VkPhysicalDeviceLimits}{@code ::maxComputeWorkGroupCount}[0] minus {@code baseGroupX}</li>
* <li>{@code groupCountY} <b>must</b> be less than or equal to {@link VkPhysicalDeviceLimits}{@code ::maxComputeWorkGroupCount}[1] minus {@code baseGroupY}</li>
* <li>{@code groupCountZ} <b>must</b> be less than or equal to {@link VkPhysicalDeviceLimits}{@code ::maxComputeWorkGroupCount}[2] minus {@code baseGroupZ}</li>
* <li>If any of {@code baseGroupX}, {@code baseGroupY}, or {@code baseGroupZ} are not zero, then the bound compute pipeline <b>must</b> have been created with the {@link #VK_PIPELINE_CREATE_DISPATCH_BASE PIPELINE_CREATE_DISPATCH_BASE} flag</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code commandBuffer} <b>must</b> be a valid {@code VkCommandBuffer} handle</li>
* <li>{@code commandBuffer} <b>must</b> be in the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#commandbuffers-lifecycle">recording state</a></li>
* <li>The {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> support compute operations</li>
* <li>This command <b>must</b> only be called outside of a render pass instance</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code commandBuffer} <b>must</b> be externally synchronized</li>
* <li>Host access to the {@code VkCommandPool} that {@code commandBuffer} was allocated from <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>Command Properties</h5>
*
* <table class="lwjgl">
* <thead><tr><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkCommandBufferLevel">Command Buffer Levels</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#vkCmdBeginRenderPass">Render Pass Scope</a></th><th><a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkQueueFlagBits">Supported Queue Types</a></th></tr></thead>
* <tbody><tr><td>Primary Secondary</td><td>Outside</td><td>Compute</td></tr></tbody>
* </table>
*
* @param commandBuffer the command buffer into which the command will be recorded.
* @param baseGroupX the start value for the X component of {@code WorkgroupId}.
* @param baseGroupY the start value for the Y component of {@code WorkgroupId}.
* @param baseGroupZ the start value for the Z component of {@code WorkgroupId}.
* @param groupCountX the number of local workgroups to dispatch in the X dimension.
* @param groupCountY the number of local workgroups to dispatch in the Y dimension.
* @param groupCountZ the number of local workgroups to dispatch in the Z dimension.
*/
public static void vkCmdDispatchBase(VkCommandBuffer commandBuffer, @NativeType("uint32_t") int baseGroupX, @NativeType("uint32_t") int baseGroupY, @NativeType("uint32_t") int baseGroupZ, @NativeType("uint32_t") int groupCountX, @NativeType("uint32_t") int groupCountY, @NativeType("uint32_t") int groupCountZ) {
long __functionAddress = commandBuffer.getCapabilities().vkCmdDispatchBase;
if (CHECKS) {
check(__functionAddress);
}
callPV(commandBuffer.address(), baseGroupX, baseGroupY, baseGroupZ, groupCountX, groupCountY, groupCountZ, __functionAddress);
}
// --- [ vkEnumeratePhysicalDeviceGroups ] ---
/**
* Unsafe version of: {@link #vkEnumeratePhysicalDeviceGroups EnumeratePhysicalDeviceGroups}
*
* @param pPhysicalDeviceGroupCount a pointer to an integer related to the number of device groups available or queried, as described below.
*/
public static int nvkEnumeratePhysicalDeviceGroups(VkInstance instance, long pPhysicalDeviceGroupCount, long pPhysicalDeviceGroupProperties) {
long __functionAddress = instance.getCapabilities().vkEnumeratePhysicalDeviceGroups;
if (CHECKS) {
check(__functionAddress);
}
return callPPPI(instance.address(), pPhysicalDeviceGroupCount, pPhysicalDeviceGroupProperties, __functionAddress);
}
/**
* Enumerates groups of physical devices that can be used to create a single logical device.
*
* <h5>C Specification</h5>
*
* <p>To retrieve a list of the device groups present in the system, call:</p>
*
* <pre><code>
* VkResult vkEnumeratePhysicalDeviceGroups(
* VkInstance instance,
* uint32_t* pPhysicalDeviceGroupCount,
* VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* VkResult vkEnumeratePhysicalDeviceGroupsKHR(
* VkInstance instance,
* uint32_t* pPhysicalDeviceGroupCount,
* VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties);</code></pre>
*
* <h5>Description</h5>
*
* <p>If {@code pPhysicalDeviceGroupProperties} is {@code NULL}, then the number of device groups available is returned in {@code pPhysicalDeviceGroupCount}. Otherwise, {@code pPhysicalDeviceGroupCount} <b>must</b> point to a variable set by the user to the number of elements in the {@code pPhysicalDeviceGroupProperties} array, and on return the variable is overwritten with the number of structures actually written to {@code pPhysicalDeviceGroupProperties}. If {@code pPhysicalDeviceGroupCount} is less than the number of device groups available, at most {@code pPhysicalDeviceGroupCount} structures will be written, and {@link VK10#VK_INCOMPLETE INCOMPLETE} will be returned instead of {@link VK10#VK_SUCCESS SUCCESS}, to indicate that not all the available device groups were returned.</p>
*
* <p>Every physical device <b>must</b> be in exactly one device group.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code instance} <b>must</b> be a valid {@code VkInstance} handle</li>
* <li>{@code pPhysicalDeviceGroupCount} <b>must</b> be a valid pointer to a {@code uint32_t} value</li>
* <li>If the value referenced by {@code pPhysicalDeviceGroupCount} is not 0, and {@code pPhysicalDeviceGroupProperties} is not {@code NULL}, {@code pPhysicalDeviceGroupProperties} <b>must</b> be a valid pointer to an array of {@code pPhysicalDeviceGroupCount} {@link VkPhysicalDeviceGroupProperties} structures</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* <li>{@link VK10#VK_INCOMPLETE INCOMPLETE}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_INITIALIZATION_FAILED ERROR_INITIALIZATION_FAILED}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkPhysicalDeviceGroupProperties}</p>
*
* @param instance a handle to a Vulkan instance previously created with {@link VK10#vkCreateInstance CreateInstance}.
* @param pPhysicalDeviceGroupCount a pointer to an integer related to the number of device groups available or queried, as described below.
* @param pPhysicalDeviceGroupProperties either {@code NULL} or a pointer to an array of {@link VkPhysicalDeviceGroupProperties} structures.
*/
@NativeType("VkResult")
public static int vkEnumeratePhysicalDeviceGroups(VkInstance instance, @NativeType("uint32_t *") IntBuffer pPhysicalDeviceGroupCount, @Nullable @NativeType("VkPhysicalDeviceGroupProperties *") VkPhysicalDeviceGroupProperties.Buffer pPhysicalDeviceGroupProperties) {
if (CHECKS) {
check(pPhysicalDeviceGroupCount, 1);
checkSafe(pPhysicalDeviceGroupProperties, pPhysicalDeviceGroupCount.get(pPhysicalDeviceGroupCount.position()));
}
return nvkEnumeratePhysicalDeviceGroups(instance, memAddress(pPhysicalDeviceGroupCount), memAddressSafe(pPhysicalDeviceGroupProperties));
}
// --- [ vkGetImageMemoryRequirements2 ] ---
/** Unsafe version of: {@link #vkGetImageMemoryRequirements2 GetImageMemoryRequirements2} */
public static void nvkGetImageMemoryRequirements2(VkDevice device, long pInfo, long pMemoryRequirements) {
long __functionAddress = device.getCapabilities().vkGetImageMemoryRequirements2;
if (CHECKS) {
check(__functionAddress);
}
callPPPV(device.address(), pInfo, pMemoryRequirements, __functionAddress);
}
/**
* Returns the memory requirements for specified Vulkan object.
*
* <h5>C Specification</h5>
*
* <p>To determine the memory requirements for an image resource, call:</p>
*
* <pre><code>
* void vkGetImageMemoryRequirements2(
* VkDevice device,
* const VkImageMemoryRequirementsInfo2* pInfo,
* VkMemoryRequirements2* pMemoryRequirements);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetImageMemoryRequirements2KHR(
* VkDevice device,
* const VkImageMemoryRequirementsInfo2* pInfo,
* VkMemoryRequirements2* pMemoryRequirements);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pInfo} <b>must</b> be a valid pointer to a valid {@link VkImageMemoryRequirementsInfo2} structure</li>
* <li>{@code pMemoryRequirements} <b>must</b> be a valid pointer to a {@link VkMemoryRequirements2} structure</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkImageMemoryRequirementsInfo2}, {@link VkMemoryRequirements2}</p>
*
* @param device the logical device that owns the image.
* @param pInfo a pointer to a {@link VkImageMemoryRequirementsInfo2} structure containing parameters required for the memory requirements query.
* @param pMemoryRequirements a pointer to a {@link VkMemoryRequirements2} structure in which the memory requirements of the image object are returned.
*/
public static void vkGetImageMemoryRequirements2(VkDevice device, @NativeType("VkImageMemoryRequirementsInfo2 const *") VkImageMemoryRequirementsInfo2 pInfo, @NativeType("VkMemoryRequirements2 *") VkMemoryRequirements2 pMemoryRequirements) {
nvkGetImageMemoryRequirements2(device, pInfo.address(), pMemoryRequirements.address());
}
// --- [ vkGetBufferMemoryRequirements2 ] ---
/** Unsafe version of: {@link #vkGetBufferMemoryRequirements2 GetBufferMemoryRequirements2} */
public static void nvkGetBufferMemoryRequirements2(VkDevice device, long pInfo, long pMemoryRequirements) {
long __functionAddress = device.getCapabilities().vkGetBufferMemoryRequirements2;
if (CHECKS) {
check(__functionAddress);
}
callPPPV(device.address(), pInfo, pMemoryRequirements, __functionAddress);
}
/**
* Returns the memory requirements for specified Vulkan object.
*
* <h5>C Specification</h5>
*
* <p>To determine the memory requirements for a buffer resource, call:</p>
*
* <pre><code>
* void vkGetBufferMemoryRequirements2(
* VkDevice device,
* const VkBufferMemoryRequirementsInfo2* pInfo,
* VkMemoryRequirements2* pMemoryRequirements);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetBufferMemoryRequirements2KHR(
* VkDevice device,
* const VkBufferMemoryRequirementsInfo2* pInfo,
* VkMemoryRequirements2* pMemoryRequirements);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pInfo} <b>must</b> be a valid pointer to a valid {@link VkBufferMemoryRequirementsInfo2} structure</li>
* <li>{@code pMemoryRequirements} <b>must</b> be a valid pointer to a {@link VkMemoryRequirements2} structure</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkBufferMemoryRequirementsInfo2}, {@link VkMemoryRequirements2}</p>
*
* @param device the logical device that owns the buffer.
* @param pInfo a pointer to a {@link VkBufferMemoryRequirementsInfo2} structure containing parameters required for the memory requirements query.
* @param pMemoryRequirements a pointer to a {@link VkMemoryRequirements2} structure in which the memory requirements of the buffer object are returned.
*/
public static void vkGetBufferMemoryRequirements2(VkDevice device, @NativeType("VkBufferMemoryRequirementsInfo2 const *") VkBufferMemoryRequirementsInfo2 pInfo, @NativeType("VkMemoryRequirements2 *") VkMemoryRequirements2 pMemoryRequirements) {
nvkGetBufferMemoryRequirements2(device, pInfo.address(), pMemoryRequirements.address());
}
// --- [ vkGetImageSparseMemoryRequirements2 ] ---
/**
* Unsafe version of: {@link #vkGetImageSparseMemoryRequirements2 GetImageSparseMemoryRequirements2}
*
* @param pSparseMemoryRequirementCount a pointer to an integer related to the number of sparse memory requirements available or queried, as described below.
*/
public static void nvkGetImageSparseMemoryRequirements2(VkDevice device, long pInfo, long pSparseMemoryRequirementCount, long pSparseMemoryRequirements) {
long __functionAddress = device.getCapabilities().vkGetImageSparseMemoryRequirements2;
if (CHECKS) {
check(__functionAddress);
}
callPPPPV(device.address(), pInfo, pSparseMemoryRequirementCount, pSparseMemoryRequirements, __functionAddress);
}
/**
* Query the memory requirements for a sparse image.
*
* <h5>C Specification</h5>
*
* <p>To query sparse memory requirements for an image, call:</p>
*
* <pre><code>
* void vkGetImageSparseMemoryRequirements2(
* VkDevice device,
* const VkImageSparseMemoryRequirementsInfo2* pInfo,
* uint32_t* pSparseMemoryRequirementCount,
* VkSparseImageMemoryRequirements2* pSparseMemoryRequirements);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetImageSparseMemoryRequirements2KHR(
* VkDevice device,
* const VkImageSparseMemoryRequirementsInfo2* pInfo,
* uint32_t* pSparseMemoryRequirementCount,
* VkSparseImageMemoryRequirements2* pSparseMemoryRequirements);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pInfo} <b>must</b> be a valid pointer to a valid {@link VkImageSparseMemoryRequirementsInfo2} structure</li>
* <li>{@code pSparseMemoryRequirementCount} <b>must</b> be a valid pointer to a {@code uint32_t} value</li>
* <li>If the value referenced by {@code pSparseMemoryRequirementCount} is not 0, and {@code pSparseMemoryRequirements} is not {@code NULL}, {@code pSparseMemoryRequirements} <b>must</b> be a valid pointer to an array of {@code pSparseMemoryRequirementCount} {@link VkSparseImageMemoryRequirements2} structures</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkImageSparseMemoryRequirementsInfo2}, {@link VkSparseImageMemoryRequirements2}</p>
*
* @param device the logical device that owns the image.
* @param pInfo a pointer to a {@link VkImageSparseMemoryRequirementsInfo2} structure containing parameters required for the memory requirements query.
* @param pSparseMemoryRequirementCount a pointer to an integer related to the number of sparse memory requirements available or queried, as described below.
* @param pSparseMemoryRequirements either {@code NULL} or a pointer to an array of {@link VkSparseImageMemoryRequirements2} structures.
*/
public static void vkGetImageSparseMemoryRequirements2(VkDevice device, @NativeType("VkImageSparseMemoryRequirementsInfo2 const *") VkImageSparseMemoryRequirementsInfo2 pInfo, @NativeType("uint32_t *") IntBuffer pSparseMemoryRequirementCount, @Nullable @NativeType("VkSparseImageMemoryRequirements2 *") VkSparseImageMemoryRequirements2.Buffer pSparseMemoryRequirements) {
if (CHECKS) {
check(pSparseMemoryRequirementCount, 1);
checkSafe(pSparseMemoryRequirements, pSparseMemoryRequirementCount.get(pSparseMemoryRequirementCount.position()));
}
nvkGetImageSparseMemoryRequirements2(device, pInfo.address(), memAddress(pSparseMemoryRequirementCount), memAddressSafe(pSparseMemoryRequirements));
}
// --- [ vkGetPhysicalDeviceFeatures2 ] ---
/** Unsafe version of: {@link #vkGetPhysicalDeviceFeatures2 GetPhysicalDeviceFeatures2} */
public static void nvkGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice, long pFeatures) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceFeatures2;
if (CHECKS) {
check(__functionAddress);
}
callPPV(physicalDevice.address(), pFeatures, __functionAddress);
}
/**
* Reports capabilities of a physical device.
*
* <h5>C Specification</h5>
*
* <p>To query supported features defined by the core or extensions, call:</p>
*
* <pre><code>
* void vkGetPhysicalDeviceFeatures2(
* VkPhysicalDevice physicalDevice,
* VkPhysicalDeviceFeatures2* pFeatures);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetPhysicalDeviceFeatures2KHR(
* VkPhysicalDevice physicalDevice,
* VkPhysicalDeviceFeatures2* pFeatures);</code></pre>
*
* <h5>Description</h5>
*
* <p>Each structure in {@code pFeatures} and its {@code pNext} chain contains members corresponding to fine-grained features. {@code vkGetPhysicalDeviceFeatures2} writes each member to a boolean value indicating whether that feature is supported.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code pFeatures} <b>must</b> be a valid pointer to a {@link VkPhysicalDeviceFeatures2} structure</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkPhysicalDeviceFeatures2}</p>
*
* @param physicalDevice the physical device from which to query the supported features.
* @param pFeatures a pointer to a {@link VkPhysicalDeviceFeatures2} structure in which the physical device features are returned.
*/
public static void vkGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice, @NativeType("VkPhysicalDeviceFeatures2 *") VkPhysicalDeviceFeatures2 pFeatures) {
nvkGetPhysicalDeviceFeatures2(physicalDevice, pFeatures.address());
}
// --- [ vkGetPhysicalDeviceProperties2 ] ---
/** Unsafe version of: {@link #vkGetPhysicalDeviceProperties2 GetPhysicalDeviceProperties2} */
public static void nvkGetPhysicalDeviceProperties2(VkPhysicalDevice physicalDevice, long pProperties) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceProperties2;
if (CHECKS) {
check(__functionAddress);
}
callPPV(physicalDevice.address(), pProperties, __functionAddress);
}
/**
* Returns properties of a physical device.
*
* <h5>C Specification</h5>
*
* <p>To query general properties of physical devices once enumerated, call:</p>
*
* <pre><code>
* void vkGetPhysicalDeviceProperties2(
* VkPhysicalDevice physicalDevice,
* VkPhysicalDeviceProperties2* pProperties);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetPhysicalDeviceProperties2KHR(
* VkPhysicalDevice physicalDevice,
* VkPhysicalDeviceProperties2* pProperties);</code></pre>
*
* <h5>Description</h5>
*
* <p>Each structure in {@code pProperties} and its {@code pNext} chain contains members corresponding to implementation-dependent properties, behaviors, or limits. {@code vkGetPhysicalDeviceProperties2} fills in each member to specify the corresponding value for the implementation.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code pProperties} <b>must</b> be a valid pointer to a {@link VkPhysicalDeviceProperties2} structure</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkPhysicalDeviceProperties2}</p>
*
* @param physicalDevice the handle to the physical device whose properties will be queried.
* @param pProperties a pointer to a {@link VkPhysicalDeviceProperties2} structure in which properties are returned.
*/
public static void vkGetPhysicalDeviceProperties2(VkPhysicalDevice physicalDevice, @NativeType("VkPhysicalDeviceProperties2 *") VkPhysicalDeviceProperties2 pProperties) {
nvkGetPhysicalDeviceProperties2(physicalDevice, pProperties.address());
}
// --- [ vkGetPhysicalDeviceFormatProperties2 ] ---
/** Unsafe version of: {@link #vkGetPhysicalDeviceFormatProperties2 GetPhysicalDeviceFormatProperties2} */
public static void nvkGetPhysicalDeviceFormatProperties2(VkPhysicalDevice physicalDevice, int format, long pFormatProperties) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceFormatProperties2;
if (CHECKS) {
check(__functionAddress);
}
callPPV(physicalDevice.address(), format, pFormatProperties, __functionAddress);
}
/**
* Lists physical device’s format capabilities.
*
* <h5>C Specification</h5>
*
* <p>To query supported format features which are properties of the physical device, call:</p>
*
* <pre><code>
* void vkGetPhysicalDeviceFormatProperties2(
* VkPhysicalDevice physicalDevice,
* VkFormat format,
* VkFormatProperties2* pFormatProperties);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetPhysicalDeviceFormatProperties2KHR(
* VkPhysicalDevice physicalDevice,
* VkFormat format,
* VkFormatProperties2* pFormatProperties);</code></pre>
*
* <h5>Description</h5>
*
* <p>{@code vkGetPhysicalDeviceFormatProperties2} behaves similarly to {@link VK10#vkGetPhysicalDeviceFormatProperties GetPhysicalDeviceFormatProperties}, with the ability to return extended information in a {@code pNext} chain of output structures.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code format} <b>must</b> be a valid {@code VkFormat} value</li>
* <li>{@code pFormatProperties} <b>must</b> be a valid pointer to a {@link VkFormatProperties2} structure</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkFormatProperties2}</p>
*
* @param physicalDevice the physical device from which to query the format properties.
* @param format the format whose properties are queried.
* @param pFormatProperties a pointer to a {@link VkFormatProperties2} structure in which physical device properties for {@code format} are returned.
*/
public static void vkGetPhysicalDeviceFormatProperties2(VkPhysicalDevice physicalDevice, @NativeType("VkFormat") int format, @NativeType("VkFormatProperties2 *") VkFormatProperties2 pFormatProperties) {
nvkGetPhysicalDeviceFormatProperties2(physicalDevice, format, pFormatProperties.address());
}
// --- [ vkGetPhysicalDeviceImageFormatProperties2 ] ---
/** Unsafe version of: {@link #vkGetPhysicalDeviceImageFormatProperties2 GetPhysicalDeviceImageFormatProperties2} */
public static int nvkGetPhysicalDeviceImageFormatProperties2(VkPhysicalDevice physicalDevice, long pImageFormatInfo, long pImageFormatProperties) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceImageFormatProperties2;
if (CHECKS) {
check(__functionAddress);
}
return callPPPI(physicalDevice.address(), pImageFormatInfo, pImageFormatProperties, __functionAddress);
}
/**
* Lists physical device’s image format capabilities.
*
* <h5>C Specification</h5>
*
* <p>To query additional capabilities specific to image types, call:</p>
*
* <pre><code>
* VkResult vkGetPhysicalDeviceImageFormatProperties2(
* VkPhysicalDevice physicalDevice,
* const VkPhysicalDeviceImageFormatInfo2* pImageFormatInfo,
* VkImageFormatProperties2* pImageFormatProperties);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* VkResult vkGetPhysicalDeviceImageFormatProperties2KHR(
* VkPhysicalDevice physicalDevice,
* const VkPhysicalDeviceImageFormatInfo2* pImageFormatInfo,
* VkImageFormatProperties2* pImageFormatProperties);</code></pre>
*
* <h5>Description</h5>
*
* <p>{@code vkGetPhysicalDeviceImageFormatProperties2} behaves similarly to {@link VK10#vkGetPhysicalDeviceImageFormatProperties GetPhysicalDeviceImageFormatProperties}, with the ability to return extended information in a {@code pNext} chain of output structures.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code pImageFormatInfo} <b>must</b> be a valid pointer to a valid {@link VkPhysicalDeviceImageFormatInfo2} structure</li>
* <li>{@code pImageFormatProperties} <b>must</b> be a valid pointer to a {@link VkImageFormatProperties2} structure</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_FORMAT_NOT_SUPPORTED ERROR_FORMAT_NOT_SUPPORTED}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkImageFormatProperties2}, {@link VkPhysicalDeviceImageFormatInfo2}</p>
*
* @param physicalDevice the physical device from which to query the image capabilities.
* @param pImageFormatInfo a pointer to a {@link VkPhysicalDeviceImageFormatInfo2} structure describing the parameters that would be consumed by {@link VK10#vkCreateImage CreateImage}.
* @param pImageFormatProperties a pointer to a {@link VkImageFormatProperties2} structure in which capabilities are returned.
*/
@NativeType("VkResult")
public static int vkGetPhysicalDeviceImageFormatProperties2(VkPhysicalDevice physicalDevice, @NativeType("VkPhysicalDeviceImageFormatInfo2 const *") VkPhysicalDeviceImageFormatInfo2 pImageFormatInfo, @NativeType("VkImageFormatProperties2 *") VkImageFormatProperties2 pImageFormatProperties) {
return nvkGetPhysicalDeviceImageFormatProperties2(physicalDevice, pImageFormatInfo.address(), pImageFormatProperties.address());
}
// --- [ vkGetPhysicalDeviceQueueFamilyProperties2 ] ---
/**
* Unsafe version of: {@link #vkGetPhysicalDeviceQueueFamilyProperties2 GetPhysicalDeviceQueueFamilyProperties2}
*
* @param pQueueFamilyPropertyCount a pointer to an integer related to the number of queue families available or queried, as described in {@link VK10#vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties}.
*/
public static void nvkGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice, long pQueueFamilyPropertyCount, long pQueueFamilyProperties) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceQueueFamilyProperties2;
if (CHECKS) {
check(__functionAddress);
}
callPPPV(physicalDevice.address(), pQueueFamilyPropertyCount, pQueueFamilyProperties, __functionAddress);
}
/**
* Reports properties of the queues of the specified physical device.
*
* <h5>C Specification</h5>
*
* <p>To query properties of queues available on a physical device, call:</p>
*
* <pre><code>
* void vkGetPhysicalDeviceQueueFamilyProperties2(
* VkPhysicalDevice physicalDevice,
* uint32_t* pQueueFamilyPropertyCount,
* VkQueueFamilyProperties2* pQueueFamilyProperties);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetPhysicalDeviceQueueFamilyProperties2KHR(
* VkPhysicalDevice physicalDevice,
* uint32_t* pQueueFamilyPropertyCount,
* VkQueueFamilyProperties2* pQueueFamilyProperties);</code></pre>
*
* <h5>Description</h5>
*
* <p>{@code vkGetPhysicalDeviceQueueFamilyProperties2} behaves similarly to {@link VK10#vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties}, with the ability to return extended information in a {@code pNext} chain of output structures.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code pQueueFamilyPropertyCount} <b>must</b> be a valid pointer to a {@code uint32_t} value</li>
* <li>If the value referenced by {@code pQueueFamilyPropertyCount} is not 0, and {@code pQueueFamilyProperties} is not {@code NULL}, {@code pQueueFamilyProperties} <b>must</b> be a valid pointer to an array of {@code pQueueFamilyPropertyCount} {@link VkQueueFamilyProperties2} structures</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkQueueFamilyProperties2}</p>
*
* @param physicalDevice the handle to the physical device whose properties will be queried.
* @param pQueueFamilyPropertyCount a pointer to an integer related to the number of queue families available or queried, as described in {@link VK10#vkGetPhysicalDeviceQueueFamilyProperties GetPhysicalDeviceQueueFamilyProperties}.
* @param pQueueFamilyProperties either {@code NULL} or a pointer to an array of {@link VkQueueFamilyProperties2} structures.
*/
public static void vkGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice, @NativeType("uint32_t *") IntBuffer pQueueFamilyPropertyCount, @Nullable @NativeType("VkQueueFamilyProperties2 *") VkQueueFamilyProperties2.Buffer pQueueFamilyProperties) {
if (CHECKS) {
check(pQueueFamilyPropertyCount, 1);
checkSafe(pQueueFamilyProperties, pQueueFamilyPropertyCount.get(pQueueFamilyPropertyCount.position()));
}
nvkGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, memAddress(pQueueFamilyPropertyCount), memAddressSafe(pQueueFamilyProperties));
}
// --- [ vkGetPhysicalDeviceMemoryProperties2 ] ---
/** Unsafe version of: {@link #vkGetPhysicalDeviceMemoryProperties2 GetPhysicalDeviceMemoryProperties2} */
public static void nvkGetPhysicalDeviceMemoryProperties2(VkPhysicalDevice physicalDevice, long pMemoryProperties) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceMemoryProperties2;
if (CHECKS) {
check(__functionAddress);
}
callPPV(physicalDevice.address(), pMemoryProperties, __functionAddress);
}
/**
* Reports memory information for the specified physical device.
*
* <h5>C Specification</h5>
*
* <p>To query memory properties, call:</p>
*
* <pre><code>
* void vkGetPhysicalDeviceMemoryProperties2(
* VkPhysicalDevice physicalDevice,
* VkPhysicalDeviceMemoryProperties2* pMemoryProperties);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetPhysicalDeviceMemoryProperties2KHR(
* VkPhysicalDevice physicalDevice,
* VkPhysicalDeviceMemoryProperties2* pMemoryProperties);</code></pre>
*
* <h5>Description</h5>
*
* <p>{@code vkGetPhysicalDeviceMemoryProperties2} behaves similarly to {@link VK10#vkGetPhysicalDeviceMemoryProperties GetPhysicalDeviceMemoryProperties}, with the ability to return extended information in a {@code pNext} chain of output structures.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code pMemoryProperties} <b>must</b> be a valid pointer to a {@link VkPhysicalDeviceMemoryProperties2} structure</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkPhysicalDeviceMemoryProperties2}</p>
*
* @param physicalDevice the handle to the device to query.
* @param pMemoryProperties a pointer to a {@link VkPhysicalDeviceMemoryProperties2} structure in which the properties are returned.
*/
public static void vkGetPhysicalDeviceMemoryProperties2(VkPhysicalDevice physicalDevice, @NativeType("VkPhysicalDeviceMemoryProperties2 *") VkPhysicalDeviceMemoryProperties2 pMemoryProperties) {
nvkGetPhysicalDeviceMemoryProperties2(physicalDevice, pMemoryProperties.address());
}
// --- [ vkGetPhysicalDeviceSparseImageFormatProperties2 ] ---
/**
* Unsafe version of: {@link #vkGetPhysicalDeviceSparseImageFormatProperties2 GetPhysicalDeviceSparseImageFormatProperties2}
*
* @param pPropertyCount a pointer to an integer related to the number of sparse format properties available or queried, as described below.
*/
public static void nvkGetPhysicalDeviceSparseImageFormatProperties2(VkPhysicalDevice physicalDevice, long pFormatInfo, long pPropertyCount, long pProperties) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceSparseImageFormatProperties2;
if (CHECKS) {
check(__functionAddress);
}
callPPPPV(physicalDevice.address(), pFormatInfo, pPropertyCount, pProperties, __functionAddress);
}
/**
* Retrieve properties of an image format applied to sparse images.
*
* <h5>C Specification</h5>
*
* <p>{@code vkGetPhysicalDeviceSparseImageFormatProperties2} returns an array of {@link VkSparseImageFormatProperties2}. Each element will describe properties for one set of image aspects that are bound simultaneously in the image. This is usually one element for each aspect in the image, but for interleaved depth/stencil images there is only one element describing the combined aspects.</p>
*
* <pre><code>
* void vkGetPhysicalDeviceSparseImageFormatProperties2(
* VkPhysicalDevice physicalDevice,
* const VkPhysicalDeviceSparseImageFormatInfo2* pFormatInfo,
* uint32_t* pPropertyCount,
* VkSparseImageFormatProperties2* pProperties);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetPhysicalDeviceSparseImageFormatProperties2KHR(
* VkPhysicalDevice physicalDevice,
* const VkPhysicalDeviceSparseImageFormatInfo2* pFormatInfo,
* uint32_t* pPropertyCount,
* VkSparseImageFormatProperties2* pProperties);</code></pre>
*
* <h5>Description</h5>
*
* <p>{@code vkGetPhysicalDeviceSparseImageFormatProperties2} behaves identically to {@link VK10#vkGetPhysicalDeviceSparseImageFormatProperties GetPhysicalDeviceSparseImageFormatProperties}, with the ability to return extended information by adding extending structures to the {@code pNext} chain of its {@code pProperties} parameter.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code pFormatInfo} <b>must</b> be a valid pointer to a valid {@link VkPhysicalDeviceSparseImageFormatInfo2} structure</li>
* <li>{@code pPropertyCount} <b>must</b> be a valid pointer to a {@code uint32_t} value</li>
* <li>If the value referenced by {@code pPropertyCount} is not 0, and {@code pProperties} is not {@code NULL}, {@code pProperties} <b>must</b> be a valid pointer to an array of {@code pPropertyCount} {@link VkSparseImageFormatProperties2} structures</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkPhysicalDeviceSparseImageFormatInfo2}, {@link VkSparseImageFormatProperties2}</p>
*
* @param physicalDevice the physical device from which to query the sparse image format properties.
* @param pFormatInfo a pointer to a {@link VkPhysicalDeviceSparseImageFormatInfo2} structure containing input parameters to the command.
* @param pPropertyCount a pointer to an integer related to the number of sparse format properties available or queried, as described below.
* @param pProperties either {@code NULL} or a pointer to an array of {@link VkSparseImageFormatProperties2} structures.
*/
public static void vkGetPhysicalDeviceSparseImageFormatProperties2(VkPhysicalDevice physicalDevice, @NativeType("VkPhysicalDeviceSparseImageFormatInfo2 const *") VkPhysicalDeviceSparseImageFormatInfo2 pFormatInfo, @NativeType("uint32_t *") IntBuffer pPropertyCount, @Nullable @NativeType("VkSparseImageFormatProperties2 *") VkSparseImageFormatProperties2.Buffer pProperties) {
if (CHECKS) {
check(pPropertyCount, 1);
checkSafe(pProperties, pPropertyCount.get(pPropertyCount.position()));
}
nvkGetPhysicalDeviceSparseImageFormatProperties2(physicalDevice, pFormatInfo.address(), memAddress(pPropertyCount), memAddressSafe(pProperties));
}
// --- [ vkTrimCommandPool ] ---
/**
* Trim a command pool.
*
* <h5>C Specification</h5>
*
* <p>To trim a command pool, call:</p>
*
* <pre><code>
* void vkTrimCommandPool(
* VkDevice device,
* VkCommandPool commandPool,
* VkCommandPoolTrimFlags flags);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkTrimCommandPoolKHR(
* VkDevice device,
* VkCommandPool commandPool,
* VkCommandPoolTrimFlags flags);</code></pre>
*
* <h5>Description</h5>
*
* <p>Trimming a command pool recycles unused memory from the command pool back to the system. Command buffers allocated from the pool are not affected by the command.</p>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>This command provides applications with some control over the internal memory allocations used by command pools.</p>
*
* <p>Unused memory normally arises from command buffers that have been recorded and later reset, such that they are no longer using the memory. On reset, a command buffer can return memory to its command pool, but the only way to release memory from a command pool to the system requires calling {@link VK10#vkResetCommandPool ResetCommandPool}, which cannot be executed while any command buffers from that pool are still in use. Subsequent recording operations into command buffers will re-use this memory but since total memory requirements fluctuate over time, unused memory can accumulate.</p>
*
* <p>In this situation, trimming a command pool <b>may</b> be useful to return unused memory back to the system, returning the total outstanding memory allocated by the pool back to a more “{@code average}” value.</p>
*
* <p>Implementations utilize many internal allocation strategies that make it impossible to guarantee that all unused memory is released back to the system. For instance, an implementation of a command pool <b>may</b> involve allocating memory in bulk from the system and sub-allocating from that memory. In such an implementation any live command buffer that holds a reference to a bulk allocation would prevent that allocation from being freed, even if only a small proportion of the bulk allocation is in use.</p>
*
* <p>In most cases trimming will result in a reduction in allocated but unused memory, but it does not guarantee the “{@code ideal}” behavior.</p>
*
* <p>Trimming <b>may</b> be an expensive operation, and <b>should</b> not be called frequently. Trimming <b>should</b> be treated as a way to relieve memory pressure after application-known points when there exists enough unused memory that the cost of trimming is “{@code worth}” it.</p>
* </div>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code commandPool} <b>must</b> be a valid {@code VkCommandPool} handle</li>
* <li>{@code flags} <b>must</b> be 0</li>
* <li>{@code commandPool} <b>must</b> have been created, allocated, or retrieved from {@code device}</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code commandPool} <b>must</b> be externally synchronized</li>
* </ul>
*
* @param device the logical device that owns the command pool.
* @param commandPool the command pool to trim.
* @param flags reserved for future use.
*/
public static void vkTrimCommandPool(VkDevice device, @NativeType("VkCommandPool") long commandPool, @NativeType("VkCommandPoolTrimFlags") int flags) {
long __functionAddress = device.getCapabilities().vkTrimCommandPool;
if (CHECKS) {
check(__functionAddress);
}
callPJV(device.address(), commandPool, flags, __functionAddress);
}
// --- [ vkGetDeviceQueue2 ] ---
/** Unsafe version of: {@link #vkGetDeviceQueue2 GetDeviceQueue2} */
public static void nvkGetDeviceQueue2(VkDevice device, long pQueueInfo, long pQueue) {
long __functionAddress = device.getCapabilities().vkGetDeviceQueue2;
if (CHECKS) {
check(__functionAddress);
}
callPPPV(device.address(), pQueueInfo, pQueue, __functionAddress);
}
/**
* Get a queue handle from a device.
*
* <h5>C Specification</h5>
*
* <p>To retrieve a handle to a {@code VkQueue} object with specific {@code VkDeviceQueueCreateFlags} creation flags, call:</p>
*
* <pre><code>
* void vkGetDeviceQueue2(
* VkDevice device,
* const VkDeviceQueueInfo2* pQueueInfo,
* VkQueue* pQueue);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pQueueInfo} <b>must</b> be a valid pointer to a valid {@link VkDeviceQueueInfo2} structure</li>
* <li>{@code pQueue} <b>must</b> be a valid pointer to a {@code VkQueue} handle</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkDeviceQueueInfo2}</p>
*
* @param device the logical device that owns the queue.
* @param pQueueInfo a pointer to a {@link VkDeviceQueueInfo2} structure, describing parameters of the device queue to be retrieved.
* @param pQueue a pointer to a {@code VkQueue} object that will be filled with the handle for the requested queue.
*/
public static void vkGetDeviceQueue2(VkDevice device, @NativeType("VkDeviceQueueInfo2 const *") VkDeviceQueueInfo2 pQueueInfo, @NativeType("VkQueue *") PointerBuffer pQueue) {
if (CHECKS) {
check(pQueue, 1);
}
nvkGetDeviceQueue2(device, pQueueInfo.address(), memAddress(pQueue));
}
// --- [ vkCreateSamplerYcbcrConversion ] ---
/** Unsafe version of: {@link #vkCreateSamplerYcbcrConversion CreateSamplerYcbcrConversion} */
public static int nvkCreateSamplerYcbcrConversion(VkDevice device, long pCreateInfo, long pAllocator, long pYcbcrConversion) {
long __functionAddress = device.getCapabilities().vkCreateSamplerYcbcrConversion;
if (CHECKS) {
check(__functionAddress);
if (pAllocator != NULL) { VkAllocationCallbacks.validate(pAllocator); }
}
return callPPPPI(device.address(), pCreateInfo, pAllocator, pYcbcrConversion, __functionAddress);
}
/**
* Create a new Y′C<sub>B</sub>C<sub>R</sub> conversion.
*
* <h5>C Specification</h5>
*
* <p>To create a {@code VkSamplerYcbcrConversion}, call:</p>
*
* <pre><code>
* VkResult vkCreateSamplerYcbcrConversion(
* VkDevice device,
* const VkSamplerYcbcrConversionCreateInfo* pCreateInfo,
* const VkAllocationCallbacks* pAllocator,
* VkSamplerYcbcrConversion* pYcbcrConversion);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* VkResult vkCreateSamplerYcbcrConversionKHR(
* VkDevice device,
* const VkSamplerYcbcrConversionCreateInfo* pCreateInfo,
* const VkAllocationCallbacks* pAllocator,
* VkSamplerYcbcrConversion* pYcbcrConversion);</code></pre>
*
* <h5>Description</h5>
*
* <p>The interpretation of the configured sampler Y′C<sub>B</sub>C<sub>R</sub> conversion is described in more detail in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#textures-sampler-YCbCr-conversion">the description of sampler Y′C<sub>B</sub>C<sub>R</sub> conversion</a> in the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#textures">Image Operations</a> chapter.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>The <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-samplerYcbcrConversion">sampler Y′C<sub>B</sub>C<sub>R</sub> conversion feature</a> <b>must</b> be enabled</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pCreateInfo} <b>must</b> be a valid pointer to a valid {@link VkSamplerYcbcrConversionCreateInfo} structure</li>
* <li>If {@code pAllocator} is not {@code NULL}, {@code pAllocator} <b>must</b> be a valid pointer to a valid {@link VkAllocationCallbacks} structure</li>
* <li>{@code pYcbcrConversion} <b>must</b> be a valid pointer to a {@code VkSamplerYcbcrConversion} handle</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkAllocationCallbacks}, {@link VkSamplerYcbcrConversionCreateInfo}</p>
*
* @param device the logical device that creates the sampler Y′C<sub>B</sub>C<sub>R</sub> conversion.
* @param pCreateInfo a pointer to a {@link VkSamplerYcbcrConversionCreateInfo} structure specifying the requested sampler Y′C<sub>B</sub>C<sub>R</sub> conversion.
* @param pAllocator controls host memory allocation as described in the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#memory-allocation">Memory Allocation</a> chapter.
* @param pYcbcrConversion a pointer to a {@code VkSamplerYcbcrConversion} handle in which the resulting sampler Y′C<sub>B</sub>C<sub>R</sub> conversion is returned.
*/
@NativeType("VkResult")
public static int vkCreateSamplerYcbcrConversion(VkDevice device, @NativeType("VkSamplerYcbcrConversionCreateInfo const *") VkSamplerYcbcrConversionCreateInfo pCreateInfo, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator, @NativeType("VkSamplerYcbcrConversion *") LongBuffer pYcbcrConversion) {
if (CHECKS) {
check(pYcbcrConversion, 1);
}
return nvkCreateSamplerYcbcrConversion(device, pCreateInfo.address(), memAddressSafe(pAllocator), memAddress(pYcbcrConversion));
}
// --- [ vkDestroySamplerYcbcrConversion ] ---
/** Unsafe version of: {@link #vkDestroySamplerYcbcrConversion DestroySamplerYcbcrConversion} */
public static void nvkDestroySamplerYcbcrConversion(VkDevice device, long ycbcrConversion, long pAllocator) {
long __functionAddress = device.getCapabilities().vkDestroySamplerYcbcrConversion;
if (CHECKS) {
check(__functionAddress);
if (pAllocator != NULL) { VkAllocationCallbacks.validate(pAllocator); }
}
callPJPV(device.address(), ycbcrConversion, pAllocator, __functionAddress);
}
/**
* Destroy a created Y′C<sub>B</sub>C<sub>R</sub> conversion.
*
* <h5>C Specification</h5>
*
* <p>To destroy a sampler Y′C<sub>B</sub>C<sub>R</sub> conversion, call:</p>
*
* <pre><code>
* void vkDestroySamplerYcbcrConversion(
* VkDevice device,
* VkSamplerYcbcrConversion ycbcrConversion,
* const VkAllocationCallbacks* pAllocator);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkDestroySamplerYcbcrConversionKHR(
* VkDevice device,
* VkSamplerYcbcrConversion ycbcrConversion,
* const VkAllocationCallbacks* pAllocator);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>If {@code ycbcrConversion} is not {@link VK10#VK_NULL_HANDLE NULL_HANDLE}, {@code ycbcrConversion} <b>must</b> be a valid {@code VkSamplerYcbcrConversion} handle</li>
* <li>If {@code pAllocator} is not {@code NULL}, {@code pAllocator} <b>must</b> be a valid pointer to a valid {@link VkAllocationCallbacks} structure</li>
* <li>If {@code ycbcrConversion} is a valid handle, it <b>must</b> have been created, allocated, or retrieved from {@code device}</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code ycbcrConversion} <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkAllocationCallbacks}</p>
*
* @param device the logical device that destroys the Y′C<sub>B</sub>C<sub>R</sub> conversion.
* @param ycbcrConversion the conversion to destroy.
* @param pAllocator controls host memory allocation as described in the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#memory-allocation">Memory Allocation</a> chapter.
*/
public static void vkDestroySamplerYcbcrConversion(VkDevice device, @NativeType("VkSamplerYcbcrConversion") long ycbcrConversion, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator) {
nvkDestroySamplerYcbcrConversion(device, ycbcrConversion, memAddressSafe(pAllocator));
}
// --- [ vkCreateDescriptorUpdateTemplate ] ---
/** Unsafe version of: {@link #vkCreateDescriptorUpdateTemplate CreateDescriptorUpdateTemplate} */
public static int nvkCreateDescriptorUpdateTemplate(VkDevice device, long pCreateInfo, long pAllocator, long pDescriptorUpdateTemplate) {
long __functionAddress = device.getCapabilities().vkCreateDescriptorUpdateTemplate;
if (CHECKS) {
check(__functionAddress);
VkDescriptorUpdateTemplateCreateInfo.validate(pCreateInfo);
if (pAllocator != NULL) { VkAllocationCallbacks.validate(pAllocator); }
}
return callPPPPI(device.address(), pCreateInfo, pAllocator, pDescriptorUpdateTemplate, __functionAddress);
}
/**
* Create a new descriptor update template.
*
* <h5>C Specification</h5>
*
* <p>Updating a large {@code VkDescriptorSet} array <b>can</b> be an expensive operation since an application <b>must</b> specify one {@link VkWriteDescriptorSet} structure for each descriptor or descriptor array to update, each of which re-specifies the same state when updating the same descriptor in multiple descriptor sets. For cases when an application wishes to update the same set of descriptors in multiple descriptor sets allocated using the same {@code VkDescriptorSetLayout}, {@link #vkUpdateDescriptorSetWithTemplate UpdateDescriptorSetWithTemplate} <b>can</b> be used as a replacement for {@link VK10#vkUpdateDescriptorSets UpdateDescriptorSets}.</p>
*
* <p>{@code VkDescriptorUpdateTemplate} allows implementations to convert a set of descriptor update operations on a single descriptor set to an internal format that, in conjunction with {@link #vkUpdateDescriptorSetWithTemplate UpdateDescriptorSetWithTemplate} or {@link KHRPushDescriptor#vkCmdPushDescriptorSetWithTemplateKHR CmdPushDescriptorSetWithTemplateKHR} , <b>can</b> be more efficient compared to calling {@link VK10#vkUpdateDescriptorSets UpdateDescriptorSets} or {@link KHRPushDescriptor#vkCmdPushDescriptorSetKHR CmdPushDescriptorSetKHR} . The descriptors themselves are not specified in the {@code VkDescriptorUpdateTemplate}, rather, offsets into an application provided pointer to host memory are specified, which are combined with a pointer passed to {@link #vkUpdateDescriptorSetWithTemplate UpdateDescriptorSetWithTemplate} or {@link KHRPushDescriptor#vkCmdPushDescriptorSetWithTemplateKHR CmdPushDescriptorSetWithTemplateKHR} . This allows large batches of updates to be executed without having to convert application data structures into a strictly-defined Vulkan data structure.</p>
*
* <p>To create a descriptor update template, call:</p>
*
* <pre><code>
* VkResult vkCreateDescriptorUpdateTemplate(
* VkDevice device,
* const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
* const VkAllocationCallbacks* pAllocator,
* VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* VkResult vkCreateDescriptorUpdateTemplateKHR(
* VkDevice device,
* const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
* const VkAllocationCallbacks* pAllocator,
* VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pCreateInfo} <b>must</b> be a valid pointer to a valid {@link VkDescriptorUpdateTemplateCreateInfo} structure</li>
* <li>If {@code pAllocator} is not {@code NULL}, {@code pAllocator} <b>must</b> be a valid pointer to a valid {@link VkAllocationCallbacks} structure</li>
* <li>{@code pDescriptorUpdateTemplate} <b>must</b> be a valid pointer to a {@code VkDescriptorUpdateTemplate} handle</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkAllocationCallbacks}, {@link VkDescriptorUpdateTemplateCreateInfo}</p>
*
* @param device the logical device that creates the descriptor update template.
* @param pCreateInfo a pointer to a {@link VkDescriptorUpdateTemplateCreateInfo} structure specifying the set of descriptors to update with a single call to {@link KHRPushDescriptor#vkCmdPushDescriptorSetWithTemplateKHR CmdPushDescriptorSetWithTemplateKHR} or {@link #vkUpdateDescriptorSetWithTemplate UpdateDescriptorSetWithTemplate}.
* @param pAllocator controls host memory allocation as described in the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#memory-allocation">Memory Allocation</a> chapter.
* @param pDescriptorUpdateTemplate a pointer to a {@code VkDescriptorUpdateTemplate} handle in which the resulting descriptor update template object is returned.
*/
@NativeType("VkResult")
public static int vkCreateDescriptorUpdateTemplate(VkDevice device, @NativeType("VkDescriptorUpdateTemplateCreateInfo const *") VkDescriptorUpdateTemplateCreateInfo pCreateInfo, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator, @NativeType("VkDescriptorUpdateTemplate *") LongBuffer pDescriptorUpdateTemplate) {
if (CHECKS) {
check(pDescriptorUpdateTemplate, 1);
}
return nvkCreateDescriptorUpdateTemplate(device, pCreateInfo.address(), memAddressSafe(pAllocator), memAddress(pDescriptorUpdateTemplate));
}
// --- [ vkDestroyDescriptorUpdateTemplate ] ---
/** Unsafe version of: {@link #vkDestroyDescriptorUpdateTemplate DestroyDescriptorUpdateTemplate} */
public static void nvkDestroyDescriptorUpdateTemplate(VkDevice device, long descriptorUpdateTemplate, long pAllocator) {
long __functionAddress = device.getCapabilities().vkDestroyDescriptorUpdateTemplate;
if (CHECKS) {
check(__functionAddress);
if (pAllocator != NULL) { VkAllocationCallbacks.validate(pAllocator); }
}
callPJPV(device.address(), descriptorUpdateTemplate, pAllocator, __functionAddress);
}
/**
* Destroy a descriptor update template object.
*
* <h5>C Specification</h5>
*
* <p>To destroy a descriptor update template, call:</p>
*
* <pre><code>
* void vkDestroyDescriptorUpdateTemplate(
* VkDevice device,
* VkDescriptorUpdateTemplate descriptorUpdateTemplate,
* const VkAllocationCallbacks* pAllocator);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkDestroyDescriptorUpdateTemplateKHR(
* VkDevice device,
* VkDescriptorUpdateTemplate descriptorUpdateTemplate,
* const VkAllocationCallbacks* pAllocator);</code></pre>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>If {@link VkAllocationCallbacks} were provided when {@code descriptorUpdateTemplate} was created, a compatible set of callbacks <b>must</b> be provided here</li>
* <li>If no {@link VkAllocationCallbacks} were provided when {@code descriptorUpdateTemplate} was created, {@code pAllocator} <b>must</b> be {@code NULL}</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>If {@code descriptorUpdateTemplate} is not {@link VK10#VK_NULL_HANDLE NULL_HANDLE}, {@code descriptorUpdateTemplate} <b>must</b> be a valid {@code VkDescriptorUpdateTemplate} handle</li>
* <li>If {@code pAllocator} is not {@code NULL}, {@code pAllocator} <b>must</b> be a valid pointer to a valid {@link VkAllocationCallbacks} structure</li>
* <li>If {@code descriptorUpdateTemplate} is a valid handle, it <b>must</b> have been created, allocated, or retrieved from {@code device}</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code descriptorUpdateTemplate} <b>must</b> be externally synchronized</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkAllocationCallbacks}</p>
*
* @param device the logical device that has been used to create the descriptor update template
* @param descriptorUpdateTemplate the descriptor update template to destroy.
* @param pAllocator controls host memory allocation as described in the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#memory-allocation">Memory Allocation</a> chapter.
*/
public static void vkDestroyDescriptorUpdateTemplate(VkDevice device, @NativeType("VkDescriptorUpdateTemplate") long descriptorUpdateTemplate, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator) {
nvkDestroyDescriptorUpdateTemplate(device, descriptorUpdateTemplate, memAddressSafe(pAllocator));
}
// --- [ vkUpdateDescriptorSetWithTemplate ] ---
/**
* Update the contents of a descriptor set object using an update template.
*
* <h5>C Specification</h5>
*
* <p>Once a {@code VkDescriptorUpdateTemplate} has been created, descriptor sets <b>can</b> be updated by calling:</p>
*
* <pre><code>
* void vkUpdateDescriptorSetWithTemplate(
* VkDevice device,
* VkDescriptorSet descriptorSet,
* VkDescriptorUpdateTemplate descriptorUpdateTemplate,
* const void* pData);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkUpdateDescriptorSetWithTemplateKHR(
* VkDevice device,
* VkDescriptorSet descriptorSet,
* VkDescriptorUpdateTemplate descriptorUpdateTemplate,
* const void* pData);</code></pre>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code pData} <b>must</b> be a valid pointer to a memory containing one or more valid instances of {@link VkDescriptorImageInfo}, {@link VkDescriptorBufferInfo}, or {@code VkBufferView} in a layout defined by {@code descriptorUpdateTemplate} when it was created with {@link #vkCreateDescriptorUpdateTemplate CreateDescriptorUpdateTemplate}</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code descriptorSet} <b>must</b> be a valid {@code VkDescriptorSet} handle</li>
* <li>{@code descriptorUpdateTemplate} <b>must</b> be a valid {@code VkDescriptorUpdateTemplate} handle</li>
* <li>{@code descriptorUpdateTemplate} <b>must</b> have been created, allocated, or retrieved from {@code device}</li>
* </ul>
*
* <h5>Host Synchronization</h5>
*
* <ul>
* <li>Host access to {@code descriptorSet} <b>must</b> be externally synchronized</li>
* </ul>
*
* <pre><code>
* struct AppBufferView {
* VkBufferView bufferView;
* uint32_t applicationRelatedInformation;
* };
*
* struct AppDataStructure
* {
* VkDescriptorImageInfo imageInfo; // a single image info
* VkDescriptorBufferInfo bufferInfoArray[3]; // 3 buffer infos in an array
* AppBufferView bufferView[2]; // An application defined structure containing a bufferView
* // ... some more application related data
* };
*
* const VkDescriptorUpdateTemplateEntry descriptorUpdateTemplateEntries[] =
* {
* // binding to a single image descriptor
* {
* 0, // binding
* 0, // dstArrayElement
* 1, // descriptorCount
* VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, // descriptorType
* offsetof(AppDataStructure, imageInfo), // offset
* 0 // stride is not required if descriptorCount is 1
* },
*
* // binding to an array of buffer descriptors
* {
* 1, // binding
* 0, // dstArrayElement
* 3, // descriptorCount
* VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType
* offsetof(AppDataStructure, bufferInfoArray), // offset
* sizeof(VkDescriptorBufferInfo) // stride, descriptor buffer infos are compact
* },
*
* // binding to an array of buffer views
* {
* 2, // binding
* 0, // dstArrayElement
* 2, // descriptorCount
* VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, // descriptorType
* offsetof(AppDataStructure, bufferView) +
* offsetof(AppBufferView, bufferView), // offset
* sizeof(AppBufferView) // stride, bufferViews do not have to be compact
* },
* };
*
* // create a descriptor update template for descriptor set updates
* const VkDescriptorUpdateTemplateCreateInfo createInfo =
* {
* VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO, // sType
* NULL, // pNext
* 0, // flags
* 3, // descriptorUpdateEntryCount
* descriptorUpdateTemplateEntries, // pDescriptorUpdateEntries
* VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET, // templateType
* myLayout, // descriptorSetLayout
* 0, // pipelineBindPoint, ignored by given templateType
* 0, // pipelineLayout, ignored by given templateType
* 0, // set, ignored by given templateType
* };
*
* VkDescriptorUpdateTemplate myDescriptorUpdateTemplate;
* myResult = vkCreateDescriptorUpdateTemplate(
* myDevice,
* &createInfo,
* NULL,
* &myDescriptorUpdateTemplate);
*
* AppDataStructure appData;
*
* // fill appData here or cache it in your engine
* vkUpdateDescriptorSetWithTemplate(myDevice, myDescriptorSet, myDescriptorUpdateTemplate, &appData);</code></pre>
*
* @param device the logical device that updates the descriptor set.
* @param descriptorSet the descriptor set to update
* @param descriptorUpdateTemplate a {@code VkDescriptorUpdateTemplate} object specifying the update mapping between {@code pData} and the descriptor set to update.
* @param pData a pointer to memory containing one or more {@link VkDescriptorImageInfo}, {@link VkDescriptorBufferInfo}, or {@code VkBufferView} structures or {@code VkAccelerationStructureKHR} or {@code VkAccelerationStructureNV} handles used to write the descriptors.
*/
public static void vkUpdateDescriptorSetWithTemplate(VkDevice device, @NativeType("VkDescriptorSet") long descriptorSet, @NativeType("VkDescriptorUpdateTemplate") long descriptorUpdateTemplate, @NativeType("void const *") long pData) {
long __functionAddress = device.getCapabilities().vkUpdateDescriptorSetWithTemplate;
if (CHECKS) {
check(__functionAddress);
check(pData);
}
callPJJPV(device.address(), descriptorSet, descriptorUpdateTemplate, pData, __functionAddress);
}
// --- [ vkGetPhysicalDeviceExternalBufferProperties ] ---
/** Unsafe version of: {@link #vkGetPhysicalDeviceExternalBufferProperties GetPhysicalDeviceExternalBufferProperties} */
public static void nvkGetPhysicalDeviceExternalBufferProperties(VkPhysicalDevice physicalDevice, long pExternalBufferInfo, long pExternalBufferProperties) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceExternalBufferProperties;
if (CHECKS) {
check(__functionAddress);
}
callPPPV(physicalDevice.address(), pExternalBufferInfo, pExternalBufferProperties, __functionAddress);
}
/**
* Query external handle types supported by buffers.
*
* <h5>C Specification</h5>
*
* <p>To query the external handle types supported by buffers, call:</p>
*
* <pre><code>
* void vkGetPhysicalDeviceExternalBufferProperties(
* VkPhysicalDevice physicalDevice,
* const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo,
* VkExternalBufferProperties* pExternalBufferProperties);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetPhysicalDeviceExternalBufferPropertiesKHR(
* VkPhysicalDevice physicalDevice,
* const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo,
* VkExternalBufferProperties* pExternalBufferProperties);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code pExternalBufferInfo} <b>must</b> be a valid pointer to a valid {@link VkPhysicalDeviceExternalBufferInfo} structure</li>
* <li>{@code pExternalBufferProperties} <b>must</b> be a valid pointer to a {@link VkExternalBufferProperties} structure</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkExternalBufferProperties}, {@link VkPhysicalDeviceExternalBufferInfo}</p>
*
* @param physicalDevice the physical device from which to query the buffer capabilities.
* @param pExternalBufferInfo a pointer to a {@link VkPhysicalDeviceExternalBufferInfo} structure describing the parameters that would be consumed by {@link VK10#vkCreateBuffer CreateBuffer}.
* @param pExternalBufferProperties a pointer to a {@link VkExternalBufferProperties} structure in which capabilities are returned.
*/
public static void vkGetPhysicalDeviceExternalBufferProperties(VkPhysicalDevice physicalDevice, @NativeType("VkPhysicalDeviceExternalBufferInfo const *") VkPhysicalDeviceExternalBufferInfo pExternalBufferInfo, @NativeType("VkExternalBufferProperties *") VkExternalBufferProperties pExternalBufferProperties) {
nvkGetPhysicalDeviceExternalBufferProperties(physicalDevice, pExternalBufferInfo.address(), pExternalBufferProperties.address());
}
// --- [ vkGetPhysicalDeviceExternalFenceProperties ] ---
/** Unsafe version of: {@link #vkGetPhysicalDeviceExternalFenceProperties GetPhysicalDeviceExternalFenceProperties} */
public static void nvkGetPhysicalDeviceExternalFenceProperties(VkPhysicalDevice physicalDevice, long pExternalFenceInfo, long pExternalFenceProperties) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceExternalFenceProperties;
if (CHECKS) {
check(__functionAddress);
}
callPPPV(physicalDevice.address(), pExternalFenceInfo, pExternalFenceProperties, __functionAddress);
}
/**
* Function for querying external fence handle capabilities.
*
* <h5>C Specification</h5>
*
* <p>Fences <b>may</b> support import and export of their <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#synchronization-fences-payloads">payload</a> to external handles. To query the external handle types supported by fences, call:</p>
*
* <pre><code>
* void vkGetPhysicalDeviceExternalFenceProperties(
* VkPhysicalDevice physicalDevice,
* const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo,
* VkExternalFenceProperties* pExternalFenceProperties);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetPhysicalDeviceExternalFencePropertiesKHR(
* VkPhysicalDevice physicalDevice,
* const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo,
* VkExternalFenceProperties* pExternalFenceProperties);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code pExternalFenceInfo} <b>must</b> be a valid pointer to a valid {@link VkPhysicalDeviceExternalFenceInfo} structure</li>
* <li>{@code pExternalFenceProperties} <b>must</b> be a valid pointer to a {@link VkExternalFenceProperties} structure</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkExternalFenceProperties}, {@link VkPhysicalDeviceExternalFenceInfo}</p>
*
* @param physicalDevice the physical device from which to query the fence capabilities.
* @param pExternalFenceInfo a pointer to a {@link VkPhysicalDeviceExternalFenceInfo} structure describing the parameters that would be consumed by {@link VK10#vkCreateFence CreateFence}.
* @param pExternalFenceProperties a pointer to a {@link VkExternalFenceProperties} structure in which capabilities are returned.
*/
public static void vkGetPhysicalDeviceExternalFenceProperties(VkPhysicalDevice physicalDevice, @NativeType("VkPhysicalDeviceExternalFenceInfo const *") VkPhysicalDeviceExternalFenceInfo pExternalFenceInfo, @NativeType("VkExternalFenceProperties *") VkExternalFenceProperties pExternalFenceProperties) {
nvkGetPhysicalDeviceExternalFenceProperties(physicalDevice, pExternalFenceInfo.address(), pExternalFenceProperties.address());
}
// --- [ vkGetPhysicalDeviceExternalSemaphoreProperties ] ---
/** Unsafe version of: {@link #vkGetPhysicalDeviceExternalSemaphoreProperties GetPhysicalDeviceExternalSemaphoreProperties} */
public static void nvkGetPhysicalDeviceExternalSemaphoreProperties(VkPhysicalDevice physicalDevice, long pExternalSemaphoreInfo, long pExternalSemaphoreProperties) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceExternalSemaphoreProperties;
if (CHECKS) {
check(__functionAddress);
}
callPPPV(physicalDevice.address(), pExternalSemaphoreInfo, pExternalSemaphoreProperties, __functionAddress);
}
/**
* Function for querying external semaphore handle capabilities.
*
* <h5>C Specification</h5>
*
* <p>Semaphores <b>may</b> support import and export of their <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#synchronization-semaphores-payloads">payload</a> to external handles. To query the external handle types supported by semaphores, call:</p>
*
* <pre><code>
* void vkGetPhysicalDeviceExternalSemaphoreProperties(
* VkPhysicalDevice physicalDevice,
* const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo,
* VkExternalSemaphoreProperties* pExternalSemaphoreProperties);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetPhysicalDeviceExternalSemaphorePropertiesKHR(
* VkPhysicalDevice physicalDevice,
* const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo,
* VkExternalSemaphoreProperties* pExternalSemaphoreProperties);</code></pre>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code pExternalSemaphoreInfo} <b>must</b> be a valid pointer to a valid {@link VkPhysicalDeviceExternalSemaphoreInfo} structure</li>
* <li>{@code pExternalSemaphoreProperties} <b>must</b> be a valid pointer to a {@link VkExternalSemaphoreProperties} structure</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkExternalSemaphoreProperties}, {@link VkPhysicalDeviceExternalSemaphoreInfo}</p>
*
* @param physicalDevice the physical device from which to query the semaphore capabilities.
* @param pExternalSemaphoreInfo a pointer to a {@link VkPhysicalDeviceExternalSemaphoreInfo} structure describing the parameters that would be consumed by {@link VK10#vkCreateSemaphore CreateSemaphore}.
* @param pExternalSemaphoreProperties a pointer to a {@link VkExternalSemaphoreProperties} structure in which capabilities are returned.
*/
public static void vkGetPhysicalDeviceExternalSemaphoreProperties(VkPhysicalDevice physicalDevice, @NativeType("VkPhysicalDeviceExternalSemaphoreInfo const *") VkPhysicalDeviceExternalSemaphoreInfo pExternalSemaphoreInfo, @NativeType("VkExternalSemaphoreProperties *") VkExternalSemaphoreProperties pExternalSemaphoreProperties) {
nvkGetPhysicalDeviceExternalSemaphoreProperties(physicalDevice, pExternalSemaphoreInfo.address(), pExternalSemaphoreProperties.address());
}
// --- [ vkGetDescriptorSetLayoutSupport ] ---
/** Unsafe version of: {@link #vkGetDescriptorSetLayoutSupport GetDescriptorSetLayoutSupport} */
public static void nvkGetDescriptorSetLayoutSupport(VkDevice device, long pCreateInfo, long pSupport) {
long __functionAddress = device.getCapabilities().vkGetDescriptorSetLayoutSupport;
if (CHECKS) {
check(__functionAddress);
VkDescriptorSetLayoutCreateInfo.validate(pCreateInfo);
}
callPPPV(device.address(), pCreateInfo, pSupport, __functionAddress);
}
/**
* Query whether a descriptor set layout can be created.
*
* <h5>C Specification</h5>
*
* <p>To query information about whether a descriptor set layout <b>can</b> be created, call:</p>
*
* <pre><code>
* void vkGetDescriptorSetLayoutSupport(
* VkDevice device,
* const VkDescriptorSetLayoutCreateInfo* pCreateInfo,
* VkDescriptorSetLayoutSupport* pSupport);</code></pre>
*
* <p>or the equivalent command</p>
*
* <pre><code>
* void vkGetDescriptorSetLayoutSupportKHR(
* VkDevice device,
* const VkDescriptorSetLayoutCreateInfo* pCreateInfo,
* VkDescriptorSetLayoutSupport* pSupport);</code></pre>
*
* <h5>Description</h5>
*
* <p>Some implementations have limitations on what fits in a descriptor set which are not easily expressible in terms of existing limits like {@code maxDescriptorSet}*, for example if all descriptor types share a limited space in memory but each descriptor is a different size or alignment. This command returns information about whether a descriptor set satisfies this limit. If the descriptor set layout satisfies the {@link VkPhysicalDeviceMaintenance3Properties}{@code ::maxPerSetDescriptors} limit, this command is guaranteed to return {@link VK10#VK_TRUE TRUE} in {@link VkDescriptorSetLayoutSupport}{@code ::supported}. If the descriptor set layout exceeds the {@link VkPhysicalDeviceMaintenance3Properties}{@code ::maxPerSetDescriptors} limit, whether the descriptor set layout is supported is implementation-dependent and <b>may</b> depend on whether the descriptor sizes and alignments cause the layout to exceed an internal limit.</p>
*
* <p>This command does not consider other limits such as {@code maxPerStageDescriptor}*, and so a descriptor set layout that is supported according to this command <b>must</b> still satisfy the pipeline layout limits such as {@code maxPerStageDescriptor}* in order to be used in a pipeline layout.</p>
*
* <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5>
*
* <p>This is a {@code VkDevice} query rather than {@code VkPhysicalDevice} because the answer <b>may</b> depend on enabled features.</p>
* </div>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code device} <b>must</b> be a valid {@code VkDevice} handle</li>
* <li>{@code pCreateInfo} <b>must</b> be a valid pointer to a valid {@link VkDescriptorSetLayoutCreateInfo} structure</li>
* <li>{@code pSupport} <b>must</b> be a valid pointer to a {@link VkDescriptorSetLayoutSupport} structure</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VkDescriptorSetLayoutCreateInfo}, {@link VkDescriptorSetLayoutSupport}</p>
*
* @param device the logical device that would create the descriptor set layout.
* @param pCreateInfo a pointer to a {@link VkDescriptorSetLayoutCreateInfo} structure specifying the state of the descriptor set layout object.
* @param pSupport a pointer to a {@link VkDescriptorSetLayoutSupport} structure, in which information about support for the descriptor set layout object is returned.
*/
public static void vkGetDescriptorSetLayoutSupport(VkDevice device, @NativeType("VkDescriptorSetLayoutCreateInfo const *") VkDescriptorSetLayoutCreateInfo pCreateInfo, @NativeType("VkDescriptorSetLayoutSupport *") VkDescriptorSetLayoutSupport pSupport) {
nvkGetDescriptorSetLayoutSupport(device, pCreateInfo.address(), pSupport.address());
}
/** Array version of: {@link #vkEnumerateInstanceVersion EnumerateInstanceVersion} */
@NativeType("VkResult")
public static int vkEnumerateInstanceVersion(@NativeType("uint32_t *") int[] pApiVersion) {
long __functionAddress = VK.getGlobalCommands().vkEnumerateInstanceVersion;
if (CHECKS) {
check(__functionAddress);
check(pApiVersion, 1);
}
return callPI(pApiVersion, __functionAddress);
}
/** Array version of: {@link #vkGetDeviceGroupPeerMemoryFeatures GetDeviceGroupPeerMemoryFeatures} */
public static void vkGetDeviceGroupPeerMemoryFeatures(VkDevice device, @NativeType("uint32_t") int heapIndex, @NativeType("uint32_t") int localDeviceIndex, @NativeType("uint32_t") int remoteDeviceIndex, @NativeType("VkPeerMemoryFeatureFlags *") int[] pPeerMemoryFeatures) {
long __functionAddress = device.getCapabilities().vkGetDeviceGroupPeerMemoryFeatures;
if (CHECKS) {
check(__functionAddress);
check(pPeerMemoryFeatures, 1);
}
callPPV(device.address(), heapIndex, localDeviceIndex, remoteDeviceIndex, pPeerMemoryFeatures, __functionAddress);
}
/** Array version of: {@link #vkEnumeratePhysicalDeviceGroups EnumeratePhysicalDeviceGroups} */
@NativeType("VkResult")
public static int vkEnumeratePhysicalDeviceGroups(VkInstance instance, @NativeType("uint32_t *") int[] pPhysicalDeviceGroupCount, @Nullable @NativeType("VkPhysicalDeviceGroupProperties *") VkPhysicalDeviceGroupProperties.Buffer pPhysicalDeviceGroupProperties) {
long __functionAddress = instance.getCapabilities().vkEnumeratePhysicalDeviceGroups;
if (CHECKS) {
check(__functionAddress);
check(pPhysicalDeviceGroupCount, 1);
checkSafe(pPhysicalDeviceGroupProperties, pPhysicalDeviceGroupCount[0]);
}
return callPPPI(instance.address(), pPhysicalDeviceGroupCount, memAddressSafe(pPhysicalDeviceGroupProperties), __functionAddress);
}
/** Array version of: {@link #vkGetImageSparseMemoryRequirements2 GetImageSparseMemoryRequirements2} */
public static void vkGetImageSparseMemoryRequirements2(VkDevice device, @NativeType("VkImageSparseMemoryRequirementsInfo2 const *") VkImageSparseMemoryRequirementsInfo2 pInfo, @NativeType("uint32_t *") int[] pSparseMemoryRequirementCount, @Nullable @NativeType("VkSparseImageMemoryRequirements2 *") VkSparseImageMemoryRequirements2.Buffer pSparseMemoryRequirements) {
long __functionAddress = device.getCapabilities().vkGetImageSparseMemoryRequirements2;
if (CHECKS) {
check(__functionAddress);
check(pSparseMemoryRequirementCount, 1);
checkSafe(pSparseMemoryRequirements, pSparseMemoryRequirementCount[0]);
}
callPPPPV(device.address(), pInfo.address(), pSparseMemoryRequirementCount, memAddressSafe(pSparseMemoryRequirements), __functionAddress);
}
/** Array version of: {@link #vkGetPhysicalDeviceQueueFamilyProperties2 GetPhysicalDeviceQueueFamilyProperties2} */
public static void vkGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice, @NativeType("uint32_t *") int[] pQueueFamilyPropertyCount, @Nullable @NativeType("VkQueueFamilyProperties2 *") VkQueueFamilyProperties2.Buffer pQueueFamilyProperties) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceQueueFamilyProperties2;
if (CHECKS) {
check(__functionAddress);
check(pQueueFamilyPropertyCount, 1);
checkSafe(pQueueFamilyProperties, pQueueFamilyPropertyCount[0]);
}
callPPPV(physicalDevice.address(), pQueueFamilyPropertyCount, memAddressSafe(pQueueFamilyProperties), __functionAddress);
}
/** Array version of: {@link #vkGetPhysicalDeviceSparseImageFormatProperties2 GetPhysicalDeviceSparseImageFormatProperties2} */
public static void vkGetPhysicalDeviceSparseImageFormatProperties2(VkPhysicalDevice physicalDevice, @NativeType("VkPhysicalDeviceSparseImageFormatInfo2 const *") VkPhysicalDeviceSparseImageFormatInfo2 pFormatInfo, @NativeType("uint32_t *") int[] pPropertyCount, @Nullable @NativeType("VkSparseImageFormatProperties2 *") VkSparseImageFormatProperties2.Buffer pProperties) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceSparseImageFormatProperties2;
if (CHECKS) {
check(__functionAddress);
check(pPropertyCount, 1);
checkSafe(pProperties, pPropertyCount[0]);
}
callPPPPV(physicalDevice.address(), pFormatInfo.address(), pPropertyCount, memAddressSafe(pProperties), __functionAddress);
}
/** Array version of: {@link #vkCreateSamplerYcbcrConversion CreateSamplerYcbcrConversion} */
@NativeType("VkResult")
public static int vkCreateSamplerYcbcrConversion(VkDevice device, @NativeType("VkSamplerYcbcrConversionCreateInfo const *") VkSamplerYcbcrConversionCreateInfo pCreateInfo, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator, @NativeType("VkSamplerYcbcrConversion *") long[] pYcbcrConversion) {
long __functionAddress = device.getCapabilities().vkCreateSamplerYcbcrConversion;
if (CHECKS) {
check(__functionAddress);
check(pYcbcrConversion, 1);
if (pAllocator != null) { VkAllocationCallbacks.validate(pAllocator.address()); }
}
return callPPPPI(device.address(), pCreateInfo.address(), memAddressSafe(pAllocator), pYcbcrConversion, __functionAddress);
}
/** Array version of: {@link #vkCreateDescriptorUpdateTemplate CreateDescriptorUpdateTemplate} */
@NativeType("VkResult")
public static int vkCreateDescriptorUpdateTemplate(VkDevice device, @NativeType("VkDescriptorUpdateTemplateCreateInfo const *") VkDescriptorUpdateTemplateCreateInfo pCreateInfo, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator, @NativeType("VkDescriptorUpdateTemplate *") long[] pDescriptorUpdateTemplate) {
long __functionAddress = device.getCapabilities().vkCreateDescriptorUpdateTemplate;
if (CHECKS) {
check(__functionAddress);
check(pDescriptorUpdateTemplate, 1);
VkDescriptorUpdateTemplateCreateInfo.validate(pCreateInfo.address());
if (pAllocator != null) { VkAllocationCallbacks.validate(pAllocator.address()); }
}
return callPPPPI(device.address(), pCreateInfo.address(), memAddressSafe(pAllocator), pDescriptorUpdateTemplate, __functionAddress);
}
}
|
/*
* Copyright 2002-2018 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
*
* 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 org.springframework.mock.web;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import jakarta.servlet.http.Part;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Mock implementation of {@code jakarta.servlet.http.Part}.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 4.3.12
* @see MockHttpServletRequest#addPart
* @see MockMultipartFile
*/
public class MockPart implements Part {
private final String name;
@Nullable
private final String filename;
private final byte[] content;
private final HttpHeaders headers = new HttpHeaders();
/**
* Constructor for a part with byte[] content only.
* @see #getHeaders()
*/
public MockPart(String name, @Nullable byte[] content) {
this(name, null, content);
}
/**
* Constructor for a part with a filename and byte[] content.
* @see #getHeaders()
*/
public MockPart(String name, @Nullable String filename, @Nullable byte[] content) {
Assert.hasLength(name, "'name' must not be empty");
this.name = name;
this.filename = filename;
this.content = (content != null ? content : new byte[0]);
this.headers.setContentDispositionFormData(name, filename);
}
@Override
public String getName() {
return this.name;
}
@Override
@Nullable
public String getSubmittedFileName() {
return this.filename;
}
@Override
@Nullable
public String getContentType() {
MediaType contentType = this.headers.getContentType();
return (contentType != null ? contentType.toString() : null);
}
@Override
public long getSize() {
return this.content.length;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(this.content);
}
@Override
public void write(String fileName) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void delete() throws IOException {
throw new UnsupportedOperationException();
}
@Override
@Nullable
public String getHeader(String name) {
return this.headers.getFirst(name);
}
@Override
public Collection<String> getHeaders(String name) {
Collection<String> headerValues = this.headers.get(name);
return (headerValues != null ? headerValues : Collections.emptyList());
}
@Override
public Collection<String> getHeaderNames() {
return this.headers.keySet();
}
/**
* Return the {@link HttpHeaders} backing header related accessor methods,
* allowing for populating selected header entries.
*/
public final HttpHeaders getHeaders() {
return this.headers;
}
}
|
/**
* Copyright 2012 multibit.org
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.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.multibit.file;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import junit.framework.TestCase;
import org.joda.money.CurrencyUnit;
import org.junit.Test;
import org.multibit.Constants;
import org.multibit.CreateControllers;
import org.multibit.controller.bitcoin.BitcoinController;
import org.multibit.exchange.CurrencyConverter;
import org.multibit.model.bitcoin.WalletData;
import org.multibit.model.exchange.ExchangeModel;
import org.multibit.viewsystem.swing.action.ExportTransactionsSubmitAction;
import com.google.dogecoin.core.Wallet;
public class ExportTransactionsSubmitActionTest extends TestCase {
public static final String WALLETS_TESTDATA_DIRECTORY = "wallets";
public static final String TEST_EXPORT_PREFIX = "testExport";
public static final String PROTOBUF1_WALLET_FILE = "protobuf1.wallet";
@Test
public void testExportTransactions() throws Exception {
// Create MultiBit controller.
final CreateControllers.Controllers controllers = CreateControllers.createControllers();
final BitcoinController bitcoinController = controllers.bitcoinController;
// Initialise currency converter.
bitcoinController.getModel().setUserPreference(ExchangeModel.TICKER_FIRST_ROW_CURRENCY, "EUR");
CurrencyConverter.INSTANCE.initialise(bitcoinController);
CurrencyConverter.INSTANCE.setRate(BigDecimal.valueOf(10.0));
ExportTransactionsSubmitAction action = new ExportTransactionsSubmitAction(bitcoinController, null);
assertNotNull(action);
// Load up the test wallet /wallets/protobuf1.
// This has (at least) two transactions in it.
File directory = new File(".");
String currentPath = directory.getAbsolutePath();
String testDirectory = currentPath + File.separator + Constants.TESTDATA_DIRECTORY + File.separator
+ WALLETS_TESTDATA_DIRECTORY;
String testWalletFile = testDirectory + File.separator + PROTOBUF1_WALLET_FILE;
// Load up the test wallet
FileHandler fileHandler = new FileHandler(bitcoinController);
Wallet testWallet = fileHandler.loadFromFile(new File(testWalletFile)).getWallet();
assertNotNull(testWallet);
assertTrue("Wrong number of transactions in wallet", testWallet.getTransactions(true).size() >= 2);
// Write the transactions out to a file.
File exportFile = File.createTempFile(TEST_EXPORT_PREFIX, ".csv");
exportFile.delete();
exportFile.deleteOnExit();
// Check the file does not exist initially.
assertTrue("Export file exists when it should not", !exportFile.exists());
String exportTransactionsFilename = exportFile.getAbsolutePath();
WalletData walletData = new WalletData();
walletData.setWallet(testWallet);
walletData.setWalletFilename(testWalletFile);
action.exportTransactionsDoIt(walletData, exportTransactionsFilename);
// Check the file does exist now.
assertTrue("Export file does not exists when it should", exportFile.exists());
FileInputStream fileInputStream = new FileInputStream(exportTransactionsFilename);
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream, "UTF-8"));
// Read file line by line.
String line0 = bufferedReader.readLine();
String line1 = bufferedReader.readLine();
String line2 = bufferedReader.readLine();
// Close the input stream.
dataInputStream.close();
assertNotNull("No header row read in", line0);
assertNotNull("No row 1 read in", line1);
assertNotNull("No row 2 read in", line2);
assertEquals("Header row incorrect", "Date,Description,Amount (BTC),Amount (\u20AC),Transaction Id", line0);
// Note \u5317\u4EAC = Beijing in Chinese.
String row1Expected = "29 Jul 2013 10:23,\"Sent to \"\"unencrypted-1-\u5317\u4EAC\"\" (1CQH7Hp9nNQVDcKtFVwbA8tqPMNWDBvqE3)\",-0.015,-0.15,28916ed8592a4cf216d8eac7e5ccb5a08771f439e508ec2861b7ff612e15b827";
String row2Expected = "29 Jul 2013 10:00,\"Received with \"\"protobuf 1.1.\u5317\u4EAC\"\" (1GtMdodCNN5ewFcEUxxVBziBrLtQzSuZvq)\",0.015,0.15,5eeabb42d0522c40cc63dace7746d5f82cd51292bc50a38c4dd68a854ec6cd77";
assertEquals("Row 1 incorrect", row1Expected, line1);
assertEquals("Row 2 incorrect", row2Expected, line2);
}
}
|
package edu.sfsu.cs.orange.ocr;
import edu.sfsu.cs.orange.ocr.CaptureActivity;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.CountDownLatch;
/**
* This thread does all the heavy lifting of decoding the images.
*
* The code for this class was adapted from the ZXing project: http://code.google.com/p/zxing
*/
final class DecodeThread extends Thread {
private final CaptureActivity activity;
private Handler handler;
private final CountDownLatch handlerInitLatch;
DecodeThread(CaptureActivity activity) {
this.activity = activity;
handlerInitLatch = new CountDownLatch(1);
}
Handler getHandler() {
try {
handlerInitLatch.await();
} catch (InterruptedException ie) {
// continue?
}
return handler;
}
@Override
public void run() {
Looper.prepare();
handler = new DecodeHandler(activity);
handlerInitLatch.countDown();
Looper.loop();
}
}
|
package io.nutz.nutzsite.module.test.services;
import io.nutz.nutzsite.common.service.BaseService;
import io.nutz.nutzsite.module.test.models.Monitor;
/**
* 数据接口 服务层实现
*
* @author haiming
* @date 2021-03-27
*/
public interface MonitorService extends BaseService<Monitor> {
Object tableList(int pageNum,int pageSize,String objId,String ckpId);
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.txn.compactor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.common.ValidTxnList;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.CompactionRequest;
import org.apache.hadoop.hive.metastore.api.CompactionType;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.ShowCompactRequest;
import org.apache.hadoop.hive.metastore.api.ShowCompactResponse;
import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
import org.apache.hadoop.hive.metastore.txn.CompactionTxnHandler;
import org.apache.hadoop.hive.metastore.txn.TxnHandler;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.StringUtils;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A class to initiate compactions. This will run in a separate thread.
*/
public class Initiator extends CompactorThread {
static final private String CLASS_NAME = Initiator.class.getName();
static final private Log LOG = LogFactory.getLog(CLASS_NAME);
private long checkInterval;
@Override
public void run() {
// Make sure nothing escapes this run method and kills the metastore at large,
// so wrap it in a big catch Throwable statement.
try {
recoverFailedCompactions(false);
int abortedThreshold = HiveConf.getIntVar(conf,
HiveConf.ConfVars.HIVE_COMPACTOR_ABORTEDTXN_THRESHOLD);
// Make sure we run through the loop once before checking to stop as this makes testing
// much easier. The stop value is only for testing anyway and not used when called from
// HiveMetaStore.
do {
long startedAt = System.currentTimeMillis();
// Wrap the inner parts of the loop in a catch throwable so that any errors in the loop
// don't doom the entire thread.
try {
ShowCompactResponse currentCompactions = txnHandler.showCompact(new ShowCompactRequest());
ValidTxnList txns =
CompactionTxnHandler.createValidCompactTxnList(txnHandler.getOpenTxnsInfo());
Set<CompactionInfo> potentials = txnHandler.findPotentialCompactions(abortedThreshold);
LOG.debug("Found " + potentials.size() + " potential compactions, " +
"checking to see if we should compact any of them");
for (CompactionInfo ci : potentials) {
LOG.debug("Checking to see if we should compact " + ci.getFullPartitionName());
try {
Table t = resolveTable(ci);
if (t == null) {
// Most likely this means it's a temp table
LOG.debug("Can't find table " + ci.getFullTableName() + ", assuming it's a temp " +
"table and moving on.");
continue;
}
// check if no compaction set for this table
if (noAutoCompactSet(t)) {
LOG.info("Table " + tableName(t) + " marked true so we will not compact it.");
continue;
}
// Check to see if this is a table level request on a partitioned table. If so,
// then it's a dynamic partitioning case and we shouldn't check the table itself.
if (t.getPartitionKeys() != null && t.getPartitionKeys().size() > 0 &&
ci.partName == null) {
LOG.debug("Skipping entry for " + ci.getFullTableName() + " as it is from dynamic" +
" partitioning");
continue;
}
// Check if we already have initiated or are working on a compaction for this partition
// or table. If so, skip it. If we are just waiting on cleaning we can still check,
// as it may be time to compact again even though we haven't cleaned.
if (lookForCurrentCompactions(currentCompactions, ci)) {
LOG.debug("Found currently initiated or working compaction for " +
ci.getFullPartitionName() + " so we will not initiate another compaction");
continue;
}
// Figure out who we should run the file operations as
Partition p = resolvePartition(ci);
StorageDescriptor sd = resolveStorageDescriptor(t, p);
String runAs = findUserToRunAs(sd.getLocation(), t);
CompactionType compactionNeeded = checkForCompaction(ci, txns, sd, runAs);
if (compactionNeeded != null) requestCompaction(ci, runAs, compactionNeeded);
} catch (Throwable t) {
LOG.error("Caught exception while trying to determine if we should compact " +
ci.getFullPartitionName() + ". Marking clean to avoid repeated failures, " +
"" + StringUtils.stringifyException(t));
txnHandler.markCleaned(ci);
}
}
// Check for timed out remote workers.
recoverFailedCompactions(true);
// Clean anything from the txns table that has no components left in txn_components.
txnHandler.cleanEmptyAbortedTxns();
} catch (Throwable t) {
LOG.error("Initiator loop caught unexpected exception this time through the loop: " +
StringUtils.stringifyException(t));
}
long elapsedTime = System.currentTimeMillis() - startedAt;
if (elapsedTime >= checkInterval || stop.get()) continue;
else Thread.sleep(checkInterval - elapsedTime);
} while (!stop.get());
} catch (Throwable t) {
LOG.error("Caught an exception in the main loop of compactor initiator, exiting " +
StringUtils.stringifyException(t));
}
}
@Override
public void init(AtomicBoolean stop, AtomicBoolean looped) throws MetaException {
super.init(stop, looped);
checkInterval =
conf.getTimeVar(HiveConf.ConfVars.HIVE_COMPACTOR_CHECK_INTERVAL, TimeUnit.MILLISECONDS) ;
}
private void recoverFailedCompactions(boolean remoteOnly) throws MetaException {
if (!remoteOnly) txnHandler.revokeFromLocalWorkers(Worker.hostname());
txnHandler.revokeTimedoutWorkers(HiveConf.getTimeVar(conf,
HiveConf.ConfVars.HIVE_COMPACTOR_WORKER_TIMEOUT, TimeUnit.MILLISECONDS));
}
// Figure out if there are any currently running compactions on the same table or partition.
private boolean lookForCurrentCompactions(ShowCompactResponse compactions,
CompactionInfo ci) {
if (compactions.getCompacts() != null) {
for (ShowCompactResponseElement e : compactions.getCompacts()) {
if (!e.getState().equals(TxnHandler.CLEANING_RESPONSE) &&
e.getDbname().equals(ci.dbname) &&
e.getTablename().equals(ci.tableName) &&
(e.getPartitionname() == null && ci.partName == null ||
e.getPartitionname().equals(ci.partName))) {
return true;
}
}
}
return false;
}
private CompactionType checkForCompaction(final CompactionInfo ci,
final ValidTxnList txns,
final StorageDescriptor sd,
final String runAs)
throws IOException, InterruptedException {
// If it's marked as too many aborted, we already know we need to compact
if (ci.tooManyAborts) {
LOG.debug("Found too many aborted transactions for " + ci.getFullPartitionName() + ", " +
"initiating major compaction");
return CompactionType.MAJOR;
}
if (runJobAsSelf(runAs)) {
return determineCompactionType(ci, txns, sd);
} else {
LOG.info("Going to initiate as user " + runAs);
UserGroupInformation ugi = UserGroupInformation.createProxyUser(runAs,
UserGroupInformation.getLoginUser());
return ugi.doAs(new PrivilegedExceptionAction<CompactionType>() {
@Override
public CompactionType run() throws Exception {
return determineCompactionType(ci, txns, sd);
}
});
}
}
private CompactionType determineCompactionType(CompactionInfo ci, ValidTxnList txns,
StorageDescriptor sd)
throws IOException, InterruptedException {
boolean noBase = false;
Path location = new Path(sd.getLocation());
FileSystem fs = location.getFileSystem(conf);
AcidUtils.Directory dir = AcidUtils.getAcidState(location, conf, txns);
Path base = dir.getBaseDirectory();
long baseSize = 0;
FileStatus stat = null;
if (base != null) {
stat = fs.getFileStatus(base);
if (!stat.isDir()) {
LOG.error("Was assuming base " + base.toString() + " is directory, but it's a file!");
return null;
}
baseSize = sumDirSize(fs, base);
}
List<FileStatus> originals = dir.getOriginalFiles();
for (FileStatus origStat : originals) {
baseSize += origStat.getLen();
}
long deltaSize = 0;
List<AcidUtils.ParsedDelta> deltas = dir.getCurrentDirectories();
for (AcidUtils.ParsedDelta delta : deltas) {
stat = fs.getFileStatus(delta.getPath());
if (!stat.isDir()) {
LOG.error("Was assuming delta " + delta.getPath().toString() + " is a directory, " +
"but it's a file!");
return null;
}
deltaSize += sumDirSize(fs, delta.getPath());
}
if (baseSize == 0 && deltaSize > 0) {
noBase = true;
} else {
float deltaPctThreshold = HiveConf.getFloatVar(conf,
HiveConf.ConfVars.HIVE_COMPACTOR_DELTA_PCT_THRESHOLD);
boolean bigEnough = (float)deltaSize/(float)baseSize > deltaPctThreshold;
if (LOG.isDebugEnabled()) {
StringBuffer msg = new StringBuffer("delta size: ");
msg.append(deltaSize);
msg.append(" base size: ");
msg.append(baseSize);
msg.append(" threshold: ");
msg.append(deltaPctThreshold);
msg.append(" will major compact: ");
msg.append(bigEnough);
LOG.debug(msg);
}
if (bigEnough) return CompactionType.MAJOR;
}
int deltaNumThreshold = HiveConf.getIntVar(conf,
HiveConf.ConfVars.HIVE_COMPACTOR_DELTA_NUM_THRESHOLD);
boolean enough = deltas.size() > deltaNumThreshold;
if (enough) {
LOG.debug("Found " + deltas.size() + " delta files, threshold is " + deltaNumThreshold +
(enough ? "" : "not") + " and no base, requesting " + (noBase ? "major" : "minor") +
" compaction");
// If there's no base file, do a major compaction
return noBase ? CompactionType.MAJOR : CompactionType.MINOR;
}
return null;
}
private long sumDirSize(FileSystem fs, Path dir) throws IOException {
long size = 0;
FileStatus[] buckets = fs.listStatus(dir, FileUtils.HIDDEN_FILES_PATH_FILTER);
for (int i = 0; i < buckets.length; i++) {
size += buckets[i].getLen();
}
return size;
}
private void requestCompaction(CompactionInfo ci, String runAs, CompactionType type) throws MetaException {
String s = "Requesting " + type.toString() + " compaction for " + ci.getFullPartitionName();
LOG.info(s);
CompactionRequest rqst = new CompactionRequest(ci.dbname, ci.tableName, type);
if (ci.partName != null) rqst.setPartitionname(ci.partName);
rqst.setRunas(runAs);
txnHandler.compact(rqst);
}
// Because TABLE_NO_AUTO_COMPACT was originally assumed to be NO_AUTO_COMPACT and then was moved
// to no_auto_compact, we need to check it in both cases.
private boolean noAutoCompactSet(Table t) {
String noAutoCompact =
t.getParameters().get(hive_metastoreConstants.TABLE_NO_AUTO_COMPACT);
if (noAutoCompact == null) {
noAutoCompact =
t.getParameters().get(hive_metastoreConstants.TABLE_NO_AUTO_COMPACT.toUpperCase());
}
return noAutoCompact != null && noAutoCompact.equalsIgnoreCase("true");
}
}
|
package sagiyehezkel.matchappserver.games;
import java.util.ArrayList;
import java.util.Arrays;
import sagiyehezkel.matchappserver.Util;
public class ConnectFour extends Game {
// Number of connected discs to look for in order to win
final private int NUM_OF_CONNECTED_TO_WIN = 4;
final private int NUM_OF_ROWS = 6;
final private int NUM_OF_COLUMNS = 7;
ArrayList<String> moves;
public ConnectFour() {
super(GamesFactory.CONNECT_FOUR);
}
@Override
public void updateStatusFromString(String player, String newStatus) {
if (newStatus != null) {
moves = Util.fromStringToList(newStatus);
if ((player != null) && checkIfGameCompleted()) {
mWinnerPlayer = player;
}
}
}
@Override
public boolean checkIfGameCompleted() {
Integer[][] gameBoard = new Integer[NUM_OF_ROWS][NUM_OF_COLUMNS];
for (int i = 0; i < NUM_OF_ROWS; ++i)
Arrays.fill(gameBoard[i], 0);
int lastCellEditedRow = 0;
int lastCellEditedCol = 0;
int playerNum = 0;
for (String cell : moves) {
int lastCellIndex = Integer.parseInt(cell);
lastCellEditedRow = lastCellIndex / NUM_OF_COLUMNS;
lastCellEditedCol = lastCellIndex % NUM_OF_COLUMNS;
gameBoard[lastCellEditedRow][lastCellEditedCol] = playerNum + 1;
playerNum = (playerNum + 1) % 2;
}
int lastPlayerCode = gameBoard[lastCellEditedRow][lastCellEditedCol];
boolean foundConnectFour = false;
// Check Down
if (!foundConnectFour &&
// Verify the row is "high" enough so it's possible to have enough connected disks down
(lastCellEditedRow <= NUM_OF_ROWS - NUM_OF_CONNECTED_TO_WIN)) {
foundConnectFour = true;
for (int i = 1; foundConnectFour && i < NUM_OF_CONNECTED_TO_WIN; ++i) {
int nextLocationCode = gameBoard[lastCellEditedRow + i][lastCellEditedCol];
foundConnectFour = (lastPlayerCode == nextLocationCode);
}
}
// Check Row
if (!foundConnectFour) {
int foundConnected = 0;
for (int i = 1; !foundConnectFour && i < NUM_OF_COLUMNS; ++i) {
int nextLocationCode = gameBoard[lastCellEditedRow][i];
if (nextLocationCode == lastPlayerCode)
++foundConnected;
else
foundConnected = 0;
foundConnectFour = (foundConnected == NUM_OF_CONNECTED_TO_WIN);
}
}
int curScanRow;
int curScanCol;
// Check main diagonal
if (!foundConnectFour) {
curScanRow = lastCellEditedRow - NUM_OF_CONNECTED_TO_WIN;
curScanCol = lastCellEditedCol - NUM_OF_CONNECTED_TO_WIN;
// Move to valid indexes
while (curScanRow < 0 || curScanCol < 0) {
++curScanRow;
++curScanCol;
}
int foundConnected = 0;
while (!foundConnectFour &&
curScanRow < NUM_OF_ROWS &&
curScanCol < NUM_OF_COLUMNS) {
int nextLocationCode = gameBoard[curScanRow][curScanCol];
if (nextLocationCode == lastPlayerCode)
++foundConnected;
else
foundConnected = 0;
foundConnectFour = (foundConnected == NUM_OF_CONNECTED_TO_WIN);
++curScanRow;
++curScanCol;
}
}
// Check second diagonal
if (!foundConnectFour) {
curScanRow = lastCellEditedRow + NUM_OF_CONNECTED_TO_WIN;
curScanCol = lastCellEditedCol - NUM_OF_CONNECTED_TO_WIN;
// Move to valid indexes
while (curScanRow >= NUM_OF_ROWS || curScanCol < 0) {
--curScanRow;
++curScanCol;
}
int foundConnected = 0;
while (!foundConnectFour &&
curScanRow >= 0 &&
curScanCol < NUM_OF_COLUMNS) {
int nextLocationCode = gameBoard[curScanRow][curScanCol];
if (nextLocationCode == lastPlayerCode)
++foundConnected;
else
foundConnected = 0;
foundConnectFour = (foundConnected == NUM_OF_CONNECTED_TO_WIN);
--curScanRow;
++curScanCol;
}
}
return foundConnectFour;
}
}
|
package com.github.christianfranco.geomatch.entities;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* Created by Christian Franco on 11/12/2016.
*/
public class PhoneNumberTest {
@Test
public void newPhoneNumber() throws Exception {
PhoneNumber phoneNumber = ImmutablePhoneNumber.of(351, 212333444L, ImmutableLocale.of("PT", "Lisbon"));
assertThat(phoneNumber.getCountryNumber(), is(351));
assertThat(phoneNumber.getNationalNumber(), is(212333444L));
assertThat(phoneNumber.toE164Format(), is("+351212333444"));
assertThat(phoneNumber.getLocale(), is(ImmutableLocale.of("PT", "Lisbon")));
}
@Test
public void newPhoneNumber_tollFree() throws Exception {
PhoneNumber phoneNumber = ImmutablePhoneNumber.of(351, 212333444L, ImmutableLocale.of("PT", PhoneNumber.TOLL_FREE));
assertThat(phoneNumber.getCountryNumber(), is(351));
assertThat(phoneNumber.getNationalNumber(), is(212333444L));
assertThat(phoneNumber.toE164Format(), is("+351212333444"));
assertThat(phoneNumber.getLocale(), is(ImmutableLocale.of("PT", PhoneNumber.TOLL_FREE)));
}
}
|
package org.cleanas2.service.net;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.BHttpConnectionBase;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.cleanas2.message.IncomingMessage;
import org.cleanas2.service.CertificateService;
import org.cleanas2.service.net.processor.AsyncMdnProcessor;
import org.cleanas2.service.net.util.*;
import javax.inject.Inject;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.boon.Lists.list;
/**
* Handles receiving Async MDNs, silly.
*
* @author Andrew Backer {@literal awbacker@gmail.com / andrew.backer@powere2e.com}
*/
public class AsyncMdnReceiverHandler implements HttpRequestHandler {
private static final Log logger = LogFactory.getLog(AsyncMdnReceiverHandler.class.getSimpleName());
private final CertificateService certs;
@Inject
public AsyncMdnReceiverHandler(CertificateService certs) {
this.certs = certs;
}
private void validateRequestFormat(HttpRequest request) throws HttpException {
if (!NetUtil.isPost(request)) {
logger.error("request was not POST");
throw new ProtocolException(request.getRequestLine().getMethod() + " method not supported");
}
for (String s : list("AS2-From", "AS2-To")) {
Header h = request.getFirstHeader(s);
if (h == null || isBlank(h.getValue())) {
throw new ProtocolException("The required '" + s + "' header was not present");
}
}
if (!(request instanceof HttpEntityEnclosingRequest)) {
throw new ProtocolException("The request did not contain an entity");
}
}
/**
* Handles the actual incoming request. This should set up and deal with connection specific items, such as creating
* the container class, and handling the errors in a way that the MDN receiver does not see the details of server
* to server communication.
*/
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
logger.info("handler invoked");
BHttpConnectionBase connection = (BHttpConnectionBase) context.getAttribute("connection");
IncomingMessage msg = new IncomingMessage(connection, request);
try {
validateRequestFormat(request);
} catch (Exception e) {
logger.error("Invalid request: " + e.getMessage());
throw e;
}
try {
//E2ELogUtil.mdnAsyncReceiveStart(as2msg);
MimeBodyPart mimeData = MimeUtil.fromHttpRequest((HttpEntityEnclosingRequest) request);
if (MimeUtil.isSigned(mimeData)) {
X509Certificate senderCert = certs.getCertificate(msg.senderId);
mimeData = MimeUtil.verifyAndRemoveSignature(mimeData, senderCert);
}
if (MdnUtil.isBodyPartMdn(mimeData)) {
AsyncMdnProcessor mp = new AsyncMdnProcessor(msg, mimeData);
mp.process(response);
} else {
logger.error("Mime body part was not valid or or not an MDN ");
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
response.setEntity(new StringEntity("Mime body part was not recognized as an MDN"));
}
} catch (MessagingException e) {
logger.debug("Messaging Exception", e);
response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
response.setEntity(new StringEntity(e.getMessage()));
} catch (GeneralSecurityException e) {
response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
response.setEntity(new StringEntity(e.getMessage()));
logger.debug("Encryption/Security related exception", e);
} finally {
logger.debug("MDN Receipt Finished");
//E2ELogUtil.mdnReceiveEnd(as2msg);
}
}
}
|
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.transaction.interceptor;
import java.io.Serializable;
import java.lang.reflect.Method;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
/**
* Very simple implementation of TransactionAttributeSource which will always return
* the same TransactionAttribute for all methods fed to it. The TransactionAttribute
* may be specified, but will otherwise default to PROPAGATION_REQUIRED. This may be
* used in the cases where you want to use the same transaction attribute with all
* methods being handled by a transaction interceptor.
*
* @author Colin Sampaleanu
* @since 15.10.2003
* @see org.springframework.transaction.interceptor.TransactionProxyFactoryBean
* @see org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator
*/
@SuppressWarnings("serial")
public class MatchAlwaysTransactionAttributeSource implements TransactionAttributeSource, Serializable {
private TransactionAttribute transactionAttribute = new DefaultTransactionAttribute();
/**
* Allows a transaction attribute to be specified, using the String form, for
* example, "PROPAGATION_REQUIRED".
* @param transactionAttribute The String form of the transactionAttribute to use.
* @see org.springframework.transaction.interceptor.TransactionAttributeEditor
*/
public void setTransactionAttribute(TransactionAttribute transactionAttribute) {
this.transactionAttribute = transactionAttribute;
}
@Override
public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
return (method == null || ClassUtils.isUserLevelMethod(method) ? this.transactionAttribute : null);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof MatchAlwaysTransactionAttributeSource)) {
return false;
}
MatchAlwaysTransactionAttributeSource otherTas = (MatchAlwaysTransactionAttributeSource) other;
return ObjectUtils.nullSafeEquals(this.transactionAttribute, otherTas.transactionAttribute);
}
@Override
public int hashCode() {
return MatchAlwaysTransactionAttributeSource.class.hashCode();
}
@Override
public String toString() {
return getClass().getName() + ": " + this.transactionAttribute;
}
}
|
package com.baeldung.example;
import com.baeldung.junit.tags.example.EmployeeDAO;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeUnitTest {
@Mock
private JdbcTemplate jdbcTemplate;
private EmployeeDAO employeeDAO;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
employeeDAO = new EmployeeDAO();
employeeDAO.setJdbcTemplate(jdbcTemplate);
}
@Test
public void givenNumberOfEmployeeWhenCountEmployeeThenCountMatch() {
// given
Mockito.when(jdbcTemplate.queryForObject(Mockito.any(String.class), Mockito.eq(Integer.class)))
.thenReturn(1);
// when
int countOfEmployees = employeeDAO.getCountOfEmployees();
// then
Assert.assertThat(countOfEmployees, CoreMatchers.is(1));
}
}
|
/*
* Copyright 2002-2021 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
*
* 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 org.springframework.web.servlet.mvc.method.annotation;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.util.WebUtils;
/**
* A convenient base class for {@link ControllerAdvice @ControllerAdvice} classes
* that wish to provide centralized exception handling across all
* {@code @RequestMapping} methods through {@code @ExceptionHandler} methods.
*
* <p>This base class provides an {@code @ExceptionHandler} method for handling
* internal Spring MVC exceptions. This method returns a {@code ResponseEntity}
* for writing to the response with a {@link HttpMessageConverter message converter},
* in contrast to
* {@link org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver
* DefaultHandlerExceptionResolver} which returns a
* {@link org.springframework.web.servlet.ModelAndView ModelAndView}.
*
* <p>If there is no need to write error content to the response body, or when
* using view resolution (e.g., via {@code ContentNegotiatingViewResolver}),
* then {@code DefaultHandlerExceptionResolver} is good enough.
*
* <p>Note that in order for an {@code @ControllerAdvice} subclass to be
* detected, {@link ExceptionHandlerExceptionResolver} must be configured.
*
* @author Rossen Stoyanchev
* @since 3.2
* @see #handleException(Exception, WebRequest)
* @see org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver
*/
public abstract class ResponseEntityExceptionHandler {
/**
* Log category to use when no mapped handler is found for a request.
* @see #pageNotFoundLogger
*/
public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";
/**
* Specific logger to use when no mapped handler is found for a request.
* @see #PAGE_NOT_FOUND_LOG_CATEGORY
*/
protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);
/**
* Common logger for use in subclasses.
*/
protected final Log logger = LogFactory.getLog(getClass());
/**
* Provides handling for standard Spring MVC exceptions.
* @param ex the target exception
* @param request the current request
*/
@ExceptionHandler({
HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class,
HttpMediaTypeNotAcceptableException.class,
MissingPathVariableException.class,
MissingServletRequestParameterException.class,
ServletRequestBindingException.class,
ConversionNotSupportedException.class,
TypeMismatchException.class,
HttpMessageNotReadableException.class,
HttpMessageNotWritableException.class,
MethodArgumentNotValidException.class,
MissingServletRequestPartException.class,
BindException.class,
NoHandlerFoundException.class,
AsyncRequestTimeoutException.class
})
@Nullable
public final ResponseEntity<Object> handleException(Exception ex, WebRequest request) throws Exception {
HttpHeaders headers = new HttpHeaders();
if (ex instanceof HttpRequestMethodNotSupportedException) {
HttpStatus status = HttpStatus.METHOD_NOT_ALLOWED;
return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, headers, status, request);
}
else if (ex instanceof HttpMediaTypeNotSupportedException) {
HttpStatus status = HttpStatus.UNSUPPORTED_MEDIA_TYPE;
return handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException) ex, headers, status, request);
}
else if (ex instanceof HttpMediaTypeNotAcceptableException) {
HttpStatus status = HttpStatus.NOT_ACCEPTABLE;
return handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException) ex, headers, status, request);
}
else if (ex instanceof MissingPathVariableException) {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
return handleMissingPathVariable((MissingPathVariableException) ex, headers, status, request);
}
else if (ex instanceof MissingServletRequestParameterException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
return handleMissingServletRequestParameter((MissingServletRequestParameterException) ex, headers, status, request);
}
else if (ex instanceof ServletRequestBindingException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
return handleServletRequestBindingException((ServletRequestBindingException) ex, headers, status, request);
}
else if (ex instanceof ConversionNotSupportedException) {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
return handleConversionNotSupported((ConversionNotSupportedException) ex, headers, status, request);
}
else if (ex instanceof TypeMismatchException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
return handleTypeMismatch((TypeMismatchException) ex, headers, status, request);
}
else if (ex instanceof HttpMessageNotReadableException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
return handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, headers, status, request);
}
else if (ex instanceof HttpMessageNotWritableException) {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
return handleHttpMessageNotWritable((HttpMessageNotWritableException) ex, headers, status, request);
}
else if (ex instanceof MethodArgumentNotValidException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
return handleMethodArgumentNotValid((MethodArgumentNotValidException) ex, headers, status, request);
}
else if (ex instanceof MissingServletRequestPartException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
return handleMissingServletRequestPart((MissingServletRequestPartException) ex, headers, status, request);
}
else if (ex instanceof BindException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
return handleBindException((BindException) ex, headers, status, request);
}
else if (ex instanceof NoHandlerFoundException) {
HttpStatus status = HttpStatus.NOT_FOUND;
return handleNoHandlerFoundException((NoHandlerFoundException) ex, headers, status, request);
}
else if (ex instanceof AsyncRequestTimeoutException) {
HttpStatus status = HttpStatus.SERVICE_UNAVAILABLE;
return handleAsyncRequestTimeoutException((AsyncRequestTimeoutException) ex, headers, status, request);
}
else {
// Unknown exception, typically a wrapper with a common MVC exception as cause
// (since @ExceptionHandler type declarations also match first-level causes):
// We only deal with top-level MVC exceptions here, so let's rethrow the given
// exception for further processing through the HandlerExceptionResolver chain.
throw ex;
}
}
/**
* Customize the response for HttpRequestMethodNotSupportedException.
* <p>This method logs a warning, sets the "Allow" header, and delegates to
* {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(
HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
pageNotFoundLogger.warn(ex.getMessage());
Set<HttpMethod> supportedMethods = ex.getSupportedHttpMethods();
if (!CollectionUtils.isEmpty(supportedMethods)) {
headers.setAllow(supportedMethods);
}
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for HttpMediaTypeNotSupportedException.
* <p>This method sets the "Accept" header and delegates to
* {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(
HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
List<MediaType> mediaTypes = ex.getSupportedMediaTypes();
if (!CollectionUtils.isEmpty(mediaTypes)) {
headers.setAccept(mediaTypes);
if (request instanceof ServletWebRequest) {
ServletWebRequest servletWebRequest = (ServletWebRequest) request;
if (HttpMethod.PATCH.equals(servletWebRequest.getHttpMethod())) {
headers.setAcceptPatch(mediaTypes);
}
}
}
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for HttpMediaTypeNotAcceptableException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleHttpMediaTypeNotAcceptable(
HttpMediaTypeNotAcceptableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for MissingPathVariableException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
* @since 4.2
*/
protected ResponseEntity<Object> handleMissingPathVariable(
MissingPathVariableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for MissingServletRequestParameterException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleMissingServletRequestParameter(
MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for ServletRequestBindingException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleServletRequestBindingException(
ServletRequestBindingException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for ConversionNotSupportedException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleConversionNotSupported(
ConversionNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for TypeMismatchException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleTypeMismatch(
TypeMismatchException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for HttpMessageNotReadableException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleHttpMessageNotReadable(
HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for HttpMessageNotWritableException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleHttpMessageNotWritable(
HttpMessageNotWritableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for MethodArgumentNotValidException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for MissingServletRequestPartException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleMissingServletRequestPart(
MissingServletRequestPartException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for BindException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleBindException(
BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for NoHandlerFoundException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
* @since 4.0
*/
protected ResponseEntity<Object> handleNoHandlerFoundException(
NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* Customize the response for AsyncRequestTimeoutException.
* <p>This method delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param webRequest the current request
* @return a {@code ResponseEntity} instance
* @since 4.2.8
*/
@Nullable
protected ResponseEntity<Object> handleAsyncRequestTimeoutException(
AsyncRequestTimeoutException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) {
if (webRequest instanceof ServletWebRequest) {
ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
HttpServletResponse response = servletWebRequest.getResponse();
if (response != null && response.isCommitted()) {
if (logger.isWarnEnabled()) {
logger.warn("Async request timed out");
}
return null;
}
}
return handleExceptionInternal(ex, null, headers, status, webRequest);
}
/**
* A single place to customize the response body of all exception types.
* <p>The default implementation sets the {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE}
* request attribute and creates a {@link ResponseEntity} from the given
* body, headers, and status.
* @param ex the exception
* @param body the body for the response
* @param headers the headers for the response
* @param status the response status
* @param request the current request
*/
protected ResponseEntity<Object> handleExceptionInternal(
Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex, WebRequest.SCOPE_REQUEST);
}
return new ResponseEntity<>(body, headers, status);
}
}
|
// Class private_indirect_write
// Generated on Tue Nov 16 15:44:49 UTC 1999
//
class private_indirect_write {
private int foo;
class private_indirect_write_inner {
void test () {
}
class other {
void test () {
foo = 670;
}
}
}
void foo ()
{
private_indirect_write_inner inn = this.new private_indirect_write_inner ();
private_indirect_write_inner.other x = inn.new other ();
x.test ();
System.out.println ("foo="+foo);
}
public static void main (String[] arg)
{
System.out.println ("Testing class `private_indirect_write'...");
new private_indirect_write().foo ();
}
}
|
package org.dhis2.utils.customviews;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableField;
import androidx.databinding.ViewDataBinding;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import org.dhis2.BR;
import org.dhis2.R;
import org.dhis2.data.forms.dataentry.fields.datetime.OnDateSelected;
import org.dhis2.databinding.CustomCellViewBinding;
import org.dhis2.usescases.datasets.dataSetTable.dataSetSection.DataSetTableAdapter;
import org.dhis2.utils.ColorUtils;
import org.dhis2.utils.DateUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import timber.log.Timber;
/**
* QUADRAM. Created by frodriguez on 1/15/2018.
*/
public class TimeView extends FieldLayout implements View.OnClickListener {
private TextInputEditText editText;
private TextInputLayout inputLayout;
private ViewDataBinding binding;
private TextView labelText;
private OnDateSelected listener;
private String label;
private String description;
private Date date;
private View clearButton;
private View descriptionLabel;
private ImageView descriptionIcon;
public TimeView(Context context) {
super(context);
init(context);
}
public TimeView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public TimeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void setLayout() {
binding = DataBindingUtil.inflate(inflater, R.layout.date_time_view, this, true);
editText = findViewById(R.id.inputEditText);
inputLayout = findViewById(R.id.inputLayout);
labelText = findViewById(R.id.label);
descriptionLabel = findViewById(R.id.descriptionLabel);
descriptionIcon = findViewById(R.id.descIcon);
inputLayout.setHint(getContext().getString(R.string.select_time));
descriptionIcon.setImageResource(R.drawable.ic_form_time);
clearButton = findViewById(R.id.clear_button);
clearButton.setOnClickListener(v -> {
clearTime();
});
editText.setFocusable(false); //Makes editText not editable
editText.setClickable(true);// but clickable
editText.setOnFocusChangeListener(this::onFocusChanged);
editText.setOnClickListener(this);
descriptionIcon.setOnClickListener(this);
}
public void setCellLayout(ObservableField<DataSetTableAdapter.TableScale> tableScale) {
binding = DataBindingUtil.inflate(inflater, R.layout.custom_cell_view, this, true);
((CustomCellViewBinding) binding).setTableScale(tableScale);
editText = findViewById(R.id.inputEditText);
editText.setFocusable(false); //Makes editText not editable
editText.setClickable(true);// but clickable
editText.setOnFocusChangeListener(this::onFocusChanged);
editText.setOnClickListener(this);
}
public void setIsBgTransparent(boolean isBgTransparent) {
this.isBgTransparent = isBgTransparent;
setLayout();
}
public void setLabel(String label) {
this.label = label;
binding.setVariable(BR.label, label);
binding.executePendingBindings();
}
public void setDescription(String description) {
this.description = description;
descriptionLabel.setVisibility(description != null ? View.VISIBLE : View.GONE);
binding.setVariable(BR.description, description);
binding.executePendingBindings();
}
public void initData(String data) {
if (data != null) {
date = null;
try {
date = DateUtils.timeFormat().parse(data);
} catch (ParseException e) {
Timber.e(e);
}
data = date != null ? DateUtils.timeFormat().format(date) : data;
}
editText.setText(data);
updateDeleteVisibility(clearButton);
}
public void setWarning(String msg) {
inputLayout.setErrorTextAppearance(R.style.warning_appearance);
inputLayout.setError(msg);
}
public void setError(String msg) {
inputLayout.setErrorTextAppearance(R.style.error_appearance);
inputLayout.setError(msg);
editText.setText(null);
editText.requestFocus();
}
public void setMandatory() {
ImageView mandatory = binding.getRoot().findViewById(R.id.ic_mandatory);
mandatory.setVisibility(View.VISIBLE);
}
public void setDateListener(OnDateSelected listener) {
this.listener = listener;
}
private void onFocusChanged(View view, boolean b) {
if (b)
onClick(view);
}
@Override
public void onClick(View view) {
requestFocus();
activate();
final Calendar c = Calendar.getInstance();
if (date != null)
c.setTime(date);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
boolean is24HourFormat = DateFormat.is24HourFormat(getContext());
SimpleDateFormat twentyFourHourFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
SimpleDateFormat twelveHourFormat = new SimpleDateFormat("hh:mm a", Locale.getDefault());
TimePickerDialog dialog = new TimePickerDialog(getContext(), (timePicker, hourOfDay, minutes) -> {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minutes);
Date selectedDate = calendar.getTime();
String calendarTime;
if (is24HourFormat) {
calendarTime = twentyFourHourFormat.format(selectedDate);
editText.setText(calendarTime);
} else {
calendarTime = twelveHourFormat.format(selectedDate);
editText.setText(calendarTime);
}
listener.onDateSelected(selectedDate);
nextFocus(view);
date = null;
updateDeleteVisibility(clearButton);
}, hour, minute, is24HourFormat);
dialog.setTitle(label);
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getContext().getString(R.string.date_dialog_clear), (timeDialog, which) -> {
clearTime();
});
dialog.show();
}
@Override
public void dispatchSetActivated(boolean activated) {
super.dispatchSetActivated(activated);
if (activated) {
labelText.setTextColor(ColorUtils.getPrimaryColor(getContext(), ColorUtils.ColorType.PRIMARY));
} else {
labelText.setTextColor(ResourcesCompat.getColor(getResources(), R.color.textPrimary, null));
}
}
public TextInputEditText getEditText() {
return editText;
}
public void setEditable(Boolean editable) {
editText.setEnabled(editable);
clearButton.setEnabled(editable);
descriptionIcon.setEnabled(editable);
editText.setTextColor(
!isBgTransparent ? ColorUtils.getPrimaryColor(getContext(), ColorUtils.ColorType.ACCENT) :
ContextCompat.getColor(getContext(), R.color.textPrimary)
);
setEditable(editable,
labelText,
inputLayout,
findViewById(R.id.descIcon),
descriptionLabel,
clearButton
);
updateDeleteVisibility(clearButton);
}
private void clearTime() {
editText.setText(null);
listener.onDateSelected(null);
date = null;
updateDeleteVisibility(clearButton);
}
@Override
protected boolean hasValue() {
return editText.getText() != null && !editText.getText().toString().isEmpty();
}
@Override
protected boolean isEditable() {
return editText.isEnabled();
}
}
|
/*
* Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datatorrent.lib.db;
/**
* This is the base implementation for a pass-through output adapter of a transactional store.
* This implementation provides the "exactly once" guarantee.
* A concrete operator should be created from this skeleton implementation.
* <p>
* "Pass-through" means it does not wait for end window to write to the store. It will begin transaction at begin window and write to the store as the tuples
* come and commit the transaction at end window.
* </p>
* @displayName Abstract Pass Through Transactionable Store Output
* @category Store
* @tags transactional, output operator
*
* @param <T> The tuple type
* @param <S> The store type
* @since 0.9.3
*/
public abstract class AbstractPassThruTransactionableStoreOutputOperator<T, S extends TransactionableStore> extends AbstractTransactionableStoreOutputOperator<T, S>
{
@Override
public void beginWindow(long windowId)
{
super.beginWindow(windowId);
store.beginTransaction();
}
@Override
public void endWindow()
{
store.storeCommittedWindowId(appId, operatorId, currentWindowId);
store.commitTransaction();
committedWindowId = currentWindowId;
super.endWindow();
}
}
|
package colorpool.testbutton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import colorpool.core.*;
//listener per il bottone di test
public class TestButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Movements.stopBalls();
Game.getGame().pot(Game.getGame().getWhiteBall());
}
}
|
/*
* Copyright 2000-2019 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.struts.inplace.reference;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.util.ProcessingContext;
import com.intellij.util.xml.DomElement;
import org.jetbrains.annotations.NotNull;
public abstract class XmlAttributeReferenceProvider extends BaseReferenceProvider {
protected XmlAttributeReferenceProvider(final String canonicalName) {
super(canonicalName);
}
protected XmlAttributeReferenceProvider(final Class<? extends DomElement> clazz) {
super(clazz);
}
@Override
@NotNull
public PsiReference[] getReferencesByElement(@NotNull final PsiElement psiElement,
@NotNull final ProcessingContext context) {
return getReferencesByElement(psiElement);
}
public PsiReference[] getReferencesByElement(@NotNull final PsiElement psiElement) {
final String val = ((XmlAttributeValue) psiElement).getValue();
if (val.startsWith("${") ||
val.startsWith("<%")) {
return PsiReference.EMPTY_ARRAY;
}
return create((XmlAttributeValue) psiElement);
}
protected abstract PsiReference[] create(final XmlAttributeValue attribute);
}
|
/**
* Copyright © 2016-2019 The Thingsboard 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 thingsboard.dao.mapper;
import org.apache.ibatis.annotations.Param;
import thingsboard.common.data.Tenant;
import thingsboard.common.data.id.TenantId;
import thingsboard.common.data.page.TextPageLink;
import thingsboard.dao.Dao;
import java.util.List;
public interface TenantDaoMapper extends Dao<Tenant> {
/**
* Save or update tenant object
*
* @param tenant the tenant object
* @return saved tenant object
*/
Tenant save(@Param("tenantId")TenantId tenantId, @Param("tenant")Tenant tenant);
/**
* Find tenants by region and page link.
*
* @param region the region
* @param pageLink the page link
* @return the list of tenant objects
*/
List<Tenant> findTenantsByRegion(@Param("tenantId")TenantId tenantId, @Param("region")String region, @Param("pageLink")TextPageLink pageLink);
}
|
package uk.ac.strath.contextualtriggers.data;
import android.support.annotation.Nullable;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
public class StepAndGoalData extends AbstractData {
private HashMap<String, DayData> history;
public StepAndGoalData(HashMap<String, DayData> data) {
this.history = data;
}
public StepAndGoalData() {
this(new HashMap<>());
}
public Map<String, DayData> getHistory() {
return history;
}
public void updateDay(DayData day) {
history.put(day.date.toString(), day);
}
@Nullable
public DayData getDay(LocalDate day) {
return history.get(day.toString());
}
@Override
public boolean equals(Object o) {
if (o instanceof StepAndGoalData) {
boolean b = super.equals(o);
b &= ((StepAndGoalData) o).history.size() == this.history.size();
for (String s : ((StepAndGoalData) o).history.keySet()) {
b &= ((StepAndGoalData) o).history.get(s).equals(this.history.get(s));
}
return b;
}
return false;
}
public static Type getType() {
return StepAndGoalData.class;
}
}
|
package com.litongjava.modules.dev.tools.file.sync.controller;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
/**
* @author create by ping-e-lee on 2021年7月9日 下午4:42:49
* @version 1.0
* @desc
*/
@Path("/")
public class IndexController extends Controller {
public void index() {
// renderText("litongjava-dev-tools-file-sync");
// redirect("/index.html");
redirect("/backend/sync_info/sync_info_list.html");
}
public void version() {
renderText("v1.0-2021年7月9日16:44:11");
}
}
|
/**
* Copyright (c) The openTCS Authors.
*
* This program is free software and subject to the MIT license. (For details,
* see the licensing information (LICENSE.txt) you should have received with
* this copy of the software.)
*/
package org.opentcs.kernel.xmlhost.status;
import static java.util.Objects.requireNonNull;
import org.opentcs.data.TCSObjectEvent;
/**
* A command for the message dispatcher's connection handler.
*
* @author Stefan Walter (Fraunhofer IML)
*/
abstract class ConnectionCommand
implements Comparable<ConnectionCommand> {
private final int priority;
private final long creationTime;
public ConnectionCommand(int priority) {
this.priority = priority;
this.creationTime = System.currentTimeMillis();
}
@Override
public int compareTo(ConnectionCommand o) {
// Natural ordering of commands by (1) priority and (2) age.
if (priority < o.priority) {
return -1;
}
else if (priority > o.priority) {
return 1;
}
else if (this.creationTime < o.creationTime) {
return -1;
}
else if (this.creationTime > o.creationTime) {
return 1;
}
else {
return 0;
}
}
/**
* Indicates the receiving task should be terminated.
*/
public static class PoisonPill
extends ConnectionCommand {
/**
* Creates a new instance.
*/
public PoisonPill() {
super(1);
}
}
/**
* Indicates the receiving task should process an event.
*/
public static class ProcessObjectEvent
extends ConnectionCommand {
/**
* The event to be processed.
*/
private final TCSObjectEvent event;
/**
* Creates a new instance.
*
* @param event The event to be processed.
*/
public ProcessObjectEvent(TCSObjectEvent event) {
super(2);
this.event = requireNonNull(event, "event");
}
/**
* Returns the event to be processed.
*
* @return The event to be processed.
*/
public TCSObjectEvent getEvent() {
return event;
}
}
}
|
/*
* The MIT License
*
* Copyright 2015 Thibault Debatty.
*
* 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.
*/
package info.debatty.java.lsh;
import java.io.Serializable;
/**
*
* @author Thibault Debatty
*/
public class LSHSuperBit extends LSH implements Serializable {
private SuperBit sb;
/**
* LSH implementation relying on SuperBit, to bin vectors s times (stages) in b
* buckets (per stage), in a space with n dimensions. Input vectors with a high
* cosine similarity have a high probability of falling in the same bucket...
*
* Supported input types: - double[] - int[] - others to come...
*
* @param stages stages
* @param buckets buckets (per stage)
* @param dimensions dimensionality
*/
public LSHSuperBit(final int stages, final int buckets, final int dimensions) {
super(stages, buckets);
int code_length = stages * buckets / 2;
int superbit = computeSuperBit(stages, buckets, dimensions);
this.sb = new SuperBit(dimensions, superbit, code_length / superbit);
}
/**
* LSH implementation relying on SuperBit, to bin vectors s times (stages) in b
* buckets (per stage), in a space with n dimensions. Input vectors with a high
* cosine similarity have a high probability of falling in the same bucket...
*
* Supported input types: - double[] - int[] - others to come...
*
* @param stages stages
* @param buckets buckets (per stage)
* @param dimensions dimensionality
* @param seed random number generator seed. using the same value will
* guarantee identical hashes across object instantiations
*
*/
public LSHSuperBit(final int stages, final int buckets, final int dimensions, final long seed) {
super(stages, buckets);
int code_length = stages * buckets / 2;
int superbit = computeSuperBit(stages, buckets, dimensions);
this.sb = new SuperBit(dimensions, superbit, code_length / superbit, seed);
}
/**
* Compute the superbit value.
*
* @param stages
* @param buckets
* @param dimensions
* @return
*/
private int computeSuperBit(final int stages, final int buckets, final int dimensions) {
// SuperBit code length
int code_length = stages * buckets / 2;
int superbit; // superbit value
for (superbit = dimensions; superbit >= 1; superbit--) {
if (code_length % superbit == 0) {
break;
}
}
if (superbit == 0) {
throw new IllegalArgumentException("Superbit is 0 with parameters: s=" + stages + " b=" + buckets + " n=" + dimensions);
}
return superbit;
}
/**
* Empty constructor, used only for serialization.
*/
public LSHSuperBit() {
}
/**
* Hash (bin) a vector in s stages into b buckets.
*
* @param vector
* @return
*/
public final int[] hash(final double[] vector) {
return hashSignature(sb.signature(vector));
}
/**
* Hash (bin) a vector in s stages into b buckets.
*
* @param vector
* @return
*/
public final int[] hash(final int[] vector) {
double[] d = new double[vector.length];
for (int i = 0; i < vector.length; i++) {
d[i] = (double) vector[i];
}
return hash(d);
}
}
|
/*================================================================================
Copyright (c) 2013 Steve Jin. 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 names of copyright holders 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 COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class HostVMotionNetConfig extends DynamicData {
public HostVirtualNic[] candidateVnic;
public String selectedVnic;
public HostVirtualNic[] getCandidateVnic() {
return this.candidateVnic;
}
public String getSelectedVnic() {
return this.selectedVnic;
}
public void setCandidateVnic(HostVirtualNic[] candidateVnic) {
this.candidateVnic=candidateVnic;
}
public void setSelectedVnic(String selectedVnic) {
this.selectedVnic=selectedVnic;
}
}
|
package in.jvapps.disable_battery_optimization;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import com.thelittlefireman.appkillermanager.managers.KillerManager;
import java.util.List;
import in.jvapps.disable_battery_optimization.utils.BatteryOptimizationUtil;
import in.jvapps.disable_battery_optimization.utils.PrefKeys;
import in.jvapps.disable_battery_optimization.utils.PrefUtils;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;
/**
* DisableBatteryOptimizationPlugin
*/
public class DisableBatteryOptimizationPlugin implements FlutterPlugin, ActivityAware, MethodCallHandler {
private Context mContext;
private Activity mActivity;
// These are null when not using v2 embedding.
private MethodChannel channel;
private static final int REQUEST_DISABLE_BATTERY_OPTIMIZATIONS = 2244;
private final String TAG = "DisableOptimization";
private static final String CHANNEL_NAME = "in.jvapps.disable_battery_optimization";
private String autoStartTitle;
private String autoStartMessage;
private String manBatteryTitle;
private String manBatteryMessage;
// This static function is optional and equivalent to onAttachedToEngine. It supports the old
// pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
// plugin registration via this function while apps migrate to use the new Android APIs
// post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
//
// It is encouraged to share logic between onAttachedToEngine and registerWith to keep
// them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
// depending on the user's project. onAttachedToEngine or registerWith must both be defined
// in the same class.
public static void registerWith(PluginRegistry.Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), CHANNEL_NAME);
channel.setMethodCallHandler(new DisableBatteryOptimizationPlugin(registrar.activity(), registrar.activeContext()));
}
private DisableBatteryOptimizationPlugin(Activity activity, Context context) {
if (activity != null)
mActivity = activity;
if (context != null)
mContext = context;
}
/**
* Default constructor for DisableBatteryOptimizationPlugin.
*
* <p>Use this constructor when adding this plugin to an app with v2 embedding.
*/
public DisableBatteryOptimizationPlugin() {
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
switch (call.method) {
case "showEnableAutoStart":
try {
List arguments = (List) call.arguments;
if (arguments != null) {
autoStartTitle = String.valueOf(arguments.get(0));
autoStartMessage = String.valueOf(arguments.get(1));
showAutoStartEnabler(null, null);
result.success(true);
} else {
Log.e(TAG, "Unable to request enableAutoStart. Arguments are null");
result.success(false);
}
} catch (Exception ex) {
Log.e(TAG, "Exception in showEnableAutoStart. " + ex.toString());
result.success(false);
}
break;
case "showDisableManBatteryOptimization":
try {
List arguments = (List) call.arguments;
if (arguments != null) {
manBatteryTitle = String.valueOf(arguments.get(0));
manBatteryMessage = String.valueOf(arguments.get(1));
showManBatteryOptimizationDisabler(false);
result.success(true);
} else {
Log.e(TAG, "Unable to request disable manufacturer battery optimization. Arguments are null");
result.success(false);
}
} catch (Exception ex) {
Log.e(TAG, "Exception in showDisableManBatteryOptimization. " + ex.toString());
result.success(false);
}
break;
case "showDisableBatteryOptimization":
try {
showIgnoreBatteryPermissions();
result.success(true);
} catch (Exception ex) {
Log.e(TAG, "Exception in showDisableBatteryOptimization. " + ex.toString());
result.success(false);
}
break;
case "disableAllOptimizations":
try {
List arguments = (List) call.arguments;
if (arguments != null) {
autoStartTitle = String.valueOf(arguments.get(0));
autoStartMessage = String.valueOf(arguments.get(1));
manBatteryTitle = String.valueOf(arguments.get(2));
manBatteryMessage = String.valueOf(arguments.get(3));
handleIgnoreAllBatteryPermission();
result.success(true);
} else {
Log.e(TAG, "Unable to request disable all optimizations. Arguments are null");
result.success(false);
}
} catch (Exception ex) {
Log.e(TAG, "Exception in disableAllOptimizations. " + ex.toString());
result.success(false);
}
break;
case "isAutoStartEnabled":
result.success(getManAutoStart());
break;
case "isBatteryOptimizationDisabled":
result.success(BatteryOptimizationUtil.isIgnoringBatteryOptimizations(mContext));
break;
case "isManBatteryOptimizationDisabled":
result.success(getManBatteryOptimization());
break;
case "isAllOptimizationsDisabled":
result.success(getManAutoStart() && BatteryOptimizationUtil.isIgnoringBatteryOptimizations(mContext) && getManBatteryOptimization());
break;
default:
result.notImplemented();
}
}
@Override
public void onAttachedToEngine(FlutterPluginBinding binding) {
channel = new MethodChannel(binding.getBinaryMessenger(), CHANNEL_NAME);
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
}
@Override
public void onAttachedToActivity(ActivityPluginBinding binding) {
mActivity = binding.getActivity();
mContext = mActivity.getApplicationContext();
channel.setMethodCallHandler(this);
}
@Override
public void onDetachedFromActivityForConfigChanges() {
mActivity = null;
}
@Override
public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) {
mActivity = binding.getActivity();
}
@Override
public void onDetachedFromActivity() {
mActivity = null;
channel.setMethodCallHandler(null);
}
private void showAutoStartEnabler(@NonNull final BatteryOptimizationUtil.OnBatteryOptimizationAccepted positiveCallback,
@NonNull final BatteryOptimizationUtil.OnBatteryOptimizationCanceled negativeCallback) {
BatteryOptimizationUtil.showBatteryOptimizationDialog(
mContext,
KillerManager.Actions.ACTION_AUTOSTART,
autoStartTitle,
autoStartMessage,
positiveCallback,
negativeCallback
);
}
private void showManBatteryOptimizationDisabler(boolean isRequestNativeBatteryOptimizationDisabler) {
BatteryOptimizationUtil.showBatteryOptimizationDialog(
mContext,
KillerManager.Actions.ACTION_POWERSAVING,
manBatteryTitle,
manBatteryMessage,
() -> {
setManBatteryOptimization(true);
if (isRequestNativeBatteryOptimizationDisabler) {
showIgnoreBatteryPermissions();
}
},
() -> {
if (isRequestNativeBatteryOptimizationDisabler) {
showIgnoreBatteryPermissions();
}
}
);
}
private void showIgnoreBatteryPermissions() {
if (!BatteryOptimizationUtil.isIgnoringBatteryOptimizations(mContext)) {
final Intent ignoreBatteryOptimizationsIntent = BatteryOptimizationUtil.getIgnoreBatteryOptimizationsIntent(mContext);
if (ignoreBatteryOptimizationsIntent != null) {
mContext.startActivity(ignoreBatteryOptimizationsIntent);
} else {
Log.i(TAG, "Can't ignore the battery optimization as the intent is null");
}
} else {
Log.i(TAG, "Battery optimization is already disabled");
}
}
private void handleIgnoreAllBatteryPermission() {
boolean isManBatteryOptimizationDisabled = getManBatteryOptimization();
if (!getManAutoStart()) {
showAutoStartEnabler(() -> {
setManAutoStart(true);
if (!isManBatteryOptimizationDisabled)
showManBatteryOptimizationDisabler(true);
else
showIgnoreBatteryPermissions();
}, () -> {
if (!isManBatteryOptimizationDisabled)
showManBatteryOptimizationDisabler(true);
else
showIgnoreBatteryPermissions();
});
} else {
if (!isManBatteryOptimizationDisabled)
showManBatteryOptimizationDisabler(true);
else
showIgnoreBatteryPermissions();
}
}
public void setManBatteryOptimization(boolean val) {
PrefUtils.saveToPrefs(mContext, PrefKeys.IS_MAN_BATTERY_OPTIMIZATION_ACCEPTED, val);
}
public boolean getManBatteryOptimization() {
return (boolean) PrefUtils.getFromPrefs(mContext, PrefKeys.IS_MAN_BATTERY_OPTIMIZATION_ACCEPTED, false);
}
public void setManAutoStart(boolean val) {
PrefUtils.saveToPrefs(mContext, PrefKeys.IS_MAN_AUTO_START_ACCEPTED, val);
}
public boolean getManAutoStart() {
return (boolean) PrefUtils.getFromPrefs(mContext, PrefKeys.IS_MAN_AUTO_START_ACCEPTED, false);
}
}
|
package com.sanshengshui.netty.client;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
@Sharable
public class ClientHandler extends SimpleChannelInboundHandler<String> {
/**
* 接受server返回的信息
*
* @param ctx 保存 Channel 相关的所有上下文信息,同时关联一个 ChannelHandler 对象。
* @param msg 信息
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.err.println(msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
|
package me.lusory.relate.query.operation;
import org.springframework.data.relational.core.mapping.RelationalPersistentEntity;
import reactor.core.publisher.Mono;
import java.util.HashSet;
import java.util.Set;
abstract class AbstractProcessor<R extends AbstractProcessor.Request> {
protected abstract Mono<Void> executeRequests(Operation op);
protected boolean canExecuteRequest(R request) {
if (!request.canExecute()) {
return false;
}
request.dependencies.removeIf(Request::isDone);
return request.dependencies.isEmpty();
}
protected Mono<Void> doOperations(Operation op) {
return executeRequests(op);
}
abstract static class Request {
RelationalPersistentEntity<?> entityType;
boolean executed = false;
Set<Request> dependencies = new HashSet<>();
<T> Request(RelationalPersistentEntity<T> entityType) {
this.entityType = entityType;
}
void dependsOn(Request dependency) {
if (dependency.dependencies.contains(this)) {
throw new IllegalStateException("Cyclic dependency between requests");
}
dependencies.add(dependency);
}
protected boolean canExecute() {
return !executed;
}
protected boolean isDone() {
return executed;
}
}
}
|
package rp.util;
import java.util.Hashtable;
import lejos.robotics.RangeReadings;
import rp.config.RangeScannerDescription;
/**
*
* Utility functions to make using certain sensors easier.
*
* @author Nick Hawes
*
*/
public abstract class SensorUtils {
public static final Hashtable<Integer, String> COLOUR_NAMES;
static {
COLOUR_NAMES = new Hashtable<Integer, String>();
COLOUR_NAMES.put(0, "black");
COLOUR_NAMES.put(1, "violet");
COLOUR_NAMES.put(2, "purple");
COLOUR_NAMES.put(3, "blue");
COLOUR_NAMES.put(4, "green");
COLOUR_NAMES.put(5, "lime");
COLOUR_NAMES.put(6, "yellow");
COLOUR_NAMES.put(7, "orange");
COLOUR_NAMES.put(8, "red");
COLOUR_NAMES.put(9, "crimson");
COLOUR_NAMES.put(10, "magenta");
COLOUR_NAMES.put(11, "pastel");
COLOUR_NAMES.put(12, "pastel");
COLOUR_NAMES.put(13, "pastel");
COLOUR_NAMES.put(14, "pastel");
COLOUR_NAMES.put(15, "pastel");
COLOUR_NAMES.put(16, "pastel");
COLOUR_NAMES.put(17, "white");
}
public static String toColourName(int _colourNumber) {
return COLOUR_NAMES.get(_colourNumber);
}
/**
* Return a list of range readings which are the minimum for each individual
* reading paired across the inputs.
*
* @param _r1
* @param _r2
* @return
*/
public static RangeReadings getMinimumValues(RangeReadings _r1,
RangeReadings _r2) {
RangeReadings jointReadings = new RangeReadings(_r2.getNumReadings());
assert _r1.size() <= _r2.size();
for (int i = 0; i < _r2.getNumReadings(); i++) {
assert _r1.getAngle(i) == _r2.getAngle(i);
float map = _r1.getRange(i);
float obs = _r2.getRange(i);
// System.out.println("map: " + mapReadings.getRange(i));
// System.out.println("obs: " + obstacleReadings.getRange(i));
if (RangeScannerDescription.isValidReading(map)
&& RangeScannerDescription.isValidReading(obs)) {
jointReadings.setRange(i, _r1.getAngle(i), Math.min(map, obs));
} else if (!RangeScannerDescription.isValidReading(map)) {
jointReadings.setRange(i, _r1.getAngle(i), obs);
} else {
jointReadings.setRange(i, _r1.getAngle(i), map);
}
}
return jointReadings;
}
}
|
package com.android.assistant;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class CollegeAdapter extends RecyclerView.Adapter<CollegeAdapter.ViewHolder>{
private List<College> mCollegeList;
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.college_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
holder.collegeName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
College college = mCollegeList.get(position);
String collegeName = college.getName();
int collegeImageId = college.getImageId();
SharedPreferences preferences = parent.getContext().getSharedPreferences("data", Context.MODE_PRIVATE);
String imageId = preferences.getString(collegeName, "");
String collegeContent = preferences.getString(collegeName + "介绍", "");
Intent intent = new Intent(parent.getContext(), CollegeActivity.class);
intent.putExtra(CollegeActivity.COLLEGE_NAME, collegeName);
intent.putExtra(CollegeActivity.COLLEGE_IMAGE_ID, imageId);
intent.putExtra("学院介绍", collegeContent);
// intent.putExtra(CollegeActivity.COLLEGE_IMAGE_ID, collegeImageId);
parent.getContext().startActivity(intent);
}
});
holder.collegeImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
College college = mCollegeList.get(position);
String collegeName = college.getName();
int collegeImageId = college.getImageId();
SharedPreferences preferences = parent.getContext().getSharedPreferences("data", Context.MODE_PRIVATE);
String imageId = preferences.getString(collegeName, "");
String collegeContent = preferences.getString(collegeName + "介绍", "");
Intent intent = new Intent(parent.getContext(), CollegeActivity.class);
intent.putExtra(CollegeActivity.COLLEGE_NAME, collegeName);
intent.putExtra(CollegeActivity.COLLEGE_IMAGE_ID, imageId);
intent.putExtra("学院介绍", collegeContent);
// intent.putExtra(CollegeActivity.COLLEGE_IMAGE_ID, collegeImageId);
parent.getContext().startActivity(intent);
}
});
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
College college = mCollegeList.get(position);
holder.collegeImage.setImageResource(college.getImageId());
holder.collegeName.setText(college.getName());
}
@Override
public int getItemCount() {
return mCollegeList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder{
ImageView collegeImage;
TextView collegeName;
public ViewHolder(@NonNull View itemView) {
super(itemView);
collegeImage = (ImageView) itemView.findViewById(R.id.college_image);
collegeName = (TextView) itemView.findViewById(R.id.college_name);
}
}
public CollegeAdapter(List<College> collegeList){
mCollegeList = collegeList;
}
}
|
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.debug.gui.breakpoint;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.util.*;
import java.util.stream.Collectors;
import javax.swing.SwingUtilities;
import docking.ActionContext;
import docking.Tool;
import docking.action.*;
import docking.actions.PopupActionProvider;
import ghidra.app.context.ProgramLocationActionContext;
import ghidra.app.events.ProgramClosedPluginEvent;
import ghidra.app.events.ProgramOpenedPluginEvent;
import ghidra.app.plugin.PluginCategoryNames;
import ghidra.app.plugin.core.debug.DebuggerPluginPackage;
import ghidra.app.plugin.core.debug.event.TraceClosedPluginEvent;
import ghidra.app.plugin.core.debug.event.TraceOpenedPluginEvent;
import ghidra.app.plugin.core.debug.gui.DebuggerResources;
import ghidra.app.plugin.core.debug.gui.DebuggerResources.*;
import ghidra.app.services.*;
import ghidra.app.services.LogicalBreakpoint.State;
import ghidra.app.util.viewer.listingpanel.MarkerClickedListener;
import ghidra.async.AsyncDebouncer;
import ghidra.async.AsyncTimer;
import ghidra.framework.options.AutoOptions;
import ghidra.framework.options.annotation.*;
import ghidra.framework.plugintool.*;
import ghidra.framework.plugintool.annotation.AutoServiceConsumed;
import ghidra.framework.plugintool.util.PluginStatus;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.listing.*;
import ghidra.program.util.*;
import ghidra.trace.model.Trace;
import ghidra.trace.model.TraceLocation;
import ghidra.trace.model.breakpoint.TraceBreakpointKind;
import ghidra.trace.model.breakpoint.TraceBreakpointKind.TraceBreakpointKindSet;
import ghidra.trace.model.program.TraceProgramView;
import ghidra.util.Msg;
@PluginInfo(
shortDescription = "Debugger breakpoint marker service plugin",
description = "Marks logical breakpoints and provides actions in the listings",
category = PluginCategoryNames.DEBUGGER,
packageName = DebuggerPluginPackage.NAME,
status = PluginStatus.RELEASED,
eventsConsumed = {
ProgramOpenedPluginEvent.class,
ProgramClosedPluginEvent.class,
TraceOpenedPluginEvent.class,
TraceClosedPluginEvent.class,
},
servicesRequired = {
DebuggerLogicalBreakpointService.class,
MarkerService.class,
})
public class DebuggerBreakpointMarkerPlugin extends Plugin
implements PopupActionProvider {
protected static Address computeAddressFromContext(ActionContext context) {
if (context == null) {
return null;
}
if (context instanceof ProgramLocationActionContext) {
ProgramLocationActionContext ctx = (ProgramLocationActionContext) context;
if (ctx.hasSelection()) {
ProgramSelection sel = ctx.getSelection();
AddressRange range = sel.getRangeContaining(ctx.getAddress());
if (range != null) {
return range.getMinAddress();
}
}
return ctx.getAddress();
}
Object obj = context.getContextObject();
if (obj instanceof MarkerLocation) {
MarkerLocation ml = (MarkerLocation) obj;
return ml.getAddr();
}
return null;
}
/**
* Attempt to derive a location from the given context
*
* <p>
* Currently, this supports {@link ProgramLocationActionContext} and {@link MarkerLocation}.
*
* @param context a possible location context
* @return the program location, or {@code null}
*/
protected static ProgramLocation getLocationFromContext(ActionContext context) {
if (context == null) {
return null;
}
if (context instanceof ProgramLocationActionContext) {
ProgramLocationActionContext ctx = (ProgramLocationActionContext) context;
if (ctx.hasSelection()) {
ProgramSelection sel = ctx.getSelection();
AddressRange range = sel.getRangeContaining(ctx.getAddress());
if (range != null) {
return new ProgramLocation(ctx.getProgram(), range.getMinAddress());
}
}
return ctx.getLocation();
}
Object obj = context.getContextObject();
if (obj instanceof MarkerLocation) {
MarkerLocation ml = (MarkerLocation) obj;
return new ProgramLocation(ml.getProgram(), ml.getAddr());
}
return null;
}
protected static long computeLengthFromContext(ActionContext context) {
if (context == null) {
return 1;
}
if (context instanceof ProgramLocationActionContext) {
ProgramLocationActionContext ctx = (ProgramLocationActionContext) context;
if (ctx.hasSelection()) {
ProgramSelection sel = ctx.getSelection();
AddressRange range = sel.getRangeContaining(ctx.getAddress());
if (range != null) {
return range.getLength();
}
}
CodeUnit cu = ctx.getCodeUnit();
if (cu instanceof Data) {
return cu.getLength();
}
}
return 1;
}
protected static boolean contextHasLocation(ActionContext context) {
return getLocationFromContext(context) != null;
}
protected static Trace getTraceFromContext(ActionContext context) {
ProgramLocation loc = getLocationFromContext(context);
if (loc == null) {
return null;
}
Program progOrView = loc.getProgram();
if (progOrView instanceof TraceProgramView) {
TraceProgramView view = (TraceProgramView) progOrView;
return view.getTrace();
}
return null;
}
protected static boolean contextHasTrace(ActionContext context) {
return getTraceFromContext(context) != null;
}
protected static long computeDefaultLength(ActionContext context,
Collection<TraceBreakpointKind> selected) {
if (selected.isEmpty() ||
selected.contains(TraceBreakpointKind.HW_EXECUTE) ||
selected.contains(TraceBreakpointKind.SW_EXECUTE)) {
return 1;
}
return computeLengthFromContext(context);
}
protected static Set<TraceBreakpointKind> computeDefaultKinds(ActionContext ctx,
Collection<TraceBreakpointKind> supported) {
if (supported.isEmpty()) {
return Set.of();
}
long length = computeLengthFromContext(ctx);
if (length == 1) {
ProgramLocation loc = getLocationFromContext(ctx);
Listing listing = loc.getProgram().getListing();
CodeUnit cu = listing.getCodeUnitContaining(loc.getAddress());
if (cu instanceof Instruction) {
if (supported.contains(TraceBreakpointKind.SW_EXECUTE)) {
return Set.of(TraceBreakpointKind.SW_EXECUTE);
}
else if (supported.contains(TraceBreakpointKind.HW_EXECUTE)) {
return Set.of(TraceBreakpointKind.HW_EXECUTE);
}
return Set.of();
}
Data data = (Data) cu;
if (!data.isDefined()) {
if (supported.size() == 1) {
return Set.copyOf(supported);
}
return Set.of();
}
}
// TODO: Consider memory protections?
Set<TraceBreakpointKind> result =
new HashSet<>(Set.of(TraceBreakpointKind.READ, TraceBreakpointKind.WRITE));
result.retainAll(supported);
return result;
}
protected Color colorForState(State state) {
if (state.isEnabled()) {
if (state.isEffective()) {
return breakpointEnabledMarkerColor;
}
else {
return breakpointIneffEnMarkerColor;
}
}
else {
if (state.isEffective()) {
return breakpointDisabledMarkerColor;
}
else {
return breakpointIneffDisMarkerColor;
}
}
}
protected boolean stateColorsBackground(State state) {
if (state.isEnabled()) {
if (state.isEffective()) {
return breakpointEnabledColoringBackground;
}
else {
return breakpointIneffEnColoringBackground;
}
}
else {
if (state.isEffective()) {
return breakpointDisabledColoringBackground;
}
else {
return breakpointIneffDisColoringBackground;
}
}
}
/**
* A variety of marker sets (one for each logical state) attached to a program or trace view
*/
protected class BreakpointMarkerSets {
final Program program;
final Map<State, MarkerSet> sets = new HashMap<>();
protected BreakpointMarkerSets(Program program) {
this.program = program;
// Prevent default bookmark icons from obscuring breakpoints
if (!(program instanceof TraceProgramView)) {
BookmarkManager manager = program.getBookmarkManager();
manager.defineType(LogicalBreakpoint.BREAKPOINT_ENABLED_BOOKMARK_TYPE,
DebuggerResources.ICON_BLANK,
DebuggerResources.DEFAULT_COLOR_ENABLED_BREAKPOINT_MARKERS,
MarkerService.BREAKPOINT_PRIORITY - 1);
manager.defineType(LogicalBreakpoint.BREAKPOINT_DISABLED_BOOKMARK_TYPE,
DebuggerResources.ICON_BLANK,
DebuggerResources.DEFAULT_COLOR_ENABLED_BREAKPOINT_MARKERS,
MarkerService.BREAKPOINT_PRIORITY - 1);
}
for (State state : State.values()) {
getMarkerSet(state);
}
}
MarkerSet getMarkerSet(State state) {
return sets.computeIfAbsent(state, this::doGetMarkerSet);
}
MarkerSet doGetMarkerSet(State state) {
if (state.icon == null) {
return null;
}
MarkerSet set = markerService.getMarkerSet(state.display, program);
if (set != null) {
return set;
}
return markerService.createPointMarker(state.display, state.display, program,
MarkerService.BREAKPOINT_PRIORITY, true, true, stateColorsBackground(state),
colorForState(state), state.icon, true);
}
public void setEnabledMarkerColor(Color color) {
for (State state : State.values()) {
if (state == State.NONE || !state.isEnabled() || !state.isEffective()) {
continue;
}
getMarkerSet(state).setMarkerColor(color);
}
}
public void setDisabledMarkerColor(Color color) {
for (State state : State.values()) {
if (state == State.NONE || state.isEnabled() || !state.isEffective()) {
continue;
}
getMarkerSet(state).setMarkerColor(color);
}
}
public void setIneffectiveEnabledMarkerColor(Color color) {
for (State state : State.values()) {
if (state == State.NONE || !state.isEnabled() || state.isEffective()) {
continue;
}
getMarkerSet(state).setMarkerColor(color);
}
}
public void setIneffectiveDisabledMarkerColor(Color color) {
for (State state : State.values()) {
if (state == State.NONE || state.isEnabled() || state.isEffective()) {
continue;
}
getMarkerSet(state).setMarkerColor(color);
}
}
public void setEnabledColoringBackground(boolean coloringBackground) {
for (State state : State.values()) {
if (state == State.NONE || !state.isEnabled() || !state.isEffective()) {
continue;
}
getMarkerSet(state).setColoringBackground(coloringBackground);
}
}
public void setDisabledColoringBackground(boolean coloringBackground) {
for (State state : State.values()) {
if (state == State.NONE || state.isEnabled() || !state.isEffective()) {
continue;
}
getMarkerSet(state).setColoringBackground(coloringBackground);
}
}
public void setIneffectiveEnabledColoringBackground(boolean coloringBackground) {
for (State state : State.values()) {
if (state == State.NONE || !state.isEnabled() || state.isEffective()) {
continue;
}
getMarkerSet(state).setColoringBackground(coloringBackground);
}
}
public void setIneffectiveDisabledColoringBackground(boolean coloringBackground) {
for (State state : State.values()) {
if (state == State.NONE || state.isEnabled() || state.isEffective()) {
continue;
}
getMarkerSet(state).setColoringBackground(coloringBackground);
}
}
public void dispose() {
for (State state : State.values()) {
MarkerSet set = sets.get(state);
if (set != null) {
markerService.removeMarker(set, program);
}
}
}
public void clear() {
for (State state : State.values()) {
MarkerSet set = sets.get(state);
if (set != null) {
set.clearAll();
}
}
}
}
private class UpdateMarksBreakpointRecordChangeListener
implements LogicalBreakpointsChangeListener {
@Override
public void breakpointAdded(LogicalBreakpoint breakpoint) {
updateDebouncer.contact(null);
}
@Override
public void breakpointUpdated(LogicalBreakpoint breakpoint) {
updateDebouncer.contact(null);
}
@Override
public void breakpointRemoved(LogicalBreakpoint breakpoint) {
updateDebouncer.contact(null);
}
}
private class ToggleBreakpointsMarkerClickedListener implements MarkerClickedListener {
@Override
public void markerDoubleClicked(MarkerLocation location) {
ProgramLocationActionContext context =
new ProgramLocationActionContext(null, location.getProgram(),
new ProgramLocation(location.getProgram(), location.getAddr()), null, null);
if (contextCanManipulateBreakpoints(context)) {
doToggleBreakpointsAt(ToggleBreakpointAction.NAME, context);
}
}
}
protected static State computeState(LogicalBreakpoint breakpoint, Program programOrView) {
if (programOrView instanceof TraceProgramView) {
TraceProgramView view = (TraceProgramView) programOrView;
return breakpoint.computeStateForTrace(view.getTrace());
}
// Program view should consider all trace placements
// TODO: A mode for only considering the current trace (for effectiveness in program)
return breakpoint.computeState();
}
/**
* It seems the purpose of this was to omit the program mode from the dynamic listing. I don't
* think we need that anymore, so I've just delegated to exactly the same as the breakpoint
* service, which will include the program mode, if applicable. TODO: Remove this and just call
* the service's version directly?
*
* @param loc
* @return
*/
protected State computeState(ProgramLocation loc) {
return breakpointService.computeState(loc);
}
protected class ToggleBreakpointAction extends AbstractToggleBreakpointAction {
public static final String GROUP = DebuggerResources.GROUP_BREAKPOINTS;
public ToggleBreakpointAction() {
super(DebuggerBreakpointMarkerPlugin.this);
setKeyBindingData(new KeyBindingData(KeyEvent.VK_K, 0));
setPopupMenuData(new MenuData(new String[] { NAME }, ICON, GROUP));
tool.addAction(this);
setEnabled(true);
}
@Override
public void actionPerformed(ActionContext context) {
doToggleBreakpointsAt(NAME, context);
}
@Override
public boolean isEnabledForContext(ActionContext context) {
if (!contextCanManipulateBreakpoints(context)) {
return false;
}
return true;
}
}
protected class SetBreakpointAction extends AbstractSetBreakpointAction {
public static final String GROUP = DebuggerResources.GROUP_BREAKPOINTS;
private final Set<TraceBreakpointKind> kinds;
public SetBreakpointAction(Set<TraceBreakpointKind> kinds) {
super(DebuggerBreakpointMarkerPlugin.this);
this.kinds = kinds;
setPopupMenuData(new MenuData(
new String[] { NAME, TraceBreakpointKindSet.encode(kinds) }, ICON, GROUP));
tool.addAction(this);
setEnabled(true);
}
@Override
public void actionPerformed(ActionContext context) {
if (!contextCanManipulateBreakpoints(context)) {
return;
}
ProgramLocation location = getLocationFromContext(context);
long length = computeDefaultLength(context, kinds);
placeBreakpointDialog.prompt(tool, breakpointService, NAME, location, length, kinds,
"");
}
@Override
public boolean isEnabledForContext(ActionContext context) {
if (!contextCanManipulateBreakpoints(context)) {
return false;
}
ProgramLocation loc = getLocationFromContext(context);
if (!(loc.getProgram() instanceof TraceProgramView)) {
return true;
}
TraceRecorder recorder = getRecorderFromContext(context);
if (recorder == null) {
return false;
}
if (!recorder.getSupportedBreakpointKinds().containsAll(kinds)) {
return false;
}
return true;
}
}
protected class EnableBreakpointAction extends AbstractEnableBreakpointAction {
public static final String GROUP = DebuggerResources.GROUP_BREAKPOINTS;
public EnableBreakpointAction() {
super(DebuggerBreakpointMarkerPlugin.this);
setPopupMenuData(new MenuData(new String[] { NAME }, ICON, GROUP));
tool.addAction(this);
setEnabled(true);
}
@Override
public void actionPerformed(ActionContext context) {
if (!contextCanManipulateBreakpoints(context)) {
return;
}
ProgramLocation location = getLocationFromContext(context);
Set<LogicalBreakpoint> col = breakpointService.getBreakpointsAt(location);
breakpointService.enableAll(col, getTraceFromContext(context)).exceptionally(ex -> {
breakpointError(NAME, "Could not enable breakpoint", ex);
return null;
});
}
@Override
public boolean isEnabledForContext(ActionContext context) {
if (!contextCanManipulateBreakpoints(context)) {
return false;
}
ProgramLocation location = getLocationFromContext(context);
State state = computeState(location);
if (state == State.ENABLED || state == State.NONE) {
return false;
}
return true;
}
}
protected class DisableBreakpointAction extends AbstractDisableBreakpointAction {
public static final String GROUP = DebuggerResources.GROUP_BREAKPOINTS;
public DisableBreakpointAction() {
super(DebuggerBreakpointMarkerPlugin.this);
setPopupMenuData(new MenuData(new String[] { NAME }, ICON, GROUP));
tool.addAction(this);
setEnabled(true);
}
@Override
public void actionPerformed(ActionContext context) {
if (!contextCanManipulateBreakpoints(context)) {
return;
}
ProgramLocation location = getLocationFromContext(context);
Set<LogicalBreakpoint> col = breakpointService.getBreakpointsAt(location);
breakpointService.disableAll(col, getTraceFromContext(context)).exceptionally(ex -> {
breakpointError(NAME, "Could not disable breakpoint", ex);
return null;
});
}
@Override
public boolean isEnabledForContext(ActionContext context) {
if (!contextCanManipulateBreakpoints(context)) {
return false;
}
ProgramLocation location = getLocationFromContext(context);
State state = computeState(location);
if (state == State.DISABLED || state == State.NONE) {
return false;
}
return true;
}
}
// TODO: Make sub-menu listing all breakpoints present here?
// TODO: If so, include a "remove all" (at this address) action
protected class ClearBreakpointAction extends AbstractClearBreakpointAction {
public static final String GROUP = DebuggerResources.GROUP_BREAKPOINTS;
public ClearBreakpointAction() {
super(DebuggerBreakpointMarkerPlugin.this);
setPopupMenuData(new MenuData(new String[] { NAME }, ICON, GROUP));
tool.addAction(this);
setEnabled(true);
}
@Override
public void actionPerformed(ActionContext context) {
if (!contextCanManipulateBreakpoints(context)) {
return;
}
ProgramLocation location = getLocationFromContext(context);
Set<LogicalBreakpoint> col = breakpointService.getBreakpointsAt(location);
breakpointService.deleteAll(col, getTraceFromContext(context)).exceptionally(ex -> {
breakpointError(NAME, "Could not delete breakpoint", ex);
return null;
});
}
@Override
public boolean isEnabledForContext(ActionContext context) {
if (!contextCanManipulateBreakpoints(context)) {
return false;
}
ProgramLocation location = getLocationFromContext(context);
State state = computeState(location);
if (state == State.NONE) {
return false;
}
return true;
}
}
// @AutoServiceConsumed via method
private MarkerService markerService;
// @AutoServiceConsumed via method
private DebuggerLogicalBreakpointService breakpointService;
@AutoServiceConsumed
private DebuggerModelService modelService;
@AutoServiceConsumed
private DebuggerStaticMappingService mappingService;
@AutoServiceConsumed
private DebuggerTraceManagerService traceManager;
@AutoServiceConsumed
private DebuggerConsoleService consoleService;
@SuppressWarnings("unused")
private final AutoService.Wiring autoServiceWiring;
@AutoOptionDefined(
name = DebuggerResources.OPTION_NAME_COLORS_ENABLED_BREAKPOINT_MARKERS, //
description = "Background color for memory at an enabled breakpoint", //
help = @HelpInfo(anchor = "colors"))
private Color breakpointEnabledMarkerColor =
DebuggerResources.DEFAULT_COLOR_ENABLED_BREAKPOINT_MARKERS;
@AutoOptionDefined(
name = DebuggerResources.OPTION_NAME_COLORS_ENABLED_BREAKPOINT_COLORING_BACKGROUND, //
description = "Whether or not to color background for memory at an enabled breakpoint", //
help = @HelpInfo(anchor = "colors"))
private boolean breakpointEnabledColoringBackground =
DebuggerResources.DEFAULT_COLOR_ENABLED_BREAKPOINT_COLORING_BACKGROUND;
@AutoOptionDefined(
name = DebuggerResources.OPTION_NAME_COLORS_DISABLED_BREAKPOINT_MARKERS, //
description = "Background color for memory at a disabled breakpoint", //
help = @HelpInfo(anchor = "colors"))
private Color breakpointDisabledMarkerColor =
DebuggerResources.DEFAULT_COLOR_DISABLED_BREAKPOINT_MARKERS;
@AutoOptionDefined(
name = DebuggerResources.OPTION_NAME_COLORS_DISABLED_BREAKPOINT_COLORING_BACKGROUND, //
description = "Whether or not to color background for memory at a disabled breakpoint", //
help = @HelpInfo(anchor = "colors"))
private boolean breakpointDisabledColoringBackground =
DebuggerResources.DEFAULT_COLOR_DISABLED_BREAKPOINT_COLORING_BACKGROUND;
@AutoOptionDefined(
name = DebuggerResources.OPTION_NAME_COLORS_INEFF_EN_BREAKPOINT_MARKERS, //
description = "Background color for memory at an enabled, but ineffective, breakpoint", //
help = @HelpInfo(anchor = "colors"))
private Color breakpointIneffEnMarkerColor =
DebuggerResources.DEFAULT_COLOR_INEFF_EN_BREAKPOINT_MARKERS;
@AutoOptionDefined(
name = DebuggerResources.OPTION_NAME_COLORS_INEFF_EN_BREAKPOINT_COLORING_BACKGROUND, //
description = "Whether or not to color background for memory at an enabled, but ineffective, breakpoint", //
help = @HelpInfo(anchor = "colors"))
private boolean breakpointIneffEnColoringBackground =
DebuggerResources.DEFAULT_COLOR_INEFF_EN_BREAKPOINT_COLORING_BACKGROUND;
@AutoOptionDefined(
name = DebuggerResources.OPTION_NAME_COLORS_INEFF_DIS_BREAKPOINT_MARKERS, //
description = "Background color for memory at an disabled, but ineffective, breakpoint", //
help = @HelpInfo(anchor = "colors"))
private Color breakpointIneffDisMarkerColor =
DebuggerResources.DEFAULT_COLOR_INEFF_DIS_BREAKPOINT_MARKERS;
@AutoOptionDefined(
name = DebuggerResources.OPTION_NAME_COLORS_INEFF_DIS_BREAKPOINT_COLORING_BACKGROUND, //
description = "Whether or not to color background for memory at an disabled, but ineffective, breakpoint", //
help = @HelpInfo(anchor = "colors"))
private boolean breakpointIneffDisColoringBackground =
DebuggerResources.DEFAULT_COLOR_INEFF_DIS_BREAKPOINT_COLORING_BACKGROUND;
@SuppressWarnings("unused")
private final AutoOptions.Wiring autoOptionsWiring;
private final Map<Program, BreakpointMarkerSets> markersByProgram = new HashMap<>();
private final LogicalBreakpointsChangeListener updateMarksListener =
new UpdateMarksBreakpointRecordChangeListener();
private final MarkerClickedListener markerClickedListener =
new ToggleBreakpointsMarkerClickedListener();
private final AsyncDebouncer<Void> updateDebouncer =
new AsyncDebouncer<>(AsyncTimer.DEFAULT_TIMER, 50);
// package access for testing
SetBreakpointAction actionSetSoftwareBreakpoint;
SetBreakpointAction actionSetExecuteBreakpoint;
SetBreakpointAction actionSetReadWriteBreakpoint;
SetBreakpointAction actionSetReadBreakpoint;
SetBreakpointAction actionSetWriteBreakpoint;
ToggleBreakpointAction actionToggleBreakpoint;
EnableBreakpointAction actionEnableBreakpoint;
DisableBreakpointAction actionDisableBreakpoint;
ClearBreakpointAction actionClearBreakpoint;
DebuggerPlaceBreakpointDialog placeBreakpointDialog = new DebuggerPlaceBreakpointDialog();
public DebuggerBreakpointMarkerPlugin(PluginTool tool) {
super(tool);
this.autoServiceWiring = AutoService.wireServicesProvidedAndConsumed(this);
this.autoOptionsWiring = AutoOptions.wireOptions(this);
updateDebouncer.addListener(__ -> SwingUtilities.invokeLater(() -> updateAllMarks()));
tool.addPopupActionProvider(this);
}
@Override
protected void init() {
super.init();
createActions();
}
@AutoOptionConsumed(name = DebuggerResources.OPTION_NAME_COLORS_ENABLED_BREAKPOINT_MARKERS)
private void setEnabledBreakpointMarkerColor(Color breakpointMarkerColor) {
for (BreakpointMarkerSets markers : markersByProgram.values()) {
markers.setEnabledMarkerColor(breakpointMarkerColor);
}
}
@AutoOptionConsumed(
name = DebuggerResources.OPTION_NAME_COLORS_ENABLED_BREAKPOINT_COLORING_BACKGROUND)
private void setEnabledBreakpointMarkerBackground(boolean breakpointColoringBackground) {
for (BreakpointMarkerSets markers : markersByProgram.values()) {
markers.setEnabledColoringBackground(breakpointColoringBackground);
}
}
@AutoOptionConsumed(name = DebuggerResources.OPTION_NAME_COLORS_DISABLED_BREAKPOINT_MARKERS)
private void setDisabledBreakpointMarkerColor(Color breakpointMarkerColor) {
for (BreakpointMarkerSets markers : markersByProgram.values()) {
markers.setDisabledMarkerColor(breakpointMarkerColor);
}
}
@AutoOptionConsumed(
name = DebuggerResources.OPTION_NAME_COLORS_DISABLED_BREAKPOINT_COLORING_BACKGROUND)
private void setDisabledBreakpointMarkerBackground(boolean breakpointColoringBackground) {
for (BreakpointMarkerSets markers : markersByProgram.values()) {
markers.setDisabledColoringBackground(breakpointColoringBackground);
}
}
@AutoOptionConsumed(
name = DebuggerResources.OPTION_NAME_COLORS_INEFF_EN_BREAKPOINT_MARKERS)
private void setIneffectiveEBreakpointMarkerColor(Color breakpointMarkerColor) {
for (BreakpointMarkerSets markers : markersByProgram.values()) {
markers.setIneffectiveEnabledMarkerColor(breakpointMarkerColor);
}
}
@AutoOptionConsumed(
name = DebuggerResources.OPTION_NAME_COLORS_INEFF_EN_BREAKPOINT_COLORING_BACKGROUND)
private void setIneffectiveEBreakpointMarkerBackground(boolean breakpointColoringBackground) {
for (BreakpointMarkerSets markers : markersByProgram.values()) {
markers.setIneffectiveEnabledColoringBackground(breakpointColoringBackground);
}
}
@AutoOptionConsumed(
name = DebuggerResources.OPTION_NAME_COLORS_INEFF_DIS_BREAKPOINT_MARKERS)
private void setIneffectiveDBreakpointMarkerColor(Color breakpointMarkerColor) {
for (BreakpointMarkerSets markers : markersByProgram.values()) {
markers.setIneffectiveDisabledMarkerColor(breakpointMarkerColor);
}
}
@AutoOptionConsumed(
name = DebuggerResources.OPTION_NAME_COLORS_INEFF_DIS_BREAKPOINT_COLORING_BACKGROUND)
private void setIneffectiveDBreakpointMarkerBackground(boolean breakpointColoringBackground) {
for (BreakpointMarkerSets markers : markersByProgram.values()) {
markers.setIneffectiveDisabledColoringBackground(breakpointColoringBackground);
}
}
protected TraceRecorder getRecorderFromContext(ActionContext context) {
if (modelService == null) {
return null;
}
Trace trace = getTraceFromContext(context);
return modelService.getRecorder(trace);
}
protected Set<TraceRecorder> getRecordersFromContext(ActionContext context) {
TraceRecorder single = getRecorderFromContext(context);
if (single != null) {
return Set.of(single);
}
if (mappingService == null || modelService == null) {
return Set.of();
}
ProgramLocation loc = getLocationFromContext(context);
if (loc == null || loc.getProgram() instanceof TraceProgramView) {
return Set.of();
}
Set<TraceRecorder> result = new HashSet<>();
for (TraceLocation tloc : mappingService.getOpenMappedLocations(loc)) {
TraceRecorder rec = modelService.getRecorder(tloc.getTrace());
if (rec != null) {
result.add(rec);
}
}
return result;
}
protected boolean contextHasRecorder(ActionContext ctx) {
return getRecorderFromContext(ctx) != null;
}
protected boolean contextCanManipulateBreakpoints(ActionContext ctx) {
if (breakpointService == null) {
return false;
}
if (!contextHasLocation(ctx)) {
return false;
}
// Programs, or live traces, but not dead traces
if (contextHasTrace(ctx) && !contextHasRecorder(ctx)) {
return false;
}
return true;
}
protected Set<TraceBreakpointKind> getSupportedKindsFromContext(ActionContext context) {
Set<TraceRecorder> recorders = getRecordersFromContext(context);
if (recorders.isEmpty()) {
return EnumSet.allOf(TraceBreakpointKind.class);
}
return recorders.stream()
.flatMap(rec -> rec.getSupportedBreakpointKinds().stream())
.collect(Collectors.toSet());
}
protected void doToggleBreakpointsAt(String title, ActionContext context) {
// TODO: Seems like this should be in logical breakpoint service?
if (breakpointService == null) {
return;
}
ProgramLocation loc = getLocationFromContext(context);
if (loc == null) {
return;
}
Set<LogicalBreakpoint> bs = breakpointService.getBreakpointsAt(loc);
if (bs == null || bs.isEmpty()) {
Set<TraceBreakpointKind> supported = getSupportedKindsFromContext(context);
if (supported.isEmpty()) {
breakpointError(title, "It seems this target does not support breakpoints.");
return;
}
Set<TraceBreakpointKind> kinds = computeDefaultKinds(context, supported);
long length = computeDefaultLength(context, kinds);
placeBreakpointDialog.prompt(tool, breakpointService, title, loc, length, kinds, "");
return;
}
State state = breakpointService.computeState(bs, loc);
/**
* If we're in the static listing, this will return null, indicating we should use the
* program's perspective. The methods taking trace should accept a null trace and behave
* accordingly. If in the dynamic listing, we act in the context of the returned trace.
*/
Trace trace = getTraceFromContext(context);
boolean mapped = breakpointService.anyMapped(bs, trace);
State toggled = state.getToggled(mapped);
if (toggled.isEnabled()) {
breakpointService.enableAll(bs, trace).exceptionally(ex -> {
breakpointError(title, "Could not enable breakpoints", ex);
return null;
});
}
else {
breakpointService.disableAll(bs, trace).exceptionally(ex -> {
breakpointError(title, "Could not disable breakpoints", ex);
return null;
});
}
}
/**
* Instantiate a marker set for the given program or trace view
*
* @param program the (static) program or (dynamic) trace view
* @return the marker sets
*/
protected BreakpointMarkerSets createMarkers(Program program) {
synchronized (markersByProgram) {
BreakpointMarkerSets newSets = new BreakpointMarkerSets(program);
BreakpointMarkerSets oldSets = markersByProgram.put(program, newSets);
assert oldSets == null;
return newSets;
}
}
protected void removeMarkers(Program program) {
synchronized (markersByProgram) {
BreakpointMarkerSets oldSets = markersByProgram.remove(program);
oldSets.dispose();
}
}
protected void doMarks(BreakpointMarkerSets marks,
Map<Address, Set<LogicalBreakpoint>> byAddress,
java.util.function.Function<LogicalBreakpoint, State> stateFunc) {
for (Map.Entry<Address, Set<LogicalBreakpoint>> bEnt : byAddress.entrySet()) {
Map<Long, State> byLength = new HashMap<>();
for (LogicalBreakpoint lb : bEnt.getValue()) {
byLength.compute(lb.getLength(), (l, e) -> (e == null ? State.NONE : e)
.sameAdddress(stateFunc.apply(lb)));
}
Address start = bEnt.getKey();
for (Map.Entry<Long, State> sEnt : byLength.entrySet()) {
Address end = start.add(sEnt.getKey() - 1);
MarkerSet set = marks.getMarkerSet(sEnt.getValue());
if (set != null) {
set.add(start, end);
}
}
}
}
protected void updateAllMarks() {
synchronized (markersByProgram) {
for (BreakpointMarkerSets markerSet : markersByProgram.values()) {
markerSet.clear();
}
if (breakpointService == null) {
return;
}
for (Map.Entry<Program, BreakpointMarkerSets> pEnt : markersByProgram.entrySet()) {
Program program = pEnt.getKey();
BreakpointMarkerSets marks = pEnt.getValue();
if (program instanceof TraceProgramView) {
TraceProgramView view = (TraceProgramView) program;
Trace trace = view.getTrace();
doMarks(marks, breakpointService.getBreakpoints(trace),
lb -> lb.computeStateForTrace(trace));
}
else {
doMarks(marks, breakpointService.getBreakpoints(program),
lb -> lb.computeStateForProgram(program));
}
}
}
}
@AutoServiceConsumed
private void setMarkerService(MarkerService markerService) {
if (this.markerService != null) {
this.markerService.setMarkerClickedListener(null);
}
this.markerService = markerService;
if (this.markerService != null) {
this.markerService.setMarkerClickedListener(markerClickedListener);
}
}
@AutoServiceConsumed
private void setLogicalBreakpointService(DebuggerLogicalBreakpointService breakpointService) {
if (this.breakpointService != null) {
this.breakpointService.removeChangeListener(updateMarksListener);
}
this.breakpointService = breakpointService;
if (this.breakpointService != null) {
breakpointService.addChangeListener(updateMarksListener);
updateAllMarks();
}
}
protected void createActions() {
actionSetSoftwareBreakpoint =
new SetBreakpointAction(Set.of(TraceBreakpointKind.SW_EXECUTE));
actionSetExecuteBreakpoint =
new SetBreakpointAction(Set.of(TraceBreakpointKind.HW_EXECUTE));
actionSetReadWriteBreakpoint =
new SetBreakpointAction(Set.of(TraceBreakpointKind.READ, TraceBreakpointKind.WRITE));
actionSetReadBreakpoint = new SetBreakpointAction(Set.of(TraceBreakpointKind.READ));
actionSetWriteBreakpoint = new SetBreakpointAction(Set.of(TraceBreakpointKind.WRITE));
actionToggleBreakpoint = new ToggleBreakpointAction();
actionEnableBreakpoint = new EnableBreakpointAction();
actionDisableBreakpoint = new DisableBreakpointAction();
actionClearBreakpoint = new ClearBreakpointAction();
tool.setMenuGroup(new String[] { SetBreakpointAction.NAME }, SetBreakpointAction.GROUP);
}
@Override
public List<DockingActionIf> getPopupActions(Tool __, ActionContext context) {
return List.of(); // TODO: Actions by individual breakpoint?
}
@Override
public void processEvent(PluginEvent event) {
if (event instanceof ProgramOpenedPluginEvent) {
ProgramOpenedPluginEvent evt = (ProgramOpenedPluginEvent) event;
createMarkers(evt.getProgram());
updateAllMarks();
}
else if (event instanceof ProgramClosedPluginEvent) {
ProgramClosedPluginEvent evt = (ProgramClosedPluginEvent) event;
removeMarkers(evt.getProgram());
}
else if (event instanceof TraceOpenedPluginEvent) {
TraceOpenedPluginEvent evt = (TraceOpenedPluginEvent) event;
TraceProgramView view = evt.getTrace().getProgramView();
createMarkers(view);
updateAllMarks();
}
else if (event instanceof TraceClosedPluginEvent) {
TraceClosedPluginEvent evt = (TraceClosedPluginEvent) event;
Trace trace = evt.getTrace();
Map<Program, BreakpointMarkerSets> copyOfMarkers;
synchronized (markersByProgram) {
copyOfMarkers = Map.copyOf(markersByProgram);
}
for (Map.Entry<Program, BreakpointMarkerSets> ent : copyOfMarkers.entrySet()) {
Program program = ent.getKey();
if (!(program instanceof TraceProgramView)) {
continue;
}
TraceProgramView view = (TraceProgramView) program;
if (view.getTrace() != trace) {
continue;
}
removeMarkers(view);
}
}
}
protected void breakpointError(String title, String message) {
if (consoleService == null) {
Msg.showError(this, null, title, message);
return;
}
consoleService.log(DebuggerResources.ICON_LOG_ERROR, message);
}
protected void breakpointError(String title, String message, Throwable ex) {
if (consoleService == null) {
Msg.showError(this, null, title, message, ex);
return;
}
Msg.error(this, message, ex);
consoleService.log(DebuggerResources.ICON_LOG_ERROR, message + " (" + ex + ")");
}
}
|
/*
* Copyright 2017 Apereo
*
* 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.tle.web.sections.jquery.libraries;
import com.tle.common.i18n.CurrentLocale;
import com.tle.core.javascript.JavascriptModule;
import com.tle.web.DebugSettings;
import com.tle.web.sections.jquery.JQueryLibraryInclude;
import com.tle.web.sections.jquery.libraries.effects.JQueryUIEffects;
import com.tle.web.sections.render.PreRenderable;
@SuppressWarnings("nls")
public class JQueryUIAccordion implements JavascriptModule
{
private static final long serialVersionUID = 1L;
/**
* Includes jquery.ui.accordion.js
*/
public static final PreRenderable PRERENDER = new JQueryLibraryInclude(
DebugSettings.isDebuggingMode() ? "jquery.ui.accordion.js" : "jquery.ui.accordion.min.js",
JQueryUICore.PRERENDER, JQueryUIWidget.PRERENDER, JQueryUIEffects.PRERENDER_ALL);
@Override
public String getDisplayName()
{
return CurrentLocale.get("com.tle.web.sections.jquery.modules.ui.accordion.name");
}
@Override
public String getId()
{
return "uiaccordion";
}
@Override
public Object getPreRenderer()
{
return PRERENDER;
}
}
|
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.bpmn.definition.property.cm;
import java.util.Objects;
import javax.validation.Valid;
import org.jboss.errai.common.client.api.annotations.MapsTo;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.jboss.errai.databinding.client.api.Bindable;
import org.kie.workbench.common.forms.adf.definitions.annotations.FieldParam;
import org.kie.workbench.common.forms.adf.definitions.annotations.FormDefinition;
import org.kie.workbench.common.forms.adf.definitions.annotations.FormField;
import org.kie.workbench.common.forms.adf.definitions.settings.FieldPolicy;
import org.kie.workbench.common.forms.fields.shared.fieldTypes.basic.textBox.type.TextBoxFieldType;
import org.kie.workbench.common.stunner.bpmn.definition.BPMNPropertySet;
import org.kie.workbench.common.stunner.bpmn.forms.model.VariablesEditorFieldType;
import org.kie.workbench.common.stunner.bpmn.forms.model.cm.RolesEditorFieldType;
import org.kie.workbench.common.stunner.core.definition.annotation.Property;
import org.kie.workbench.common.stunner.core.definition.annotation.PropertySet;
import org.kie.workbench.common.stunner.core.util.HashUtil;
@Portable
@Bindable
@PropertySet
@FormDefinition(
policy = FieldPolicy.ONLY_MARKED,
startElement = "caseIdPrefix"
)
public class CaseManagementSet implements BPMNPropertySet {
@Property
@FormField(type = TextBoxFieldType.class)
private CaseIdPrefix caseIdPrefix;
@Property
@FormField(
type = RolesEditorFieldType.class,
afterElement = "caseIdPrefix"
)
@Valid
private CaseRoles caseRoles;
@Property
@FormField(
type = VariablesEditorFieldType.class,
settings = {@FieldParam(name = "caseFileVariable", value = "true")}
)
@Valid
private CaseFileVariables caseFileVariables;
public CaseManagementSet() {
this(new CaseIdPrefix(), new CaseRoles(), new CaseFileVariables());
}
public CaseManagementSet(final @MapsTo("caseIdPrefix") CaseIdPrefix caseIdPrefix,
final @MapsTo("caseRoles") CaseRoles caseRoles,
final @MapsTo("caseFileVariables") CaseFileVariables caseFileVariables) {
this.caseRoles = caseRoles;
this.caseFileVariables = caseFileVariables;
this.caseIdPrefix = caseIdPrefix;
}
public CaseIdPrefix getCaseIdPrefix() {
return caseIdPrefix;
}
public void setCaseIdPrefix(CaseIdPrefix caseIdPrefix) {
this.caseIdPrefix = caseIdPrefix;
}
public CaseRoles getCaseRoles() {
return caseRoles;
}
public void setCaseRoles(CaseRoles caseRoles) {
this.caseRoles = caseRoles;
}
public CaseFileVariables getCaseFileVariables() {
return caseFileVariables;
}
public void setCaseFileVariables(CaseFileVariables caseFileVariables) {
this.caseFileVariables = caseFileVariables;
}
@Override
public int hashCode() {
return HashUtil.combineHashCodes(caseIdPrefix.hashCode(), caseRoles.hashCode(),
caseFileVariables.hashCode());
}
@Override
public boolean equals(Object o) {
if (!(o instanceof CaseManagementSet)) {
return false;
}
CaseManagementSet other = (CaseManagementSet) o;
return Objects.equals(caseRoles, other.caseRoles) &&
Objects.equals(getCaseIdPrefix(), other.caseIdPrefix) &&
Objects.equals(caseFileVariables, other.caseFileVariables);
}
}
|
/*
* 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.carbondata.core.metadata.schema.datamap;
import org.apache.carbondata.common.annotations.InterfaceAudience;
/**
* Property that can be specified when creating DataMap
*/
@InterfaceAudience.Internal
public class DataMapProperty {
/**
* For datamap created with 'WITH DEFERRED REBUILD' syntax, we will add this
* property internally
*/
public static final String DEFERRED_REBUILD = "_internal.deferred.rebuild";
/**
* internal property, true if it needs full refresh, thus it does not support incremental load
*/
public static final String FULL_REFRESH = "full_refresh";
}
|
/*
* 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.skywalking.apm.agent.core.jvm.gc;
import java.util.List;
import org.apache.skywalking.apm.network.language.agent.*;
/**
* @author wusheng
*/
public interface GCMetricAccessor {
List<GC> getGCList();
}
|
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.rest.api.v2010.account;
import com.twilio.base.Updater;
import com.twilio.converter.Promoter;
import com.twilio.exception.ApiConnectionException;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
import java.net.URI;
public class IncomingPhoneNumberUpdater extends Updater<IncomingPhoneNumber> {
private String pathAccountSid;
private final String pathSid;
private String accountSid;
private String apiVersion;
private String friendlyName;
private String smsApplicationSid;
private HttpMethod smsFallbackMethod;
private URI smsFallbackUrl;
private HttpMethod smsMethod;
private URI smsUrl;
private URI statusCallback;
private HttpMethod statusCallbackMethod;
private String voiceApplicationSid;
private Boolean voiceCallerIdLookup;
private HttpMethod voiceFallbackMethod;
private URI voiceFallbackUrl;
private HttpMethod voiceMethod;
private URI voiceUrl;
private IncomingPhoneNumber.EmergencyStatus emergencyStatus;
private String emergencyAddressSid;
private String trunkSid;
private IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode;
private String identitySid;
private String addressSid;
/**
* Construct a new IncomingPhoneNumberUpdater.
*
* @param pathSid The sid
*/
public IncomingPhoneNumberUpdater(final String pathSid) {
this.pathSid = pathSid;
}
/**
* Construct a new IncomingPhoneNumberUpdater.
*
* @param pathAccountSid The new owner of the phone number
* @param pathSid The sid
*/
public IncomingPhoneNumberUpdater(final String pathAccountSid,
final String pathSid) {
this.pathAccountSid = pathAccountSid;
this.pathSid = pathSid;
}
/**
* The unique 34 character id of the account to which you wish to transfer this
* phone number. See [Exchanging Numbers Between
* Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers)..
*
* @param accountSid The new owner of the phone number
* @return this
*/
public IncomingPhoneNumberUpdater setAccountSid(final String accountSid) {
this.accountSid = accountSid;
return this;
}
/**
* Calls to this phone number will start a new TwiML session with this API
* version. Either `2010-04-01` or `2008-08-01`..
*
* @param apiVersion The Twilio REST API version to use
* @return this
*/
public IncomingPhoneNumberUpdater setApiVersion(final String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/**
* A human readable descriptive text for this resource, up to 64 characters
* long. By default, the `FriendlyName` is a nicely formatted version of the
* phone number..
*
* @param friendlyName A human readable description of this resource
* @return this
*/
public IncomingPhoneNumberUpdater setFriendlyName(final String friendlyName) {
this.friendlyName = friendlyName;
return this;
}
/**
* The 34 character sid of the application Twilio should use to handle SMSs sent
* to this number. If a `SmsApplicationSid` is present, Twilio will ignore all
* of the SMS urls above and use those set on the application instead..
*
* @param smsApplicationSid Unique string that identifies the application
* @return this
*/
public IncomingPhoneNumberUpdater setSmsApplicationSid(final String smsApplicationSid) {
this.smsApplicationSid = smsApplicationSid;
return this;
}
/**
* The HTTP method that should be used to request the `SmsFallbackUrl`. Either
* `GET` or `POST`..
*
* @param smsFallbackMethod HTTP method used with sms fallback url
* @return this
*/
public IncomingPhoneNumberUpdater setSmsFallbackMethod(final HttpMethod smsFallbackMethod) {
this.smsFallbackMethod = smsFallbackMethod;
return this;
}
/**
* A URL that Twilio will request if an error occurs requesting or executing the
* TwiML defined by `SmsUrl`..
*
* @param smsFallbackUrl URL Twilio will request if an error occurs in
* executing TwiML
* @return this
*/
public IncomingPhoneNumberUpdater setSmsFallbackUrl(final URI smsFallbackUrl) {
this.smsFallbackUrl = smsFallbackUrl;
return this;
}
/**
* A URL that Twilio will request if an error occurs requesting or executing the
* TwiML defined by `SmsUrl`..
*
* @param smsFallbackUrl URL Twilio will request if an error occurs in
* executing TwiML
* @return this
*/
public IncomingPhoneNumberUpdater setSmsFallbackUrl(final String smsFallbackUrl) {
return setSmsFallbackUrl(Promoter.uriFromString(smsFallbackUrl));
}
/**
* The HTTP method Twilio will use when making requests to the `SmsUrl`. Either
* `GET` or `POST`..
*
* @param smsMethod HTTP method to use with sms url
* @return this
*/
public IncomingPhoneNumberUpdater setSmsMethod(final HttpMethod smsMethod) {
this.smsMethod = smsMethod;
return this;
}
/**
* The URL that Twilio should request when somebody sends an SMS to the new
* phone number..
*
* @param smsUrl URL Twilio will request when receiving an SMS
* @return this
*/
public IncomingPhoneNumberUpdater setSmsUrl(final URI smsUrl) {
this.smsUrl = smsUrl;
return this;
}
/**
* The URL that Twilio should request when somebody sends an SMS to the new
* phone number..
*
* @param smsUrl URL Twilio will request when receiving an SMS
* @return this
*/
public IncomingPhoneNumberUpdater setSmsUrl(final String smsUrl) {
return setSmsUrl(Promoter.uriFromString(smsUrl));
}
/**
* The URL that Twilio will request to pass status parameters (such as call
* ended) to your application..
*
* @param statusCallback URL Twilio will use to pass status parameters
* @return this
*/
public IncomingPhoneNumberUpdater setStatusCallback(final URI statusCallback) {
this.statusCallback = statusCallback;
return this;
}
/**
* The URL that Twilio will request to pass status parameters (such as call
* ended) to your application..
*
* @param statusCallback URL Twilio will use to pass status parameters
* @return this
*/
public IncomingPhoneNumberUpdater setStatusCallback(final String statusCallback) {
return setStatusCallback(Promoter.uriFromString(statusCallback));
}
/**
* The HTTP method Twilio will use to make requests to the `StatusCallback` URL.
* Either `GET` or `POST`..
*
* @param statusCallbackMethod HTTP method twilio will use with status callback
* @return this
*/
public IncomingPhoneNumberUpdater setStatusCallbackMethod(final HttpMethod statusCallbackMethod) {
this.statusCallbackMethod = statusCallbackMethod;
return this;
}
/**
* The 34 character sid of the application Twilio should use to handle phone
* calls to this number. If a `VoiceApplicationSid` is present, Twilio will
* ignore all of the voice urls above and use those set on the application
* instead. Setting a `VoiceApplicationSid` will automatically delete your
* `TrunkSid` and vice versa..
*
* @param voiceApplicationSid The unique sid of the application to handle this
* number
* @return this
*/
public IncomingPhoneNumberUpdater setVoiceApplicationSid(final String voiceApplicationSid) {
this.voiceApplicationSid = voiceApplicationSid;
return this;
}
/**
* Look up the caller's caller-ID name from the CNAM database ($0.01 per look
* up). Either `true` or `false`..
*
* @param voiceCallerIdLookup Look up the caller's caller-ID
* @return this
*/
public IncomingPhoneNumberUpdater setVoiceCallerIdLookup(final Boolean voiceCallerIdLookup) {
this.voiceCallerIdLookup = voiceCallerIdLookup;
return this;
}
/**
* The HTTP method Twilio will use when requesting the `VoiceFallbackUrl`.
* Either `GET` or `POST`..
*
* @param voiceFallbackMethod HTTP method used with fallback_url
* @return this
*/
public IncomingPhoneNumberUpdater setVoiceFallbackMethod(final HttpMethod voiceFallbackMethod) {
this.voiceFallbackMethod = voiceFallbackMethod;
return this;
}
/**
* A URL that Twilio will request if an error occurs requesting or executing the
* TwiML defined by `VoiceUrl`..
*
* @param voiceFallbackUrl URL Twilio will request when an error occurs in TwiML
* @return this
*/
public IncomingPhoneNumberUpdater setVoiceFallbackUrl(final URI voiceFallbackUrl) {
this.voiceFallbackUrl = voiceFallbackUrl;
return this;
}
/**
* A URL that Twilio will request if an error occurs requesting or executing the
* TwiML defined by `VoiceUrl`..
*
* @param voiceFallbackUrl URL Twilio will request when an error occurs in TwiML
* @return this
*/
public IncomingPhoneNumberUpdater setVoiceFallbackUrl(final String voiceFallbackUrl) {
return setVoiceFallbackUrl(Promoter.uriFromString(voiceFallbackUrl));
}
/**
* The HTTP method Twilio will use when requesting the above `Url`. Either `GET`
* or `POST`..
*
* @param voiceMethod HTTP method used with the voice url
* @return this
*/
public IncomingPhoneNumberUpdater setVoiceMethod(final HttpMethod voiceMethod) {
this.voiceMethod = voiceMethod;
return this;
}
/**
* The URL that Twilio should request when somebody dials the phone number. The
* VoiceURL will no longer be used if a `VoiceApplicationSid` or a `TrunkSid`
* is set..
*
* @param voiceUrl URL Twilio will request when receiving a call
* @return this
*/
public IncomingPhoneNumberUpdater setVoiceUrl(final URI voiceUrl) {
this.voiceUrl = voiceUrl;
return this;
}
/**
* The URL that Twilio should request when somebody dials the phone number. The
* VoiceURL will no longer be used if a `VoiceApplicationSid` or a `TrunkSid`
* is set..
*
* @param voiceUrl URL Twilio will request when receiving a call
* @return this
*/
public IncomingPhoneNumberUpdater setVoiceUrl(final String voiceUrl) {
return setVoiceUrl(Promoter.uriFromString(voiceUrl));
}
/**
* The emergency_status.
*
* @param emergencyStatus The emergency_status
* @return this
*/
public IncomingPhoneNumberUpdater setEmergencyStatus(final IncomingPhoneNumber.EmergencyStatus emergencyStatus) {
this.emergencyStatus = emergencyStatus;
return this;
}
/**
* The emergency_address_sid.
*
* @param emergencyAddressSid The emergency_address_sid
* @return this
*/
public IncomingPhoneNumberUpdater setEmergencyAddressSid(final String emergencyAddressSid) {
this.emergencyAddressSid = emergencyAddressSid;
return this;
}
/**
* The 34 character sid of the Trunk Twilio should use to handle phone calls to
* this number. If a `TrunkSid` is present, Twilio will ignore all of the voice
* urls and voice applications above and use those set on the Trunk. Setting a
* `TrunkSid` will automatically delete your `VoiceApplicationSid` and vice
* versa..
*
* @param trunkSid Unique string to identify the trunk
* @return this
*/
public IncomingPhoneNumberUpdater setTrunkSid(final String trunkSid) {
this.trunkSid = trunkSid;
return this;
}
/**
* The voice_receive_mode.
*
* @param voiceReceiveMode The voice_receive_mode
* @return this
*/
public IncomingPhoneNumberUpdater setVoiceReceiveMode(final IncomingPhoneNumber.VoiceReceiveMode voiceReceiveMode) {
this.voiceReceiveMode = voiceReceiveMode;
return this;
}
/**
* The 34 character sid of the identity Twilio should use to associate with the
* number. Identities are required in some regions to meet local regulations.
*
* @param identitySid Unique string that identifies the identity associated
* with number
* @return this
*/
public IncomingPhoneNumberUpdater setIdentitySid(final String identitySid) {
this.identitySid = identitySid;
return this;
}
/**
* The 34 character sid of the address Twilio should associate with the number.
* If the number has address restrictions, only another address that satisfies
* the requirement can replace the existing one..
*
* @param addressSid Unique string that identifies the address associated with
* number
* @return this
*/
public IncomingPhoneNumberUpdater setAddressSid(final String addressSid) {
this.addressSid = addressSid;
return this;
}
/**
* Make the request to the Twilio API to perform the update.
*
* @param client TwilioRestClient with which to make the request
* @return Updated IncomingPhoneNumber
*/
@Override
@SuppressWarnings("checkstyle:linelength")
public IncomingPhoneNumber update(final TwilioRestClient client) {
this.pathAccountSid = this.pathAccountSid == null ? client.getAccountSid() : this.pathAccountSid;
Request request = new Request(
HttpMethod.POST,
Domains.API.toString(),
"/2010-04-01/Accounts/" + this.pathAccountSid + "/IncomingPhoneNumbers/" + this.pathSid + ".json",
client.getRegion()
);
addPostParams(request);
Response response = client.request(request);
if (response == null) {
throw new ApiConnectionException("IncomingPhoneNumber update failed: Unable to connect to server");
} else if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) {
RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper());
if (restException == null) {
throw new ApiException("Server Error, no content");
}
throw new ApiException(
restException.getMessage(),
restException.getCode(),
restException.getMoreInfo(),
restException.getStatus(),
null
);
}
return IncomingPhoneNumber.fromJson(response.getStream(), client.getObjectMapper());
}
/**
* Add the requested post parameters to the Request.
*
* @param request Request to add post params to
*/
private void addPostParams(final Request request) {
if (accountSid != null) {
request.addPostParam("AccountSid", accountSid);
}
if (apiVersion != null) {
request.addPostParam("ApiVersion", apiVersion);
}
if (friendlyName != null) {
request.addPostParam("FriendlyName", friendlyName);
}
if (smsApplicationSid != null) {
request.addPostParam("SmsApplicationSid", smsApplicationSid);
}
if (smsFallbackMethod != null) {
request.addPostParam("SmsFallbackMethod", smsFallbackMethod.toString());
}
if (smsFallbackUrl != null) {
request.addPostParam("SmsFallbackUrl", smsFallbackUrl.toString());
}
if (smsMethod != null) {
request.addPostParam("SmsMethod", smsMethod.toString());
}
if (smsUrl != null) {
request.addPostParam("SmsUrl", smsUrl.toString());
}
if (statusCallback != null) {
request.addPostParam("StatusCallback", statusCallback.toString());
}
if (statusCallbackMethod != null) {
request.addPostParam("StatusCallbackMethod", statusCallbackMethod.toString());
}
if (voiceApplicationSid != null) {
request.addPostParam("VoiceApplicationSid", voiceApplicationSid);
}
if (voiceCallerIdLookup != null) {
request.addPostParam("VoiceCallerIdLookup", voiceCallerIdLookup.toString());
}
if (voiceFallbackMethod != null) {
request.addPostParam("VoiceFallbackMethod", voiceFallbackMethod.toString());
}
if (voiceFallbackUrl != null) {
request.addPostParam("VoiceFallbackUrl", voiceFallbackUrl.toString());
}
if (voiceMethod != null) {
request.addPostParam("VoiceMethod", voiceMethod.toString());
}
if (voiceUrl != null) {
request.addPostParam("VoiceUrl", voiceUrl.toString());
}
if (emergencyStatus != null) {
request.addPostParam("EmergencyStatus", emergencyStatus.toString());
}
if (emergencyAddressSid != null) {
request.addPostParam("EmergencyAddressSid", emergencyAddressSid);
}
if (trunkSid != null) {
request.addPostParam("TrunkSid", trunkSid);
}
if (voiceReceiveMode != null) {
request.addPostParam("VoiceReceiveMode", voiceReceiveMode.toString());
}
if (identitySid != null) {
request.addPostParam("IdentitySid", identitySid);
}
if (addressSid != null) {
request.addPostParam("AddressSid", addressSid);
}
}
}
|
package gobblin.metrics.metric.filter;
import static org.mockito.Mockito.mock;
import com.codahale.metrics.Metric;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Tests for {@link MetricNameRegexFilter}.
*/
@Test
public class MetricNameRegexFilterTest {
@Test
public void matchesTest() {
MetricNameRegexFilter metricNameRegexFilter1 = new MetricNameRegexFilter(".*");
Assert.assertTrue(metricNameRegexFilter1.matches("test1", mock(Metric.class)));
Assert.assertTrue(metricNameRegexFilter1.matches("test2", mock(Metric.class)));
Assert.assertTrue(metricNameRegexFilter1.matches("test3", mock(Metric.class)));
MetricNameRegexFilter metricNameRegexFilter2 = new MetricNameRegexFilter("test1");
Assert.assertTrue(metricNameRegexFilter2.matches("test1", mock(Metric.class)));
Assert.assertFalse(metricNameRegexFilter2.matches("test2", mock(Metric.class)));
Assert.assertFalse(metricNameRegexFilter2.matches("test3", mock(Metric.class)));
}
}
|
package com.github.diegopacheco.dynomite.cluster.checker.cluster.cache;
import java.util.concurrent.TimeUnit;
import javax.inject.Singleton;
import org.apache.log4j.Logger;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.netflix.dyno.jedis.DynoJedisClient;
@Singleton
public class DynoClientCache {
private static Cache<String, DynoJedisClient> cache;
private static final Logger logger = Logger.getLogger(DynoClientCache.class);
static {
cache = CacheBuilder.newBuilder().
maximumSize(500).
expireAfterAccess(2, TimeUnit.HOURS).
removalListener(new RemovalListener<String, DynoJedisClient>() {
@Override
public void onRemoval(RemovalNotification<String, DynoJedisClient> notification) {
logger.debug("Removing... " + notification.getKey());
try {
notification.getValue().stopClient();
} catch (Exception e) {
logger.error("Error on close evicted client. EX: " + e);
}
}
}).build();
}
public static DynoJedisClient get(String seeds) {
try {
return cache.getIfPresent(seeds);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void put(String seeds, DynoJedisClient client) {
cache.put(seeds, client);
}
}
|
package no.uib.probe.csf.pr.touch.view.core;
import com.vaadin.event.LayoutEvents;
import com.vaadin.event.MouseEvents;
import com.vaadin.server.ThemeResource;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Image;
import com.vaadin.ui.Label;
/**
* This class represents the welcome page and left side panels buttons.
*
* @author Yehia Farag
*/
public abstract class BigBtn extends HorizontalLayout implements LayoutEvents.LayoutClickListener, MouseEvents.ClickListener {
/**
* Main icon image for the button.
*/
private final Image buttonIcon;
/**
* Main icon container.
*/
private final ImageContainerBtn thumbContainer;
/**
* Get the main icon container layout
*
* @return thumbContainer The icon container.
*/
public ImageContainerBtn getThumbBtn() {
return thumbContainer;
}
/**
* Constructor to initialize the main attributes.
*
* @param header main header title.
* @param text The button text.
* @param imgUrl icon URL.
*/
public BigBtn(String header, String text, String imgUrl) {
this.setWidthUndefined();
this.setMargin(false);
int lineHeight = 35;
this.addLayoutClickListener(BigBtn.this);
this.setStyleName("bigbtn");
buttonIcon = new Image();
buttonIcon.setSource(new ThemeResource(imgUrl));
buttonIcon.addStyleName("blink");
this.addComponent(buttonIcon);
String labelText = "<b>" + header + "</b><br/><font size='1'>" + text + "</font>";
Label btnLabel = new Label(labelText);
btnLabel.setContentMode(ContentMode.HTML);
this.addComponent(btnLabel);
this.setComponentAlignment(btnLabel, Alignment.MIDDLE_LEFT);
btnLabel.setWidth(240, Unit.PIXELS);
btnLabel.setHeight(lineHeight, Unit.PIXELS);
thumbContainer = new ImageContainerBtn() {
@Override
public void onClick() {
BigBtn.this.onClick();
}
};
thumbContainer.updateIcon(new ThemeResource(imgUrl));
thumbContainer.setEnabled(true);
thumbContainer.setReadOnly(false);
buttonIcon.setWidth(70, Unit.PIXELS);
buttonIcon.setHeight(70, Unit.PIXELS);
thumbContainer.setWidth(40, Unit.PIXELS);
thumbContainer.setHeight(40, Unit.PIXELS);
}
/**
* Layout clicked listener implementation.
*
* @param event Click the button event.
*/
@Override
public void layoutClick(LayoutEvents.LayoutClickEvent event) {
onClick();
}
/**
* Do the implemented action.
* @param event Click the button event.
*/
@Override
public void click(MouseEvents.ClickEvent event) {
onClick();
}
/**
* On click do the button function (to be implemented).
*/
public abstract void onClick();
}
|
package devjluvisi.mlb.api.gui.pages;
import devjluvisi.mlb.api.gui.MenuView;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
public interface Page {
/**
* Gets the name of the page. If the name is null, the name of the menu would be
* used.
*
* @return the name of the page
*/
String getName();
/**
* Gets the whole content of the page at this moment (it may be animated).
*
* @return an array of the items
*/
ItemStack[] getContent();
/**
* @return the type of the page
*/
PageType getPageType();
void onClick(MenuView view, ClickType clickType, int slot, ItemStack itemStack);
}
|
package org.alee.component.skin.pack;
import android.content.Context;
import androidx.annotation.NonNull;
import org.alee.component.skin.util.task.TaskQueue;
import org.alee.component.skin.util.task.template.ITask;
import org.alee.component.skin.util.task.template.ITaskQueue;
/**********************************************************
*
* @author: MY.Liu
* @date: 2021/2/13
* @description: xxxx
*
*********************************************************/
final class LoadThemeSkinQueue {
private final Context mContext;
private IThemeSkinPack mThemeSkinPack;
private ILoadThemeSkinObserver mLoadThemeSkinObserver;
private ITaskQueue mTaskQueue;
LoadThemeSkinQueue(@NonNull Context context) {
mContext = context;
}
void addTask(@NonNull BaseThemeSkinPack skinPack) {
if (null == mTaskQueue) {
mTaskQueue = new TaskQueue().beginTask(new LoadThemeSkinTask(skinPack, mContext));
return;
}
mTaskQueue.then(new DependentTask(skinPack, mContext));
}
void performTask(@NonNull IThemeSkinPack skinPack, ILoadThemeSkinObserver observer) {
mThemeSkinPack = skinPack;
mLoadThemeSkinObserver = observer;
mTaskQueue.execute().whenComplete(success -> {
if (null == mLoadThemeSkinObserver) {
return;
}
mLoadThemeSkinObserver.onLoadCompleted(mThemeSkinPack);
});
}
private static final class DependentTask implements ITask {
private final BaseThemeSkinPack mThemeSkinPack;
private final Context mContext;
public DependentTask(@NonNull BaseThemeSkinPack skinPack, @NonNull Context context) {
mThemeSkinPack = skinPack;
mContext = context;
}
/**
* 执行任务
*
* @return 是否执行成功
* @throws Throwable 一切异常
*/
@Override
public boolean doWork() throws Throwable {
return new LoadThemeSkinTask(mThemeSkinPack, mContext).doWork();
}
}
}
|
/*
* 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.ignite.internal.processors.platform;
import org.apache.ignite.internal.util.typedef.internal.S;
/**
* Exception raised when interop callback is not set in native platform.
*/
@SuppressWarnings("UnusedDeclaration")
public class PlatformNoCallbackException extends PlatformException {
/** */
private static final long serialVersionUID = 0L;
/**
* Constructor.
*/
public PlatformNoCallbackException() {
// No-op.
}
/**
* Constructor.
*
* @param msg Message.
*/
public PlatformNoCallbackException(String msg) {
super(msg);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(PlatformNoCallbackException.class, this);
}
}
|
/*
* Copyright 2021 Collate
* 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.openmetadata.catalog.resources.mlmodels;
import com.google.inject.Inject;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.ExternalDocumentation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import javax.json.JsonPatch;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.PATCH;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import org.openmetadata.catalog.Entity;
import org.openmetadata.catalog.api.data.CreateMlModel;
import org.openmetadata.catalog.entity.data.MlModel;
import org.openmetadata.catalog.jdbi3.CollectionDAO;
import org.openmetadata.catalog.jdbi3.MlModelRepository;
import org.openmetadata.catalog.resources.Collection;
import org.openmetadata.catalog.security.Authorizer;
import org.openmetadata.catalog.security.SecurityUtil;
import org.openmetadata.catalog.type.EntityHistory;
import org.openmetadata.catalog.util.EntityUtil.Fields;
import org.openmetadata.catalog.util.RestUtil;
import org.openmetadata.catalog.util.RestUtil.PatchResponse;
import org.openmetadata.catalog.util.RestUtil.PutResponse;
import org.openmetadata.catalog.util.ResultList;
@Path("/v1/mlmodels")
@Api(value = "MlModels collection", tags = "MlModels collection")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Collection(name = "mlmodels")
public class MlModelResource {
public static final String COLLECTION_PATH = "v1/mlmodels/";
private final MlModelRepository dao;
private final Authorizer authorizer;
public static MlModel addHref(UriInfo uriInfo, MlModel mlmodel) {
mlmodel.setHref(RestUtil.getHref(uriInfo, COLLECTION_PATH, mlmodel.getId()));
Entity.withHref(uriInfo, mlmodel.getOwner());
Entity.withHref(uriInfo, mlmodel.getDashboard());
Entity.withHref(uriInfo, mlmodel.getFollowers());
return mlmodel;
}
@Inject
public MlModelResource(CollectionDAO dao, Authorizer authorizer) {
Objects.requireNonNull(dao, "ModelRepository must not be null");
this.dao = new MlModelRepository(dao);
this.authorizer = authorizer;
}
public static class MlModelList extends ResultList<MlModel> {
@SuppressWarnings("unused")
MlModelList() {
// Empty constructor needed for deserialization
}
public MlModelList(List<MlModel> data, String beforeCursor, String afterCursor, int total)
throws GeneralSecurityException, UnsupportedEncodingException {
super(data, beforeCursor, afterCursor, total);
}
}
static final String FIELDS =
"owner,dashboard,algorithm,mlFeatures,mlHyperParameters,mlStore,server," + "followers,tags,usageSummary";
public static final List<String> FIELD_LIST = Arrays.asList(FIELDS.replaceAll(" ", "").split(","));
@GET
@Valid
@Operation(
summary = "List ML Models",
tags = "mlModels",
description =
"Get a list of ML Models. Use `fields` parameter to get only necessary fields. "
+ " Use cursor-based pagination to limit the number "
+ "entries in the list using `limit` and `before` or `after` query params.",
responses = {
@ApiResponse(
responseCode = "200",
description = "List of models",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = MlModelList.class)))
})
public ResultList<MlModel> list(
@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@Parameter(
description = "Fields requested in the returned resource",
schema = @Schema(type = "string", example = FIELDS))
@QueryParam("fields")
String fieldsParam,
@Parameter(description = "Limit the number models returned. (1 to 1000000, " + "default = 10)")
@DefaultValue("10")
@Min(1)
@Max(1000000)
@QueryParam("limit")
int limitParam,
@Parameter(description = "Returns list of models before this cursor", schema = @Schema(type = "string"))
@QueryParam("before")
String before,
@Parameter(description = "Returns list of models after this cursor", schema = @Schema(type = "string"))
@QueryParam("after")
String after)
throws IOException, GeneralSecurityException, ParseException {
RestUtil.validateCursors(before, after);
Fields fields = new Fields(FIELD_LIST, fieldsParam);
ResultList<MlModel> mlmodels;
if (before != null) { // Reverse paging
mlmodels = dao.listBefore(uriInfo, fields, null, limitParam, before);
} else { // Forward paging or first page
mlmodels = dao.listAfter(uriInfo, fields, null, limitParam, after);
}
mlmodels.getData().forEach(m -> addHref(uriInfo, m));
return mlmodels;
}
@GET
@Path("/{id}")
@Operation(
summary = "Get an ML Model",
tags = "mlModels",
description = "Get an ML Model by `id`.",
responses = {
@ApiResponse(
responseCode = "200",
description = "The model",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = MlModel.class))),
@ApiResponse(responseCode = "404", description = "Model for instance {id} is not found")
})
public MlModel get(
@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@PathParam("id") String id,
@Parameter(
description = "Fields requested in the returned resource",
schema = @Schema(type = "string", example = FIELDS))
@QueryParam("fields")
String fieldsParam)
throws IOException, ParseException {
Fields fields = new Fields(FIELD_LIST, fieldsParam);
return addHref(uriInfo, dao.get(uriInfo, id, fields));
}
@GET
@Path("/name/{fqn}")
@Operation(
summary = "Get an ML Model by name",
tags = "mlModels",
description = "Get an ML Model by fully qualified name.",
responses = {
@ApiResponse(
responseCode = "200",
description = "The model",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = MlModel.class))),
@ApiResponse(responseCode = "404", description = "Model for instance {id} is not found")
})
public MlModel getByName(
@Context UriInfo uriInfo,
@PathParam("fqn") String fqn,
@Context SecurityContext securityContext,
@Parameter(
description = "Fields requested in the returned resource",
schema = @Schema(type = "string", example = FIELDS))
@QueryParam("fields")
String fieldsParam)
throws IOException, ParseException {
Fields fields = new Fields(FIELD_LIST, fieldsParam);
return addHref(uriInfo, dao.getByName(uriInfo, fqn, fields));
}
@POST
@Operation(
summary = "Create an ML Model",
tags = "mlModels",
description = "Create a new ML Model.",
responses = {
@ApiResponse(
responseCode = "200",
description = "ML Model",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = CreateMlModel.class))),
@ApiResponse(responseCode = "400", description = "Bad request")
})
public Response create(
@Context UriInfo uriInfo, @Context SecurityContext securityContext, @Valid CreateMlModel create)
throws IOException {
SecurityUtil.checkAdminOrBotRole(authorizer, securityContext);
MlModel mlModel = getMlModel(securityContext, create);
mlModel = addHref(uriInfo, dao.create(uriInfo, mlModel));
return Response.created(mlModel.getHref()).entity(mlModel).build();
}
@PATCH
@Path("/{id}")
@Operation(
summary = "Update an ML Model",
tags = "mlModels",
description = "Update an existing ML Model using JsonPatch.",
externalDocs = @ExternalDocumentation(description = "JsonPatch RFC", url = "https://tools.ietf.org/html/rfc6902"))
@Consumes(MediaType.APPLICATION_JSON_PATCH_JSON)
public Response patch(
@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@Parameter(description = "Id of the ML Model", schema = @Schema(type = "string")) @PathParam("id") String id,
@RequestBody(
description = "JsonPatch with array of operations",
content =
@Content(
mediaType = MediaType.APPLICATION_JSON_PATCH_JSON,
examples = {
@ExampleObject("[" + "{op:remove, path:/a}," + "{op:add, path: /b, value: val}" + "]")
}))
JsonPatch patch)
throws IOException, ParseException {
Fields fields = new Fields(FIELD_LIST, FIELDS);
MlModel mlModel = dao.get(uriInfo, id, fields);
SecurityUtil.checkAdminRoleOrPermissions(authorizer, securityContext, dao.getOwnerReference(mlModel));
PatchResponse<MlModel> response =
dao.patch(uriInfo, UUID.fromString(id), securityContext.getUserPrincipal().getName(), patch);
addHref(uriInfo, response.getEntity());
return response.toResponse();
}
@PUT
@Operation(
summary = "Create or update an ML Model",
tags = "mlModels",
description = "Create a new ML Model, if it does not exist or update an existing model.",
responses = {
@ApiResponse(
responseCode = "200",
description = "The model",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = MlModel.class))),
@ApiResponse(responseCode = "400", description = "Bad request")
})
public Response createOrUpdate(
@Context UriInfo uriInfo, @Context SecurityContext securityContext, @Valid CreateMlModel create)
throws IOException, ParseException {
MlModel mlModel = getMlModel(securityContext, create);
SecurityUtil.checkAdminRoleOrPermissions(authorizer, securityContext, dao.getOwnerReference(mlModel));
PutResponse<MlModel> response = dao.createOrUpdate(uriInfo, mlModel);
addHref(uriInfo, response.getEntity());
return response.toResponse();
}
@PUT
@Path("/{id}/followers")
@Operation(
summary = "Add a follower",
tags = "mlModels",
description = "Add a user identified by `userId` as follower of this model",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "model for instance {id} is not found")
})
public Response addFollower(
@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@Parameter(description = "Id of the model", schema = @Schema(type = "string")) @PathParam("id") String id,
@Parameter(description = "Id of the user to be added as follower", schema = @Schema(type = "string"))
String userId)
throws IOException {
return dao.addFollower(securityContext.getUserPrincipal().getName(), UUID.fromString(id), UUID.fromString(userId))
.toResponse();
}
@DELETE
@Path("/{id}/followers/{userId}")
@Operation(
summary = "Remove a follower",
tags = "mlModels",
description = "Remove the user identified `userId` as a follower of the model.")
public Response deleteFollower(
@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@Parameter(description = "Id of the model", schema = @Schema(type = "string")) @PathParam("id") String id,
@Parameter(description = "Id of the user being removed as follower", schema = @Schema(type = "string"))
@PathParam("userId")
String userId)
throws IOException {
return dao.deleteFollower(
securityContext.getUserPrincipal().getName(), UUID.fromString(id), UUID.fromString(userId))
.toResponse();
}
@GET
@Path("/{id}/versions")
@Operation(
summary = "List Ml Model versions",
tags = "mlModels",
description = "Get a list of all the versions of an Ml Model identified by `id`",
responses = {
@ApiResponse(
responseCode = "200",
description = "List of Ml Model versions",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = EntityHistory.class)))
})
public EntityHistory listVersions(
@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@Parameter(description = "ML Model Id", schema = @Schema(type = "string")) @PathParam("id") String id)
throws IOException, ParseException {
return dao.listVersions(id);
}
@GET
@Path("/{id}/versions/{version}")
@Operation(
summary = "Get a version of the ML Model",
tags = "mlModels",
description = "Get a version of the ML Model by given `id`",
responses = {
@ApiResponse(
responseCode = "200",
description = "MlModel",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = MlModel.class))),
@ApiResponse(
responseCode = "404",
description = "ML Model for instance {id} and version {version} is " + "not found")
})
public MlModel getVersion(
@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@Parameter(description = "ML Model Id", schema = @Schema(type = "string")) @PathParam("id") String id,
@Parameter(
description = "ML Model version number in the form `major`.`minor`",
schema = @Schema(type = "string", example = "0.1 or 1.1"))
@PathParam("version")
String version)
throws IOException, ParseException {
return dao.getVersion(id, version);
}
@DELETE
@Path("/{id}")
@Operation(
summary = "Delete an ML Model",
tags = "mlModels",
description = "Delete an ML Model by `id`.",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "model for instance {id} is not found")
})
public Response delete(
@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@Parameter(description = "Id of the ML Model", schema = @Schema(type = "string")) @PathParam("id") String id)
throws IOException {
SecurityUtil.checkAdminOrBotRole(authorizer, securityContext);
dao.delete(UUID.fromString(id), false);
return Response.ok().build();
}
private MlModel getMlModel(SecurityContext securityContext, CreateMlModel create) {
return new MlModel()
.withId(UUID.randomUUID())
.withName(create.getName())
.withDisplayName(create.getDisplayName())
.withDescription(create.getDescription())
.withDashboard(create.getDashboard())
.withAlgorithm(create.getAlgorithm())
.withMlFeatures(create.getMlFeatures())
.withMlHyperParameters(create.getMlHyperParameters())
.withMlStore(create.getMlStore())
.withServer(create.getServer())
.withTags(create.getTags())
.withOwner(create.getOwner())
.withUpdatedBy(securityContext.getUserPrincipal().getName())
.withUpdatedAt(new Date());
}
}
|
/**
*
* Copyright 2004, 2005 The Apache Software Foundation or its licensors, as applicable.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.console.internaldb;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Map;
public class InternalDBHelper {
private static final int RDBMS_DERBY = 1;
private static final int RDBMS_MSSQL = 2;
private static final String JNDI_DERBY = "java:comp/env/SystemDatasource";
private static final Map derbyDBInfo = new Hashtable();
/**
* Returns the database metadata as a map.
*
* @return
*/
public Map getDBInfo() {
derbyDBInfo.clear();
Connection conn = null;
try {
conn = DerbyConnectionUtil.getSystemDBConnection();
DatabaseMetaData dbMD = (DatabaseMetaData) conn.getMetaData();
// DB
derbyDBInfo.put("URL", removeNull(dbMD.getURL()));
derbyDBInfo.put("Username", removeNull(dbMD.getUserName()));
derbyDBInfo.put("Read Only", removeNull(String.valueOf(dbMD
.isReadOnly())));
derbyDBInfo.put("DB Product Name", removeNull(dbMD
.getDatabaseProductName()));
derbyDBInfo.put("DB Product Version", removeNull(dbMD
.getDatabaseProductVersion()));
derbyDBInfo.put("DB Major Version", removeNull(String.valueOf(dbMD
.getDatabaseMajorVersion())));
derbyDBInfo.put("DB Minor Version", removeNull(String.valueOf(dbMD
.getDatabaseMinorVersion())));
// Driver
derbyDBInfo.put("Driver Name", removeNull(dbMD.getDriverName()));
derbyDBInfo.put("Driver Version", removeNull(dbMD
.getDriverVersion()));
derbyDBInfo.put("Driver Major Version", removeNull(String
.valueOf(dbMD.getDriverMajorVersion())));
derbyDBInfo.put("Driver Minor Version", removeNull(String
.valueOf(dbMD.getDriverMinorVersion())));
// JDBC
derbyDBInfo.put("JDBC Major Version", removeNull(String
.valueOf(dbMD.getJDBCMajorVersion())));
derbyDBInfo.put("JDBC Minor Version", removeNull(String
.valueOf(dbMD.getJDBCMinorVersion())));
// Functions
derbyDBInfo.put("Numeric Functions", removeNull(dbMD
.getNumericFunctions()));
derbyDBInfo.put("String Functions", removeNull(dbMD
.getStringFunctions()));
derbyDBInfo.put("System Functions", removeNull(dbMD
.getSystemFunctions()));
derbyDBInfo.put("Time Date Functions", removeNull(dbMD
.getTimeDateFunctions()));
// Etc
derbyDBInfo.put("Supported SQL Keywords", removeNull(dbMD
.getSQLKeywords().replace(',', ' ')));
derbyDBInfo.put("Supported Types", removeNull(getColumnData(dbMD
.getTypeInfo(), "TYPE_NAME")));
derbyDBInfo.put("Table Types", removeNull(getColumnData(dbMD
.getTableTypes(), "TABLE_TYPE")));
derbyDBInfo.put("Schemas", removeNull(getColumnData(dbMD
.getSchemas(), "TABLE_SCHEM")));
String tx = null;
switch (dbMD.getDefaultTransactionIsolation()) {
case Connection.TRANSACTION_NONE:
tx = "not supported";
break;
case Connection.TRANSACTION_READ_COMMITTED:
tx = "dirty reads are prevented; non-repeatable reads and phantom reads can occur";
break;
case Connection.TRANSACTION_READ_UNCOMMITTED:
tx = "dirty reads, non-repeatable reads and phantom reads can occur";
break;
case Connection.TRANSACTION_REPEATABLE_READ:
tx = "dirty reads and non-repeatable reads are prevented; phantom reads can occur";
break;
case Connection.TRANSACTION_SERIALIZABLE:
tx = "dirty reads, non-repeatable reads and phantom reads are prevented";
break;
default:
tx = "";
break;
}
derbyDBInfo.put("Default Transaction Isolation", removeNull(tx));
String holdability = null;
switch (dbMD.getResultSetHoldability()) {
case ResultSet.HOLD_CURSORS_OVER_COMMIT:
holdability = "hold cursors over commit";
break;
case ResultSet.CLOSE_CURSORS_AT_COMMIT:
holdability = "close cursors at commit";
break;
default:
holdability = "";
break;
}
derbyDBInfo.put("Result Set Holdability", removeNull(holdability));
String sqlStateType = null;
switch (dbMD.getSQLStateType()) {
case DatabaseMetaData.sqlStateXOpen:
sqlStateType = "X/Open SQL CLI";
break;
case DatabaseMetaData.sqlStateSQL99:
sqlStateType = "SQL99";
break;
default:
sqlStateType = "";
break;
}
derbyDBInfo.put("SQL State Type", removeNull(sqlStateType));
} catch (SQLException e) {
printSQLError((SQLException) e);
} finally {
// close DB connection
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
// problem closing DB connection
}
}
return derbyDBInfo;
}
private String removeNull(String s) {
return ((s == null) ? "" : s);
}
/**
* Get a specific column data as a string separated by ','.
*
* @param rs
* @param colName
* @return
*/
private String getColumnData(ResultSet rs, String colName) {
StringBuffer result = new StringBuffer();
try {
ResultSetMetaData rsmd = rs.getMetaData();
// 1) Get column number
int selectedCol = -1;
int numberOfColumns = rsmd.getColumnCount();
for (int i = 1; i <= numberOfColumns; i++) {
String columnName = rsmd.getColumnName(i);
if (columnName.equals(colName)) {
selectedCol = i;
break;
}
}
// 2) Get data
boolean firstData = true;
while (rs.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
if (i == selectedCol) {
if (firstData) {
firstData = false;
} else {
result.append(',');
}
String columnValue = rs.getString(i);
result.append(columnValue);
}
}
}
} catch (SQLException e) {
printSQLError((SQLException) e);
}
return result.toString();
}
/**
* Print the SQL exception including chained exceptions
* if there is one.
*
* @param e
*/
private void printSQLError(SQLException e) {
while (e != null) {
System.out.println(e.toString());
e = e.getNextException();
}
}
}
|
package com.demo.api.query;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class FindGiftCardQry implements Serializable {
private String id;
}
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/**
* HTTP message parser and writer APIs for synchronous, blocking
* communication.
*/
package org.apache.http.io;
|
package vim;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import java.io.IOException;
import java.io.File;
public class Groovy implements Interpreter {
private Binding binding;
private GroovyShell shell;
public Groovy() {
binding = new Binding();
binding.setVariable("Vim", Vim.getInstance());
shell = new GroovyShell(binding);
}
@Override
public void onExit() {
;
}
@Override
public String ex_java(String text) {
Object ret = shell.evaluate(text);
if (ret != null)
return ret.toString();
else
return null;
}
@Override
public String ex_javafile(String path) throws IOException {
File file = new File(path);
if (!file.exists()) {
Vim.emsg("Path given to Groovy.evalFile() does not exist: " +
path);
return null;
}
if (!file.canRead()) {
Vim.emsg("Path given to Groovy.evalFile() cannot be read: " +
path);
return null;
}
Object ret = shell.evaluate(file);
if (ret != null)
return ret.toString();
else
return null;
}
@Override
public Object do_javaeval(String text) {
return null;
}
}
|
package org.springframework.cloud.client.serviceregistry;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.test.ClassPathExclusions;
import org.springframework.cloud.test.ModifiedClassPathRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.fail;
/**
* @author Spencer Gibb
*/
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions({"spring-boot-actuator-*.jar", "spring-boot-starter-actuator-*.jar"})
public class ServiceRegistryAutoConfigurationTests {
@Test
public void runsWithoutActuator() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfig.class).web(WebApplicationType.NONE).run();
try {
context.getBean("serviceRegistryEndpoint");
fail("found a bean that shouldn't be there");
} catch (NoSuchBeanDefinitionException e) {
// success
}
}
@Configuration
protected static class TestConfig {
}
}
|
package edu.fiuba.algo3.modelo.continente;
import java.util.*;
import edu.fiuba.algo3.modelo.juego.Jugador;
import edu.fiuba.algo3.modelo.juego.Pais;
public abstract class Continente {
private final String nombre;
private final HashMap<String, Pais> paises = new HashMap<>();
public Continente(String unNombre){
this.nombre = unNombre;
}
public void aniadirPais(Pais unPais){
if (!this.paises.containsKey(unPais.obtenerNombre()))
this.paises.put(unPais.obtenerNombre(), unPais);
}
public String obtenerNombre(){
return this.nombre;
}
public Collection<Pais>obtenerPaises() {
return paises.values();
}
public Pais obtenerPais(String unPais) { return paises.get(unPais);
}
abstract int cantidadEjercitosExtra();
public int obtenerEjercitosExtra(Jugador unJugador){
for(Pais pais : this.obtenerPaises()){
if(!pais.perteneceA(unJugador)){
return 0;
}
}
return this.cantidadEjercitosExtra();
}
}
|
package com.small.saasdriver.utils.bitmap;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
/**
* 本地缓存工具类
*
*
*/
public class LocalCacheUtils {
private static final String LOCAL_PATH = Environment
.getExternalStorageDirectory().getAbsolutePath() + "/zhbj_cache_88";
/**
* 从本地读取图片
*
* @param url
* @return
*/
public Bitmap getBitmapFromLocal(String url) {
try {
String fileName = MD5Encoder.encode(url);
File file = new File(LOCAL_PATH, fileName);
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(
file));
return bitmap;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 向本地存图片
*
* @param url
* @param bitmap
*/
public void putBitmapToLocal(String url, Bitmap bitmap) {
try {
String fileName = MD5Encoder.encode(url);
File file = new File(LOCAL_PATH, fileName);
File parent = file.getParentFile();
// 创建父文件夹
if (!parent.exists()) {
parent.mkdirs();
}
bitmap.compress(CompressFormat.JPEG, 100,
new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
// Copyright (c) 2015 ServiceStack LLC. All rights reserved.
// License: https://servicestack.net/bsd-license.txt
package net.servicestack.client;
import java.util.ArrayList;
public class WebServiceException extends RuntimeException {
int StatusCode;
String StatusDescription;
String ResponseBody;
ResponseStatus ResponseStatus;
public WebServiceException(
int statusCode, String statusDescription, String responseBody)
{
StatusCode = statusCode;
StatusDescription = statusDescription;
ResponseBody = responseBody;
}
public void setResponseStatus(ResponseStatus responseStatus){
ResponseStatus = responseStatus;
}
public ResponseStatus getResponseStatus(){
return ResponseStatus;
}
public String getErrorCode(){
return ResponseStatus != null ? ResponseStatus.errorCode : null;
}
public String getErrorMessage(){
return ResponseStatus != null ? ResponseStatus.message : null;
}
public String getServerStackTrace(){
return ResponseStatus != null ? ResponseStatus.stackTrace : null;
}
public int getStatusCode() {
return this.StatusCode;
}
public String getStatusDescription() {
return this.StatusDescription;
}
public ArrayList<ResponseError> getFieldErrors(){
ArrayList<ResponseError> fieldErrors = ResponseStatus != null
? ResponseStatus.getErrors()
: null;
return fieldErrors != null ? fieldErrors : new ArrayList<ResponseError>();
}
}
|
package com.alipay.api.domain;
import java.util.Date;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 商户订单中心商品订单开放接口返回结果
*
* @author auto create
* @since 1.0, 2018-11-27 15:37:09
*/
public class ItemOrderOpenData extends AlipayObject {
private static final long serialVersionUID = 5669117859577441395L;
/**
* 商品订单扩展信息
*/
@ApiField("ext_info")
private String extInfo;
/**
* 订单创建时间
*/
@ApiField("gmt_create")
private Date gmtCreate;
/**
* 订单修改时间
*/
@ApiField("gmt_modified")
private Date gmtModified;
/**
* 商品ID
*/
@ApiField("item_id")
private String itemId;
/**
* 商品名称
*/
@ApiField("item_name")
private String itemName;
/**
* 商品订单ID
*/
@ApiField("item_order_id")
private String itemOrderId;
/**
* 关联主订单ID
*/
@ApiField("order_id")
private String orderId;
/**
* 商品数量
*/
@ApiField("quantity")
private Long quantity;
/**
* 实付金额;单位:分
*/
@ApiField("real_amount")
private Long realAmount;
/**
* 商品SKUID
*/
@ApiField("sku_id")
private String skuId;
/**
* 商品快照ID
*/
@ApiField("snapshot_id")
private String snapshotId;
/**
* 商品订单状态;INIT(初始化)、WAIT_PAY(待支付)、PAID(已支付)、SUCCESS_FINISHED(已完结)、REFUNDED(已退款)、CLOSED(已关闭)
*/
@ApiField("status")
private String status;
/**
* 商户补贴金额;单位:分
*/
@ApiField("subsidy_amount")
private Long subsidyAmount;
/**
* 商品单价;单位:分
*/
@ApiField("unit_price")
private Long unitPrice;
public String getExtInfo() {
return this.extInfo;
}
public void setExtInfo(String extInfo) {
this.extInfo = extInfo;
}
public Date getGmtCreate() {
return this.gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return this.gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
public String getItemId() {
return this.itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemName() {
return this.itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemOrderId() {
return this.itemOrderId;
}
public void setItemOrderId(String itemOrderId) {
this.itemOrderId = itemOrderId;
}
public String getOrderId() {
return this.orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public Long getQuantity() {
return this.quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public Long getRealAmount() {
return this.realAmount;
}
public void setRealAmount(Long realAmount) {
this.realAmount = realAmount;
}
public String getSkuId() {
return this.skuId;
}
public void setSkuId(String skuId) {
this.skuId = skuId;
}
public String getSnapshotId() {
return this.snapshotId;
}
public void setSnapshotId(String snapshotId) {
this.snapshotId = snapshotId;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public Long getSubsidyAmount() {
return this.subsidyAmount;
}
public void setSubsidyAmount(Long subsidyAmount) {
this.subsidyAmount = subsidyAmount;
}
public Long getUnitPrice() {
return this.unitPrice;
}
public void setUnitPrice(Long unitPrice) {
this.unitPrice = unitPrice;
}
}
|
package me.chanjar.weixin.cp.constant;
import lombok.experimental.UtilityClass;
/**
* <pre>
* 企业微信常量
* Created by Binary Wang on 2018/8/25.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@UtilityClass
public class WxCpConsts {
/**
* 企业微信端推送过来的事件类型.
* 参考文档:https://work.weixin.qq.com/api/doc#12974
*/
@UtilityClass
public static class EventType {
/**
* 成员关注事件.
*/
public static final String SUBSCRIBE = "subscribe";
/**
* 成员取消关注事件.
*/
public static final String UNSUBSCRIBE = "unsubscribe";
/**
* 进入应用事件.
*/
public static final String ENTER_AGENT = "enter_agent";
/**
* 上报地理位置.
*/
public static final String LOCATION = "LOCATION";
/**
* 异步任务完成事件推送.
*/
public static final String BATCH_JOB_RESULT = "batch_job_result";
/**
* 企业微信通讯录变更事件.
*/
public static final String CHANGE_CONTACT = "change_contact";
/**
* 点击菜单拉取消息的事件推送.
*/
public static final String CLICK = "click";
/**
* 点击菜单跳转链接的事件推送.
*/
public static final String VIEW = "view";
/**
* 扫码推事件的事件推送.
*/
public static final String SCANCODE_PUSH = "scancode_push";
/**
* 扫码推事件且弹出“消息接收中”提示框的事件推送.
*/
public static final String SCANCODE_WAITMSG = "scancode_waitmsg";
/**
* 弹出系统拍照发图的事件推送.
*/
public static final String PIC_SYSPHOTO = "pic_sysphoto";
/**
* 弹出拍照或者相册发图的事件推送.
*/
public static final String PIC_PHOTO_OR_ALBUM = "pic_photo_or_album";
/**
* 弹出微信相册发图器的事件推送.
*/
public static final String PIC_WEIXIN = "pic_weixin";
/**
* 弹出地理位置选择器的事件推送.
*/
public static final String LOCATION_SELECT = "location_select";
/**
* 任务卡片事件推送.
*/
public static final String TASKCARD_CLICK = "taskcard_click";
/**
* 企业成员添加外部联系人事件推送
*/
public static final String CHANGE_EXTERNAL_CONTACT = "change_external_contact";
/**
* 企业微信审批事件推送(自建应用审批)
*/
public static final String OPEN_APPROVAL_CHANGE = "open_approval_change";
/**
* 企业微信审批事件推送(系统审批)
*/
public static final String SYS_APPROVAL_CHANGE = "sys_approval_change";
/**
* 修改日历事件
*/
public static final String MODIFY_CALENDAR = "modify_calendar";
/**
* 删除日历事件
*/
public static final String DELETE_CALENDAR = "delete_calendar";
/**
* 添加日程事件
*/
public static final String ADD_SCHEDULE = "add_schedule";
/**
* 修改日程事件
*/
public static final String MODIFY_SCHEDULE = "modify_schedule";
/**
* 删除日程事件
*/
public static final String DELETE_SCHEDULE = "delete_schedule";
}
/**
* 企业外部联系人变更事件的CHANGE_TYPE
*/
@UtilityClass
public static class ExternalContactChangeType {
/**
* 新增外部联系人
*/
public static final String ADD_EXTERNAL_CONTACT = "add_external_contact";
/**
* 删除外部联系人
*/
public static final String DEL_EXTERNAL_CONTACT = "del_external_contact";
/**
* 外部联系人免验证添加成员事件
*/
public static final String ADD_HALF_EXTERNAL_CONTACT = "add_half_external_contact";
/**
* 删除跟进成员事件
*/
public static final String DEL_FOLLOW_USER = "del_follow_user";
}
/**
* 企业微信通讯录变更事件.
*/
@UtilityClass
public static class ContactChangeType {
/**
* 新增成员事件.
*/
public static final String CREATE_USER = "create_user";
/**
* 更新成员事件.
*/
public static final String UPDATE_USER = "update_user";
/**
* 删除成员事件.
*/
public static final String DELETE_USER = "delete_user";
/**
* 新增部门事件.
*/
public static final String CREATE_PARTY = "create_party";
/**
* 更新部门事件.
*/
public static final String UPDATE_PARTY = "update_party";
/**
* 删除部门事件.
*/
public static final String DELETE_PARTY = "delete_party";
/**
* 标签成员变更事件.
*/
public static final String UPDATE_TAG = "update_tag";
}
/**
* 互联企业发送应用消息的消息类型.
*/
@UtilityClass
public static class LinkedCorpMsgType {
/**
* 文本消息.
*/
public static final String TEXT = "text";
/**
* 图片消息.
*/
public static final String IMAGE = "image";
/**
* 视频消息.
*/
public static final String VIDEO = "video";
/**
* 图文消息(点击跳转到外链).
*/
public static final String NEWS = "news";
/**
* 图文消息(点击跳转到图文消息页面).
*/
public static final String MPNEWS = "mpnews";
/**
* markdown消息.
* (目前仅支持markdown语法的子集,微工作台(原企业号)不支持展示markdown消息)
*/
public static final String MARKDOWN = "markdown";
/**
* 发送文件.
*/
public static final String FILE = "file";
/**
* 文本卡片消息.
*/
public static final String TEXTCARD = "textcard";
/**
* 小程序通知消息.
*/
public static final String MINIPROGRAM_NOTICE = "miniprogram_notice";
}
/**
* 群机器人的消息类型.
*/
@UtilityClass
public static class GroupRobotMsgType {
/**
* 文本消息.
*/
public static final String TEXT = "text";
/**
* 图片消息.
*/
public static final String IMAGE = "image";
/**
* markdown消息.
*/
public static final String MARKDOWN = "markdown";
/**
* 图文消息(点击跳转到外链).
*/
public static final String NEWS = "news";
}
/**
* 应用推送消息的消息类型.
*/
@UtilityClass
public static class AppChatMsgType {
/**
* 文本消息.
*/
public static final String TEXT = "text";
/**
* 图片消息.
*/
public static final String IMAGE = "image";
/**
* 语音消息.
*/
public static final String VOICE = "voice";
/**
* 视频消息.
*/
public static final String VIDEO = "video";
/**
* 发送文件(CP专用).
*/
public static final String FILE = "file";
/**
* 文本卡片消息(CP专用).
*/
public static final String TEXTCARD = "textcard";
/**
* 图文消息(点击跳转到外链).
*/
public static final String NEWS = "news";
/**
* 图文消息(点击跳转到图文消息页面).
*/
public static final String MPNEWS = "mpnews";
/**
* markdown消息.
*/
public static final String MARKDOWN = "markdown";
}
@UtilityClass
public static class WorkBenchType {
/*
* 关键数据型
* */
public static final String KEYDATA = "keydata";
/*
* 图片型
* */
public static final String IMAGE = "image";
/*
* 列表型
* */
public static final String LIST = "list";
/*
* webview型
* */
public static final String WEBVIEW = "webview";
}
@UtilityClass
public static class WelcomeMsgType {
/**
* 图片消息.
*/
public static final String IMAGE = "image";
/**
* 图文消息.
*/
public static final String LINK = "link";
/**
* 视频消息.
*/
public static final String VIDEO = "video";
/**
* 小程序消息.
*/
public static final String MINIPROGRAM = "miniprogram";
/**
* 文件消息.
*/
public static final String FILE = "file";
}
@UtilityClass
public static class ProductAttachmentType {
/**
* 图片消息.
*/
public static final String IMAGE = "image";
}
}
|
/*
* Copyright 2007 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 grails.plugin.searchable.internal.compass.mapping;
import grails.core.GrailsDomainClass;
import grails.core.GrailsDomainClassProperty;
import grails.plugin.searchable.internal.SearchableUtils;
import grails.plugin.searchable.internal.util.GrailsDomainClassUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @author Maurice Nicholson
*/
public abstract class AbstractSearchableGrailsDomainClassCompassClassMapper implements SearchableGrailsDomainClassCompassClassMapper {
private static final List<String> DEFAULT_EXCLUDED_PROPERTIES = Arrays.asList("password");
private SearchableGrailsDomainClassPropertyMappingFactory domainClassPropertyMappingFactory;
private List defaultExcludedProperties;
private SearchableGrailsDomainClassCompassClassMapper parent;
/**
* Get the CompassClassMapping for the given GrailsDomainClass
*
* @param grailsDomainClass the Grails domain class
* @param searchableGrailsDomainClasses a collection of searchable GrailsDomainClass instances
* @return the CompassClassMapping
*/
public CompassClassMapping getCompassClassMapping(GrailsDomainClass grailsDomainClass, Collection searchableGrailsDomainClasses) {
return getCompassClassMapping(grailsDomainClass, searchableGrailsDomainClasses, SearchableUtils.getSearchablePropertyValue(grailsDomainClass), getExcludedProperties());
}
protected CompassClassPropertyMapping getDefaultPropertyMapping(GrailsDomainClassProperty property, Collection searchableClasses) {
return domainClassPropertyMappingFactory.getGrailsDomainClassPropertyMapping(property, searchableClasses);
}
protected List getInheritedPropertyMappings(GrailsDomainClass grailsDomainClass, Collection searchableGrailsDomainClasses, List excludedProperties) {
List parentMappedProperties = new ArrayList();
GrailsDomainClass superClass = GrailsDomainClassUtils.getSuperClass(grailsDomainClass, searchableGrailsDomainClasses);
while (superClass != null) {
List parentClassPropertyMappings = parent.getCompassClassPropertyMappings(superClass, searchableGrailsDomainClasses, SearchableUtils.getSearchablePropertyValue(superClass), excludedProperties);
SearchableGrailsDomainClassCompassMappingUtils.mergePropertyMappings(parentMappedProperties, parentClassPropertyMappings);
superClass = GrailsDomainClassUtils.getSuperClass(superClass, searchableGrailsDomainClasses);
}
return parentMappedProperties;
}
protected List getExcludedProperties() {
if (defaultExcludedProperties != null) {
return defaultExcludedProperties;
}
return DEFAULT_EXCLUDED_PROPERTIES;
}
public void setDefaultExcludedProperties(List defaultExcludedProperties) {
this.defaultExcludedProperties = defaultExcludedProperties;
}
public SearchableGrailsDomainClassPropertyMappingFactory getDomainClassPropertyMappingStrategyFactory() {
return domainClassPropertyMappingFactory;
}
public void setDomainClassPropertyMappingStrategyFactory(SearchableGrailsDomainClassPropertyMappingFactory domainClassPropertyMappingFactory) {
this.domainClassPropertyMappingFactory = domainClassPropertyMappingFactory;
}
public SearchableGrailsDomainClassCompassClassMapper getParent() {
return parent;
}
public void setParent(SearchableGrailsDomainClassCompassClassMapper parent) {
this.parent = parent;
}
}
|
package co.lq.modules.quartz.domain;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.CreationTimestamp;
import lombok.Getter;
import lombok.Setter;
/**
* @author billy
* @date 2019-01-07
*/
@Getter
@Setter
@Entity
@Table(name = "quartz_job")
public class QuartzJob implements Serializable {
public static final String JOB_KEY = "JOB_KEY";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@NotNull(groups = { Update.class })
private Long id;
/** 定时器名称 */
@Column(name = "job_name")
private String jobName;
/** Bean名称 */
@Column(name = "bean_name")
@NotBlank
private String beanName;
/** 方法名称 */
@Column(name = "method_name")
@NotBlank
private String methodName;
/** 参数 */
@Column(name = "params")
private String params;
/** cron表达式 */
@Column(name = "cron_expression")
@NotBlank
private String cronExpression;
/** 状态 */
@Column(name = "is_pause")
private Boolean isPause = false;
/** 备注 */
@Column(name = "remark")
@NotBlank
private String remark;
@Column(name = "create_time")
@CreationTimestamp
private Timestamp createTime;
public @interface Update {
}
}
|
/*
* TaskUnifier
* Copyright (c) 2013, Benjamin Leclerc
* 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 TaskUnifier or the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.leclercb.taskunifier.gui.components.notes.table;
import javax.swing.table.AbstractTableModel;
import com.leclercb.commons.api.utils.CheckUtils;
import com.leclercb.taskunifier.api.models.Note;
import com.leclercb.taskunifier.gui.api.accessor.PropertyAccessor;
import com.leclercb.taskunifier.gui.components.notes.NoteColumnList;
public class NotePrintTableModel extends AbstractTableModel {
private Note[] notes;
public NotePrintTableModel(Note[] notes) {
CheckUtils.isNotNull(notes);
this.notes = notes;
}
public Note getNote(int row) {
return this.notes[row];
}
public PropertyAccessor<Note> getNoteColumn(int col) {
return NoteColumnList.getInstance().getAccessor(col);
}
@Override
public int getColumnCount() {
return NoteColumnList.getInstance().getSize();
}
@Override
public int getRowCount() {
return this.notes.length;
}
@Override
public String getColumnName(int col) {
return this.getNoteColumn(col).getLabel();
}
@Override
public Class<?> getColumnClass(int col) {
return this.getNoteColumn(col).getType().getType();
}
@Override
public Object getValueAt(int row, int col) {
return this.getNoteColumn(col).getProperty(this.notes[row]);
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
@Override
public void setValueAt(Object value, int row, int col) {
}
}
|
/*
* Copyright 2011 JBoss 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 org.drools.guvnor.client.common;
import java.util.Set;
/**
* A interface defining the means to find available bindings for specific
* data-types
*/
public interface IBindingProvider {
Set<String> getBindings(String dataType);
}
|
/*
* Licensed to the University of California, Berkeley 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 tachyon.heartbeat;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* This class can be used for controlling when a heartbeat executes.
*/
public final class ScheduledTimer implements HeartbeatTimer {
private final String mThreadName;
private final Lock mLock;
private final Condition mCondition;
/**
* Creates a new instance of {@link ScheduledTimer}.
*
* @param threadName the thread name
* @param intervalMs the heartbeat interval (unused)
*/
public ScheduledTimer(String threadName, long intervalMs) {
mThreadName = threadName;
mLock = new ReentrantLock();
mCondition = mLock.newCondition();
}
/**
* @return the thread name
*/
public String getThreadName() {
return mThreadName;
}
/**
* Schedules execution of the heartbeat.
*/
public void schedule() {
mLock.lock();
mCondition.signal();
mLock.unlock();
}
/**
* Waits until the heartbeat is scheduled for execution.
*
* @throws InterruptedException if the thread is interrupted while waiting
*/
public synchronized void tick() throws InterruptedException {
HeartbeatScheduler.addTimer(this);
mLock.lock();
mCondition.await();
mLock.unlock();
}
}
|
/**
* Created by java-echarts library.
* @author: cattong <aronter@gmail.com>
*/
package com.beyongx.echarts.charts.line.select;
import java.io.Serializable;
import java.util.Map;
//import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
*
* {_more_}
*/
@lombok.Data
@EqualsAndHashCode(callSuper = false)
public class ItemStyle implements Serializable {
private static final long serialVersionUID = 1L;
private String color; // Default: '自适应'
private String borderColor; // Default: '#000'
private String borderWidth; // Default: 0
private Object borderType; //string|number|Array Default: 'solid'
private String borderDashOffset; // Default: 0
private String borderCap; // Default: 'butt'
private String borderJoin; // Default: 'bevel'
private String borderMiterLimit; // Default: 10
private Integer shadowBlur; //
private String shadowColor; //
private String shadowOffsetX; // Default: 0
private String shadowOffsetY; // Default: 0
private String opacity; // Default: 1
public ItemStyle()
{
}
public ItemStyle(Map<String, Object> property)
{
}
}
|
package com.minhtetoo.goodfood.events;
import android.content.Context;
import com.minhtetoo.goodfood.data.vo.FeaturedVO;
import com.minhtetoo.goodfood.data.vo.GuideVO;
import com.minhtetoo.goodfood.data.vo.PromotionVO;
import java.util.List;
/**
* Created by min on 1/19/2018.
*/
public class RestAPIEvent {
public static class EmptyResponseEvent {
}
public static class ErrorInvokingAPIEvent {
private String errorMsg;
public ErrorInvokingAPIEvent(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getErrorMsg() {
return errorMsg;
}
}
public static class FeaturedDataLoadedEvent {
private int loadedPageIndex;
private List<FeaturedVO> mloadedFeatureds;
private Context context;
public FeaturedDataLoadedEvent(int loadedPageIndex, List<FeaturedVO> loadedFeatureds, Context context) {
this.loadedPageIndex = loadedPageIndex;
this.mloadedFeatureds = loadedFeatureds;
this.context = context;
}
public int getLoadedPageIndex() {
return loadedPageIndex;
}
public List<FeaturedVO> getLoadFeatureds() {
return mloadedFeatureds;
}
public Context getContext() {
return context;
}
}
public static class PromotionDataLoadedEvent {
private int loadedPageIndex;
private List<PromotionVO> mloadedPromotions;
private Context context;
public PromotionDataLoadedEvent(int loadedPageIndex, List<PromotionVO> loadedPromotions, Context context) {
this.loadedPageIndex = loadedPageIndex;
this.mloadedPromotions = loadedPromotions;
this.context = context;
}
public int getLoadedPageIndex() {
return loadedPageIndex;
}
public List<PromotionVO> getLoadedPromotions() {
return mloadedPromotions;
}
public Context getContext() {
return context;
}
}
public static class GuuideDataLoadedEvent {
private int loadedPageIndex;
private List<GuideVO> mloadedGuides;
private Context context;
public GuuideDataLoadedEvent(int loadedPageIndex, List<GuideVO> loadedGuides, Context context) {
this.loadedPageIndex = loadedPageIndex;
this.mloadedGuides = loadedGuides;
this.context = context;
}
public int getLoadedPageIndex() {
return loadedPageIndex;
}
public List<GuideVO> getLoadedGuides() {
return mloadedGuides;
}
public Context getContext() {
return context;
}
}
}
|
/*
* Copyright [1999-2015] Wellcome Trust Sanger Institute and the
* EMBL-European Bioinformatics Institute
* Copyright [2016-2018] EMBL-European Bioinformatics Institute
*
* 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.ensembl.healthcheck.testcase.funcgen;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.Team;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
/**
* Check that every segmentation_file entry which has been used in the current
* Regulatory Build is linked to a BIGBED entry in the data_file table.
* Check that the file actually exists on the disk.
*
* @author ilavidas
*/
public class SegmentationFileHasBigBed extends DataFileTableHasFile {
public SegmentationFileHasBigBed() {
setTeamResponsible(Team.FUNCGEN);
setDescription("Check that every segmentation_file entry which has "
+ "been used in the current Regulatory Build is linked to a "
+ "BIGBED entry in the data_file table. Check that the file " +
"actually exists on the disk.");
}
@Override
protected FileType getFileType() {
return FileType.BIGBED;
}
@Override
protected TableName getTableName() {
return TableName.segmentation_file;
}
@Override
HashMap<Integer, String> getTableIDs(DatabaseRegistryEntry dbre) {
HashMap<Integer, String> tableIDs = new HashMap<Integer, String>();
Connection con = dbre.getConnection();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT segmentation_file_id," +
"segmentation_file.name FROM segmentation_file JOIN " +
"regulatory_build USING(regulatory_build_id) WHERE " +
"regulatory_build.is_current=1");
while (rs != null && rs.next()) {
tableIDs.put(rs.getInt(1), rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}
return tableIDs;
}
}
|
/*
* Original author: Daniel Jaschob <djaschob .at. uw.edu>
*
* Copyright 2018 University of Washington - Seattle, WA
*
* 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.yeastrc.limelight.limelight_webapp.spring_mvc_parts.data_pages.rest_controllers.other_like_project;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.yeastrc.limelight.limelight_webapp.access_control.access_control_rest_controller.ValidateWebSessionAccess_ToWebservice_ForAccessLevelAnd_ProjectIdsIF;
import org.yeastrc.limelight.limelight_shared.enum_classes.PsmPeptideMatchedProteinAnnotationType;
import org.yeastrc.limelight.limelight_webapp.exceptions.LimelightInternalErrorException;
import org.yeastrc.limelight.limelight_webapp.exceptions.webservice_access_exceptions.Limelight_WS_BadRequest_InvalidParameter_Exception;
import org.yeastrc.limelight.limelight_webapp.exceptions.webservice_access_exceptions.Limelight_WS_ErrorResponse_Base_Exception;
import org.yeastrc.limelight.limelight_webapp.exceptions.webservice_access_exceptions.Limelight_WS_InternalServerError_Exception;
import org.yeastrc.limelight.limelight_webapp.searchers.ProjectLevelDefaultFltrAnnCutoffs_For_DisplayOnMgmtPage_Searcher.ProjectLevelDefaultFltrAnnCutoffs_For_DisplayOnMgmtPage_Searcher__ResultItem;
import org.yeastrc.limelight.limelight_webapp.searchers.ProjectLevelDefaultFltrAnnCutoffs_For_DisplayOnMgmtPage_Searcher_IF;
import org.yeastrc.limelight.limelight_webapp.spring_mvc_parts.data_pages.rest_controllers.AA_RestWSControllerPaths_Constants;
import org.yeastrc.limelight.limelight_webapp.spring_mvc_parts.rest_controller_utils_common.Unmarshal_RestRequest_JSON_ToObject;
import org.yeastrc.limelight.limelight_webapp.web_utils.MarshalObjectToJSON;
import org.yeastrc.limelight.limelight_webapp.webservice_sync_tracking.Validate_WebserviceSyncTracking_CodeIF;
/**
* Get - Project Level Filter Default Cutoffs Override
*
*/
@RestController
public class Project_Level_Filter_Default_Cutoffs_Override_Maint__Get_RestWebserviceController {
private static final Logger log = LoggerFactory.getLogger( Project_Level_Filter_Default_Cutoffs_Override_Maint__Get_RestWebserviceController.class );
@Autowired
private Validate_WebserviceSyncTracking_CodeIF validate_WebserviceSyncTracking_Code;
@Autowired
private ValidateWebSessionAccess_ToWebservice_ForAccessLevelAnd_ProjectIdsIF validateWebSessionAccess_ToWebservice_ForAccessLevelAnd_ProjectIds;
@Autowired
private ProjectLevelDefaultFltrAnnCutoffs_For_DisplayOnMgmtPage_Searcher_IF projectLevelDefaultFltrAnnCutoffs_For_DisplayOnMgmtPage_Searcher;
@Autowired
private Unmarshal_RestRequest_JSON_ToObject unmarshal_RestRequest_JSON_ToObject;
@Autowired
private MarshalObjectToJSON marshalObjectToJSON;
/**
*
*/
public Project_Level_Filter_Default_Cutoffs_Override_Maint__Get_RestWebserviceController() {
super();
// log.warn( "constructor no params called" );
}
// Convert result object graph to JSON in byte[] in the controller body so can cache it
// These 2 annotations work the same
// Mapping the value in {} in the path to parameters in the method:
//
// The value in {} has to match the value in the "value = " in the @PathVariable
// If they don't match, a 500 error is thrown and nothing is logged and the method is not called.
// If there is no "value = " in the @PathVariable, the method parameter name is used.
@PostMapping(
path = {
AA_RestWSControllerPaths_Constants.PATH_START_ALL
+ AA_RestWSControllerPaths_Constants.PROJECT_LEVEL_FILTER_DEFAULT_CUTOFFS_OVERRIDE_MAINT__GET__REST_WEBSERVICE_CONTROLLER
},
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE )
// @RequestMapping(
// path = AA_RestWSControllerPaths_Constants.,
// method = RequestMethod.POST,
// consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public @ResponseBody ResponseEntity<byte[]> projectView(
@RequestBody byte[] postBody,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse
) throws Exception {
try {
// log.warn( "projectView(...) called" );
// Throws exception extended from Limelight_WS_ErrorResponse_Base_Exception
// to return specific error to web app JS code if webserviceSyncTracking is not current value
validate_WebserviceSyncTracking_Code.validate_webserviceSyncTracking_Code( httpServletRequest );
// Always accept POST body as byte[] and parse to JSON here so have POST body for caching or other needs
if ( postBody == null ) {
log.warn( "No Post Body" );
throw new Limelight_WS_BadRequest_InvalidParameter_Exception();
}
WebserviceRequest webserviceRequest = unmarshal_RestRequest_JSON_ToObject.getObjectFromJSONByteArray( postBody, WebserviceRequest.class );
// String postBodyAsString = new String( postBody, StandardCharsets.UTF_8 );
String projectIdentifier = webserviceRequest.projectIdentifier;
if ( StringUtils.isEmpty( projectIdentifier ) ) {
log.warn( "projectIdentifier is empty or not assigned" );
throw new Limelight_WS_BadRequest_InvalidParameter_Exception();
}
int projectId = 0;
try {
projectId = Integer.parseInt( projectIdentifier );
} catch ( RuntimeException e ) {
log.warn( "Project Identifier not parsable to int: " + projectIdentifier );
throw new Limelight_WS_BadRequest_InvalidParameter_Exception();
}
List<Integer> projectIds = new ArrayList<>( 1 );
projectIds.add( projectId );
// ValidateWebSessionAccess_ToWebservice_ForAccessLevelAndProjectIds_Result validateWebSessionAccess_ToWebservice_ForAccessLevelAndProjectIds_Result =
validateWebSessionAccess_ToWebservice_ForAccessLevelAnd_ProjectIds
.validatePublicAccessCodeReadAllowed( projectIds, httpServletRequest );
List<ProjectLevelDefaultFltrAnnCutoffs_For_DisplayOnMgmtPage_Searcher__ResultItem> dbList =
projectLevelDefaultFltrAnnCutoffs_For_DisplayOnMgmtPage_Searcher.getAllForProjectId( projectId );
List<WebserviceResultEntry> reportedPeptideEntriesList = new ArrayList<>( dbList.size() );
List<WebserviceResultEntry> psmEntriesList = new ArrayList<>( dbList.size() );
for ( ProjectLevelDefaultFltrAnnCutoffs_For_DisplayOnMgmtPage_Searcher__ResultItem resultItem : dbList ) {
WebserviceResultEntry webserviceResultEntry = new WebserviceResultEntry();
// webserviceResultEntry.id = resultItem.getId();
webserviceResultEntry.searchProgramName = resultItem.getSearchProgramName();
webserviceResultEntry.annotationTypeName = resultItem.getAnnotationTypeName();
webserviceResultEntry.annotationCutoffValue = resultItem.getAnnotationCutoffValue();
webserviceResultEntry.annotationCutoffValueString = resultItem.getAnnotationCutoffValueString();
if ( resultItem.getPsmPeptideMatchedProteinAnnotationType() == PsmPeptideMatchedProteinAnnotationType.PEPTIDE ) {
reportedPeptideEntriesList.add( webserviceResultEntry );
} else if ( resultItem.getPsmPeptideMatchedProteinAnnotationType() == PsmPeptideMatchedProteinAnnotationType.PSM ) {
psmEntriesList.add( webserviceResultEntry );
} else {
String msg = "Unknown value for resultItem.getPsmPeptideAnnotationType(): " + resultItem.getPsmPeptideMatchedProteinAnnotationType();
log.error( msg );
throw new LimelightInternalErrorException( msg );
}
}
WebserviceResult_CutoffValues cutoffValues = new WebserviceResult_CutoffValues();
cutoffValues.reportedPeptideEntriesList = reportedPeptideEntriesList;
cutoffValues.psmEntriesList = psmEntriesList;
WebserviceResult webserviceResult = new WebserviceResult();
webserviceResult.status = true;
webserviceResult.cutoffValues = cutoffValues;
byte[] responseAsJSON = marshalObjectToJSON.getJSONByteArray( webserviceResult );
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body( responseAsJSON );
} catch ( Limelight_WS_ErrorResponse_Base_Exception e ) {
// only rethrow Error Response Exceptions
throw e;
} catch ( Exception e ) {
String msg = "Failed in controller: ";
log.error( msg, e );
throw new Limelight_WS_InternalServerError_Exception();
}
}
/**
* Input to function webserviceMethod(..)
*/
public static class WebserviceRequest {
private String projectIdentifier;
public void setProjectIdentifier(String projectIdentifier) {
this.projectIdentifier = projectIdentifier;
}
}
/**
* result from Webservice
*
*/
public static class WebserviceResult {
private boolean status;
private WebserviceResult_CutoffValues cutoffValues;
public boolean isStatus() {
return status;
}
public WebserviceResult_CutoffValues getCutoffValues() {
return cutoffValues;
}
}
/**
* cutoffValues in WebserviceResult
*
*/
public static class WebserviceResult_CutoffValues {
private List<WebserviceResultEntry> reportedPeptideEntriesList;
private List<WebserviceResultEntry> psmEntriesList;
public List<WebserviceResultEntry> getReportedPeptideEntriesList() {
return reportedPeptideEntriesList;
}
public List<WebserviceResultEntry> getPsmEntriesList() {
return psmEntriesList;
}
}
/**
* Entry in WebserviceResult_CutoffValues
*
*/
public static class WebserviceResultEntry {
private String searchProgramName;
private String annotationTypeName;
private double annotationCutoffValue;
private String annotationCutoffValueString;
public String getSearchProgramName() {
return searchProgramName;
}
public String getAnnotationTypeName() {
return annotationTypeName;
}
public double getAnnotationCutoffValue() {
return annotationCutoffValue;
}
public String getAnnotationCutoffValueString() {
return annotationCutoffValueString;
}
}
}
|
/*-
* ============LICENSE_START==========================================
* ONAP Portal
* ===================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ===================================================================
*
* Unless otherwise specified, all software contained herein is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this software 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.
*
* Unless otherwise specified, all documentation contained herein is licensed
* under the Creative Commons License, Attribution 4.0 Intl. (the "License");
* you may not use this documentation except in compliance with the License.
* You may obtain a copy of the License at
*
* https://creativecommons.org/licenses/by/4.0/
*
* Unless required by applicable law or agreed to in writing, documentation
* 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.
*
* ============LICENSE_END============================================
*
*
*/
package org.onap.portalapp.conf;
import org.onap.portalsdk.core.conf.HibernateMappingLocatable;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
@Component
@Profile("src")
public class HibernateMappingLocations implements HibernateMappingLocatable {
public Resource[] getMappingLocations() {
return new Resource[] { new ClassPathResource("../fusion/orm/Fusion.hbm.xml"),
new ClassPathResource("../fusion/orm/EP.hbm.xml"),
new ClassPathResource("../fusion/orm/Workflow.hbm.xml") };
}
@Override
public String[] getPackagesToScan() {
return new String[] { "org.onap" };
}
}
|
/*
* (C) Copyright 2021 Boni Garcia (https://bonigarcia.github.io/)
*
* 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.github.bonigarcia.wdm.test.generic;
import static java.lang.invoke.MethodHandles.lookup;
import static org.junit.jupiter.api.condition.OS.LINUX;
import static org.slf4j.LoggerFactory.getLogger;
import java.time.Duration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import io.github.bonigarcia.wdm.WebDriverManager;
/**
* Test with generic manager.
*
* @author Boni Garcia
* @since 5.0.0
*/
@EnabledOnOs(LINUX)
class GenericCreateTest {
final Logger log = getLogger(lookup().lookupClass());
WebDriver driver;
WebDriverManager wdm;
@AfterEach
void teardown() {
wdm.quit();
System.clearProperty("wdm.defaultBrowser");
}
@ParameterizedTest
@ValueSource(strings = { "chrome", "firefox" })
void test(String defaultBrowser) {
System.setProperty("wdm.defaultBrowser", defaultBrowser);
wdm = WebDriverManager.getInstance();
driver = wdm.create();
String sutUrl = "https://bonigarcia.dev/selenium-webdriver-java/";
driver.get(sutUrl);
String title = driver.getTitle();
log.debug("The title of {} is {}", sutUrl, title);
Wait<WebDriver> wait = new WebDriverWait(driver,
Duration.ofSeconds(30));
wait.until(d -> d.getTitle().contains("Selenium WebDriver"));
}
}
|
package dicounter.message;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import dicounter.overlaynet.node.NodeAddress;
import java.util.UUID;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
@JsonDeserialize(builder = AggregateTriggersResponse.AggregateTriggersResponseBuilder.class)
public class AggregateTriggersResponse implements DicounterMessage {
private final UUID countingTaskId;
private final UUID id;
private final int roundNo;
private final NodeAddress aggregatingLeaderAddress;
private final NodeAddress reportingNodeAddress;
private final long numReceivedTriggers;
@JsonIgnore
@Override
public DicounterMessageType getType() {
return DicounterMessageType.AGGREGATE_TRIGGERS_RESPONSE;
}
@JsonPOJOBuilder(withPrefix = "")
public static final class AggregateTriggersResponseBuilder {
}
}
|
/*
* Copyright 2012-2016 JetBrains s.r.o
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.jetpad.cell.toDom;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.DOM;
import jetbrains.jetpad.cell.Cell;
import jetbrains.jetpad.cell.CellPropertySpec;
import jetbrains.jetpad.cell.mappersUtil.CounterSpec;
import jetbrains.jetpad.cell.mappersUtil.Counters;
import jetbrains.jetpad.cell.mappersUtil.HasCounters;
import jetbrains.jetpad.cell.mappersUtil.PopupManager;
import jetbrains.jetpad.mapper.Mapper;
import jetbrains.jetpad.mapper.MappingContext;
import jetbrains.jetpad.model.collections.list.ObservableList;
import jetbrains.jetpad.model.composite.Composites;
import jetbrains.jetpad.model.event.EventHandler;
import jetbrains.jetpad.model.property.PropertyChangeEvent;
import jetbrains.jetpad.values.Color;
import java.util.AbstractList;
import java.util.Collection;
import java.util.List;
import static jetbrains.jetpad.cell.toDom.CellContainerToDomMapper.CSS;
import static jetbrains.jetpad.cell.toDom.CellContainerToDomMapper.ELEMENT;
abstract class BaseCellMapper<SourceT extends Cell> extends Mapper<SourceT, Element> implements HasCounters, EventHandler<PropertyChangeEvent<Cell>> {
private static final String BACKGROUND = "background";
private static final String UNDERLINE_SUFFIX = " bottom repeat-x";
private CellToDomContext myContext;
private Counters myCounters;
private List<Mapper<?, ?>> myChildMappers = null;
private List<Node> myChildTargets = null;
private PopupManager myPopupManager;
private Color myAncestorBackground;
private boolean myWasPopup;
BaseCellMapper(SourceT source, CellToDomContext ctx, Element target) {
super(source, target);
if (ctx == null) {
throw new IllegalArgumentException();
}
myContext = ctx;
}
protected CellToDomContext getContext() {
return myContext;
}
@Override
protected void onAttach(MappingContext ctx) {
super.onAttach(ctx);
myContext.register(this);
myWasPopup = Composites.<Cell>isNonCompositeChild(getSource());
getSource().getProp(ELEMENT).set(getTarget());
getTarget().addClassName(CSS.cell());
if (isAutoChildManagement()) {
myChildMappers = createChildList();
myChildTargets = divWrappedElementChildren(getTarget());
ObservableList<Cell> children = getSource().children();
for (int i = 0; i < children.size(); i++) {
childAdded(i, children.get(i));
}
}
myPopupManager = createPopupManager();
myPopupManager.attach(getSource());
refreshProperties();
}
@Override
protected void onDetach() {
getSource().getProp(ELEMENT).set(null);
getTarget().removeClassName(CSS.cell());
if (myWasPopup) {
getTarget().removeFromParent();
}
myPopupManager.dispose();
myContext.unregister(this);
super.onDetach();
}
protected boolean isLeaf() {
return false;
}
protected boolean isAutoChildManagement() {
return true;
}
protected boolean isAutoPopupManagement() {
return true;
}
@Override
public final int getCounter(CounterSpec spec) {
if (myCounters == null) return 0;
return myCounters.getCounter(spec);
}
@Override
public final void changeCounter(CounterSpec spec, int delta) {
if (myCounters == null) {
myCounters = new Counters();
}
myCounters.changeCounter(spec, delta);
if (myCounters.isEmpty()) {
myCounters = null;
}
}
void childAdded(int index, Cell child) {
if (!isAutoChildManagement()) return;
BaseCellMapper<? extends Cell> mapper = myContext.apply(child);
myChildTargets.add(index, mapper.getTarget());
myChildMappers.add(index, mapper);
}
void childRemoved(int index, Cell child) {
if (!isAutoChildManagement()) return;
myChildMappers.remove(index);
myChildTargets.remove(index);
}
@Override
public final void onEvent(PropertyChangeEvent<Cell> event) {
myPopupManager.onEvent(event);
}
void onPopupPropertyChanged(CellPropertySpec<?> prop, PropertyChangeEvent<?> change) {
if (getParent() == null) return;
((BaseCellMapper<?>) getParent()).myPopupManager.onPopupPropertyChanged(getSource(), prop, change);
}
void setAncestorBackground(Color background) {
myAncestorBackground = background;
}
void refreshProperties() {
boolean selected = getSource().get(Cell.SELECTED) || getCounter(Counters.SELECT_COUNT) > 0;
boolean focusHighlighted = getSource().get(Cell.FOCUS_HIGHLIGHTED) || getCounter(Counters.HIGHLIGHT_COUNT) > 0;
Color background = getSource().get(Cell.BACKGROUND);
applyStyle(selected, focusHighlighted, (background == null ? myAncestorBackground : background));
}
private void applyStyle(boolean selected, boolean focusHighlighted, Color background) {
updateCssStyle(CSS.outlined(), focusHighlighted && !isLeaf() && !selected);
updateCssStyle(CSS.selected(), selected);
updateCssStyle(CSS.paired(), getSource().get(Cell.PAIR_HIGHLIGHTED));
updateCssStyle(CSS.link(), getSource().get(Cell.LINK));
String backgroundColor = null;
if (isLeaf() && focusHighlighted) {
backgroundColor = CSS.currentHighlightColor();
} else if (background != null) {
backgroundColor = background.toCssColor();
}
String underline = getSource().get(Cell.LINK) && getSource().get(Cell.HOVERED) ? CSS.blueUnderline()
: getSource().get(Cell.RED_UNDERLINE) ? CSS.redUnderline()
: getSource().get(Cell.YELLOW_UNDERLINE) ? CSS.yellowUnderline() : null;
applyBackground(backgroundColor, underline);
Style style = getTarget().getStyle();
Color borderColor = getSource().get(Cell.BORDER_COLOR);
style.setBorderStyle(borderColor == null ? Style.BorderStyle.NONE : Style.BorderStyle.SOLID);
style.setBorderWidth(borderColor == null ? 0 : 1, Style.Unit.PX);
style.setBorderColor(borderColor == null ? null : borderColor.toCssColor());
updateCssStyle(CSS.hidden(), !getSource().get(Cell.VISIBLE));
updateCssStyle(CSS.hasShadow(), getSource().get(Cell.HAS_SHADOW));
}
final void updateCssStyle(String cssStyle, boolean apply) {
if (apply) {
getTarget().addClassName(cssStyle);
} else {
getTarget().removeClassName(cssStyle);
}
}
private void applyBackground(String color, String underline) {
Style style = getTarget().getStyle();
if (color == null) {
if (underline == null) {
style.clearProperty(BACKGROUND);
} else {
style.setProperty(BACKGROUND, underline + UNDERLINE_SUFFIX);
}
} else {
if (underline == null) {
style.setProperty(BACKGROUND, color);
} else {
style.setProperty(BACKGROUND, underline + UNDERLINE_SUFFIX + " " + color);
}
}
}
List<Node> divWrappedElementChildren(final Element e) {
return new AbstractList<Node>() {
@Override
public Node get(int index) {
return e.getChild(index).getFirstChild();
}
@Override
public Node set(int index, Node element) {
if (element.getParentElement() != null) {
throw new IllegalStateException();
}
Element wrapperDiv = DOM.createDiv();
wrapperDiv.appendChild(element);
Node child = e.getChild(index);
e.replaceChild(child, wrapperDiv);
return child;
}
@Override
public void add(int index, Node element) {
if (element.getParentElement() != null) {
throw new IllegalStateException();
}
Element wrapperDiv = DOM.createDiv();
wrapperDiv.appendChild(element);
if (index == 0) {
e.insertFirst(wrapperDiv);
} else {
Node prev = e.getChild(index - 1);
e.insertAfter(wrapperDiv, prev);
}
}
@Override
public Node remove(int index) {
Element childWrapper = (Element) e.getChild(index);
get(index).removeFromParent();
e.removeChild(childWrapper);
return childWrapper;
}
@Override
public int size() {
return e.getChildCount();
}
};
}
protected PopupManager createPopupManager() {
return new DomPopupManager(myContext) {
@Override
protected Collection<Mapper<? extends Cell, ? extends Element>> createContainer() {
return createChildSet();
}
};
}
}
|
package org.apereo.cas.web.flow;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.config.CasCoreAuthenticationServiceSelectionStrategyConfiguration;
import org.apereo.cas.config.CasCoreConfiguration;
import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.config.CasScimConfiguration;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.MockWebServer;
import org.apereo.cas.web.flow.config.CasCoreWebflowConfiguration;
import org.apereo.cas.web.flow.config.CasWebflowContextConfiguration;
import org.apereo.cas.web.support.WebUtils;
import com.unboundid.scim.data.Meta;
import com.unboundid.scim.data.Name;
import com.unboundid.scim.data.UserResource;
import com.unboundid.scim.marshal.json.JsonMarshaller;
import com.unboundid.scim.schema.CoreSchema;
import com.unboundid.scim.sdk.Resources;
import lombok.val;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.execution.Action;
import org.springframework.webflow.test.MockRequestContext;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import static org.junit.Assert.*;
/**
* This is {@link PrincipalScimV1ProvisionerActionTests}.
*
* @author Misagh Moayyed
* @since 5.3.0
*/
@SpringBootTest(classes = {
CasScimConfiguration.class,
CasCoreWebflowConfiguration.class,
CasWebflowContextConfiguration.class,
CasCoreServicesConfiguration.class,
CasCoreUtilConfiguration.class,
CasCoreConfiguration.class,
CasCoreAuthenticationServiceSelectionStrategyConfiguration.class,
RefreshAutoConfiguration.class
})
@TestPropertySource(properties = {"cas.scim.target=http://localhost:8215",
"cas.scim.version=1", "cas.scim.username=casuser", "cas.scim.password=Mellon"})
public class PrincipalScimV1ProvisionerActionTests {
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
@Qualifier("principalScimProvisionerAction")
private Action principalScimProvisionerAction;
@Test
public void verifyAction() throws Exception {
val context = new MockRequestContext();
val request = new MockHttpServletRequest();
context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
WebUtils.putAuthentication(CoreAuthenticationTestUtils.getAuthentication(), context);
WebUtils.putCredential(context, CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword());
val user = new UserResource(CoreSchema.USER_DESCRIPTOR);
user.setActive(true);
user.setDisplayName("CASUser");
user.setId("casuser");
val name = new Name("formatted", "family",
"middle", "givenMame", "prefix", "prefix2");
name.setGivenName("casuser");
user.setName(name);
val meta = new Meta(new Date(), new Date(), new URI("http://localhost:8215"), "1");
meta.setCreated(new Date());
user.setMeta(meta);
val resources = new Resources(CollectionUtils.wrapList(user));
val stream = new ByteArrayOutputStream();
resources.marshal(new JsonMarshaller(), stream);
val data = stream.toString();
try (val webServer = new MockWebServer(8215,
new ByteArrayResource(data.getBytes(StandardCharsets.UTF_8), "REST Output"), MediaType.APPLICATION_JSON_VALUE)) {
webServer.start();
assertEquals(CasWebflowConstants.TRANSITION_ID_SUCCESS, principalScimProvisionerAction.execute(context).getId());
}
}
}
|
package org.firstinspires.ftc.teamcode.teleop;
import com.edinaftcrobotics.drivetrain.Mecanum;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DigitalChannel;
import org.firstinspires.ftc.teamcode.robot.PieceOfCake;
import org.opencv.core.Mat;
@TeleOp(name="Teleop", group="Teleop")
public class RobotOpMode extends OpMode {
private PieceOfCake robot = new PieceOfCake();
private boolean intakeYPressed = false;
private boolean intakeAPressed = false;
private boolean flipBPressed = false;
private boolean bumpersPressed = false;
private boolean intakeInToggledOn = false;
private boolean intakeOutToggledOn = false;
private Mecanum mecanum = null;
private boolean TopFlipSet = false;
private boolean liftXPressed = false;
private boolean liftYPressed = false;
private boolean liftAPressed = false;
private boolean liftBPressed = false;
private boolean liftMoving = false;
private boolean limitHit = false;
private boolean topFlipTriggerPressed = false;
private int liftLocation = 0;
private boolean intakeArmActive = false;
private int timeCount = 0;
private MineralDeposit currentMDState = MineralDeposit.WAITING_TO_START;
private enum MineralDeposit {
WAITING_TO_START,
START,
FRONT_FLIPPING,
FRONT_FLIPPING_AGAIN,
FRONT_FLIPPING_BACK,
WAITING_FOR_LIFT_AND_FLIP
}
@Override
public void init(){
robot.init(hardwareMap);
mecanum = new Mecanum(robot.getFrontL(), robot.getFrontR(), robot.getBackL(), robot.getBackR(), true, telemetry);
mecanum.SetCurrentPower(1.4);
}
@Override
public void init_loop() {
if (gamepad2.dpad_up){
robot.getFrontFlip().setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.getFrontFlip().setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
}
telemetry.addData("Front Flip", "%d", robot.getFrontFlip().getCurrentPosition());
telemetry.update();
}
@Override
public void loop() {
if (TopFlipSet == false){
robot.getTopFlip().setPosition(1);
TopFlipSet = true;
}
mecanum.Drive(gamepad1.left_stick_x, gamepad1.left_stick_y, gamepad1.right_stick_x);
telemetry.addData("Back Lift", "%d", robot.getBackLift().getCurrentPosition());
telemetry.addData("Front Lift", "%d", robot.getFrontLift().getCurrentPosition());
telemetry.addData("Front Flip", "%d", robot.getFrontFlip().getCurrentPosition());
telemetry.addData("Speed", "%f", mecanum.GetCurrentPower());
telemetry.addData("Lf, rf, lb, rb: ", "%d %d %d %d", robot.getFrontL().getCurrentPosition(),
robot.getFrontR().getCurrentPosition(), robot.getBackL().getCurrentPosition(),
robot.getBackR().getCurrentPosition());
telemetry.addData("Limit Switch:", robot.getLimitSwitch().getState());
telemetry.addData("Auto Intake Active:", intakeArmActive);
if (!intakeArmActive) {
ProcessSlide();
ProcessIntake();
ProcessFrontFlip();
}
if (!intakeArmActive && !liftMoving) {
ProcessLift();
}
ProcessTopFlip();
ProcessPower();
ProcessLiftLocations();
ProcessLiftButtons();
telemetry.update();
}
private void ProcessSlide() {
if ((gamepad1.left_trigger > 0)) {
robot.getSlide().setPower(1);
} else if ((gamepad1.right_trigger > 0)) {
robot.getSlide().setPower(-1);
} else {
robot.getSlide().setPower(0);
}
}
private void ProcessIntake() {
if (gamepad1.y && !intakeYPressed) {
intakeYPressed = true;
intakeAPressed = false;
} else if (!gamepad1.y && intakeYPressed) {
if (!intakeInToggledOn) {
robot.getIntake().setPower(-1); // TODO - negative this if it spins the wrong way
intakeInToggledOn = true;
intakeOutToggledOn = false;
} else {
robot.getIntake().setPower(0);
intakeInToggledOn = false;
intakeOutToggledOn = false;
}
intakeYPressed = false;
intakeAPressed = false;
} else if (gamepad1.a && !intakeAPressed) {
intakeAPressed = true;
intakeYPressed = false;
} else if (!gamepad1.a && intakeAPressed) {
if (!intakeOutToggledOn) {
robot.getIntake().setPower(1); // TODO - negative this is if spinis the wrong way
intakeInToggledOn = false;
intakeOutToggledOn = true;
} else {
robot.getIntake().setPower(0);
intakeInToggledOn = false;
intakeOutToggledOn = false;
}
intakeAPressed = false;
intakeYPressed = false;
}
}
private void ProcessPower(){
if (gamepad1.dpad_down){
mecanum.SetCurrentPower(0.6);
} else if (gamepad1.dpad_up){
mecanum.SetCurrentPower(1.0);
} else if(gamepad1.dpad_left){
mecanum.SetCurrentPower(1.4);
}
}
private void ProcessFrontFlip() {
if (gamepad1.left_bumper || gamepad2.left_bumper) {
robot.getFrontFlip().setPower(.75);
} else if (gamepad1.right_bumper || gamepad2.right_bumper) {
robot.getFrontFlip().setPower(-1);
} else {
robot.getFrontFlip().setPower(0);
}
}
private void ProcessLift() {
robot.getBackLift().setPower(-gamepad2.left_stick_y); // TODO - change these by either flipping the negative or adding/removing a negative
robot.getFrontLift().setPower(gamepad2.left_stick_y);
if (gamepad2.left_stick_y != 0) {
topFlipTriggerPressed = false;
}
if (gamepad2.dpad_down) {
robot.getFrontLift().setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
robot.getFrontLift().setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
}
}
private void ProcessTopFlip() {
if (gamepad2.left_trigger != 0) {
robot.getTopFlip().setPosition(.35);
} else if (gamepad2.right_trigger != 0) {
robot.getTopFlip().setPosition(0);
topFlipTriggerPressed = true;
} else {
robot.getTopFlip().setPosition(1);
if (topFlipTriggerPressed) {
int pos = robot.getFrontLift().getCurrentPosition();
if (pos > 20) {
robot.getFrontLift().setPower(1);
robot.getBackLift().setPower(-1);
} else {
topFlipTriggerPressed = false;
robot.getFrontLift().setPower(0);
robot.getBackLift().setPower(0);
}
}
}
}
private void ProcessLiftLocations() {
if (liftMoving == true) {
if ((gamepad2.left_stick_y != 0) || (gamepad2.left_trigger != 0) || (gamepad2.right_trigger !=0)){
robot.getBackLift().setPower(0);
robot.getFrontLift().setPower(0);
liftAPressed = liftBPressed = liftXPressed = liftYPressed = liftMoving = false;
} else {
int pos = robot.getFrontLift().getCurrentPosition();
telemetry.addData("Difference", (liftLocation - pos));
if ((liftLocation - pos) > 0) {
if (Math.abs(liftLocation - pos) < 5) {
// close enough so stop
robot.getBackLift().setPower(0);
robot.getFrontLift().setPower(0);
liftAPressed = liftBPressed = liftXPressed = liftYPressed = liftMoving = false;
} else if (Math.abs(liftLocation - pos) < 50) {
robot.getBackLift().setPower(.5);
robot.getFrontLift().setPower(-.5);
} else {
robot.getBackLift().setPower(1);
robot.getFrontLift().setPower(-1);
}
} else if ((liftLocation - pos) < 0) {
if (Math.abs(liftLocation - pos) < 5) {
// close enough so stop
robot.getBackLift().setPower(0);
robot.getFrontLift().setPower(0);
liftAPressed = liftBPressed = liftXPressed = liftYPressed = liftMoving = false;
} else if (Math.abs(liftLocation - pos) < 50) {
robot.getBackLift().setPower(-.5);
robot.getFrontLift().setPower(.5);
} else {
// move down
robot.getBackLift().setPower(-1);
robot.getFrontLift().setPower(1);
}
}
}
}
if (gamepad2.a && !liftAPressed) {
liftLocation = 0;
liftMoving = liftAPressed = true;
liftBPressed = liftXPressed = liftYPressed = false;
} else if (gamepad2.x && !liftXPressed) {
liftLocation = 1038;
liftMoving = liftXPressed = true;
liftAPressed = liftYPressed = liftBPressed = false;
} else if (gamepad2.y && !liftYPressed) {
liftLocation = 515;
liftMoving = liftYPressed = true;
liftAPressed = liftXPressed = liftBPressed = false;
} else if (gamepad2.b && !liftBPressed) {
liftLocation = 1300;
liftMoving = liftBPressed = true;
liftAPressed = liftXPressed = liftYPressed = false;
}
}
private void ProcessLiftButtons () {
boolean limit = robot.getLimitSwitch().getState();
int pos = robot.getBackLift().getCurrentPosition();
if (gamepad1.b && !intakeArmActive){
currentMDState = MineralDeposit.START;
intakeArmActive = true;
}
if (intakeArmActive) {
if ((!limit)){
limitHit = true;
}
if ((gamepad2.left_stick_y != 0) || (gamepad2.left_bumper) ||
(gamepad2.right_bumper) || (gamepad1.left_bumper) ||
(gamepad1.right_bumper) || (gamepad2.left_trigger != 0) ||
(gamepad2.right_trigger !=0) || (gamepad1.left_trigger != 0) ||
(gamepad1.right_trigger !=0)){
robot.getBackLift().setPower(0);
robot.getBackLift().setPower(0);
robot.getFrontFlip().setPower(0);
robot.getFrontFlip().setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
robot.getSlide().setPower(0);
intakeArmActive = false;
limitHit = false;
currentMDState = MineralDeposit.WAITING_TO_START;
}
switch (currentMDState) {
case START:
robot.getFrontFlip().setMode(DcMotor.RunMode.RUN_TO_POSITION);
robot.getFrontFlip().setTargetPosition(1400);
robot.getFrontFlip().setPower(1);
if (pos > 10) {
robot.getBackLift().setPower(-0.8);
robot.getFrontLift().setPower(0.8);
}
currentMDState = MineralDeposit.FRONT_FLIPPING;
break;
case FRONT_FLIPPING:
if (robot.getFrontFlip().getCurrentPosition() < 1900) {
robot.getSlide().setPower(1);
currentMDState = MineralDeposit.WAITING_FOR_LIFT_AND_FLIP;
}
break;
case WAITING_FOR_LIFT_AND_FLIP:
if ((pos <= 10) && (robot.getFrontFlip().getCurrentPosition() < 1410) && limitHit) {
currentMDState = MineralDeposit.FRONT_FLIPPING_AGAIN;
robot.getFrontFlip().setTargetPosition(50);
timeCount = 0;
}
break;
case FRONT_FLIPPING_AGAIN:
if ((pos <= 10) &&(robot.getFrontFlip().getCurrentPosition() < 50)) {
timeCount++;
}
if (timeCount > 2) {
robot.getFrontFlip().setTargetPosition(750);
currentMDState = MineralDeposit.FRONT_FLIPPING_BACK;
}
break;
case FRONT_FLIPPING_BACK:
if (robot.getFrontFlip().getCurrentPosition() > 750) {
robot.getFrontFlip().setPower(0);
robot.getFrontFlip().setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
currentMDState = MineralDeposit.WAITING_TO_START;
intakeArmActive = false;
limitHit = false;
}
break;
}
if (limitHit) {
robot.getSlide().setPower(0);
}
if (pos <= 10) {
robot.getBackLift().setPower(0);
robot.getFrontLift().setPower(0);
}
}
}
}
|
package com.epicodus.backtalkr.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.epicodus.backtalkr.R;
import com.epicodus.backtalkr.models.Message;
import java.util.ArrayList;
public class MessageListAdapter extends RecyclerView.Adapter<MessageViewHolder> {
private ArrayList<Message> mMessages = new ArrayList<>();
private Context mContext;
public MessageListAdapter(Context context, ArrayList<Message> messages) {
mContext = context;
mMessages = messages;
}
@Override
public MessageViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_list_item, parent, false);
MessageViewHolder viewHolder = new MessageViewHolder(view, mMessages);
return viewHolder;
}
@Override
public void onBindViewHolder(MessageViewHolder holder, int position) {
holder.bindMessage(mMessages.get(position));
}
@Override
public int getItemCount() {
return mMessages.size();
}
}
|
/**
* Copyright (C) 2011 rwoo@gmx.de
*
* 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 package contains third-party classes for internal use only. */
package com.github.rwitzel.streamflyer.internal.thirdparty;
|
package org.uma.jmetal.operator.mutation.impl;
import org.uma.jmetal.operator.mutation.MutationOperator;
import org.uma.jmetal.solution.permutationsolution.PermutationSolution;
import org.uma.jmetal.util.checking.Check;
import org.uma.jmetal.util.pseudorandom.BoundedRandomGenerator;
import org.uma.jmetal.util.pseudorandom.JMetalRandom;
import org.uma.jmetal.util.pseudorandom.RandomGenerator;
/**
* This class implements a swap mutation. The solution type of the solution must be Permutation.
*
* @author Antonio J. Nebro <antonio@lcc.uma.es>
* @author Juan J. Durillo
*/
@SuppressWarnings("serial")
public class PermutationSwapMutation<T> implements MutationOperator<PermutationSolution<T>> {
private double mutationProbability;
private RandomGenerator<Double> mutationRandomGenerator;
private BoundedRandomGenerator<Integer> positionRandomGenerator;
/** Constructor */
public PermutationSwapMutation(double mutationProbability) {
this(
mutationProbability,
() -> JMetalRandom.getInstance().nextDouble(),
(a, b) -> JMetalRandom.getInstance().nextInt(a, b));
}
/** Constructor */
public PermutationSwapMutation(
double mutationProbability, RandomGenerator<Double> randomGenerator) {
this(
mutationProbability,
randomGenerator,
BoundedRandomGenerator.fromDoubleToInteger(randomGenerator));
}
/** Constructor */
public PermutationSwapMutation(
double mutationProbability,
RandomGenerator<Double> mutationRandomGenerator,
BoundedRandomGenerator<Integer> positionRandomGenerator) {
Check.probabilityIsValid(mutationProbability);
this.mutationProbability = mutationProbability;
this.mutationRandomGenerator = mutationRandomGenerator;
this.positionRandomGenerator = positionRandomGenerator;
}
/* Getters */
@Override
public double getMutationProbability() {
return mutationProbability;
}
/* Setters */
public void setMutationProbability(double mutationProbability) {
this.mutationProbability = mutationProbability;
}
/* Execute() method */
@Override
public PermutationSolution<T> execute(PermutationSolution<T> solution) {
Check.isNotNull(solution);
doMutation(solution);
return solution;
}
/** Performs the operation */
public void doMutation(PermutationSolution<T> solution) {
int permutationLength;
permutationLength = solution.getNumberOfVariables();
if ((permutationLength != 0) && (permutationLength != 1)) {
if (mutationRandomGenerator.getRandomValue() < mutationProbability) {
int pos1 = positionRandomGenerator.getRandomValue(0, permutationLength - 1);
int pos2 = positionRandomGenerator.getRandomValue(0, permutationLength - 1);
while (pos1 == pos2) {
if (pos1 == (permutationLength - 1))
pos2 = positionRandomGenerator.getRandomValue(0, permutationLength - 2);
else pos2 = positionRandomGenerator.getRandomValue(pos1, permutationLength - 1);
}
T temp = solution.getVariable(pos1);
solution.setVariable(pos1, solution.getVariable(pos2));
solution.setVariable(pos2, temp);
}
}
}
}
|
package ocd.dao.entities;
/**
* Created by t00191774 on 16/11/2016.
*
*/
public class Item {
private int itemID;
private int typeID;
private String itemName;
private String typeName;
private double price;
private double roomsToEquip;
private int bonusHealth;
private int bonusDefense;
private int bonusAttack;
private int bonusCritical;
public Item(int itemID, int typeID, String itemName, String typeName, double price, double roomsToEquip, int bonusHealth, int bonusDefense, int bonusAttack, int bonusCritical) {
this.itemID = itemID;
this.typeID = typeID;
this.itemName = itemName;
this.typeName = typeName;
this.price = price;
this.roomsToEquip = roomsToEquip;
this.bonusHealth = bonusHealth;
this.bonusDefense = bonusDefense;
this.bonusAttack = bonusAttack;
this.bonusCritical = bonusCritical;
}
public int getItemID() {
return itemID;
}
public int getTypeID() {
return typeID;
}
public String getItemName() {
return itemName;
}
public String getTypeName() {
return typeName;
}
public double getPrice() {
return price;
}
public double getRoomsToEquip() {
return roomsToEquip;
}
public int getBonusHealth() {
return bonusHealth;
}
public int getBonusDefense() {
return bonusDefense;
}
public int getBonusAttack() {
return bonusAttack;
}
public int getBonusCritical() {
return bonusCritical;
}
public String toString() {
String firstPart = "@|magenta,bold " + getItemID() + ":|@ " +
"@|cyan,bold " + getItemName() + "|@ " +
"(" + getTypeName() + ")" +
"[@|green,bold " + getRoomsToEquip() + "|@]: ";
String secondPart = "@|yellow,bold $" + getPrice() + "|@ " +
"bonuses: (health = @|green,bold " + getBonusHealth() + "%|@, " +
"defense = @|green,bold " + getBonusDefense() + "%|@, " +
"attack = @|green,bold " + getBonusAttack() + "%|@, " +
"critical = @|green,bold " + getBonusCritical() + "%|@)";
String format = "%-100s %-200s%n";
return String.format(format, firstPart, secondPart);
}
}
|
package net.andreho.common.utils;
import net.andreho.common.anno.Order;
import java.util.Comparator;
import java.util.Objects;
/**
* <br/>Created by a.hofmann on 23.03.2017 at 15:34.
*/
public class OrderUtils
implements Comparator<Object> {
private static final Class<Order> ORDER_ANNOTATION_CLASS = Order.class;
static volatile OrderUtils COMPARATOR = new OrderUtils();
/**
* @return the defined comparator instance
*/
public static Comparator<Object> comparator() {
return COMPARATOR;
}
/**
* Overrides the default behavior of this utility class
*
* @param instance is the new instance to use as comparator
*/
public static void overrideDefaults(OrderUtils instance) {
COMPARATOR = Objects.requireNonNull(instance, "Given instance can't be null.");
}
/**
* Compares two given objects using chosen {@link #comparator()}
*
* @param a instance to compare
* @param b instance to compare
* @return an integer as defined by {@link Comparator#compare(Object, Object)}
*/
public static int order(Object a,
Object b) {
return COMPARATOR.compare(a, b);
}
private static boolean isOrderAnnotationPresent(final Object a) {
return a.getClass().isAnnotationPresent(ORDER_ANNOTATION_CLASS);
}
@Override
public int compare(final Object a,
final Object b) {
if (isOrderAnnotationPresent(a) || isOrderAnnotationPresent(b)) {
final Order ao = a.getClass().getAnnotation(ORDER_ANNOTATION_CLASS);
final Order bo = b.getClass().getAnnotation(ORDER_ANNOTATION_CLASS);
if (ao != null && bo != null) {
return Integer.compare(ao.value(), bo.value());
} else if (ao != null) {
return -1;
} else if (bo != null) {
return 1;
}
}
return fallback(a, b);
}
protected int fallback(final Object a,
final Object b) {
return 0;
}
}
|
// Copyright (c) 2002-2014 JavaMOP Team. All Rights Reserved.
/*
* Copyright (C) 2007 Julio Vilmar Gesser.
*
* This file is part of Java 1.5 parser and Abstract Syntax Tree.
*
* Java 1.5 parser and Abstract Syntax Tree 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.
*
* Java 1.5 parser and Abstract Syntax Tree 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 Java 1.5 parser and Abstract Syntax Tree. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Created on 21/11/2006
*/
package javamop.parser.ast.body;
import java.util.List;
import javamop.parser.ast.expr.AnnotationExpr;
import javamop.parser.ast.visitor.GenericVisitor;
import javamop.parser.ast.visitor.VoidVisitor;
/**
* @author Julio Vilmar Gesser
*/
public final class AnnotationDeclaration extends TypeDeclaration {
private final List<AnnotationExpr> annotations;
public AnnotationDeclaration(int line, int column, int modifiers, List<AnnotationExpr> annotations, String name, List<BodyDeclaration> members) {
super(line, column, name, modifiers, members);
this.annotations = annotations;
}
public List<AnnotationExpr> getAnnotations() {
return annotations;
}
@Override
public <A> void accept(VoidVisitor<A> v, A arg) {
v.visit(this, arg);
}
@Override
public <R, A> R accept(GenericVisitor<R, A> v, A arg) {
return v.visit(this, arg);
}
}
|
package com.github.sahara3.ssolite.spring.server.repository;
import java.time.OffsetDateTime;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import com.github.sahara3.ssolite.core.model.SsoLiteAccessToken;
/**
* In-memory implementation of {@link SsoLiteAccessTokenRepository} interface.
*
* @author sahara3
*/
public class SsoLiteAccessTokenRepositoryImpl implements SsoLiteAccessTokenRepository {
private final ConcurrentMap<String, SsoLiteAccessToken> tokens = new ConcurrentHashMap<>();
@Override
public @Nullable SsoLiteAccessToken findById(String id) {
Assert.notNull(id, "id cannot be null");
SsoLiteAccessToken token = this.tokens.get(id);
return token;
}
@Override
public void save(SsoLiteAccessToken token) {
Assert.notNull(token, "token cannot be null");
this.tokens.put(token.getId(), token);
this.cleanupExpiredTokens();
}
@Override
public void delete(String id) {
Assert.notNull(id, "id cannot be null");
this.tokens.remove(id);
this.cleanupExpiredTokens();
}
protected void cleanupExpiredTokens() {
OffsetDateTime now = OffsetDateTime.now();
this.tokens.entrySet().removeIf(entry -> entry.getValue().getExpired().isBefore(now));
}
}
|
/*
* Project Name: SJBlog
* Class Name: FileTool.java
*
* Copyright © 2011-2016 SteveJrong All Rights Reserved.
*
* Licensed under the SteveJrong
*
* https://www.steve.jrong.top/
*
* 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 top.sj.tool;
import java.io.File;
/**
* 文件工具类
*
* Create User: SteveJrong
* Create Date: 2016年10月27日 下午3:40:18
* Modify User: SteveJrong
* Modify Date: 2016年10月27日 下午3:40:18
* Modify Remark:
*
* @author SteveJrong
* @version 1.0
*/
public class FileTool {
/**
* 检测文件是否存在的方法
* @param absoluteFilePath 文件绝对路径
* @return 布尔值
*/
public static Boolean checkFileExists(String absoluteFilePath) {
File file = new File(absoluteFilePath);
return file.exists();
}
}
|
/*
* LanguageTool, a natural language style checker
* Copyright (C) 2019 Sohaib Afifi, Taha Zerrouki
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.ar;
import org.junit.Before;
import org.junit.Test;
import org.languagetool.JLanguageTool;
import org.languagetool.Languages;
import org.languagetool.TestTools;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
/**
* @author Sohaib AFIFI
* @since 5.0
*/
public class ArabicWordinessRuleTest {
private final JLanguageTool lt = new JLanguageTool(Languages.getLanguageForShortCode("ar"));
@Before
public void before() {
TestTools.disableAllRulesExcept(lt, ArabicWordinessRule.AR_WORDINESS_REPLACE);
}
@Test
public void testRule() throws IOException {
// errors:
assertError("وأخيرا وليس آخرا");
}
private void assertError(String s) throws IOException {
ArabicWordinessRule rule = new ArabicWordinessRule(TestTools.getEnglishMessages());
assertEquals(1, rule.match(lt.getAnalyzedSentence(s)).length);
}
}
|
package edu.buaa.scse.niu.wechat.common.utils;
import java.util.UUID;
public class UUIDGenerator {
/**
* generate 36bytes UUID string with '-'
* eg.3d13cba3-32c6-494c-996c-17a23b0d8085
* @return
*/
public static String getNext(){
UUID uuid=UUID.randomUUID();
return uuid.toString();
}
/**
* generate 32bytes UUID string without '-'
* eg.3d13cba332c6494c996c17a23b0d8085
* @return
*/
public static String getNext32(){
String src=getNext();
String res=src.replaceAll("-", "");
return res;
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(UUIDGenerator.getNext());
System.out.println(UUIDGenerator.getNext());
System.out.println(UUIDGenerator.getNext());
}
}
|
package com.javarush.task.task32.task3205;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class CustomInvocationHandler implements InvocationHandler {
SomeInterfaceWithMethods original;
public CustomInvocationHandler(SomeInterfaceWithMethods original) {
this.original = original;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method.getName() + " in");
Object invoke = method.invoke(original, args);
System.out.println(method.getName() + " out");
return invoke;
}
}
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class StronglyConnected {
private static int numberOfStronglyConnectedComponents(ArrayList<Integer>[] adj) {
//write your code here
return 0;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
ArrayList<Integer>[] adj = (ArrayList<Integer>[])new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; i++) {
int x, y;
x = scanner.nextInt();
y = scanner.nextInt();
adj[x - 1].add(y - 1);
}
System.out.println(numberOfStronglyConnectedComponents(adj));
}
}
|
package me.deadlight.ezchestshop.Data;
import me.deadlight.ezchestshop.Data.SQLite.Database;
import me.deadlight.ezchestshop.EzChestShop;
import me.deadlight.ezchestshop.Utils.Objects.CheckProfitEntry;
import org.bukkit.OfflinePlayer;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.UUID;
import java.util.stream.Collectors;
public class PlayerContainer {
private static HashMap<UUID, PlayerContainer> playerContainerMap = new HashMap<>();
private OfflinePlayer offlinePlayer;
private UUID uuid;
private String suuid;
private HashMap<String, CheckProfitEntry> checkProfits = null;
public PlayerContainer(OfflinePlayer offlinePlayer) {
this.offlinePlayer = offlinePlayer;
this.uuid = offlinePlayer.getUniqueId();
this.suuid = this.uuid.toString();
}
public static PlayerContainer get(OfflinePlayer offlinePlayer) {
UUID uuid = offlinePlayer.getUniqueId();
if (playerContainerMap.containsKey(uuid)) {
return playerContainerMap.get(uuid);
} else {
PlayerContainer pc = new PlayerContainer(offlinePlayer);
playerContainerMap.put(uuid, pc);
return pc;
}
}
/*
▄▀▀ █▄█ ▄▀▄ █▀▄
▄██ █ █ ▀▄▀ █▀
*/
// ShopProfits
public HashMap<String, CheckProfitEntry> getProfits() {
if (checkProfits == null) {
checkProfits = new HashMap<>();
Database db = EzChestShop.getPlugin().getDatabase();
String checkProfitsList = db.getString("uuid", suuid, "checkprofits", "playerdata");
if (checkProfitsList == null || checkProfitsList.equalsIgnoreCase("") || checkProfitsList.equalsIgnoreCase("NULL")) {
checkProfits = new HashMap<>();
return checkProfits;
}
for (String entry : checkProfitsList.split(CheckProfitEntry.itemSpacer)) {
CheckProfitEntry profEntry = new CheckProfitEntry(entry);
checkProfits.put(profEntry.getId(), profEntry);
}
return checkProfits;
} else {
return checkProfits;
}
}
public void updateProfits(String id, ItemStack item, Integer buyAmount, Double buyPrice, Double buyUnitPrice, Integer sellAmount,
Double sellPrice, Double sellUnitPrice) {
if (checkProfits == null) {
checkProfits = getProfits();
}
//EzChestShop.logDebug("Map-before: " + checkProfits.size());
if (!checkProfits.containsKey(id)) {
checkProfits.put(id, new CheckProfitEntry(id, item, buyAmount, buyPrice, buyUnitPrice, sellAmount, sellPrice, sellUnitPrice));
} else {
CheckProfitEntry entry = checkProfits.get(id);
entry.setBuyAmount(entry.getBuyAmount() + buyAmount);
entry.setBuyPrice(entry.getBuyPrice() + buyPrice);
entry.setSellAmount(entry.getSellAmount() + sellAmount);
entry.setSellPrice(entry.getSellPrice() + sellPrice);
checkProfits.put(id, entry);
}
Database db = EzChestShop.getPlugin().getDatabase();
String profit_string = checkProfits.entrySet().stream().map(x -> x.getValue().toString())
.collect(Collectors.joining(CheckProfitEntry.itemSpacer));
//EzChestShop.logDebug("Profit: " + (profit_string == null ? "NULL" : profit_string) + "\n Map: " + checkProfits.size());
if (profit_string == null)
db.setString("uuid", suuid, "checkprofits", "playerdata", "NULL");
else
db.setString("uuid", suuid, "checkprofits", "playerdata", profit_string);
}
public void clearProfits() {
Database db = EzChestShop.getPlugin().getDatabase();
checkProfits.clear();
db.setString("uuid", suuid, "checkprofits", "playerdata", "NULL");
}
}
|
package org.darkstorm.minecraft.darkbot.wrapper.commands;
import org.darkstorm.minecraft.darkbot.*;
import org.darkstorm.minecraft.darkbot.wrapper.MinecraftBotWrapper;
public abstract class AbstractCommand implements Command {
protected final MinecraftBotWrapper controller;
protected final MinecraftBotImpl bot;
private final String name, description, optionDescription, optionRegex;
public AbstractCommand(MinecraftBotWrapper bot, String name, String description) {
this(bot, name, description, "", "");
}
public AbstractCommand(MinecraftBotWrapper bot, String name, String description, String optionDescription, String optionRegex) {
controller = bot;
this.bot = bot.getBot();
this.name = name;
this.description = description;
this.optionDescription = optionDescription;
this.optionRegex = optionRegex;
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return description;
}
@Override
public String getOptionDescription() {
return optionDescription;
}
@Override
public String getOptionRegex() {
return optionRegex;
}
public MinecraftBotWrapper getBot() {
return controller;
}
}
|
package ix.ginas.utils.validation;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import gov.nih.ncats.molwitch.Atom;
import gov.nih.ncats.molwitch.Bond;
import gov.nih.ncats.molwitch.Chemical;
import gov.nih.ncats.molwitch.ChemicalBuilder;
import gov.nih.ncats.molwitch.Chirality;
import gov.nih.ncats.molwitch.io.ChemFormat;
public class PeptideInterpreter {
private static final int MOD_AMINO_GROUP_ISOTOPE = 55;
public static final ChemFormat.MolFormatSpecification MOL_SPEC = new ChemFormat.MolFormatSpecification()
.setKekulization(ChemFormat.KekulizationEncoding.KEKULE);
public static Map<String, String> AAmap = new HashMap<String, String>();
public static Map<String, String> AAmap3Let = new HashMap<String, String>();
public static Map<String, Integer> AAmapCHI = new HashMap<String, Integer>();
public static Map<String, Integer> modFreq = new HashMap<String,Integer>();
public static Map<String, String> modName = new HashMap<String,String>();
public static Map<String, String> modMap = new HashMap<String,String>();
public static int modNumber=1;
public static String aminoAcids = "P\tC1C[Ne]C1;A\tO=C(O)[C@@H](N)C;C\tSC[C@H](N)C(O)=O;D\tOC(C[C@H](N)C(O)=O)=O;E\tO=C(O)[C@@H](N)CCC(O)=O;F\tN[C@H](C(O)=O)CC1=CC=CC=C1;G\tO=C(O)CN;H\tN[C@@H](CC1=CN=CN1)C(O)=O;I\tO=C(O)[C@@H](N)[C@H](C)CC;K\tN[C@H](C(O)=O)CCCCN;L\tN[C@@H](CC(C)C)C(O)=O;M\tOC([C@@H](N)CCSC)=O;N\tNC(C[C@H](N)C(O)=O)=O;P\tO=C([C@@H]1CCCN1)O;Q\tOC([C@@H](N)CCC(N)=O)=O;R\tO=C(O)[C@@H](N)CCCNC(N)=N;R\tN[C@H](C(=O)O)CCCN=C(N)N;S\tOC([C@@H](N)CO)=O;T\tC[C@H]([C@@H](C(=O)O)N)O;V\tN[C@H](C(O)=O)C(C)C;W\tO=C(O)[C@@H](N)CC1=CNC2=C1C=CC=C2;Y\tN[C@@H](CC1=CC=C(O)C=C1)C(O)=O;W\tN[C@@H](CC1=CNC2=C1C=CC=C2)C(O)=O;H\tN[C@H](C(=O)O)Cc1c[nH]cn1;I\tO=C(O)[C@@H](N)[C@@H](C)CC;H\tN[C@@H](CC1=CNC=N1)C(O)=O";
public static String aminoAcidsLet = "A Ala;R Arg;N Asn;D Asp;C Cys;E Glu;Q Gln;G Gly;H His;I Ile;L Leu;K Lys;M Met;F Phe;P Pro;S Ser;T Thr;W Trp;Y Tyr;V Val";
static {
Pattern TAB_SPLIT = Pattern.compile("\t");
for (String s : aminoAcids.split(";")) {
String[] sArray = TAB_SPLIT.split(s);
Chemical c=null;
String AA=sArray[0];
try {
c = Chemical.parse(sArray[1]);
c.makeHydrogensImplicit();
c.aromatize();
c.setAtomMapToPosition();
int[] pos = longestPeptideBackbone(c,1);
int chi=c.getAtom(pos[0]).getChirality().getParity();
AAmapCHI.put(s.split("\t")[0], chi);
} catch (Exception e1) {
e1.printStackTrace();
}
contractPeptide(c);
for (Atom ma : c.getAtoms()) {
if (ma.getAtomicNumber() == 10) {
List<Bond> toRemove = new ArrayList<>();
for(Bond b : ma.getBonds()){
Atom mn=b.getOtherAtom(ma);
if (mn.getAtomicNumber() == 10 ||mn.getMassNumber()==7||mn.getMassNumber()==6 ) {
toRemove.add(b);
}
}
for (Bond mb : toRemove) {
c.removeBond(mb);
}
}
}
// System.out.println(s);
try {
String smi=LOOKUP_HASH(c);
AAmap.put(smi, AA);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(AA.equals("P")){
c.atoms()
.filter(a-> a.getAtomicNumber()==10)
.forEach(a-> a.setMassNumber(55));
try {
String key = LOOKUP_HASH(c);
// System.out.println("P LOOKUP HAS = " + key);
AAmap.put(key, AA);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(AA.equals("T")){
try {
c.generateCoordinates();
for(Bond cb:c.getBonds()){
cb.setStereo(Bond.Stereo.NONE);
}
AAmap.put(LOOKUP_HASH(c), "T");
} catch (Exception e) {
e.printStackTrace();
}
}
}
for(String s:aminoAcidsLet.split(";")){
AAmap3Let.put(s.split("\t")[0], s.split("\t")[1]);
}
//katzelda Aug 2020 - add amidated component to be ignored
AAmap.put("QGZKDVFQNNGYKY","");
AAmap.put("PDCKRJPYJMCOFO","");
// System.out.println("DONE");
}
public static String LOOKUP_HASH(Chemical f) throws Exception{
String smiles=null;
try{
Chemical f2= f.copy();
f2.atoms()
.filter(a->a.getAtomicNumber()==10 || a.getAtomicNumber()==2)
.forEach(a->a.setImplicitHCount(0));
// System.out.println(f2.toMol());
smiles = f2.toInchi().getKey();
// System.out.println("KEY:" + smiles);
return smiles.substring(0,14);
}catch(Exception e){
e.printStackTrace();
// try{
// smiles = f2.export(Chemical.FORMAT_SMARTS).split(" ")[0];
// }catch(Exception e2){
// try{
// smiles = f2.export(Chemical.FORMAT_STDINCHI).split(" ")[0];
// }catch(Exception e3){
// smiles = f2.export(Chemical.FORMAT_MOL).replace("\n","\\n");
// }
// }
smiles = f.toMol(MOL_SPEC).replace("\n", "\\n");
}
return smiles;
}
public static void contractPeptide(Chemical c) {
contractPeptide(c,null);
}
public static void contractPeptide(Chemical c, int[] backboneAtoms) {
contractChemical(c,backboneAtoms);
}
/**
* Takes in a molecule, replaces alpha peptide bonds with [Ne],
* keeping atom map.
*
* Also replaces carbonyl with [He].
*
* And sets modified amines at alpha groups to [55Ne].
*
*
* @param m2
* @param backboneAtoms
*/
public static void contractChemical(Chemical m2, int[] backboneAtoms) {
Set<Atom> incAtoms;
// ChemicalAtom[] catoms = m2.getAtomArray();
if(backboneAtoms!=null){
incAtoms = new HashSet<>();
for(int i=0;i<backboneAtoms.length;i++){
incAtoms.add(m2.getAtom(backboneAtoms[i]));
}
}else{
incAtoms = m2.atoms().collect(Collectors.toSet());
// for(int i=0;i<m2.getAtomCount();i++){
// ChemicalAtom ma = catoms[i];
// incAtoms.add(ma);
// }
}
//Finding (C=O), replace --> [He]
for (Atom ma : m2.getAtoms()) {
if (ma.getAtomicNumber() == 6) {
for(Bond b : ma.getBonds()){
Atom otherAtom = b.getOtherAtom(ma);
if (otherAtom.getAtomicNumber() == 8 && b.getBondType() == Bond.BondType.DOUBLE) {
// if (ma.getBond(i).getType() == ChemicalBond.BOND_TYPE_DOUBLE) {
// ma.setAtomNo(2); //Helium
// m2.removeAtom(ma.getBond(i).getOtherAtom(ma)); //Remove =O
// }
ma.setAtomicNumber(2);
ma.setImplicitHCount(0);
m2.removeAtom(otherAtom);
}
}
}
}
//
for (Atom ma : m2.getAtoms()) {
if(incAtoms.contains(ma)){
//C
if (ma.getAtomicNumber() == 6) {
Atom carbonyl = null; //[He] neighbor
Atom amine = null; //-N neighbor
boolean mod = false;
for(Bond b : ma.getBonds()){
// for (int i = 0; i < ma.getBondCount(); i++) {
if (b.getOtherAtom(ma).getAtomicNumber() == 2) {
carbonyl = b.getOtherAtom(ma);
} else if (b.getBondType()== Bond.BondType.SINGLE && b.getOtherAtom(ma).getAtomicNumber() == 7) {
amine = b.getOtherAtom(ma);
}
}
//Looks like alpha carbon
if (amine != null && carbonyl != null) {
if(amine.getBondCount()>2){
mod=true;
}
for(Bond b : amine.getBonds()){
// for (int i = 0; i < amine.getBondCount(); i++) {
Atom oatom = b.getOtherAtom(amine);
if (!(oatom.getAtomToAtomMap().getAsInt() ==ma.getAtomToAtomMap().getAsInt())) {
m2.addBond(ma, oatom, b.getBondType());
if(oatom.getMassNumber()!=PeptideInterpreter.MOD_AMINO_GROUP_ISOTOPE){
oatom.setMassNumber(7);
}
}
}
m2.removeAtom(amine);
for(Bond b : carbonyl.getBonds()){
// for (int i = 0; i < carbonyl.getBondCount(); i++) {
Atom oatom = b.getOtherAtom(carbonyl);
if (oatom.getAtomicNumber() != 8) {
if (!(oatom.getAtomToAtomMap().getAsInt() ==ma.getAtomToAtomMap().getAsInt())) {
m2.addBond(ma, oatom, b.getBondType());
if(oatom.getMassNumber()!=PeptideInterpreter.MOD_AMINO_GROUP_ISOTOPE){
oatom.setMassNumber(6);
}
}
} else {
m2.removeAtom(oatom);
}
}
m2.removeAtom(carbonyl);
ma.setAtomicNumber(10);
ma.setImplicitHCount(0);
if(mod){
ma.setMassNumber(PeptideInterpreter.MOD_AMINO_GROUP_ISOTOPE);
}
}
}
}
}
m2.atoms()
.filter(a-> a.getAtomicNumber() ==10 && ( a.getMassNumber() ==7 || a.getMassNumber() == 6))
.forEach(a-> a.setMassNumber(0));
}
/*
public static int[] removeDisulfide(Molecule m2) {
List<Integer> blist = new ArrayList<Integer>();
for (MolBond mb : m2.getBondArray()) {
if (mb.getAtom1().getAtno() == 16 && mb.getAtom2().getAtno() == 16) {
m2.removeEdge(mb);
blist.add(mb.getAtom1().getAtomMap()-1);
blist.add(mb.getAtom2().getAtomMap()-1);
}
}
int[] barr = new int[blist.size()];
for(int i=0;i<barr.length;i++){
barr[i]=blist.get(i);
}
return barr;
}*/
public static int[] removeDisulfide(Chemical c2) {
List<Integer> blist = new ArrayList<Integer>();
for (Bond mb : c2.getBonds()) {
if (mb.getAtom1().getAtomicNumber() == 16 && mb.getAtom2().getAtomicNumber() == 16) {
c2.removeBond(mb);
blist.add(mb.getAtom1().getAtomToAtomMap().orElse(0)-1);
blist.add(mb.getAtom2().getAtomToAtomMap().orElse(0)-1);
//this part seems unnecessary to me
//but needed for CDK.
mb.getAtom1().setImplicitHCount(1);
mb.getAtom2().setImplicitHCount(1);
}
}
int[] barr = new int[blist.size()];
for(int i=0;i<barr.length;i++){
barr[i]=blist.get(i);
}
return barr;
}
public static int[] longestPeptideBackbone(Chemical m, int minSize)
throws Exception {
//int minSize = 3;
List<int[]> listFrags = new ArrayList<int[]>();
Chemical m3 = m.copy();
m3.setAtomMapToPosition();
Chemical m4 = m3.copy();
// System.out.println("removing disultifes");
removeDisulfide(m4);
// System.out.println("contracting peptides...");
contractPeptide(m4);
// System.out.println("now smiles is =" + m4.toSmiles());
// System.out.println(m4.atoms().map(a-> "[ " + a.getSymbol() + " " + a.getAtomToAtomMap().getAsInt() + "]").collect(Collectors.joining(",")));
Set<Integer> backboneAtoms = new HashSet<>();
Set<Integer> modind = new HashSet<>();
// System.out.println("after removing not He, Ns and Ne...");
for (Atom ma : m4.atoms().collect(Collectors.toList())) {
if(ma.getAtomicNumber() == 2 && ma.getMassNumber()==7) {
modind.add(ma.getAtomToAtomMap().orElse(0)-1);
}else if(ma.getAtomicNumber() != 10){
m4.removeAtom(ma);
}
}
// System.out.println("now smiles is =" + m4.toSmiles());
// List<Chemical> tFrags =m4.getco();
// if(tFrags.size()>1){
// //Non-alpha AA, or linked Protein
// }
for(Chemical m2:m4.getConnectedComponents()){
int[] ret = null;
//find ends, get list
for (Atom ma : m2.getAtoms()) {
if (ma.getBondCount() <=1) {
ret = new int[m2.getAtomCount()];
int numat = 0;
Atom pma = null;
while (numat < m2.getAtomCount()) {
ret[numat] = ma.getAtomToAtomMap().orElse(0) - 1;
// if (ma.equals(pma)) {
// System.out.println("going in loop? " + ma + " and pma = " + pma);
// }
for (int i = 0; i < ma.getBondCount(); i++) {
Atom ma2 = ma.getBonds().get(i).getOtherAtom(ma);
if (pma !=null && ma2.getAtomIndexInParent()==pma.getAtomIndexInParent()) {
continue;
} else {
pma = ma;
ma = ma2;
break;
}
}
numat++;
}
break;
}
}
if(ret==null && m2.getAtomCount()<1)continue;
if(ret==null){
for (Atom ma : m2.getAtoms()) {
ret = new int[m2.getAtomCount()];
int numat = 0;
Atom pma = null;
while (numat < m2.getAtomCount()) {
ret[numat] = ma.getAtomToAtomMap().orElse(0) - 1;
for (int i = 0; i < ma.getBondCount(); i++) {
Atom ma2 = ma.getBonds().get(i).getOtherAtom(ma);
if (ma2.equals(pma)) {
continue;
} else {
pma = ma;
ma = ma2;
break;
}
}
numat++;
}
break;
}
}
/*
* Now we've got a subsequence, but we need to put them in the right order (N->C)
* We do this by looking at the first two alpha atoms in the sequence.
* If the N in the first is linked to the second,
*
*/
if(ret.length>1){
boolean reverse = false;
Atom at1 = m3.getAtom(ret[0]);
Atom at2 = m3.getAtom(ret[1]);
Set<Atom> amideAtoms = new HashSet<>();
//System.out.println("ATOM NUM:" + at1.getAtno());
if(!modind.contains(ret[0])){
if(!modind.contains(ret[ret.length-1])){
for (int i = 0; i < at1.getBondCount(); i++) {
Atom n1 = at1.getBonds().get(i).getOtherAtom(at1);
if (n1.getAtomicNumber() == 7) {
for (int j = 0; j < n1.getBondCount(); j++) {
Atom m1 = n1.getBonds().get(j).getOtherAtom(n1);
if (m1 != at1) {
amideAtoms.add(m1);
}
}
}
}
for (int i = 0; i < at2.getBondCount(); i++) {
Atom n1 = at2.getBonds().get(i).getOtherAtom(at2);
if (amideAtoms.contains(n1)) {
reverse = true;
break;
}
}
}else{
reverse=true;
}
}else{
reverse=false;
}
if (reverse) {
for (int i = 0; i < ret.length / 2; i++) {
int t = ret[ret.length - 1 - i];
ret[ret.length - i - 1] = ret[i];
ret[i] = t;
}
}
}
if(ret!=null){
for(int r:ret){
backboneAtoms.add(r);
}
//System.out.println(Arrays.toString(ret));
listFrags.add(ret);
}
}
/*
* Now we've got all the alpha-amino acid chains, each in the right
* order, internally But they're not connected correctly. To do this, we
* go to each modified atom (carbonyl group), and search for the first connection to
* another backbone atom that it's not already connected to
*/
int[] ret = null;
if(listFrags.size()>1){
int tsize=0;
Map<Integer,Integer> startFrag = new HashMap<>();
List<Integer> startingIndexes = new ArrayList<>();
int startingIndex = -1;
// System.out.println("listFrags size = " + listFrags.size() + "\n" + listFrags.stream().map(Arrays::toString).collect(Collectors.joining("\n")));
for(int[] r : listFrags){
if(r!=null){
if(modind.contains(r[0])){
Set<Integer> tryAtoms = new HashSet<>(backboneAtoms);
Set<Integer> stopAtoms = new HashSet<>();
if(r.length>1) {
stopAtoms.add(r[1]);
}
stopAtoms.add(r[0]);
tryAtoms.removeAll(stopAtoms);
int con = getClosestAtomInSet(m3,r[0],tryAtoms,stopAtoms);
if(con==-1){
if(startingIndex==-1){
startingIndex = r[0];
}else{
//System.out.println("NON-CONNECTABLE");
}
startingIndexes.add(r[0]);
}else{
startFrag.put(con, r[0]);
}
}else{
startingIndex=r[0];
startingIndexes.add(r[0]);
}
for(int i=0;i<r.length-1;i++){
startFrag.put(r[i], r[i+1]);
}
tsize+=r.length;
}
}
// System.out.println("starting indexes = " + startingIndexes);
// System.out.println("startFrag map = " + startFrag);
List<Integer> longest = null;
int i=0;
for(int st:startingIndexes){
List<Integer> order = new ArrayList<>();
while(st!=-1){
order.add(st);
// System.out.println(order);
// if(!order.add(st)){
// break;
// }
Integer si = startFrag.get(st);
if(si==null || si.intValue() ==st){
break;
}
st =si;
}
if(longest == null || order.size()>longest.size()){
longest=new ArrayList<>(order);
}
//System.out.println("ORDER " + i++ + ":" +order.toString());
}
if(longest==null)return null;
ret = new int[longest.size()];
for(int j=0;j<longest.size();j++){
ret[j]=longest.get(j);
}
//System.out.println("FINAL ORDER:"+Arrays.toString(ret));
//return ret;
}
//System.out.println(Arrays.toString(ret));
if(listFrags.size()>0){
Collections.sort(listFrags,new Comparator<int[]>(){
@Override
public int compare(int[] o1, int[] o2) {
return -(o1.length-o2.length);
}
});
ret = listFrags.get(0);
}
if(ret!=null){
if(ret.length<minSize)
ret=null;
}
return ret;
}
/*
public static int getClosestAtomInSet(Molecule m, int a1, Set<Integer> aset,Set<Integer> bounds){
//ChemicalAtom ma = m.getAtom(a1);
Set<ChemicalAtom> left = new HashSet<ChemicalAtom>();
Set<ChemicalAtom> wavefront = new HashSet<ChemicalAtom>();
Map<ChemicalAtom, Integer> find = new HashMap<ChemicalAtom,Integer>();
for(int i=0;i<m.getAtomCount();i++){
if(!bounds.contains(i))
left.add(m.getAtom(i));
if(aset.contains(i)){
find.put(m.getAtom(i),i);
}
}
//left.removeAll(bounds);
wavefront.add(m.getAtom(a1));
while(wavefront.size()>0){
Set<ChemicalAtom> nwavefront = new HashSet<ChemicalAtom>();
for(ChemicalAtom ma: wavefront){
for(int i=0;i<ma.getBondCount();i++){
ChemicalAtom mb = ma.getBond(i).getOtherAtom(ma);
if(!bounds.contains(mb)){
if(left.contains(mb)){
nwavefront.add(mb);
left.remove(mb);
Integer ind = find.get(mb);
if(ind!=null){
return ind;
}
}
}
}
}
wavefront = nwavefront;
}
return -1;
}*/
public static int getClosestAtomInSet(Chemical m, int a1, Set<Integer> aset,Set<Integer> bounds){
//ChemicalAtom ma = m.getAtom(a1);
Set<Atom> left = new HashSet<>();
Set<Atom> wavefront = new HashSet<>();
Map<Atom, Integer> find = new HashMap<>();
for(int i=0;i<m.getAtomCount();i++){
if(!bounds.contains(i))
left.add(m.getAtom(i));
if(aset.contains(i)){
find.put(m.getAtom(i),i);
}
}
//left.removeAll(bounds);
wavefront.add(m.getAtom(a1));
while(!wavefront.isEmpty()){
Set<Atom> nwavefront = new HashSet<>();
for(Atom ma: wavefront){
for(Bond b : ma.getBonds()){
// for(int i=0;i<ma.getBondCount();i++){
Atom mb = b.getOtherAtom(ma);
Integer index = mb.getAtomToAtomMap().orElse(0) -1;
if(!bounds.contains(index)){
if(left.contains(mb)){
nwavefront.add(mb);
left.remove(mb);
Integer ind = find.get(mb);
if(ind!=null){
return ind;
}
}
}
}
}
wavefront = nwavefront;
}
return -1;
}
/**
*
* @param smi Structure as string
* @return Returns the amino acid sequence in the form <SEQ>;<SEQ>|<DISULFIDES>
* @throws Exception
*
* For example, a structure with two subunits, linked by a disulfide bond might give:
*
* QASCSG;NACSG|[1_4-2_3]
*/
public static Protein getAminoAcidSequence(String smi) throws Exception {
try {
smi=smi.replaceAll("M S..*", "");
// System.out.println("trying to import " + smi);
Chemical c = Chemical.parse(smi);
c.generateCoordinates();
c.aromatize();
c.kekulize();
String smi2 = c.toMol();
// System.out.println("parsed mol = " + smi2);
smi2=smi2.replaceAll("M S..*", "");
c = Chemical.parse(smi2);
// System.out.println(c.toMol());
return getAminoAcidSequence(c);
} catch (Exception e) {
e.printStackTrace();
try {
Chemical c = Chemical.parse(smi);
c.expandSGroups();
Chemical m2=buildCleanMolecule(c);
return getAminoAcidSequence(m2);
} catch (Exception e1) {
return null;
}
}
}
public static Chemical buildCleanMolecule(Chemical c){
ChemicalBuilder c2 = new ChemicalBuilder();
Map<Atom, Integer> atMap = new HashMap<>();
int i=0;
for(Atom ma : c.getAtoms()){
Atom ma2 = c2.addAtom(ma.getSymbol());
ma2.setMassNumber(ma.getMassNumber());
ma2.setCharge(ma.getCharge());
ma2.setRadical(ma.getRadical());
ma2.setAtomCoordinates(ma2.getAtomCoordinates());
//m2.add(ma2);
atMap.put(ma,i++);
}
for(Bond mb: c.getBonds()){
int a1 = atMap.get(mb.getAtom1());
int a2 = atMap.get(mb.getAtom2());
Atom at1=c2.getAtom(a1);
Atom at2=c2.getAtom(a2);
c2.addBond(at1,at2,mb.getBondType())
.setStereo(mb.getStereo());
}
return c2.build();
}
/* TODO: If it's a cyclic peptide, watch out and do something ...
*
* I guess, while getting the peptide backbone? Perhaps ...
*
*
*
*
*
*/
public static Protein getAminoAcidSequence(Chemical impMol) {
if(impMol==null){
return null;
}
if(impMol.getAtomCount()>=1024){
throw new IllegalArgumentException("Too many atoms, does not support >= 1024");
}
//System.out.println("Number of atoms:" + impMol.getAtomCount());
List<String> sequences1Let = new ArrayList<>();
Map<Integer,Integer> canonicalSequenceMap = new HashMap<>();
Chemical stdMol = impMol.copy();
stdMol.makeHydrogensImplicit();
stdMol.aromatize();
stdMol.setAtomMapToPosition();
int[] bridges = removeDisulfide(stdMol);
HashMap<Integer,String> atom_to_residue = new HashMap<Integer,String> ();
int subunit=-1;
for (Chemical c : stdMol.getConnectedComponents()) {
String ret = ""; //Full Sequence, single letter, semi-colon between subunits
subunit++; //start to 0
try {
int[] seq = longestPeptideBackbone(c,4);
//System.out.println(seq);
if(seq==null){
subunit--;
continue;
}
Map<Integer,Integer> chi = new HashMap<>();
Map<Integer,Integer> alphaAtomIndexToSeqIndex = new LinkedHashMap<>();
Chemical c2 = c.copy();
int k=0;
for (int s : seq) {
Atom atom = c2.getAtom(s);
int amap= atom.getAtomToAtomMap().orElse(0)-1;
alphaAtomIndexToSeqIndex.put(amap,k++);
// System.out.println("Found:" + atom.getChirality());
chi.put(amap, atom.getChirality().getParity());
}
contractPeptide(c2,seq);
List<Bond> toRemove = new ArrayList<>();
List<String> remBond = new ArrayList<String>();
for (Atom ma : c2.getAtoms()) {
if (ma.getAtomicNumber() == 10) {
for(Bond b : ma.getBonds()){
Atom mn= b.getOtherAtom(ma);
if (mn.getAtomicNumber() == 10 || mn.getMassNumber() ==7 || mn.getMassNumber() ==6) {
toRemove.add(b);
}
}
}
}
for (Bond mb : toRemove) {
c2.removeBond(mb);
remBond.add(mb.getAtom1().getAtomToAtomMap().orElse(0) + "_" + mb.getAtom2().getAtomToAtomMap().orElse(0));
}
String ctermmod = "";
String ntermmod = "";
Map<Integer, Integer> atomIndexToAlphaAtomIndex = new HashMap<Integer, Integer>();
Map<Integer, String> alphaAtomIndexToAA = new HashMap<Integer, String>();
for (Chemical cf : c2.getConnectedComponents()) {
int mod = 0;
int patt = -1;
Map<Integer,Atom> myatoms = new HashMap<>();
for (Atom ma : cf.getAtoms()) {
if(mod==0 || mod==55){
mod=ma.getMassNumber();
}
int pat = ma.getAtomToAtomMap().orElse(0);
if (alphaAtomIndexToSeqIndex.containsKey(pat-1)) {
patt = pat - 1;
}else{
//myatoms.put(pat-1,ma);
}
myatoms.put(pat-1,ma);
ma.clearAtomToAtomMap();
}
boolean weirdCycle = false;
//Molecule tf;
Chemical tf=null;
List<Bond> mbadd = new ArrayList<>();
for (String mb: remBond) {
int amap1= Integer.parseInt(mb.split("_")[0]);
int amap2= Integer.parseInt(mb.split("_")[1]);
Atom ma1,ma2;
//System.out.println("LOOK:" +amap1 + "," + amap2);
if((ma1 = myatoms.get(amap1-1))!=null){
if((ma2 = myatoms.get(amap2-1))!=null){
//System.out.println("GET HERE?");
Bond cb = cf.addBond(ma1, ma2, Bond.BondType.SINGLE);
mbadd.add(cb);
cf.removeBond(cb);
if(ma1.getSymbol().equals("Ne") || ma2.getSymbol().equals("Ne")){
weirdCycle=true;
}
}
}
}
if(weirdCycle){
tf=cf.copy();
}
for(Bond mb:mbadd){
cf.addBond(mb);
mb.getAtom1().clearAtomToAtomMap();
mb.getAtom2().clearAtomToAtomMap();
}
Chemical f2 = cf.copy();
int aamap = -1;
for(Atom ma:f2.getAtoms()){
if(ma.isQueryAtom()){
//Change all previously psuedo atoms to argon.
//Why? It's a placeholder for a better solution.
ma.setAtomicNumber(18);
}
if(ma.getAtomToAtomMap().isPresent()){
aamap =ma.getAtomToAtomMap().getAsInt()-1;
}
}
// System.out.println("looking up " + f2.toSmiles());
String hashKey = LOOKUP_HASH(f2);
// System.out.println(hashKey);
String aalet = AAmap.get(hashKey);
// System.out.println("WAS:" + aalet);
if(aalet==null){
// System.out.println("was null!! current map is " + AAmap);
String smiles=f2.toSmiles();
if(!weirdCycle){
smiles=decodePeptide(smiles,false);
}else{
smiles=decodePeptide(tf.toSmiles(),true);
}
// System.out.println("now smiles = " + smiles);
if(modFreq.get(smiles)==null){
modFreq.put(smiles, 1);
}else{
modFreq.put(smiles, modFreq.get(smiles)+1);
}
if(mod==6){
//TODO: make more robust cterm handling
String let = getModName(smiles);
aalet=let;
if(patt==-1){
patt=aamap;
alphaAtomIndexToSeqIndex.put(patt,k++);
}
}else{
/*
else if(mod==7){
if(smiles.equals("[7He]C")){
ntermmod="Ac-";
}else{
ntermmod="("+smiles+")-";
}
}*/
//if()
String let = getModName(smiles);
aalet=let;
}
}
//System.out.println(patt + "\t" +smi1+"\t" + smiles+ "\t" + aalet);
//modMap.put(, arg1)
//System.out.println(mod+ "\t" + patt+":"+AAmap.get(smiles) + "\t" +smiles);
for(int p:myatoms.keySet()){
atomIndexToAlphaAtomIndex.put(p, patt);
}
alphaAtomIndexToAA.put(patt, aalet);
}
ret+=ntermmod;
for (int s : alphaAtomIndexToSeqIndex.keySet()) {
String let = alphaAtomIndexToAA.get(s);
if(let==null){
//let = "[X:"+ ++letNumber + "]";
//TODO: should flag for bogus ring
//modMap.put(let,"???ring");
}else{
boolean mod = (modName.get(let)!=null);
if (!mod){
int chi1 =(chi.get(s));
int chi2 =(let!=null)?(AAmapCHI.get(let)):0;
if(chi1!=chi2 &&
(chi1==gov.nih.ncats.molwitch.Chirality.R.getParity() ||
chi1==gov.nih.ncats.molwitch.Chirality.S.getParity())
){
let=let.toLowerCase();
}
}
ret += let;
}
}
for(int key:atomIndexToAlphaAtomIndex.keySet()){
int rmap = atomIndexToAlphaAtomIndex.get(key);
try{
int seqp = alphaAtomIndexToSeqIndex.get(rmap);
atom_to_residue.put(key, (subunit+1) + "_" +(seqp+1));
}catch(Exception e){
}
}
sequences1Let.add((subunit+1) + "_" + ret);
} catch (Exception e) {
e.printStackTrace();
}
}
Collections.sort(sequences1Let,new SequenceComparator());
Protein prot = new Protein();
int sNum =1;
String ret = "";
for(String seq: sequences1Let){
String[] split = seq.split("_");
int psub = Integer.parseInt(split[0]);
String seq2 = split[1];
String seq3 = seq2.replaceAll("[0-9]", "");
String[] nmod=seq2.replaceAll("[^X|0-9]", "").replaceAll("(X[0-9][0-9]*)","$1,").split(",");
int pind=0;
for(String n:nmod){
String smi = PeptideInterpreter.modName.get(n);
if(smi!=null){
int res = seq3.indexOf("X", pind);
pind=res+1;
prot.addMod(sNum, res+1, smi);
}
}
canonicalSequenceMap.put(psub, sNum);
sequences1Let.set(sNum-1, seq2);
sNum++;
if(ret.length()>0)
ret+=";";
prot.addSubunit(seq3);
ret += seq2;
}
ret+="|";
if(sequences1Let.size()>0){
List<String> dBridges = new ArrayList<String>();
for(int i=0;i<bridges.length;i+=2){
List<String> dBridgeT = new ArrayList<String>(2);
dBridgeT.add("");
dBridgeT.add("");
String at1=canSite(atom_to_residue.get(bridges[i]),canonicalSequenceMap);
String at2=canSite(atom_to_residue.get(bridges[i+1]),canonicalSequenceMap);
dBridgeT.set(0,at1);
dBridgeT.set(1,at2);
Collections.sort(dBridgeT,new DisulfideComparator());
dBridges.add((dBridgeT.get(0) + "-" +dBridgeT.get(1)));
}
Collections.sort(dBridges,new DisulfideComparator());
for(String disulf:dBridges){
String[] ind = disulf.replace("_", "-").split("-");
if(ind.length>=4){
prot.addDSBond(Integer.parseInt(ind[0]), Integer.parseInt(ind[1]), Integer.parseInt(ind[2]), Integer.parseInt(ind[3]));
}
}
ret+=dBridges.toString();//+ "|" +modMap.toString();
}
return prot;
}
public static String getModName(String smiles){
String let = modMap.get(smiles);
if(let==null){
let="X"+modNumber++;
modMap.put(smiles,let);
modName.put(let, smiles);
}
// System.out.println("getModName of " + smiles + " is = " + let);
return let;
}
public static String canSite(String oSite,Map<Integer,Integer> newSeq){
if(oSite==null)return null;
String[] split = oSite.split("_");
int oindex = Integer.parseInt(split[0]);
int nindex = newSeq.get(oindex);
return nindex + "_" + split[1];
}
public static String decodePeptide(String str, boolean weird){
//if(true)return str;
String str2=str;
boolean omod =false;
// System.out.println("in decode peptide weird = " + weird);
if(weird){
try {
// System.out.println("before replace " + str2);
str2=str2.replace("[55Ne]","C(C([*:2])=O)([NH:9]([*:1]))");
// System.out.println("after replace " + str2);
Chemical c = Chemical.parse(str2);
Atom mat=null;
Atom mat2=null;
c.setAtomMapToPosition();
for(Atom ma:c.getAtoms()){
if(ma.getAtomToAtomMap().orElse(0)==9){
mat=ma;
ma.clearAtomToAtomMap();
}
//links to nitro
if(ma.getMassNumber()==7){
mat2=ma;
mat2.setMassNumber(0);
}
}
if(mat!=null && mat2!=null)
c.addBond(mat,mat2, Bond.BondType.SINGLE);
//addBond(d(new MolBond(mat,mat2));
try{
str2= c.toSmiles();
}catch(Exception e){
// e.printStackTrace();
str2= c.toSmarts();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
str2=str2.replaceAll("\\[7([A-Z|a-z|0-9]*)\\]", "[$1]([*:1])");
str2=str2.replaceAll("\\[6([A-Z|a-z|0-9]*)\\]", "[$1]([*:2])");
//if(str2.indexOf("[*:1]")>-1 || str2.indexOf("[*:2]")>-1)omod=true;
str2=str2.replace("[He]","C(=O)");
str2=str2.replace("[he]","C(=O)");
str2=str2.replaceAll("\\[NH[0-9]\\]","N");
//str2=str2.replace("[Ar]","[*:3]");
if(!omod){
str2=str2.replace("[Ne]","C(C([*:2])=O)(N([*:1]))");
//if(str2.contains("[55Ne]")){
// System.out.println(str2);
//}
str2=str2.replace("[55Ne]","C(C([*:2])=O)(N(C)([*:1]))");
}
// System.out.println("before try..." + str2);
try {
//System.out.println(str);
String stchange =str2.replace("[Ne]","C(C([*:2])=O)(N([*:1]))");
stchange =stchange.replace("[55Ne]","C(C([*:2])=O)(N([*:1]))");
// System.out.println("now stchange = " + stchange);
if(!str2.equals(stchange)){
str2=stchange;
Chemical c = Chemical.parse(str2);
//MolHandler mh = new MolHandler();
//mh.setMolecule(str2);
//Molecule m = mh.getMolecule();
List<Atom> merge = new ArrayList<>();
List<Atom> rem = new ArrayList<>();
c.setAtomMapToPosition();
for(Atom ma:c.getAtoms()){
if(ma.getAtomToAtomMap().orElse(0)==1){
merge.add(ma.getBonds().get(0).getOtherAtom(ma));
rem.add(ma);
}
}
for(Atom ma: rem){
c.removeAtom(ma);
}
for(int i=0;i<merge.size();i++){
for(int j=i+1;j<merge.size();j++){
c.addBond(merge.get(i),merge.get(j),Bond.BondType.SINGLE);
}
}
try{
return c.toSmiles().replace(":2",":1");
}catch(Exception e){
return c.toSmarts().replace(":2",":1");
}
}
} catch (Exception e) {
e.printStackTrace();
}
//override for pyroglu
if(str2.equals("C(=O)1CCC(C([*:2])=O)(N([*:1]))1")){
return "[*:2]C(=O)C1CCC(=O)N1";
}
return str2;
}
public static class DisulfideComparator implements Comparator<String>{
@Override
public int compare(String at1, String at2) {
if(at1==null && at2==null)return 0;
if(at2==null) return -1;
if(at1==null) return 1;
at1=at1.split("-")[0];
at2=at2.split("-")[0];
try{
int at1S=Integer.parseInt(at1.split("_")[0]);
int at2S=Integer.parseInt(at2.split("_")[0]);
int at1R=Integer.parseInt(at1.split("_")[1]);
int at2R=Integer.parseInt(at2.split("_")[1]);
if(at2S<at1S){
return 1;
}else{
if(at2S==at1S){
if(at2R<at1R){
return 1;
}
if(at2R==at1R){
return 0;
}
}
}
}catch(Exception e ){
return 0;
}
return -1;
}
}
public static class SequenceComparator implements Comparator<String>{
@Override
public int compare(String seq1, String seq2) {
if(seq1==null && seq2==null)return 0;
if(seq1==null) return -1;
if(seq2==null) return 1;
int len = seq1.length()-seq2.length();
if(len==0){
return seq1.compareTo(seq2);
}
return -len;
}
}
public static class Protein{
private static final String KEY_STRUCTURAL_MODIFICATIONS = "structuralModifications";
List<Subunit> subunits = new ArrayList<Subunit>();
List<DisulfideBond> disulfideLinks = new ArrayList<DisulfideBond>();
Map<String,List<Map>> modifications= new HashMap<String,List<Map>>();
public List<Subunit> getSubunits() {
return subunits;
}
public List<DisulfideBond> getDisulfideLinks() {
return disulfideLinks;
}
public Map<String, List<Map>> getModifications() {
return modifications;
}
public class Subunit{
int subunitIndex;
String sequence;
public Subunit(int subIndex,String seq){
this.subunitIndex=subIndex;
this.sequence=seq;
}
public int getSubunitIndex() {
return subunitIndex;
}
public String getSequence() {
return sequence;
}
}
public class DisulfideBond{
Site[] sites = new Site[2];
public DisulfideBond(int sub1, int res1, int sub2, int res2){
sites[0]=new Site(sub1,res1);
sites[1]=new Site(sub2,res2);
}
public String toString(){
return sites[0] + "-" + sites[1];
}
}
public class Site{
int subunitIndex;
int residueIndex;
public Site(int s, int r){
this.subunitIndex=s;
this.residueIndex=r;
}
public String toString(){
return subunitIndex + "_" + residueIndex;
}
}
public Protein(){
modifications.put(Protein.KEY_STRUCTURAL_MODIFICATIONS, new ArrayList());
}
public void addSubunit(String seq){
subunits.add(new Subunit(subunits.size()+1,seq));
}
public void addDSBond(int sub1,int res1, int sub2,int res2){
disulfideLinks.add(new DisulfideBond(sub1,res1,sub2,res2));
}
public void addMod(int sub, int res, String smi){
modifications.get(Protein.KEY_STRUCTURAL_MODIFICATIONS).add(makeStrModification(sub,res,smi));
}
public Map makeStrModification(int sub,int res, String smiles){
return makeStrModification(new Site[]{new Site(sub,res)},smiles);
}
public Map makeStrModification(Site[] sites, String smiles){
Map mmodMap = new HashMap();
mmodMap.put("locationType", "SITE-SPECIFIC");
mmodMap.put("sites", sites);
mmodMap.put("structuralModificationType", "AMINO_ACID_REPLACEMENT");
mmodMap.put("_molecularFragmentSmiles", smiles);
return mmodMap;
}
public String toString(){
StringBuilder sb = new StringBuilder();
boolean first =true;
for(Subunit sub:this.subunits){
if(!first)
sb.append(";");
sb.append(sub.sequence);
first=false;
}
if(this.disulfideLinks.size()>0){
sb.append("|");
first=true;
for(DisulfideBond disulf:this.disulfideLinks){
if(!first)
sb.append(";");
sb.append(disulf);
first=false;
}
}
return sb.toString();
}
/*
*
"modifications": {
"structuralModifications": [
{
"residueModified": "GLUTAMINE",
"locationType": "SITE-SPECIFIC",
"structuralModificationType": "AMINO ACID SUBSTITUTION",
"sites": [
{
"subunitIndex": 1,
"residueIndex": 1
}
],
"molecularFragmentID": "SZB83O1W42",
"molecularFragmentName": "PYROGLU",
"amountType": "PERCENT",
"amount": {
"average": 100,
"lowLimit": null,
"highLimit": null,
"unit": null,
"nonNumericValue": null
}
}
],
"agentModifications": [],
"physicalModifications": []
},
*/
}
public static void readFromFile(String fname, LineProcessor eachLine){
FileInputStream fstream;
try {
fstream = new FileInputStream(fname);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
if(!eachLine.process(strLine))break;
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public interface LineProcessor{
public boolean process(String line);
}
}
|
package org.riversun.jmws;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/** DUMMY TRANSLATION(DRY RUN MODE) */
public class AppTest
extends TestCase
{
/** DUMMY TRANSLATION(DRY RUN MODE) */
public AppTest(String testName)
{
super(testName);
}
/** DUMMY TRANSLATION(DRY RUN MODE) */
public static Test suite()
{
return new TestSuite(AppTest.class);
}
/** DUMMY TRANSLATION(DRY RUN MODE) */
public void testApp()
{
assertTrue(true);
}
}
|
/*
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.policy.evaluator;
public class FeatureRules {
private String name;
private String evaluationCriteria;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEvaluationCriteria() {
return evaluationCriteria;
}
public void setEvaluationCriteria(String evaluationCriteria) {
this.evaluationCriteria = evaluationCriteria;
}
}
|
/*
* Copyright 2012 GitHub 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.github.mobile.tests.tests.repo;
import static android.app.SearchManager.QUERY;
import static android.content.Intent.ACTION_SEARCH;
import android.content.Intent;
import com.github.mobile.tests.ActivityTest;
import com.github.mobile.ui.repo.RepositorySearchActivity;
/**
* Tests of {@link RepositorySearchActivity}
*/
public class RepositorySearchActivityTest extends
ActivityTest<RepositorySearchActivity> {
/**
* Create test
*/
public RepositorySearchActivityTest() {
super(RepositorySearchActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
setActivityIntent(new Intent(ACTION_SEARCH).putExtra(QUERY, "test"));
}
}
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.hellonotes;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int action_settings=0x7f080012;
public static final int c_img=0x7f080004;
public static final int delete=0x7f080008;
public static final int ettext=0x7f080006;
public static final int img=0x7f080001;
public static final int list=0x7f080003;
public static final int list_content=0x7f08000b;
public static final int list_img=0x7f080009;
public static final int list_time=0x7f08000c;
public static final int list_video=0x7f08000a;
public static final int s_back=0x7f080011;
public static final int s_delete=0x7f080010;
public static final int s_img=0x7f08000d;
public static final int s_tv=0x7f08000f;
public static final int s_video=0x7f08000e;
public static final int save=0x7f080007;
public static final int text=0x7f080000;
public static final int v_video=0x7f080005;
public static final int video=0x7f080002;
}
public static final class layout {
public static final int activity_main=0x7f030000;
public static final int addcontent=0x7f030001;
public static final int cell=0x7f030002;
public static final int select=0x7f030003;
}
public static final class menu {
public static final int main=0x7f070000;
}
public static final class string {
public static final int action_settings=0x7f050002;
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050001;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.