code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * Copyright 1999-2006 University of Chicago * * 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.globus.ftp; import java.io.IOException; import java.io.File; import java.io.RandomAccessFile; import java.util.Vector; import java.net.UnknownHostException; import org.globus.ftp.exception.ClientException; import org.globus.ftp.exception.ServerException; import org.globus.ftp.exception.FTPReplyParseException; import org.globus.ftp.exception.UnexpectedReplyCodeException; import org.globus.ftp.vanilla.Command; import org.globus.ftp.vanilla.Reply; import org.globus.ftp.vanilla.TransferState; import org.globus.ftp.vanilla.FTPControlChannel; import org.globus.ftp.extended.GridFTPServerFacade; import org.globus.ftp.extended.GridFTPControlChannel; import org.globus.gsi.gssapi.auth.Authorization; import org.globus.ftp.MultipleTransferComplete; import org.globus.ftp.MultipleTransferCompleteListener; import org.ietf.jgss.GSSCredential; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.common.Version; import java.io.ByteArrayOutputStream; import java.text.DecimalFormat; import org.globus.ftp.exception.FTPException; /** * This is the main user interface for GridFTP operations. * Use this class for client - server or third party transfers * with mode E, parallelism, markers, striping or GSI authentication. * Consult the manual for general usage. * <br><b>Note:</b> If using with GridFTP servers operations like * {@link #setMode(int) setMode()}, {@link #setType(int) setType()}, * {@link #setDataChannelProtection(int) setDataChannelProtection()}, * and {@link #setDataChannelAuthentication(DataChannelAuthentication) * setDataChannelAuthentication()} that affect data channel settings * <b>must</b> be called before passive or active data channel mode is set. **/ public class GridFTPClient extends FTPClient { private static Log logger = LogFactory.getLog(GridFTPClient.class.getName()); //utility alias to session and localServer protected GridFTPSession gSession; protected GridFTPServerFacade gLocalServer; protected String usageString; /** * Constructs client and connects it to the remote server. * * @param host remote server host * @param port remote server port */ public GridFTPClient(String host, int port) throws IOException, ServerException { gSession = new GridFTPSession(); session = gSession; controlChannel = new GridFTPControlChannel(host, port); controlChannel.open(); gLocalServer = new GridFTPServerFacade((GridFTPControlChannel)controlChannel); localServer = gLocalServer; gLocalServer.authorize(); this.useAllo = true; setUsageInformation("CoG", Version.getVersion()); } /** * Performs authentication with specified user credentials. * * @param credential user credentials to use. * @throws IOException on i/o error * @throws ServerException on server refusal or faulty server behavior */ public void authenticate(GSSCredential credential) throws IOException, ServerException { authenticate(credential, null); } public void setUsageInformation( String appName, String appVer) { usageString = new String( "CLIENTINFO appname=" + appName +";appver=" + appVer + ";schema=gsiftp;"); } /** * Performs authentication with specified user credentials and * a specific username (assuming the user dn maps to the passed username). * * @param credential user credentials to use. * @param username specific username to authenticate as. * @throws IOException on i/o error * @throws ServerException on server refusal or faulty server behavior */ public void authenticate(GSSCredential credential, String username) throws IOException, ServerException { ((GridFTPControlChannel)controlChannel).authenticate(credential, username); gLocalServer.setCredential(credential); gSession.authorized = true; this.username = username; // quietly send version information to the server. // ignore errors try { String version = Version.getVersion(); this.site(usageString); } catch (Exception ex) { } } /** * Performs remote directory listing like * {@link FTPClient#list(String,String) FTPClient.list()}. * <b>Note:</b> This method cannot be used * in conjunction with parallelism or striping; set parallelism to * 1 before calling it. Otherwise, use * {@link FTPClient#list(String,String,DataSink) FTPClient.list()}. * Unlike in vanilla FTP, here IMAGE mode is allowed. * For more documentation, look at FTPClient. */ public Vector list(String filter, String modifier) throws ServerException, ClientException, IOException { if (gSession.parallel > 1) { throw new ClientException( ClientException.BAD_MODE, "list cannot be called with parallelism"); } return super.list(filter, modifier); } /** * Performs remote directory listing like * {@link FTPClient#nlist(String) FTPClient.nlist()}. * <b>Note:</b> This method cannot be used * in conjunction with parallelism or striping; set parallelism to * 1 before calling it. Otherwise, use * {@link FTPClient#nlist(String,DataSink) FTPClient.nlist()}. * Unlike in vanilla FTP, here IMAGE mode is allowed. * For more documentation, look at FTPClient. */ public Vector nlist(String path) throws ServerException, ClientException, IOException { if (gSession.parallel > 1) { throw new ClientException( ClientException.BAD_MODE, "nlist cannot be called with parallelism"); } return super.nlist(path); } /** * Performs remote directory listing like * {@link FTPClient#mlsd(String) FTPClient.mlsd()}. * <b>Note:</b> This method cannot be used * in conjunction with parallelism or striping; set parallelism to * 1 before calling it. Otherwise, use * {@link FTPClient#mlsd(String,DataSink) FTPClient.mlsd()}. * Unlike in vanilla FTP, here IMAGE mode is allowed. * For more documentation, look at FTPClient. */ public Vector mlsd(String filter) throws ServerException, ClientException, IOException { if (gSession.parallel > 1) { throw new ClientException( ClientException.BAD_MODE, "mlsd cannot be called with parallelism"); } return super.mlsd(filter); } protected void listCheck() throws ClientException { // do nothing } protected void checkTransferParamsGet() throws ServerException, IOException, ClientException { Session localSession = localServer.getSession(); session.matches(localSession); // if transfer modes have not been defined, // set this (dest) as active if (session.serverMode == Session.SERVER_DEFAULT) { HostPort hp = setLocalPassive(); setActive(hp); } } protected String getModeStr(int mode) { switch (mode) { case Session.MODE_STREAM: return "S"; case Session.MODE_BLOCK: return "B"; case GridFTPSession.MODE_EBLOCK: return "E"; default: throw new IllegalArgumentException("Bad mode: " + mode); } } /** * Sets remote server TCP buffer size, in the following way: * First see if server supports "SBUF" and if so, use it. * If not, try the following commands until success: * "SITE RETRBUFSIZE", "SITE RBUFSZ", "SITE RBUFSIZ", * "SITE STORBUFSIZE", "SITE SBUFSZ", "SITE SBUFSIZ", * "SITE BUFSIZE". * Returns normally if the server confirms successfull setting of the * remote buffer size, both for sending and for receiving data. * Otherwise, throws ServerException. **/ public void setTCPBufferSize(int size) throws IOException, ServerException { if (size <= 0) { throw new IllegalArgumentException("size <= 0"); } try { boolean succeeded = false; String sizeString = Integer.toString(size); FeatureList feat = getFeatureList(); if (feat.contains(FeatureList.SBUF)) { succeeded = tryExecutingCommand( new Command("SBUF", sizeString)); } if (!succeeded) { succeeded = tryExecutingCommand( new Command("SITE BUFSIZE", sizeString)); } if (!succeeded) { succeeded = tryExecutingTwoCommands(new Command("SITE RETRBUFSIZE", sizeString), new Command("SITE STORBUFSIZE", sizeString)); } if (!succeeded) { succeeded = tryExecutingTwoCommands(new Command("SITE RBUFSZ", sizeString), new Command("SITE SBUFSZ", sizeString)); } if (!succeeded) { succeeded = tryExecutingTwoCommands(new Command("SITE RBUFSIZ", sizeString), new Command("SITE SBUFSIZ", sizeString)); } if (succeeded) { this.gSession.TCPBufferSize = size; } else { throw new ServerException(ServerException.SERVER_REFUSED, "Server refused setting TCP buffer size with any of the known commands."); } } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } private boolean tryExecutingTwoCommands(Command cmd1, Command cmd2) throws IOException, FTPReplyParseException, ServerException { boolean result = tryExecutingCommand(cmd1); if (result) { result = tryExecutingCommand(cmd2); } return result; } /* * This is like controlChannel.executeCommand, only that negative reply it * returns "false" rather than throwing exception */ private boolean tryExecutingCommand(Command cmd) throws IOException, FTPReplyParseException, ServerException { Reply reply = controlChannel.exchange(cmd); return Reply.isPositiveCompletion(reply); } /** * Sets local TCP buffer size (for both receiving and sending). **/ public void setLocalTCPBufferSize(int size) throws ClientException { if (size <=0 ) { throw new IllegalArgumentException("size <= 0"); } gLocalServer.setTCPBufferSize(size); } /** * Sets remote server to striped passive server mode (SPAS). **/ public HostPortList setStripedPassive() throws IOException, ServerException { Command cmd = new Command("SPAS", (controlChannel.isIPv6()) ? "2" : null); Reply reply = null; try { reply = controlChannel.execute(cmd); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch(FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } this.gSession.serverMode = GridFTPSession.SERVER_EPAS; if (controlChannel.isIPv6()) { gSession.serverAddressList = HostPortList.parseIPv6Format(reply.getMessage()); int size = gSession.serverAddressList.size(); for (int i=0;i<size;i++) { HostPort6 hp = (HostPort6)gSession.serverAddressList.get(i); if (hp.getHost() == null) { hp.setVersion(HostPort6.IPv6); hp.setHost(controlChannel.getHost()); } } } else { gSession.serverAddressList = HostPortList.parseIPv4Format(reply.getMessage()); } return gSession.serverAddressList; } /** * Sets remote server to striped active server mode (SPOR). **/ public void setStripedActive(HostPortList hpl) throws IOException, ServerException { Command cmd = new Command("SPOR", hpl.toFtpCmdArgument()); try { controlChannel.execute(cmd); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch(FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } this.gSession.serverMode = GridFTPSession.SERVER_EACT; } /** * Starts local server in striped passive mode. Since the local server * is not distributed, it will only listen on one socket. * * @param port required server port; can be set to FTPServerFacade.ANY_PORT * @param queue max size of queue of awaiting new data channel connection * requests * @return the HostPortList of 1 element representing the socket where the * local server is listening **/ public HostPortList setLocalStripedPassive(int port, int queue) throws IOException { return gLocalServer.setStripedPassive(port, queue); } /** * Behaves like setLocalStripedPassive(FTPServerFacade.ANY_PORT, * FTPServerFacade.DEFAULT_QUEUE) **/ public HostPortList setLocalStripedPassive() throws IOException { return gLocalServer.setStripedPassive(); } /** * Starts local server in striped active mode. * setStripedPassive() must be called before that. * This method takes no parameters. HostPortList of the remote * server, known from the last call of setStripedPassive(), is stored * internally and the local server will connect to this address. **/ public void setLocalStripedActive() throws ClientException, IOException { if (gSession.serverAddressList == null) { throw new ClientException(ClientException.CALL_PASSIVE_FIRST); } try { gLocalServer.setStripedActive(gSession.serverAddressList); } catch (UnknownHostException e) { throw new ClientException(ClientException.UNKNOWN_HOST); } } /** * Performs extended retrieve (partial retrieve mode starting * at offset 0). * * @param remoteFileName file to retrieve * @param size number of bytes of remote file to transmit * @param sink data sink to store the file * @param mListener marker listener **/ public void extendedGet(String remoteFileName, long size, DataSink sink, MarkerListener mListener) throws IOException, ClientException, ServerException { extendedGet(remoteFileName, 0, size, sink, mListener); } /** * Performs extended retrieve (partial retrieve mode). * * @param remoteFileName file to retrieve * @param offset the staring offset in the remote file * @param size number of bytes of remote file to transmit * @param sink data sink to store the file * @param mListener marker listener **/ public void extendedGet(String remoteFileName, long offset, long size, DataSink sink, MarkerListener mListener) throws IOException, ClientException, ServerException { // servers support GridFTP? checkGridFTPSupport(); // all parameters set correctly (or still unset)? checkTransferParamsGet(); gLocalServer.store(sink); controlChannel.write(new Command("ERET", "P " + offset + " " + size + " " + remoteFileName)); transferRunSingleThread(localServer.getControlChannel(), mListener); } /** * Performs extended store (adujsted store mode with offset 0). * * @param remoteFileName file name to store * @param source source for the data to transfer * @param mListener marker listener **/ public void extendedPut(String remoteFileName, DataSource source, MarkerListener mListener) throws IOException, ServerException, ClientException{ extendedPut(remoteFileName, 0, source, mListener); } /** * Performs extended store (adujsted store mode). * * @param remoteFileName file name to store * @param offset the offset added to the file pointer before storing * the blocks of the file. * @param source source for the data to transfer * @param mListener marker listener **/ public void extendedPut(String remoteFileName, long offset, DataSource source, MarkerListener mListener) throws IOException, ServerException, ClientException{ // servers support GridFTP? checkGridFTPSupport(); // all parameters set correctly (or still unset)? checkTransferParamsPut(); localServer.retrieve(source); controlChannel.write(new Command("ESTO", "A " + offset + " " + remoteFileName)); transferRunSingleThread(localServer.getControlChannel(), mListener); } /* 3rd party transfer code */ /** * Performs a third-party transfer between two servers using extended * block mode. * If server modes are unset, source will be set to active * and destination to passive. * * @param remoteSrcFile source filename * @param destination destination server * @param remoteDstFile destination filename * @param mListener transer progress listener. * Can be set to null. */ public void extendedTransfer(String remoteSrcFile, GridFTPClient destination, String remoteDstFile, MarkerListener mListener) throws IOException, ServerException, ClientException { extendedTransfer(remoteSrcFile, 0, getSize(remoteSrcFile), destination, remoteDstFile, 0, mListener); } /** * Performs a third-party transfer between two servers using extended * block mode. * If server modes are unset, source will be set to active * and destination to passive. * * @param remoteSrcFile source filename * @param remoteSrcFileOffset source filename offset * @param remoteSrcFileLength source filename length to transfer * @param destination destination server * @param remoteDstFile destination filename * @param remoteDstFileOffset destination filename offset * @param mListener transer progress listener. * Can be set to null. */ public void extendedTransfer(String remoteSrcFile, long remoteSrcFileOffset, long remoteSrcFileLength, GridFTPClient destination, String remoteDstFile, long remoteDstFileOffset, MarkerListener mListener) throws IOException, ServerException, ClientException { // FIXME: ESTO & ERET do not require MODE E this needs to be fixed // servers support GridFTP? checkGridFTPSupport(); destination.checkGridFTPSupport(); // all parameters set correctly (or still unset)? gSession.matches(destination.gSession); //mode E if (gSession.transferMode != GridFTPSession.MODE_EBLOCK) { throw new ClientException(ClientException.BAD_MODE, "Extended transfer mode is necessary"); } // if transfer modes have not been defined, // set this (source) as active if (gSession.serverMode == Session.SERVER_DEFAULT) { HostPort hp = destination.setPassive(); this.setActive(hp); } Command estoCmd = new Command("ESTO", "A " + remoteDstFileOffset + " " + remoteDstFile); destination.controlChannel.write(estoCmd); Command eretCmd = new Command("ERET", "P " + remoteSrcFileOffset + " " + remoteSrcFileLength + " " + remoteSrcFile); controlChannel.write(eretCmd); transferRunSingleThread(destination.controlChannel, mListener); } public void extendedMultipleTransfer( long remoteSrcFileOffset[], long remoteSrcFileLength[], String remoteSrcFile[], GridFTPClient destination, long remoteDstFileOffset[], String remoteDstFile[], MarkerListener mListener, MultipleTransferCompleteListener doneListener) throws IOException, ServerException, ClientException { // servers support GridFTP? checkGridFTPSupport(); destination.checkGridFTPSupport(); // all parameters set correctly (or still unset)? gSession.matches(destination.gSession); //mode E if (gSession.transferMode != GridFTPSession.MODE_EBLOCK) { throw new ClientException(ClientException.BAD_MODE, "Extended transfer mode is necessary"); } if(remoteSrcFile.length != remoteDstFile.length) { throw new ClientException(ClientException.OTHER, "All array paremeters must be smae length"); } // if transfer modes have not been defined, // set this (source) as active if (gSession.serverMode == Session.SERVER_DEFAULT) { HostPort hp = destination.setPassive(); this.setActive(hp); } /* send them all down the pipe */ for(int i = 0; i < remoteSrcFile.length; i++) { Command estoCmd = new Command("ESTO", "A " + remoteDstFileOffset[i] + " " + remoteDstFile[i]); destination.controlChannel.write(estoCmd); Command eretCmd = new Command("ERET", "P " + remoteSrcFileOffset[i]+" "+remoteSrcFileLength[i] + " " + remoteSrcFile[i]); controlChannel.write(eretCmd); } for(int i = 0; i < remoteSrcFile.length; i++) { transferRunSingleThread(destination.controlChannel, mListener); if(doneListener != null) { MultipleTransferComplete mtc; mtc = new MultipleTransferComplete( remoteSrcFile[i], remoteDstFile[i], this, destination, i); doneListener.transferComplete(mtc); } } } public void extendedMultipleTransfer( String remoteSrcFile[], GridFTPClient destination, String remoteDstFile[], MarkerListener mListener, MultipleTransferCompleteListener doneListener) throws IOException, ServerException, ClientException { // servers support GridFTP? checkGridFTPSupport(); destination.checkGridFTPSupport(); // all parameters set correctly (or still unset)? gSession.matches(destination.gSession); //mode E if (gSession.transferMode != GridFTPSession.MODE_EBLOCK) { throw new ClientException(ClientException.BAD_MODE, "Extended transfer mode is necessary"); } if(remoteSrcFile.length != remoteDstFile.length) { throw new ClientException(ClientException.OTHER, "All array paremeters must be smae length"); } // if transfer modes have not been defined, // set this (source) as active if (gSession.serverMode == Session.SERVER_DEFAULT) { HostPort hp = destination.setPassive(); this.setActive(hp); } /* send them all down the pipe */ for(int i = 0; i < remoteSrcFile.length; i++) { Command estoCmd = new Command("STOR ", remoteDstFile[i]); destination.controlChannel.write(estoCmd); Command eretCmd = new Command("RETR", remoteSrcFile[i]); controlChannel.write(eretCmd); } for(int i = 0; i < remoteSrcFile.length; i++) { transferRunSingleThread(destination.controlChannel, mListener); if(doneListener != null) { MultipleTransferComplete mtc; mtc = new MultipleTransferComplete( remoteSrcFile[i], remoteDstFile[i], this, destination, i); doneListener.transferComplete(mtc); } } } /** * assure that the server supports extended transfer features; * throw exception if not **/ protected void checkGridFTPSupport() throws IOException, ServerException { FeatureList fl = getFeatureList(); if ( !(fl.contains(FeatureList.PARALLEL) && fl.contains(FeatureList.ESTO) && fl.contains(FeatureList.ERET) && fl.contains(FeatureList.SIZE)) ) { throw new ServerException(ServerException.UNSUPPORTED_FEATURE); } } /* end 3rd party transfer code */ /** * Sets data channel authentication mode (DCAU) * * @param type for 2-party transfer must be * DataChannelAuthentication.SELF or DataChannelAuthentication.NONE **/ public void setDataChannelAuthentication(DataChannelAuthentication type) throws IOException, ServerException { Command cmd = new Command("DCAU", type.toFtpCmdArgument()); try{ controlChannel.execute(cmd); } catch (UnexpectedReplyCodeException urce) { if(!type.toFtpCmdArgument().equals("N")) { throw ServerException.embedUnexpectedReplyCodeException(urce); } } catch(FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } this.gSession.dataChannelAuthentication = type; gLocalServer.setDataChannelAuthentication(type); } /** * Sets compatibility mode with old GSIFTP server. * Locally sets data channel authentication to NONE * but does not send the command * to the remote server (the server wouldn't understand it) **/ public void setLocalNoDataChannelAuthentication() { gLocalServer.setDataChannelAuthentication(DataChannelAuthentication.NONE); } /** * Returns data channel authentication mode (DCAU). * * @return data channel authentication mode **/ public DataChannelAuthentication getDataChannelAuthentication() { return gSession.dataChannelAuthentication; } /** * Sets data channel protection level (PROT). * * @param protection should be * {@link GridFTPSession#PROTECTION_CLEAR CLEAR}, * {@link GridFTPSession#PROTECTION_SAFE SAFE}, or * {@link GridFTPSession#PROTECTION_PRIVATE PRIVATE}, or * {@link GridFTPSession#PROTECTION_CONFIDENTIAL CONFIDENTIAL}. **/ public void setDataChannelProtection(int protection) throws IOException, ServerException { String protectionStr = null; switch(protection) { case GridFTPSession.PROTECTION_CLEAR: protectionStr = "C"; break; case GridFTPSession.PROTECTION_SAFE: protectionStr = "S"; break; case GridFTPSession.PROTECTION_CONFIDENTIAL: protectionStr = "E"; break; case GridFTPSession.PROTECTION_PRIVATE: protectionStr = "P"; break; default: throw new IllegalArgumentException("Bad protection: " + protection); } Command cmd = new Command("PROT", protectionStr); try { controlChannel.execute(cmd); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch(FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } this.gSession.dataChannelProtection = protection; gLocalServer.setDataChannelProtection(protection); } /** * Returns data channel protection level. * * @return data channel protection level: * {@link GridFTPSession#PROTECTION_CLEAR CLEAR}, * {@link GridFTPSession#PROTECTION_SAFE SAFE}, or * {@link GridFTPSession#PROTECTION_PRIVATE PRIVATE}, or * {@link GridFTPSession#PROTECTION_CONFIDENTIAL CONFIDENTIAL}. **/ public int getDataChannelProtection() { return gSession.dataChannelProtection; } /** * Sets authorization method for the control channel. * * @param authorization authorization method. */ public void setAuthorization(Authorization authorization) { ((GridFTPControlChannel)this.controlChannel).setAuthorization(authorization); } /** * Returns authorization method for the control channel. * * @return authorization method performed on the control channel. */ public Authorization getAuthorization() { return ((GridFTPControlChannel)this.controlChannel).getAuthorization(); } /** * Sets control channel protection level. * * @param protection should be * {@link GridFTPSession#PROTECTION_CLEAR CLEAR}, * {@link GridFTPSession#PROTECTION_SAFE SAFE}, or * {@link GridFTPSession#PROTECTION_PRIVATE PRIVATE}, or * {@link GridFTPSession#PROTECTION_CONFIDENTIAL CONFIDENTIAL}. **/ public void setControlChannelProtection(int protection) { ((GridFTPControlChannel)this.controlChannel).setProtection(protection); } /** * Returns control channel protection level. * * @return control channel protection level: * {@link GridFTPSession#PROTECTION_CLEAR CLEAR}, * {@link GridFTPSession#PROTECTION_SAFE SAFE}, or * {@link GridFTPSession#PROTECTION_PRIVATE PRIVATE}, or * {@link GridFTPSession#PROTECTION_CONFIDENTIAL CONFIDENTIAL}. **/ public int getControlChannelProtection() { return ((GridFTPControlChannel)this.controlChannel).getProtection(); } // basic compatibility API public void get(String remoteFileName, File localFile) throws IOException, ClientException, ServerException { if (gSession.transferMode == GridFTPSession.MODE_EBLOCK) { DataSink sink = new FileRandomIO(new RandomAccessFile(localFile, "rw")); get(remoteFileName, sink, null); } else { super.get(remoteFileName, localFile); } } public void put(File localFile, String remoteFileName, boolean append) throws IOException, ServerException, ClientException{ if (gSession.transferMode == GridFTPSession.MODE_EBLOCK) { DataSource source = new FileRandomIO(new RandomAccessFile(localFile, "r")); put(remoteFileName, source, null, append); } else { super.put(localFile, remoteFileName, append); } } /** * Sets the checksum values ahead of the transfer * @param algorithm the checksume algorithm * @param value the checksum value as hexadecimal number * @exception ServerException if an error occured. */ public void setChecksum(ChecksumAlgorithm algorithm, String value) throws IOException, ServerException { String arguments = algorithm.toFtpCmdArgument() + " " + value; Command cmd = new Command("SCKS", arguments); try { controlChannel.execute(cmd); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } /** * Computes and returns a checksum of a file. * transferred. * * @param algorithm the checksume algorithm * @param offset the offset * @param length the length * @param file file to compute checksum of * @return the computed checksum * @exception ServerException if an error occured. */ public String checksum(ChecksumAlgorithm algorithm, long offset, long length, String file) throws IOException, ServerException { String arguments = algorithm.toFtpCmdArgument() + " " + String.valueOf(offset) + " " + String.valueOf(length) + " " + file; Command cmd = new Command("CKSM", arguments); Reply reply = null; try { reply = controlChannel.execute(cmd); return reply.getMessage(); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } /** * Performs a recursive directory listing starting at the given path * (or, if path is null, at the current directory of the FTP server). * MlsxEntry instances for all of the files in the subtree will be * written through the passed MlsxEntryWriter. * * @param path path to begin recursive directory listing * @param writer sink for created MlsxEntry instances * @throws ServerException * @throws ClientException * @throws IOException */ public void mlsr(String path, MlsxEntryWriter writer) throws ServerException, ClientException, IOException { if (gSession.parallel > 1) { throw new ClientException( ClientException.BAD_MODE, "mlsr cannot be called with parallelism"); } Command cmd = (path == null) ? new Command("MLSR") : new Command("MLSR", path); MlsxParserDataSink sink = new MlsxParserDataSink(writer); performTransfer(cmd, sink); } private class MlsxParserDataSink implements DataSink { private MlsxEntryWriter writer; private byte[] buf = new byte[4096]; private int pos = 0; public MlsxParserDataSink(MlsxEntryWriter w) { writer = w; } public void write(Buffer buffer) throws IOException { byte[] data = buffer.getBuffer(); int len = buffer.getLength(); int i = 0; while (i < len && pos < buf.length) { if (data[i] == '\r' || data[i] == '\n') { if (pos > 0) { try { writer.write(new MlsxEntry(new String(buf, 0, pos))); } catch (FTPException ex) { throw new IOException(); } } pos = 0; while (i < len && data[i] < ' ') ++i; } else { buf[pos++] = data[i++]; } } } public void close() throws IOException { writer.close(); } } /** * Change the Unix group membership of a file. * * @param group the name or ID of the group * @param file the file whose group membership should be changed * @exception ServerException if an error occurred. */ public void changeGroup(String group, String file) throws IOException, ServerException { String arguments = group + " " + file; Command cmd = new Command("SITE CHGRP", arguments); try { controlChannel.execute(cmd); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } /** * Change the modification time of a file. * * @param year Modifcation year * @param month Modification month (1-12) * @param day Modification day (1-31) * @param hour Modification hour (0-23) * @param min Modification minutes (0-59) * @param sec Modification seconds (0-59) * @param file file whose modification time should be changed * @throws IOException * @throws ServerException if an error occurred. */ public void changeModificationTime(int year, int month, int day, int hour, int min, int sec, String file) throws IOException, ServerException { DecimalFormat df2 = new DecimalFormat("00"); DecimalFormat df4 = new DecimalFormat("0000"); String arguments = df4.format(year) + df2.format(month) + df2.format(day) + df2.format(hour) + df2.format(min) + df2.format(sec) + " " + file; Command cmd = new Command("SITE UTIME", arguments); try { controlChannel.execute(cmd); }catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } /** * Create a symbolic link on the FTP server. * * @param link_target the path to which the symbolic link should point * @param link_name the path of the symbolic link to create * @throws IOException * @throws ServerException if an error occurred. */ public void createSymbolicLink(String link_target, String link_name) throws IOException, ServerException { String arguments = link_target.replaceAll(" ", "%20") + " " + link_name; Command cmd = new Command("SITE SYMLINK", arguments); try { controlChannel.execute(cmd); }catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } } }
gbehrmann/JGlobus
gridftp/src/main/java/org/globus/ftp/GridFTPClient.java
Java
apache-2.0
41,342
package com.zhx.one.mvp.movie.view.iview; import com.zhx.one.base.MvpView; import com.zhx.one.bean.MovieListEntity; /** * Created by 张瀚漩 on 2016/12/11. */ public interface MovieView extends MvpView { void getDataSuccess(MovieListEntity movieListEntity); }
zhanghanxuan123/One
app/src/main/java/com/zhx/one/mvp/movie/view/iview/MovieView.java
Java
apache-2.0
271
/** * Copyright 2017 OSBI Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const webpack = require('webpack'); const HtmlPlugin = require('html-webpack-plugin'); const autoprefixer = require('autoprefixer'); const path = require('path'); module.exports = { output: { path: path.join(__dirname, '../build'), filename: '[name]-[hash].js' }, plugins: [ new HtmlPlugin({ title: 'Saiku Report Viewer', template: path.join(__dirname, '../src', 'html', 'template.html') }), new webpack.LoaderOptionsPlugin({ options: { eslint: { configFile: path.join(__dirname, './eslint.core.js'), useEslintrc: false }, postcss: () => { return [autoprefixer]; } } }) ], module: { rules: [ { enforce: 'pre', test: /\.js$/, exclude: /(node_modules|bower_components)/, include: /src/, use: 'eslint-loader' }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, include: /src/, use: 'babel-loader' }, { test: /\.styl$/, use: [ 'style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]', 'postcss-loader', 'stylus-loader' ] }, { test: /\.json$/, use: 'json-loader' }, { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: 'file-loader' }, { test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, use: [ { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } } ] }, { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: [ { loader: 'url-loader', options: { limit: '10000', mimetype: 'application/octet-stream' } } ] }, { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: [ { loader: 'svg-url-loader', options: { limit: '10000', mimetype: 'application/svg+xml' } } ] }, { test: /\.(png|jpg)$/, use: [ { loader: 'url-loader', options: { limit: 8192 } } ] }, { test: /\.ico(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader' } ] }, node: { dns: 'empty', net: 'empty', tls: 'empty' }, resolve: { alias: { src: path.join(__dirname, '../src'), components: path.join(__dirname, '../src', 'components') } } };
OSBI/saiku-report-viewer-ui
config/webpack.core.js
JavaScript
apache-2.0
3,356
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Wed Jul 17 09:40:00 MST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>ConcatenatingPrincipalDecoderConsumer (BOM: * : All 2.4.1.Final-SNAPSHOT API)</title> <meta name="date" content="2019-07-17"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ConcatenatingPrincipalDecoderConsumer (BOM: * : All 2.4.1.Final-SNAPSHOT API)"; } } catch(err) { } //--> var methods = {"i0":6,"i1":18}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"],16:["t5","Default Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/ConcatenatingPrincipalDecoderConsumer.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.4.1.Final-SNAPSHOT</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoder.html" title="class in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderSupplier.html" title="interface in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html" target="_top">Frames</a></li> <li><a href="ConcatenatingPrincipalDecoderConsumer.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.wildfly.swarm.config.elytron</div> <h2 title="Interface ConcatenatingPrincipalDecoderConsumer" class="title">Interface ConcatenatingPrincipalDecoderConsumer&lt;T extends <a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoder.html" title="class in org.wildfly.swarm.config.elytron">ConcatenatingPrincipalDecoder</a>&lt;T&gt;&gt;</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Functional Interface:</dt> <dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd> </dl> <hr> <br> <pre><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a> public interface <span class="typeNameLabel">ConcatenatingPrincipalDecoderConsumer&lt;T extends <a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoder.html" title="class in org.wildfly.swarm.config.elytron">ConcatenatingPrincipalDecoder</a>&lt;T&gt;&gt;</span></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html#accept-T-">accept</a></span>(<a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html" title="type parameter in ConcatenatingPrincipalDecoderConsumer">T</a>&nbsp;value)</code> <div class="block">Configure a pre-constructed instance of ConcatenatingPrincipalDecoder resource</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>default <a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html" title="interface in org.wildfly.swarm.config.elytron">ConcatenatingPrincipalDecoderConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html" title="type parameter in ConcatenatingPrincipalDecoderConsumer">T</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html#andThen-org.wildfly.swarm.config.elytron.ConcatenatingPrincipalDecoderConsumer-">andThen</a></span>(<a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html" title="interface in org.wildfly.swarm.config.elytron">ConcatenatingPrincipalDecoderConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html" title="type parameter in ConcatenatingPrincipalDecoderConsumer">T</a>&gt;&nbsp;after)</code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="accept-org.wildfly.swarm.config.elytron.ConcatenatingPrincipalDecoder-"> <!-- --> </a><a name="accept-T-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>accept</h4> <pre>void&nbsp;accept(<a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html" title="type parameter in ConcatenatingPrincipalDecoderConsumer">T</a>&nbsp;value)</pre> <div class="block">Configure a pre-constructed instance of ConcatenatingPrincipalDecoder resource</div> </li> </ul> <a name="andThen-org.wildfly.swarm.config.elytron.ConcatenatingPrincipalDecoderConsumer-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>andThen</h4> <pre>default&nbsp;<a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html" title="interface in org.wildfly.swarm.config.elytron">ConcatenatingPrincipalDecoderConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html" title="type parameter in ConcatenatingPrincipalDecoderConsumer">T</a>&gt;&nbsp;andThen(<a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html" title="interface in org.wildfly.swarm.config.elytron">ConcatenatingPrincipalDecoderConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html" title="type parameter in ConcatenatingPrincipalDecoderConsumer">T</a>&gt;&nbsp;after)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/ConcatenatingPrincipalDecoderConsumer.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.4.1.Final-SNAPSHOT</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoder.html" title="class in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderSupplier.html" title="interface in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html" target="_top">Frames</a></li> <li><a href="ConcatenatingPrincipalDecoderConsumer.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2.4.1.Final-SNAPSHOT/apidocs/org/wildfly/swarm/config/elytron/ConcatenatingPrincipalDecoderConsumer.html
HTML
apache-2.0
12,089
package net.bytebuddy.dynamic.loading; import net.bytebuddy.test.utility.IntegrationRule; import net.bytebuddy.test.utility.MockitoRule; import net.bytebuddy.test.utility.ObjectPropertyAssertion; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.rules.TestRule; import org.mockito.Mock; import java.net.URL; import java.util.Enumeration; import java.util.NoSuchElementException; import static net.bytebuddy.matcher.ElementMatchers.isBootstrapClassLoader; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class MultipleParentClassLoaderTest { private static final String FOO = "foo", BAR = "bar", QUX = "qux", BAZ = "baz", SCHEME = "http://"; @Rule public TestRule mockitoRule = new MockitoRule(this); @Rule public MethodRule integrationRule = new IntegrationRule(); @Mock private ClassLoader first, second; private URL fooUrl, barFirstUrl, barSecondUrl, quxUrl; @Before public void setUp() throws Exception { doReturn(Foo.class).when(first).loadClass(FOO); doReturn(BarFirst.class).when(first).loadClass(BAR); when(first.loadClass(QUX)).thenThrow(new ClassNotFoundException()); when(first.loadClass(BAZ)).thenThrow(new ClassNotFoundException()); doReturn(BarSecond.class).when(second).loadClass(BAR); doReturn(Qux.class).when(second).loadClass(QUX); when(second.loadClass(BAZ)).thenThrow(new ClassNotFoundException()); fooUrl = new URL(SCHEME + FOO); barFirstUrl = new URL(SCHEME + BAR); barSecondUrl = new URL(SCHEME + BAZ); quxUrl = new URL(SCHEME + QUX); when(first.getResource(FOO)).thenReturn(fooUrl); when(first.getResource(BAR)).thenReturn(barFirstUrl); when(second.getResource(BAR)).thenReturn(barSecondUrl); when(second.getResource(QUX)).thenReturn(quxUrl); when(first.getResources(FOO)).thenReturn(new SingleElementEnumeration(fooUrl)); when(first.getResources(BAR)).thenReturn(new SingleElementEnumeration(barFirstUrl)); when(second.getResources(BAR)).thenReturn(new SingleElementEnumeration(barSecondUrl)); when(second.getResources(QUX)).thenReturn(new SingleElementEnumeration(quxUrl)); } @Test public void testSingleParentReturnsOriginal() throws Exception { assertThat(new MultipleParentClassLoader.Builder() .append(getClass().getClassLoader(), getClass().getClassLoader()) .build(), is(getClass().getClassLoader())); } @Test public void testClassLoaderFilter() throws Exception { assertThat(new MultipleParentClassLoader.Builder() .append(getClass().getClassLoader(), null) .filter(isBootstrapClassLoader()) .build(), is(getClass().getClassLoader())); } @Test public void testMultipleParentClassLoading() throws Exception { ClassLoader classLoader = new MultipleParentClassLoader.Builder().append(first, second, null).build(); assertEquals(Foo.class, classLoader.loadClass(FOO)); assertEquals(BarFirst.class, classLoader.loadClass(BAR)); assertEquals(Qux.class, classLoader.loadClass(QUX)); verify(first).loadClass(FOO); verify(first).loadClass(BAR); verify(first).loadClass(QUX); verifyNoMoreInteractions(first); verify(second).loadClass(QUX); verifyNoMoreInteractions(second); } @Test(expected = ClassNotFoundException.class) public void testMultipleParentClassLoadingNotFound() throws Exception { new MultipleParentClassLoader.Builder().append(first, second, null).build().loadClass(BAZ); } @Test @IntegrationRule.Enforce public void testMultipleParentURL() throws Exception { ClassLoader classLoader = new MultipleParentClassLoader.Builder().append(first, second, null).build(); assertThat(classLoader.getResource(FOO), is(fooUrl)); assertThat(classLoader.getResource(BAR), is(barFirstUrl)); assertThat(classLoader.getResource(QUX), is(quxUrl)); verify(first).getResource(FOO); verify(first).getResource(BAR); verify(first).getResource(QUX); verifyNoMoreInteractions(first); verify(second).getResource(QUX); verifyNoMoreInteractions(second); } @Test public void testMultipleParentURLNotFound() throws Exception { assertThat(new MultipleParentClassLoader.Builder().append(first, second, null).build().getResource(BAZ), nullValue(URL.class)); } @Test @IntegrationRule.Enforce public void testMultipleParentEnumerationURL() throws Exception { ClassLoader classLoader = new MultipleParentClassLoader.Builder().append(first, second, null).build(); Enumeration<URL> foo = classLoader.getResources(FOO); assertThat(foo.hasMoreElements(), is(true)); assertThat(foo.nextElement(), is(fooUrl)); assertThat(foo.hasMoreElements(), is(false)); Enumeration<URL> bar = classLoader.getResources(BAR); assertThat(bar.hasMoreElements(), is(true)); assertThat(bar.nextElement(), is(barFirstUrl)); assertThat(bar.hasMoreElements(), is(true)); assertThat(bar.nextElement(), is(barSecondUrl)); assertThat(bar.hasMoreElements(), is(false)); Enumeration<URL> qux = classLoader.getResources(QUX); assertThat(qux.hasMoreElements(), is(true)); assertThat(qux.nextElement(), is(quxUrl)); assertThat(qux.hasMoreElements(), is(false)); } @Test(expected = NoSuchElementException.class) public void testMultipleParentEnumerationNotFound() throws Exception { ClassLoader classLoader = new MultipleParentClassLoader.Builder().append(first, second, null).build(); Enumeration<URL> enumeration = classLoader.getResources(BAZ); assertThat(enumeration.hasMoreElements(), is(false)); enumeration.nextElement(); } @Test public void testObjectProperties() throws Exception { ObjectPropertyAssertion.of(MultipleParentClassLoader.class).applyBasic(); ObjectPropertyAssertion.of(MultipleParentClassLoader.CompoundEnumeration.class).applyBasic(); ObjectPropertyAssertion.of(MultipleParentClassLoader.Builder.class).apply(); ObjectPropertyAssertion.of(MultipleParentClassLoader.Builder.ClassLoaderCreationAction.class).apply(); } public static class Foo { /* empty */ } public static class BarFirst { /* empty */ } public static class BarSecond { /* empty */ } public static class Qux { /* empty */ } private static class SingleElementEnumeration implements Enumeration<URL> { private URL element; public SingleElementEnumeration(URL element) { this.element = element; } @Override public boolean hasMoreElements() { return element != null; } @Override public URL nextElement() { if (!hasMoreElements()) { throw new AssertionError(); } try { return element; } finally { element = null; } } } }
vic/byte-buddy
byte-buddy-dep/src/test/java/net/bytebuddy/dynamic/loading/MultipleParentClassLoaderTest.java
Java
apache-2.0
7,491
.outer-div{} .main-div{ padding: 30px 130px 30px 130px; } .left-div{ background-color: black; display: inline-block; border-style:solid; padding: 20px; } .image{ height:240px; width: 255px; border-top-left-radius: 80px; margin-top: 10px; } .left-heading-BOX-div{ height: 50px; width: 255px; background-color:red; margin-top: 1px; } .left-internal-heading-div{ margin-left: 35px; padding: 10px; font-size: 20px; color: white; } .left-internal-BOX-div{ height: 120px; width: 255px; background-color: bisque; } .left-internal-point-div{ font-size: 17px; padding: 50px 40px 60px 20px; margin-left: 20px; } .right-div{ background-color:darkmagenta; display: inline-block; border-style:solid; padding: 20px; } .right-internal-heading-div{ font-size: 20PX; margin-top: 13.5px; color: RED; margin-left: 80px; } .right-internal-BOX-div{ height: 151.5px; width: 80%; background-color:bisque; margin-left: 80px; margin-top: 5PX; } .right-internal-point-div{ font-size: 17px; padding: 50px 40px 60px 20px; margin-left: 20px; }
mazharaheer/html-css-book-practice
cv web page/style.css
CSS
apache-2.0
1,083
/************************************************************************/ /* https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/ You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. For example, given: S: "barfoothefoobarman" L: ["foo", "bar"] You should return the indices: [0,9]. (order does not matter). */ /************************************************************************/ #include <iostream> #include <vector> #include <string> #include <map> using namespace std; class Solution { public: vector<int> findSubstring(string S, vector<string> &L) { int word_count = L.size(); int word_len = L[0].length(); int str_len = word_count * word_len; int tot_len = S.length(); vector<int> result; map<string, int> mp_word; map<string, int> mp_count; for (int i = 0; i < word_count; ++i) mp_word[L[i]]++; for (int i = 0; i <= tot_len - str_len; ++i) { int index = 0; mp_count.clear(); bool flag = true; for (int j = 0; j < word_count; ++j) { string sub = S.substr(i + index, word_len); if (mp_word.find(sub) == mp_word.end()) { flag = false; break; } mp_count[sub]++; if (mp_count[sub] > mp_word[sub]) { flag = false; break; } index += word_len; } if (flag) { result.push_back(i); } } return result; } }; int main() { string S = "barfoothefoobarman"; vector<string> L; L.push_back("foo"); L.push_back("bar"); //string S = "a"; //vector<string> L; //L.push_back("a"); ////L.push_back("a"); Solution solution; vector<int> result = solution.findSubstring(S, L); for (int i = 0; i < result.size(); ++i) { cout << result[i] << ' '; } system("pause"); return 0; }
printfchan/Leetcode
Leetcode/123. Substring with Concatenation of All Words/Substring with Concatenation of All Words.cpp
C++
apache-2.0
1,908
package partyup.com.myapplication.UI.Navigation; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import partyup.com.myapplication.R; /** * Created by poliveira on 24/10/2014. */ public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.ViewHolder> { private List<NavigationItem> mData; private NavigationDrawerCallbacks mNavigationDrawerCallbacks; private int mSelectedPosition; private int mTouchedPosition = -1; public NavigationDrawerAdapter(List<NavigationItem> data) { mData = data; } public NavigationDrawerCallbacks getNavigationDrawerCallbacks() { return mNavigationDrawerCallbacks; } public void setNavigationDrawerCallbacks(NavigationDrawerCallbacks navigationDrawerCallbacks) { mNavigationDrawerCallbacks = navigationDrawerCallbacks; } @Override public NavigationDrawerAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.drawer_row, viewGroup, false); return new ViewHolder(v); } @Override public void onBindViewHolder(NavigationDrawerAdapter.ViewHolder viewHolder, final int i) { viewHolder.textView.setText(mData.get(i).getText()); viewHolder.imgIcon.setImageDrawable(mData.get(i).getDrawable()); viewHolder.linearRow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mNavigationDrawerCallbacks != null) mNavigationDrawerCallbacks.onNavigationDrawerItemSelected(i); } } ); //TODO: selected menu position, change layout accordingly if(i==0){ viewHolder.lnIndicator.setVisibility(View.VISIBLE); } else { viewHolder.lnIndicator.setVisibility(View.INVISIBLE); } } private void touchPosition(int position) { int lastPosition = mTouchedPosition; mTouchedPosition = position; if (lastPosition >= 0) notifyItemChanged(lastPosition); if (position >= 0) notifyItemChanged(position); } public void selectPosition(int position) { int lastPosition = mSelectedPosition; mSelectedPosition = position; notifyItemChanged(lastPosition); notifyItemChanged(position); } @Override public int getItemCount() { return mData != null ? mData.size() : 0; } public static class ViewHolder extends RecyclerView.ViewHolder { public TextView textView; public ImageView imgIcon; public LinearLayout linearRow; public LinearLayout lnIndicator; public ViewHolder(View itemView) { super(itemView); imgIcon= (ImageView)itemView.findViewById(R.id.img_icon); textView = (TextView) itemView.findViewById(R.id.item_name); linearRow= (LinearLayout)itemView.findViewById(R.id.linear_drawer_row); lnIndicator=(LinearLayout)itemView.findViewById(R.id.ln_indicator); } } }
ingjuanocampo/Iparty-Android
app/src/main/java/partyup/com/myapplication/UI/Navigation/NavigationDrawerAdapter.java
Java
apache-2.0
3,586
// Copyright (C) 2014 Daniel Harrison package hfile import ( "bytes" "encoding/binary" "log" ) type Iterator struct { hfile *Reader dataBlockIndex int block []byte pos int buf []byte key []byte value []byte OrderedOps } func NewIterator(r *Reader) *Iterator { var buf []byte if r.compressionCodec > CompressionNone { buf = make([]byte, int(float64(r.totalUncompressedDataBytes/uint64(len(r.index)))*1.5)) } it := Iterator{r, 0, nil, 0, buf, nil, nil, OrderedOps{nil}} return &it } func (it *Iterator) Reset() { it.dataBlockIndex = 0 it.block = nil it.pos = 0 it.key = nil it.value = nil it.ResetState() } func (it *Iterator) Seek(requested []byte) (bool, error) { var err error if err = it.CheckIfKeyOutOfOrder(requested); err != nil { return false, err } if it.key != nil && !After(requested, it.key) { if it.hfile.Debug { log.Println("[Iterator.Seek] already at or past requested") } return true, nil } blk := it.hfile.FindBlock(it.dataBlockIndex, requested) if it.hfile.Debug { log.Printf("[Iterator.Seek] picked block %d, cur %d\n", blk, it.dataBlockIndex) if len(it.hfile.index) > blk+1 { log.Printf("[Iterator.Seek] following block starts at: %v\n", it.hfile.index[blk+1].firstKeyBytes) } else { log.Printf("[Iterator.Seek] (last block)\n") } } if blk != it.dataBlockIndex { if it.hfile.Debug { log.Println("[Iterator.Seek] new block!") } it.block = nil it.dataBlockIndex = blk } ok, err := it.Next() if err != nil { return false, err } if it.hfile.Debug { log.Printf("[Iterator.Seek] looking for %v (starting at %v)\n", requested, it.key) } for ok { after := After(requested, it.key) // the key we are looking for is in our future. if it.hfile.Debug { log.Printf("[Iterator.Seek] \t %v (%v)\n", it.key, after) } if err == nil && after { // we still need to go forward. ok, err = it.Next() } else { // either we got an error or we no longer need to go forward. if it.hfile.Debug { log.Printf("[Iterator.Seek] done %v (err %v)\n", it.key, err) } return ok, err } } if it.hfile.Debug { log.Println("[Iterator.Seek] walked off block") } return ok, err } func (it *Iterator) Next() (bool, error) { var err error it.key = nil it.value = nil if it.dataBlockIndex >= len(it.hfile.index) { return false, nil } if it.block == nil { it.block, err = it.hfile.GetBlockBuf(it.dataBlockIndex, it.buf) it.pos = 8 if err != nil { return false, err } } if len(it.block)-it.pos <= 0 { it.dataBlockIndex += 1 it.block = nil return it.Next() } keyLen := int(binary.BigEndian.Uint32(it.block[it.pos : it.pos+4])) valLen := int(binary.BigEndian.Uint32(it.block[it.pos+4 : it.pos+8])) it.key = it.block[it.pos+8 : it.pos+8+keyLen] it.value = it.block[it.pos+8+keyLen : it.pos+8+keyLen+valLen] it.pos += keyLen + valLen + 8 return true, nil } func (it *Iterator) Key() []byte { ret := make([]byte, len(it.key)) copy(ret, it.key) return ret } func (it *Iterator) Value() []byte { ret := make([]byte, len(it.value)) copy(ret, it.value) return ret } func (it *Iterator) AllForPrefixes(prefixes [][]byte) (map[string][][]byte, error) { res := make(map[string][][]byte) var err error for _, prefix := range prefixes { ok := false if ok, err = it.Seek(prefix); err != nil { return nil, err } acc := make([][]byte, 0, 1) for ok && bytes.HasPrefix(it.key, prefix) { prev := it.key acc = append(acc, it.Value()) if ok, err = it.Next(); err != nil { return nil, err } if !ok || !bytes.Equal(prev, it.key) { cp := make([]byte, len(prev)) copy(cp, prev) res[string(cp)] = acc acc = make([][]byte, 0, 1) } } } return res, nil } func (it *Iterator) Release() { it.Reset() select { case it.hfile.iteratorCache <- it: default: } }
theevocater/gohfile
iterator.go
GO
apache-2.0
3,870
/* * Copyright (C) 2000-2014 Marko Salmela. * * 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.fuusio.api.plugin; import java.lang.reflect.Field; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; public class PluginBus { private static PluginBus sInstance = null; private static PluginInjector sGlobalInjector = null; private final HashMap<Class<? extends PluginInterface>, HashMap<String, PluginInvocationHandler>> mInvocationHandlers; // OPTION private final HashMap<Class<? extends PluginInterface>, HashMap<String, PlugInvocationHandler>> mSyncedInvocationHandlers; private final List<Plugin> mPlugins; private PluginBus() { mInvocationHandlers = new HashMap<>(); // OPTION mSyncedInvocationHandlers = new HashMap<>(); mPlugins = new ArrayList<>(); } @SuppressWarnings("unused") public static void setGlobalInjector(final PluginInjector injector) { sGlobalInjector = injector; } @SuppressWarnings("unused") public <T extends Plugin> List<T> getPlugins(final Class<? extends PluginInterface> pluginInterface, final String plugName) { PluginInvocationHandler handler = null; final HashMap<String, PluginInvocationHandler> handlers = mInvocationHandlers.get(pluginInterface); if (handlers != null) { handler = handlers.get(plugName); } if (handler != null) { return handler.getPlugins(); } return new ArrayList<>(); } public static PluginBus getInstance() { if (sInstance == null) { sInstance = new PluginBus(); } return sInstance; } public static <T extends PluginInterface> T getPlug(final Class<T> pluginInterface) { return sInstance.doGetPlug(pluginInterface, Plugin.DEFAULT_PLUG_NAME); } public static <T extends PluginInterface> T getPlug(final Class<T> pluginInterface, final String plugName) { return sInstance.doGetPlug(pluginInterface, plugName); } @SuppressWarnings("unchecked") public <T extends PluginInterface> T doGetPlug(final Class<T> pluginInterface, final String plugName) { final ClassLoader classLoader = pluginInterface.getClassLoader(); HashMap<String, PluginInvocationHandler> handlers = mInvocationHandlers.get(pluginInterface); if (handlers == null) { handlers = new HashMap<>(); mInvocationHandlers.put(pluginInterface, handlers); } PluginInvocationHandler handler = handlers.get(plugName); Proxy proxy; if (handler == null) { handler = new PluginInvocationHandler(pluginInterface, this); handlers.put(plugName, handler); final Class<?>[] interfaceClasses = {pluginInterface}; proxy = (Proxy) Proxy.newProxyInstance(classLoader, interfaceClasses, handler); handler.setProxy(proxy); } else { proxy = handler.getProxy(); } return (T) proxy; } public static void plug(final Plugin plugin) { sInstance.doPlug(plugin, true); } public static void plug(final Plugin plugin, final boolean useAnnotations) { sInstance.doPlug(plugin, useAnnotations); } private void doPlug(final Plugin plugin, final boolean useAnnotations) { if (mPlugins.contains(plugin)) { return; } final Class<? extends Plugin> pluginClass = plugin.getClass(); final ClassLoader classLoader = pluginClass.getClassLoader(); final PluginInjector injector = (sGlobalInjector != null) ? sGlobalInjector : getInjector(plugin); if (injector != null) { injector.onPlug(plugin); } final List<Class<? extends PluginInterface>> pluginInterfaces = getPluginInterfaces(plugin); if (useAnnotations) { final List<PlugDescriptor> descriptors = getPlugDescriptors(plugin); for (final PlugDescriptor descriptor : descriptors) { final String plugName = descriptor.getName(); final Class<? extends PluginInterface> pluginInterface = descriptor.getPluginInterface(); HashMap<String, PluginInvocationHandler> handlers = mInvocationHandlers.get(pluginInterface); if (handlers == null) { handlers = new HashMap<>(); mInvocationHandlers.put(pluginInterface, handlers); } PluginInvocationHandler handler = handlers.get(plugName); Proxy proxy; if (handler == null) { handler = new PluginInvocationHandler(pluginInterface, this); handlers.put(plugName, handler); final Class<?>[] interfaceClasses = {pluginInterface}; proxy = (Proxy) Proxy.newProxyInstance(classLoader, interfaceClasses, handler); handler.setProxy(proxy); } else { proxy = handler.getProxy(); } final Field field = descriptor.getField(); try { field.setAccessible(true); field.set(plugin, proxy); } catch (final Exception e) { throw new RuntimeException("Failed to assign to plugin field: " + field.getName()); } } } for (final Class<? extends PluginInterface> pluginInterface : pluginInterfaces) { final String plugName = plugin.getPlugName(); final PlugDescriptor descriptor = new PlugDescriptor(null, plugName, pluginInterface); descriptor.setCreated(false); HashMap<String, PluginInvocationHandler> handlers = mInvocationHandlers.get(pluginInterface); if (handlers == null) { handlers = new HashMap<>(); mInvocationHandlers.put(pluginInterface, handlers); } PluginInvocationHandler handler = handlers.get(plugName); Proxy proxy; if (handler == null) { handler = new PluginInvocationHandler(pluginInterface, this); handlers.put(plugName, handler); final Class<?>[] interfaceClasses = {pluginInterface}; proxy = (Proxy) Proxy.newProxyInstance(classLoader, interfaceClasses, handler); handler.setProxy(proxy); } handler.plug(plugin); } mPlugins.add(plugin); plugin.onPlugged(this); } private PluginInjector getInjector(final Plugin plugin) { if (plugin instanceof InjectorProvider) { return ((InjectorProvider) plugin).getInjector(); } else { return null; } } @SuppressWarnings("unchecked") private List<PlugDescriptor> getPlugDescriptors(final Plugin plugin) { final Class<?> pluginClass = plugin.getClass(); final List<PlugDescriptor> fields = new ArrayList<>(); collectPlugFields(pluginClass, fields); return fields; } @SuppressWarnings("unchecked") private void collectPlugFields(final Class<?> plugClass, final List<PlugDescriptor> descriptors) { if (Plugin.class.isAssignableFrom(plugClass)) { final Field[] fields = plugClass.getDeclaredFields(); for (final Field field : fields) { final Plugin.Plug plug = field.getAnnotation(Plugin.Plug.class); if (plug != null) { final String plugName = plug.name(); final Class<? extends PluginInterface> fieldType = (Class<? extends PluginInterface>) field.getType(); final PlugDescriptor descriptor = new PlugDescriptor(field, plugName, fieldType); descriptor.setCreated(plug.create()); descriptors.add(descriptor); } } collectPlugFields(plugClass.getSuperclass(), descriptors); } } public static void unplug(final Plugin plugin) { sInstance.doUnplug(plugin); } @SuppressWarnings("static-access") private void doUnplug(final Plugin plugin) { if (!mPlugins.contains(plugin)) { return; } final PluginInjector injector = (sGlobalInjector != null) ? sGlobalInjector : getInjector(plugin); if (injector != null) { injector.onUnplug(plugin); } final List<Class<? extends PluginInterface>> pluginInterfaces = getPluginInterfaces(plugin); final List<PlugDescriptor> descriptors = getPlugDescriptors(plugin); final List<PluginInvocationHandler> removedHandlers = new ArrayList<>(); for (final Class<? extends PluginInterface> pluginInterface : pluginInterfaces) { final Collection<PluginInvocationHandler> handlers = mInvocationHandlers.get(pluginInterface).values(); for (final PluginInvocationHandler handler : handlers) { handler.unplug(plugin); if (handler.getPluginCount() == 0) { removedHandlers.add(handler); } } } for (final PlugDescriptor descriptor : descriptors) { Field field; try { field = descriptor.getField(); field.setAccessible(true); field.set(plugin, null); } catch (final Exception pException) { throw new RuntimeException("Failed to assign to plugin field."); } } for (final PluginInvocationHandler handler : removedHandlers) { removeInvocationHandler(handler); } mPlugins.remove(plugin); plugin.onUnplugged(this); } private List<Class<? extends PluginInterface>> getPluginInterfaces(final Plugin plugin) { final Class<?> pluginClass = plugin.getClass(); final List<Class<? extends PluginInterface>> pluginInterfaces = new ArrayList<>(); collectPluginInterfaces(pluginClass, pluginInterfaces); return pluginInterfaces; } @SuppressWarnings("unchecked") private void collectPluginInterfaces(final Class<?> pluginClass, List<Class<? extends PluginInterface>> pluginInterfaces) { final Class<?>[] implementedInterfaces = pluginClass.getInterfaces(); for (final Class<?> implementedInterface : implementedInterfaces) { if (PluginInterface.class.isAssignableFrom(implementedInterface)) { if (!pluginInterfaces.contains(implementedInterface)) { pluginInterfaces.add((Class<? extends PluginInterface>) implementedInterface); } } } final Class<?> superClass = pluginClass.getSuperclass(); if (!Object.class.equals(superClass)) { collectPluginInterfaces(superClass, pluginInterfaces); } } public void removeInvocationHandler(final PluginInvocationHandler removedHandler) { final HashMap<String, PluginInvocationHandler> handlers = mInvocationHandlers.get(removedHandler.getPluginInterface()); for (final String key : handlers.keySet()) { final PluginInvocationHandler handler = handlers.get(key); if (handler == removedHandler) { handlers.remove(key); break; } } } }
Fuusio/fuusio-app
fuusio.api/src/main/java/org/fuusio/api/plugin/PluginBus.java
Java
apache-2.0
12,083
/*********************************************************************** * Copyright (c) 2013-2018 Commonwealth Computer Research, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at * http://www.opensource.org/licenses/apache2.0.php. ***********************************************************************/ package org.locationtech.geomesa.fs.storage.orc import java.nio.file.Files import java.util.UUID import com.typesafe.scalalogging.LazyLogging import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.Path import org.geotools.data.Query import org.geotools.factory.Hints import org.geotools.filter.text.ecql.ECQL import org.junit.runner.RunWith import org.locationtech.geomesa.features.ScalaSimpleFeature import org.locationtech.geomesa.fs.storage.api.{FileSystemStorage, FileSystemWriter} import org.locationtech.geomesa.fs.storage.common.{FileSystemStorageFactory, PartitionScheme} import org.locationtech.geomesa.utils.collection.SelfClosingIterator import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes import org.opengis.feature.simple.{SimpleFeature, SimpleFeatureType} import org.specs2.matcher.MatchResult import org.specs2.mutable.Specification import org.specs2.runner.JUnitRunner @RunWith(classOf[JUnitRunner]) class OrcFileSystemStorageTest extends Specification with LazyLogging { val config = new Configuration() "OrcFileSystemWriter" should { "read and write features" in { val sft = SimpleFeatureTypes.createType("orc-test", "name:String,age:Int,dtg:Date,*geom:Point:srid=4326") val features = (0 until 10).map { i => val sf = new ScalaSimpleFeature(sft, i.toString) sf.getUserData.put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE) sf.setAttribute(0, s"name$i") sf.setAttribute(1, s"$i") sf.setAttribute(2, f"2014-01-${i + 1}%02dT00:00:01.000Z") sf.setAttribute(3, s"POINT(4$i 5$i)") sf } withTestDir { dir => import scala.collection.JavaConversions._ val params = Map(FileSystemStorageFactory.EncodingParam.key -> OrcFileSystemStorage.OrcEncoding, FileSystemStorageFactory.PathParam.key -> dir.toString) val storage: FileSystemStorage = new OrcFileSystemStorageFactory().build(params) storage must not(beNull) // 8 bits resolution creates 3 partitions with our test data storage.createNewFeatureType(sft, PartitionScheme(sft, "z2", Map("z2-resolution" -> "8"))) val writers = scala.collection.mutable.Map.empty[String, FileSystemWriter] features.foreach { f => val partition = storage.getPartitionScheme(sft.getTypeName).getPartitionName(f) val writer = writers.getOrElseUpdate(partition, storage.getWriter(sft.getTypeName, partition)) writer.write(f) } writers.foreach(_._2.close()) logger.debug(s"wrote to ${writers.size} partitions for ${features.length} features") val partitions = storage.getPartitions(sft.getTypeName) partitions must haveLength(writers.size) val transformsList = Seq(null, Array("geom"), Array("geom", "dtg"), Array("geom", "name")) val doTest = testQuery(storage, sft, partitions) _ foreach(transformsList) { transforms => doTest("INCLUDE", transforms, features) doTest("IN('0', '2')", transforms, Seq(features(0), features(2))) doTest("bbox(geom,38,48,52,62) and dtg DURING 2014-01-01T00:00:00.000Z/2014-01-08T12:00:00.000Z", transforms, features.dropRight(2)) doTest("bbox(geom,42,48,52,62) and dtg DURING 2013-12-15T00:00:00.000Z/2014-01-15T00:00:00.000Z", transforms, features.drop(2)) doTest("bbox(geom,42,48,52,62)", transforms, features.drop(2)) doTest("dtg DURING 2014-01-01T00:00:00.000Z/2014-01-08T12:00:00.000Z", transforms, features.dropRight(2)) doTest("name = 'name5' and bbox(geom,38,48,52,62) and dtg DURING 2014-01-01T00:00:00.000Z/2014-01-08T12:00:00.000Z", transforms, features.slice(5, 6)) doTest("name < 'name5'", transforms, features.take(5)) doTest("name = 'name5'", transforms, features.slice(5, 6)) } } } "read and write complex features" in { val sft = SimpleFeatureTypes.createType("orc-test-complex", "name:String,age:Int,time:Long,height:Float,weight:Double,bool:Boolean," + "uuid:UUID,bytes:Bytes,list:List[Int],map:Map[String,Long]," + "line:LineString,mpt:MultiPoint,poly:Polygon,mline:MultiLineString,mpoly:MultiPolygon," + "dtg:Date,*geom:Point:srid=4326") val features = (0 until 10).map { i => val sf = new ScalaSimpleFeature(sft, i.toString) sf.getUserData.put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE) sf.setAttribute("name", s"name$i") sf.setAttribute("age", s"$i") sf.setAttribute("time", s"$i") sf.setAttribute("height", s"$i") sf.setAttribute("weight", s"$i") sf.setAttribute("bool", Boolean.box(i < 5)) sf.setAttribute("uuid", UUID.fromString(s"00000000-0000-0000-0000-00000000000$i")) sf.setAttribute("bytes", Array.tabulate[Byte](i)(i => i.toByte)) sf.setAttribute("list", Seq.tabulate[Integer](i)(i => Int.box(i))) sf.setAttribute("map", (0 until i).map(i => i.toString -> Long.box(i)).toMap) sf.setAttribute("line", s"LINESTRING(0 $i, 2 $i, 8 ${10 - i})") sf.setAttribute("mpt", s"MULTIPOINT(0 $i, 2 3)") sf.setAttribute("poly", if (i == 5) { // multipolygon example from wikipedia "POLYGON ((35 10, 45 45, 15 40, 10 20, 35 10),(20 30, 35 35, 30 20, 20 30))" } else { s"POLYGON((40 3$i, 42 3$i, 42 2$i, 40 2$i, 40 3$i))" } ) sf.setAttribute("mline", s"MULTILINESTRING((0 2, 2 $i, 8 6),(0 $i, 2 $i, 8 ${10 - i}))") sf.setAttribute("mpoly", s"MULTIPOLYGON(((-1 0, 0 $i, 1 0, 0 -1, -1 0)), ((-2 6, 1 6, 1 3, -2 3, -2 6)), ((-1 5, 2 5, 2 2, -1 2, -1 5)))") sf.setAttribute("dtg", f"2014-01-${i + 1}%02dT00:00:01.000Z") sf.setAttribute("geom", s"POINT(4$i 5$i)") sf } withTestDir { dir => import scala.collection.JavaConversions._ val params = Map(FileSystemStorageFactory.EncodingParam.key -> OrcFileSystemStorage.OrcEncoding, FileSystemStorageFactory.PathParam.key -> dir.toString) val storage: FileSystemStorage = new OrcFileSystemStorageFactory().build(params) storage must not(beNull) // 8 bits resolution creates 3 partitions with our test data storage.createNewFeatureType(sft, PartitionScheme(sft, "z2", Map("z2-resolution" -> "8"))) val writers = scala.collection.mutable.Map.empty[String, FileSystemWriter] features.foreach { f => val partition = storage.getPartitionScheme(sft.getTypeName).getPartitionName(f) val writer = writers.getOrElseUpdate(partition, storage.getWriter(sft.getTypeName, partition)) writer.write(f) } writers.foreach(_._2.close()) logger.debug(s"wrote to ${writers.size} partitions for ${features.length} features") val partitions = storage.getPartitions(sft.getTypeName) partitions must haveLength(writers.size) val transformsList = Seq(null, Array("geom"), Array("geom", "dtg"), Array("geom", "name")) val doTest = testQuery(storage, sft, partitions) _ foreach(transformsList) { transforms => doTest("INCLUDE", transforms, features) doTest("IN('0', '2')", transforms, Seq(features(0), features(2))) doTest("bbox(geom,38,48,52,62) and dtg DURING 2014-01-01T00:00:00.000Z/2014-01-08T12:00:00.000Z", transforms, features.dropRight(2)) doTest("bbox(geom,42,48,52,62) and dtg DURING 2013-12-15T00:00:00.000Z/2014-01-15T00:00:00.000Z", transforms, features.drop(2)) doTest("bbox(geom,42,48,52,62)", transforms, features.drop(2)) doTest("dtg DURING 2014-01-01T00:00:00.000Z/2014-01-08T12:00:00.000Z", transforms, features.dropRight(2)) doTest("name = 'name5' and bbox(geom,38,48,52,62) and dtg DURING 2014-01-01T00:00:00.000Z/2014-01-08T12:00:00.000Z", transforms, features.slice(5, 6)) doTest("name < 'name5'", transforms, features.take(5)) doTest("name = 'name5'", transforms, features.slice(5, 6)) } } } } def withTestDir[R](code: (Path) => R): R = { val file = new Path(Files.createTempDirectory("gm-orc-test").toUri) try { code(file) } finally { file.getFileSystem(new Configuration).delete(file, true) } } def testQuery(storage: FileSystemStorage, sft: SimpleFeatureType, partitions: Seq[String]) (filter: String, transforms: Array[String], results: Seq[SimpleFeature]): MatchResult[Any] = { import scala.collection.JavaConversions._ val query = new Query(sft.getTypeName, ECQL.toFilter(filter), transforms) val features = { val iter = SelfClosingIterator(storage.getReader(sft.getTypeName, partitions, query)) // note: need to copy features in iterator as same object is re-used iter.map(ScalaSimpleFeature.copy).toList } val attributes = Option(transforms).getOrElse(sft.getAttributeDescriptors.map(_.getLocalName).toArray) features.map(_.getID) must containTheSameElementsAs(results.map(_.getID)) forall(features) { feature => feature.getAttributes must haveLength(attributes.length) forall(attributes.zipWithIndex) { case (attribute, i) => feature.getAttribute(attribute) mustEqual feature.getAttribute(i) feature.getAttribute(attribute) mustEqual results.find(_.getID == feature.getID).get.getAttribute(attribute) } } } }
boundlessgeo/geomesa
geomesa-fs/geomesa-fs-storage/geomesa-fs-storage-orc/src/test/scala/org/locationtech/geomesa/fs/storage/orc/OrcFileSystemStorageTest.scala
Scala
apache-2.0
10,017
package com.github.ksoichiro.todo.java.springboot.domain; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.security.core.GrantedAuthority; import javax.persistence.*; import java.util.ArrayList; import java.util.Collection; import java.util.Set; @Entity @Data @EqualsAndHashCode(callSuper = false) public class User extends org.springframework.security.core.userdetails.User { @Id @GeneratedValue private Long id; @Column(nullable = false, unique = true) private String username; @Column(nullable = false) private String password; private boolean enabled; @Column(nullable = false) private Long createdAt; @Column(nullable = false) private Long updatedAt; @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinTable(name = "role_user", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<Role> roles; public User() { super("INVALID", "INVALID", false, false, false, false, new ArrayList<GrantedAuthority>()); } public User(String username, String password, boolean enabled, Collection<? extends GrantedAuthority> authorities) { super(username, password, enabled, true, true, true, authorities); setUsername(username); setPassword(password); setEnabled(enabled); } }
ksoichiro/todo
java-spring-boot/todo/app-site/src/main/java/com/github/ksoichiro/todo/java/springboot/domain/User.java
Java
apache-2.0
1,408
/* * Copyright 2000-2017 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.ui.tree; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.concurrency.Promise; import org.junit.Assert; import org.junit.Test; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.util.List; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import static com.intellij.ui.tree.TreePathUtil.convertArrayToTreePath; import static com.intellij.ui.tree.TreeTestUtil.node; import static com.intellij.util.containers.ContainerUtil.set; /** * @author Sergey.Malenkov */ public final class TreeUtilVisitTest { @Test public void testAcceptDepth1() { testFind(() -> new DepthVisitor(1), 1); } @Test public void testAcceptDepth2() { testFind(() -> new DepthVisitor(2), 4); } @Test public void testAcceptDepth3() { testFind(() -> new DepthVisitor(3), 21); } @Test public void testAcceptAll() { testFind(() -> new Visitor(), 21); } @Test public void testFindRoot() { testFind(() -> new StringFinder("Root"), 1, "Root"); } @Test public void testFindWrongRoot() { testFind(() -> new StringFinder("ROOT"), 1); } @Test public void testFindColor() { testFind(() -> new StringFinder("RootColor"), 2, "RootColor"); } @Test public void testFindWrongColor() { testFind(() -> new StringFinder("RootCOLOR"), 4); } @Test public void testFindDigit() { testFind(() -> new StringFinder("RootDigit"), 3, "RootDigit"); } @Test public void testFindWrongDigit() { testFind(() -> new StringFinder("RootDIGIT"), 4); } @Test public void testFindGreek() { testFind(() -> new StringFinder("RootGreek"), 4, "RootGreek"); } @Test public void testFindWrongGreek() { testFind(() -> new StringFinder("RootGREEK"), 4); } @Test public void testFindGreen() { testFind(() -> new StringFinder("RootColorGreen"), 4, "RootColorGreen"); } @Test public void testFindWrongGreen() { testFind(() -> new StringFinder("RootColorGREEN"), 7); } @Test public void testFindFive() { testFind(() -> new StringFinder("RootDigitFive"), 8, "RootDigitFive"); } @Test public void testFindWrongFive() { testFind(() -> new StringFinder("RootDigitFIVE"), 13); } @Test public void testFindGamma() { testFind(() -> new StringFinder("RootGreekGamma"), 7, "RootGreekGamma"); } @Test public void testFindWrongGamma() { testFind(() -> new StringFinder("RootGreekGAMMA"), 9); } private static void testFind(@NotNull Supplier<Visitor> supplier, long count) { testFind(supplier, count, null); } private static void testFind(@NotNull Supplier<Visitor> supplier, long count, String value) { TreeTest.test(TreeUtilVisitTest::root, test -> test.assertTree("+Root\n", () -> { @NotNull Visitor visitor = supplier.get(); TreeUtil.visit(test.getTree(), visitor, path -> test.invokeSafely(() -> { Assert.assertEquals(count, visitor.counter.get()); Assert.assertEquals(value, value(path)); test.done(); })); })); } @Test public void testShowRoot() { testShow(() -> new StringFinder("Root"), "+[Root]\n"); } @Test public void testShowColor() { testShow(() -> new StringFinder("RootColor"), "-Root\n" + " +[RootColor]\n" + " +RootDigit\n" + " +RootGreek\n"); } @Test public void testShowDigit() { testShow(() -> new StringFinder("RootDigit"), "-Root\n" + " +RootColor\n" + " +[RootDigit]\n" + " +RootGreek\n"); } @Test public void testShowGreek() { testShow(() -> new StringFinder("RootGreek"), "-Root\n" + " +RootColor\n" + " +RootDigit\n" + " +[RootGreek]\n"); } @Test public void testShowGreen() { testShow(() -> new StringFinder("RootColorGreen"), "-Root\n" + " -RootColor\n" + " RootColorRed\n" + " [RootColorGreen]\n" + " RootColorBlue\n" + " +RootDigit\n" + " +RootGreek\n"); } @Test public void testShowFive() { testShow(() -> new StringFinder("RootDigitFive"), "-Root\n" + " +RootColor\n" + " -RootDigit\n" + " RootDigitOne\n" + " RootDigitTwo\n" + " RootDigitThree\n" + " RootDigitFour\n" + " [RootDigitFive]\n" + " RootDigitSix\n" + " RootDigitSeven\n" + " RootDigitEight\n" + " RootDigitNine\n" + " +RootGreek\n"); } @Test public void testShowGamma() { testShow(() -> new StringFinder("RootGreekGamma"), "-Root\n" + " +RootColor\n" + " +RootDigit\n" + " -RootGreek\n" + " RootGreekAlpha\n" + " RootGreekBeta\n" + " [RootGreekGamma]\n" + " RootGreekDelta\n" + " RootGreekEpsilon\n"); } private static void testShow(@NotNull Supplier<Visitor> supplier, @NotNull String expected) { TreeTest.test(TreeUtilVisitTest::root, test -> test.assertTree("+Root\n", () -> { @NotNull Visitor visitor = supplier.get(); TreeUtil.visit(test.getTree(), visitor, path -> { test.getTree().makeVisible(path); test.addSelection(path, () -> test.assertTree(expected, true, test::done)); }); })); } @Test public void testExpandOne() { TreeTest.test(TreeUtilVisitTest::root, test -> test.assertTree("+Root\n", () -> TreeUtil.expand(test.getTree(), 1, () -> test.assertTree("-Root\n" + " +RootColor\n" + " +RootDigit\n" + " +RootGreek\n", test::done)))); } @Test public void testExpandTwo() { TreeTest.test(TreeUtilVisitTest::rootDeep, test -> test.assertTree("+Root\n", () -> TreeUtil.expand(test.getTree(), 2, () -> test.assertTree("-Root\n" + " -1\n" + " +11\n" + " +12\n" + " +13\n" + " -2\n" + " +21\n" + " +22\n" + " +23\n" + " -3\n" + " +31\n" + " +32\n" + " +33\n", test::done)))); } @Test public void testExpandAll() { TreeTest.test(TreeUtilVisitTest::root, test -> test.assertTree("+Root\n", () -> TreeUtil.expandAll(test.getTree(), () -> test.assertTree("-Root\n" + " -RootColor\n" + " RootColorRed\n" + " RootColorGreen\n" + " RootColorBlue\n" + " -RootDigit\n" + " RootDigitOne\n" + " RootDigitTwo\n" + " RootDigitThree\n" + " RootDigitFour\n" + " RootDigitFive\n" + " RootDigitSix\n" + " RootDigitSeven\n" + " RootDigitEight\n" + " RootDigitNine\n" + " -RootGreek\n" + " RootGreekAlpha\n" + " RootGreekBeta\n" + " RootGreekGamma\n" + " RootGreekDelta\n" + " RootGreekEpsilon\n", test::done)) )); } @Test public void testMakeVisible1() { testMakeVisible("-Root\n" + " +[1]\n" + " +2\n" + " +3\n", "1"); } @Test public void testMakeVisible11() { testMakeVisible("-Root\n" + " -1\n" + " +[11]\n" + " +12\n" + " +13\n" + " +2\n" + " +3\n", "1", "11"); } @Test public void testMakeVisible111() { testMakeVisible("-Root\n" + " -1\n" + " -11\n" + " +[111]\n" + " +112\n" + " +113\n" + " +12\n" + " +13\n" + " +2\n" + " +3\n", "1", "11", "111"); } @Test public void testMakeVisible1111() { testMakeVisible("-Root\n" + " -1\n" + " -11\n" + " -111\n" + " [1111]\n" + " 1112\n" + " 1113\n" + " +112\n" + " +113\n" + " +12\n" + " +13\n" + " +2\n" + " +3\n", "1", "11", "111", "1111"); } @Test public void testMakeVisible2() { testMakeVisible("-Root\n" + " +1\n" + " +[2]\n" + " +3\n", "2"); } @Test public void testMakeVisible22() { testMakeVisible("-Root\n" + " +1\n" + " -2\n" + " +21\n" + " +[22]\n" + " +23\n" + " +3\n", "2", "22"); } @Test public void testMakeVisible222() { testMakeVisible("-Root\n" + " +1\n" + " -2\n" + " +21\n" + " -22\n" + " +221\n" + " +[222]\n" + " +223\n" + " +23\n" + " +3\n", "2", "22", "222"); } @Test public void testMakeVisible2222() { testMakeVisible("-Root\n" + " +1\n" + " -2\n" + " +21\n" + " -22\n" + " +221\n" + " -222\n" + " 2221\n" + " [2222]\n" + " 2223\n" + " +223\n" + " +23\n" + " +3\n", "2", "22", "222", "2222"); } @Test public void testMakeVisible3() { testMakeVisible("-Root\n" + " +1\n" + " +2\n" + " +[3]\n", "3"); } @Test public void testMakeVisible33() { testMakeVisible("-Root\n" + " +1\n" + " +2\n" + " -3\n" + " +31\n" + " +32\n" + " +[33]\n", "3", "33"); } @Test public void testMakeVisible333() { testMakeVisible("-Root\n" + " +1\n" + " +2\n" + " -3\n" + " +31\n" + " +32\n" + " -33\n" + " +331\n" + " +332\n" + " +[333]\n", "3", "33", "333"); } @Test public void testMakeVisible3333() { testMakeVisible("-Root\n" + " +1\n" + " +2\n" + " -3\n" + " +31\n" + " +32\n" + " -33\n" + " +331\n" + " +332\n" + " -333\n" + " 3331\n" + " 3332\n" + " [3333]\n", "3", "33", "333", "3333"); } private static void testMakeVisible(String expected, String... array) { TreeTest.test(TreeUtilVisitTest::rootDeep, test -> TreeUtil.makeVisible(test.getTree(), convertArrayToVisitor(array), path -> test.addSelection(path, () -> test.assertTree(expected, true, test::done)))); } @Test public void testSelect11() { testSelect(convertArrayToVisitor("1", "11"), "-Root\n" + " -1\n" + " +[11]\n" + " +12\n" + " +13\n" + " +2\n" + " +3\n"); } @Test public void testSelect222() { testSelect(convertArrayToVisitor("2", "22", "222"), "-Root\n" + " +1\n" + " -2\n" + " +21\n" + " -22\n" + " +221\n" + " +[222]\n" + " +223\n" + " +23\n" + " +3\n"); } @Test public void testSelect3333() { testSelect(convertArrayToVisitor("3", "33", "333", "3333"), "-Root\n" + " +1\n" + " +2\n" + " -3\n" + " +31\n" + " +32\n" + " -33\n" + " +331\n" + " +332\n" + " -333\n" + " 3331\n" + " 3332\n" + " [3333]\n"); } private static void testSelect(TreeVisitor visitor, String expected) { TreeTest.test(TreeUtilVisitTest::rootDeep, test -> TreeUtil.select(test.getTree(), visitor, path -> test.assertTree(expected, true, test::done))); } @Test public void testMultiSelect3333and222and11andRoot() { TreeVisitor[] array = { convertArrayToVisitor("3", "33", "333", "3333"), convertArrayToVisitor("2", "22", "222"), convertArrayToVisitor("1", "11"), path -> TreeVisitor.Action.INTERRUPT, }; testMultiSelect(array, array.length, "-[Root]\n" + " -1\n" + " +[11]\n" + " +12\n" + " +13\n" + " -2\n" + " +21\n" + " -22\n" + " +221\n" + " +[222]\n" + " +223\n" + " +23\n" + " -3\n" + " +31\n" + " +32\n" + " -33\n" + " +331\n" + " +332\n" + " -333\n" + " 3331\n" + " 3332\n" + " [3333]\n"); } @Test public void testMultiSelectNothingExceptRoot() { TreeVisitor[] array = { convertArrayToVisitor("3", "33", "333", "[3333]"), convertArrayToVisitor("2", "22", "[222]"), convertArrayToVisitor("1", "[11]"), path -> TreeVisitor.Action.INTERRUPT, null, }; testMultiSelect(array, 1, "-[Root]\n" + " -1\n" + " +11\n" + " +12\n" + " +13\n" + " -2\n" + " +21\n" + " -22\n" + " +221\n" + " +222\n" + " +223\n" + " +23\n" + " -3\n" + " +31\n" + " +32\n" + " -33\n" + " +331\n" + " +332\n" + " -333\n" + " 3331\n" + " 3332\n" + " 3333\n"); } @Test public void testMultiSelectNothing() { TreeVisitor[] array = {null, null, null}; testMultiSelect(array, 0, "+Root\n"); } private static void testMultiSelect(@NotNull TreeVisitor[] array, int count, @NotNull String expected) { testMultiSelect(array, count, expected, TreeTest::done); } private static void testMultiSelect(@NotNull TreeVisitor[] array, int count, @NotNull String expected, @NotNull Consumer<TreeTest> then) { TreeTest.test(TreeUtilVisitTest::rootDeep, test -> TreeUtil.promiseSelect(test.getTree(), Stream.of(array)).onProcessed(paths -> { test.invokeSafely(() -> { if (count == 0) { Assert.assertNull(paths); } else { Assert.assertNotNull(paths); Assert.assertEquals(count, paths.size()); } test.assertTree(expected, true, () -> then.accept(test)); }); })); } @Test public void testCollectExpandedPaths() { testCollectExpandedPaths(set("Root", "1", "2", "22", "3", "33", "333"), test -> TreeUtil.collectExpandedPaths(test.getTree())); } @Test public void testCollectExpandedPathsWithInvisibleRoot() { testCollectExpandedPaths(set("1", "2", "22", "3", "33", "333"), test -> { test.getTree().setRootVisible(false); return TreeUtil.collectExpandedPaths(test.getTree()); }); } @Test public void testCollectExpandedPathsWithInvisibleRootUnder33() { testCollectExpandedPaths(set("33", "333"), test -> { test.getTree().setRootVisible(false); TreePath root = test.getTree().getPathForRow(14); // 33 return TreeUtil.collectExpandedPaths(test.getTree(), root); }); } @Test public void testCollectExpandedPathsWithInvisibleRootUnder333() { testCollectExpandedPaths(set("333"), test -> { test.getTree().setRootVisible(false); TreePath root = test.getTree().getPathForRow(17); // 333 return TreeUtil.collectExpandedPaths(test.getTree(), root); }); } private static void testCollectExpandedPaths(@NotNull Set<String> expected, @NotNull Function<TreeTest, List<TreePath>> getter) { testCollectSelection(test -> { List<TreePath> paths = getter.apply(test); Assert.assertEquals(expected.size(), paths.size()); paths.forEach(path -> Assert.assertTrue(expected.contains(TreeUtil.getLastUserObject(String.class, path)))); test.done(); }); } @Test public void testCollectExpandedUserObjects() { testCollectExpandedUserObjects(set("Root", "1", "2", "22", "3", "33", "333"), test -> TreeUtil.collectExpandedUserObjects(test.getTree())); } @Test public void testCollectExpandedUserObjectsWithCollapsedPath() { testCollectExpandedUserObjects(set("Root", "1", "2", "22", "3"), test -> { test.getTree().collapseRow(15); // 33 return TreeUtil.collectExpandedUserObjects(test.getTree()); }); } @Test public void testCollectExpandedUserObjectsWithCollapsedPath33Under33() { testCollectExpandedUserObjects(set(), test -> { test.getTree().collapseRow(15); // 33 TreePath root = test.getTree().getPathForRow(15); // 33 return TreeUtil.collectExpandedUserObjects(test.getTree(), root); }); } @Test public void testCollectExpandedUserObjectsWithCollapsedPath333Under33() { testCollectExpandedUserObjects(set("33"), test -> { test.getTree().collapseRow(18); // 333 TreePath root = test.getTree().getPathForRow(15); // 33 return TreeUtil.collectExpandedUserObjects(test.getTree(), root); }); } private static void testCollectExpandedUserObjects(@NotNull Set<String> expected, @NotNull Function<TreeTest, List<Object>> getter) { testCollectSelection(test -> { List<Object> objects = getter.apply(test); Assert.assertEquals(expected.size(), objects.size()); objects.forEach(object -> Assert.assertTrue(expected.contains((String)object))); test.done(); }); } @Test public void testCollectSelectedPaths() { testCollectSelectedPaths(set("11", "222", "33", "3331", "3332", "3333", "Root"), test -> TreeUtil.collectSelectedPaths(test.getTree())); } @Test public void testCollectSelectedPathsWithInvisibleRoot() { testCollectSelectedPaths(set("11", "222", "33", "3331", "3332", "3333"), test -> { test.getTree().setRootVisible(false); return TreeUtil.collectSelectedPaths(test.getTree()); }); } @Test public void testCollectSelectedPathsWithInvisibleRootUnder33() { testCollectSelectedPaths(set("33", "3331", "3332", "3333"), test -> { test.getTree().setRootVisible(false); TreePath root = test.getTree().getPathForRow(14); // 33 return TreeUtil.collectSelectedPaths(test.getTree(), root); }); } @Test public void testCollectSelectedPathsWithInvisibleRootUnder333() { testCollectSelectedPaths(set("3331", "3332", "3333"), test -> { test.getTree().setRootVisible(false); TreePath root = test.getTree().getPathForRow(17); // 333 return TreeUtil.collectSelectedPaths(test.getTree(), root); }); } private static void testCollectSelectedPaths(@NotNull Set<String> expected, @NotNull Function<TreeTest, List<TreePath>> getter) { testCollectSelection(test -> { List<TreePath> paths = getter.apply(test); Assert.assertEquals(expected.size(), paths.size()); paths.forEach(path -> Assert.assertTrue(expected.contains(TreeUtil.getLastUserObject(String.class, path)))); test.done(); }); } @Test public void testCollectSelectedUserObjects() { testCollectSelectedUserObjects(set("11", "222", "33", "3331", "3332", "3333", "Root"), test -> TreeUtil.collectSelectedUserObjects(test.getTree())); } @Test public void testCollectSelectedUserObjectsWithCollapsedPath() { testCollectSelectedUserObjects(set("11", "222", "33", "Root"), test -> { test.getTree().collapseRow(15); // 33 return TreeUtil.collectSelectedUserObjects(test.getTree()); }); } @Test public void testCollectSelectedUserObjectsWithCollapsedPathUnder33() { testCollectSelectedUserObjects(set("33"), test -> { test.getTree().collapseRow(15); // 33 TreePath root = test.getTree().getPathForRow(15); // 33 return TreeUtil.collectSelectedUserObjects(test.getTree(), root); }); } @Test public void testCollectSelectedUserObjectsWithCollapsedPathUnder333() { // collapsed parent node becomes selected if it contains selected children testCollectSelectedUserObjects(set("333"), test -> { test.getTree().collapseRow(18); // 333 TreePath root = test.getTree().getPathForRow(18); // 333 return TreeUtil.collectSelectedUserObjects(test.getTree(), root); }); } private static void testCollectSelectedUserObjects(@NotNull Set<String> expected, @NotNull Function<TreeTest, List<Object>> getter) { testCollectSelection(test -> { List<Object> objects = getter.apply(test); Assert.assertEquals(expected.size(), objects.size()); objects.forEach(object -> Assert.assertTrue(expected.contains((String)object))); test.done(); }); } private static void testCollectSelection(@NotNull Consumer<TreeTest> consumer) { TreeVisitor[] array = { convertArrayToVisitor("1", "11"), convertArrayToVisitor("2", "22", "222"), convertArrayToVisitor("3", "33"), convertArrayToVisitor("3", "33", "333", "3331"), convertArrayToVisitor("3", "33", "333", "3332"), convertArrayToVisitor("3", "33", "333", "3333"), path -> TreeVisitor.Action.INTERRUPT, }; testMultiSelect(array, array.length, "-[Root]\n" + " -1\n" + " +[11]\n" + " +12\n" + " +13\n" + " -2\n" + " +21\n" + " -22\n" + " +221\n" + " +[222]\n" + " +223\n" + " +23\n" + " -3\n" + " +31\n" + " +32\n" + " -[33]\n" + " +331\n" + " +332\n" + " -333\n" + " [3331]\n" + " [3332]\n" + " [3333]\n", consumer); } @Test public void testCollectSelectedObjectsOfType() { TreeTest.test(() -> node(Boolean.TRUE, node(101), node(1.1f)), test -> test.assertTree("+true\n", () -> TreeUtil.expandAll(test.getTree(), () -> test.assertTree("-true\n 101\n 1.1\n", () -> { TreeUtil.visitVisibleRows(test.getTree(), path -> path, path -> test.getTree().addSelectionPath(path)); test.assertTree("-[true]\n [101]\n [1.1]\n", true, () -> { Assert.assertEquals(3, TreeUtil.collectSelectedObjectsOfType(test.getTree(), Object.class).size()); Assert.assertEquals(2, TreeUtil.collectSelectedObjectsOfType(test.getTree(), Number.class).size()); Assert.assertEquals(1, TreeUtil.collectSelectedObjectsOfType(test.getTree(), Boolean.class).size()); Assert.assertEquals(1, TreeUtil.collectSelectedObjectsOfType(test.getTree(), Integer.class).size()); Assert.assertEquals(1, TreeUtil.collectSelectedObjectsOfType(test.getTree(), Float.class).size()); Assert.assertEquals(0, TreeUtil.collectSelectedObjectsOfType(test.getTree(), String.class).size()); test.done(); }); })))); } @Test public void testSelectFirstEmpty() { testSelectFirst(() -> null, true, ""); } @Test public void testSelectFirstWithRoot() { testSelectFirst(TreeUtilVisitTest::rootDeep, true, "+[Root]\n"); } @Test public void testSelectFirstWithoutRoot() { testSelectFirst(TreeUtilVisitTest::rootDeep, false, " +[1]\n" + " +2\n" + " +3\n"); } private static void testSelectFirst(@NotNull Supplier<TreeNode> root, boolean visible, @NotNull String expected) { TreeTest.test(root, test -> { test.getTree().setRootVisible(visible); TreeUtil.promiseSelectFirst(test.getTree()).onProcessed(path -> test.invokeSafely(() -> { if (expected.isEmpty()) { Assert.assertNull(path); } else { Assert.assertNotNull(path); Assert.assertTrue(test.getTree().isVisible(path)); } test.assertTree(expected, true, test::done); })); }); } @Test public void testMakeVisibleNonExistent() { testMakeVisibleNonExistent("-Root\n" + " +1\n" + " +2\n" + " -3\n" + " +31\n" + " +32\n" + " +33\n", convertArrayToVisitor("3", "NonExistent")); } @Test public void testMakeVisibleNonExistentRoot() { testMakeVisibleNonExistent("+Root\n", createRootVisitor("tOOr")); } private static void testMakeVisibleNonExistent(String expected, TreeVisitor visitor) { testNonExistent(expected, test -> TreeUtil.promiseMakeVisible(test.getTree(), visitor)); } @Test public void testExpandNonExistent() { testExpandNonExistent("-Root\n" + " +1\n" + " +2\n" + " -3\n" + " +31\n" + " +32\n" + " +33\n", convertArrayToVisitor("3", "NonExistent")); } @Test public void testExpandNonExistentRoot() { testExpandNonExistent("+Root\n", createRootVisitor("t00r")); } private static void testExpandNonExistent(String expected, TreeVisitor visitor) { testNonExistent(expected, test -> TreeUtil.promiseExpand(test.getTree(), visitor)); } private static void testNonExistent(String expected, Function<TreeTest, Promise<TreePath>> function) { TreeTest.test(TreeUtilVisitTest::rootDeep, test -> function.apply(test) .onSuccess(path -> test.invokeSafely(() -> Assert.fail("found unexpected path: " + path))) .onError(error -> test.invokeSafely(() -> { Assert.assertTrue(error instanceof CancellationException); test.assertTree(expected, test::done); }))); } private static TreeVisitor createRootVisitor(@NotNull String name) { return new TreeVisitor.ByTreePath<>(new TreePath(name), Object::toString); } private static TreeVisitor convertArrayToVisitor(@NotNull String... array) { return new TreeVisitor.ByTreePath<>(true, convertArrayToTreePath(array), Object::toString); } private static String value(TreePath path) { return path == null ? null : path.getLastPathComponent().toString(); } private static TreeNode root() { return node("Root", node("RootColor", node("RootColorRed"), node("RootColorGreen"), node("RootColorBlue")), node("RootDigit", node("RootDigitOne"), node("RootDigitTwo"), node("RootDigitThree"), node("RootDigitFour"), node("RootDigitFive"), node("RootDigitSix"), node("RootDigitSeven"), node("RootDigitEight"), node("RootDigitNine")), node("RootGreek", node("RootGreekAlpha"), node("RootGreekBeta"), node("RootGreekGamma"), node("RootGreekDelta"), node("RootGreekEpsilon"))); } private static TreeNode rootDeep() { return node("Root", node("1", node("11", node("111", "1111", "1112", "1113"), node("112", "1121", "1122", "1123"), node("113", "1131", "1132", "1133")), node("12", node("121", "1211", "1212", "1213"), node("122", "1221", "1222", "1223"), node("123", "1231", "1232", "1233")), node("13", node("131", "1311", "1312", "1313"), node("132", "1321", "1322", "1323"), node("133", "1331", "1332", "1333"))), node("2", node("21", node("211", "2111", "2112", "2113"), node("212", "2121", "2122", "2123"), node("213", "2131", "2132", "2133")), node("22", node("221", "2211", "2212", "2213"), node("222", "2221", "2222", "2223"), node("223", "2231", "2232", "2233")), node("23", node("231", "2311", "2312", "2313"), node("232", "2321", "2322", "2323"), node("233", "2331", "2332", "2333"))), node("3", node("31", node("311", "3111", "3112", "3113"), node("312", "3121", "3122", "3123"), node("313", "3131", "3132", "3133")), node("32", node("321", "3211", "3212", "3213"), node("322", "3221", "3222", "3223"), node("323", "3231", "3232", "3233")), node("33", node("331", "3311", "3312", "3313"), node("332", "3321", "3322", "3323"), node("333", "3331", "3332", "3333")))); } static class Visitor implements TreeVisitor { final AtomicLong counter = new AtomicLong(); @NotNull @Override public Action visit(@NotNull TreePath path) { counter.incrementAndGet(); if (matches(path)) return Action.INTERRUPT; if (contains(path)) return Action.CONTINUE; return Action.SKIP_CHILDREN; } protected boolean matches(@NotNull TreePath path) { return false; } protected boolean contains(@NotNull TreePath path) { return true; } } static class DepthVisitor extends Visitor { private final int depth; DepthVisitor(int depth) { this.depth = depth; } @Override protected boolean contains(@NotNull TreePath path) { return depth > path.getPathCount(); } } static class StringFinder extends Visitor { private final String value; StringFinder(@NotNull String value) { this.value = value; } @Override protected boolean matches(@NotNull TreePath path) { return value.equals(value(path)); } @Override protected boolean contains(@NotNull TreePath path) { return value.startsWith(value(path)); } } }
paplorinc/intellij-community
platform/platform-tests/testSrc/com/intellij/ui/tree/TreeUtilVisitTest.java
Java
apache-2.0
34,687
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_15.html">Class Test_AbaRouteValidator_15</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_32851_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15.html?line=8315#src-8315" >testAbaNumberCheck_32851_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:44:41 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_32851_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=6548#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
dcarda/aba.route.validator
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15_testAbaNumberCheck_32851_good_51w.html
HTML
apache-2.0
9,178
# Protosphaeridium reticulatum Viswanathiah et al., 1980 SPECIES #### Status ACCEPTED #### According to Interim Register of Marine and Nonmarine Genera #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Protozoa/Acritarcha/Protosphaeridium/Protosphaeridium reticulatum/README.md
Markdown
apache-2.0
220
linux-scripts ============= Interesting scrits for linux, for example, liferay service, alfresco service , openoffice/libreoffice service, etc...
jferna57/linux-scripts
README.md
Markdown
apache-2.0
147
package com.huawei.esdk.ivs.professional.local.impl.interceptor; import java.util.List; import java.util.Map; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.message.Message; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.service.model.MessageInfo; import org.apache.cxf.service.model.OperationInfo; public class MsgOutInterceptor extends AbstractPhaseInterceptor<Message> { public MsgOutInterceptor() { super("pre-stream"); } @SuppressWarnings({"unchecked", "rawtypes"}) public void handleMessage(Message message) throws Fault { OperationInfo operation = message.get(MessageInfo.class).getOperation(); String inputName = operation.getInputName(); if (!"login".equals(inputName)) { List session = MsgSessionHolder.getInstance().getSession(); if (session != null && !session.isEmpty()) { Map headers = (Map)message.get(Message.PROTOCOL_HEADERS); headers.put("Cookie", session); } } } }
eSDK/esdk_ivs_native_java
source/src/main/java/com/huawei/esdk/ivs/professional/local/impl/interceptor/MsgOutInterceptor.java
Java
apache-2.0
1,127
package de.taimos.dvalin.daemon; /*- * #%L * Daemon support for dvalin * %% * Copyright (C) 2015 - 2017 Taimos GmbH * %% * 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. * #L% */ public interface ISpringLifecycleListener { void afterContextStart(); void started(); void stopping(); void beforeContextStop(); void aborting(); void signalUSR2(); }
taimos/dvalin
daemon/src/main/java/de/taimos/dvalin/daemon/ISpringLifecycleListener.java
Java
apache-2.0
895
# Salvia urticifolia var. longifolia (Nutt.) Alph.Wood VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Salvia/Salvia urticifolia/Salvia urticifolia longifolia/README.md
Markdown
apache-2.0
202
/** * Copyright 2013 The Loon 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 loon.physics; import loon.core.geom.Vector2f; import loon.utils.MathUtils; public class PHingeJoint extends PJoint { private Vector2f anchor1; private Vector2f anchor2; private float angI; private float angM; private PBody b1; private PBody b2; private boolean enableLimit; private boolean enableMotor; private Vector2f impulse; private float limI; private int limitState; private Vector2f localAnchor1; private Vector2f localAnchor2; private float localAngle; private PTransformer mass; private float maxAngle; private float minAngle; private float motI; private float motorSpeed; private float motorTorque; private Vector2f relAnchor1; private Vector2f relAnchor2; private float rest; private float targetAngleSpeed; public PHingeJoint(PBody b1, PBody b2, float rel1x, float rel1y, float rel2x, float rel2y) { this.b1 = b1; this.b2 = b2; localAngle = b2.ang - b1.ang; localAnchor1 = new Vector2f(rel1x, rel1y); localAnchor2 = new Vector2f(rel2x, rel2y); b1.mAng.transpose().mulEqual(localAnchor1); b2.mAng.transpose().mulEqual(localAnchor2); anchor1 = b1.mAng.mul(localAnchor1); anchor1.addLocal(b1.pos); anchor2 = b2.mAng.mul(localAnchor2); anchor2.addLocal(b2.pos); type = PJointType.HINGE_JOINT; mass = new PTransformer(); impulse = new Vector2f(); } public Vector2f getAnchorPoint1() { return anchor1.clone(); } public Vector2f getAnchorPoint2() { return anchor2.clone(); } public PBody getBody1() { return b1; } public PBody getBody2() { return b2; } public float getLimitRestitution(float restitution) { return rest; } public float getMaxAngle() { return maxAngle; } public float getMinAngle() { return minAngle; } public float getMotorSpeed() { return motorSpeed; } public float getMotorTorque() { return motorTorque; } public Vector2f getRelativeAnchorPoint1() { return relAnchor1.clone(); } public Vector2f getRelativeAnchorPoint2() { return relAnchor2.clone(); } public boolean isEnableLimit() { return enableLimit; } public boolean isEnableMotor() { return enableMotor; } @Override void preSolve(float dt) { relAnchor1 = b1.mAng.mul(localAnchor1); relAnchor2 = b2.mAng.mul(localAnchor2); anchor1.set(relAnchor1.x + b1.pos.x, relAnchor1.y + b1.pos.y); anchor2.set(relAnchor2.x + b2.pos.x, relAnchor2.y + b2.pos.y); mass = PTransformer.calcEffectiveMass(b1, b2, relAnchor1, relAnchor2); angM = 1.0F / (b1.invI + b2.invI); float ang = b2.ang - b1.ang - localAngle; if (!enableMotor) { motI = 0.0F; } if (enableLimit) { if (ang < minAngle) { if (limitState != -1) { limI = 0.0F; } limitState = -1; if (b2.angVel - b1.angVel < 0.0F) { targetAngleSpeed = (b2.angVel - b1.angVel) * -rest; } else { targetAngleSpeed = 0.0F; } } else if (ang > maxAngle) { if (limitState != 1) { limI = 0.0F; } limitState = 1; if (b2.angVel - b1.angVel > 0.0F) { targetAngleSpeed = (b2.angVel - b1.angVel) * -rest; } else { targetAngleSpeed = 0.0F; } } else { limI = limitState = 0; } } else { limI = limitState = 0; } angI = 0.0F; b1.applyImpulse(impulse.x, impulse.y, anchor1.x, anchor1.y); b2.applyImpulse(-impulse.x, -impulse.y, anchor2.x, anchor2.y); b1.applyTorque(motI + limI); b2.applyTorque(-motI - limI); } public void setEnableLimit(boolean enable) { enableLimit = enable; } public void setEnableMotor(boolean enable) { enableMotor = enable; } public void setLimitAngle(float minAngle, float maxAngle) { this.minAngle = minAngle; this.maxAngle = maxAngle; } public void setLimitRestitution(float restitution) { rest = restitution; } public void setMaxAngle(float maxAngle) { this.maxAngle = maxAngle; } public void setMinAngle(float minAngle) { this.minAngle = minAngle; } public void setMotor(float speed, float torque) { motorSpeed = speed; motorTorque = torque; } public void setMotorSpeed(float speed) { motorSpeed = speed; } public void setMotorTorque(float torque) { motorTorque = torque; } public void setRelativeAnchorPoint1(float relx, float rely) { localAnchor1.set(relx, rely); b1.mAng.transpose().mulEqual(localAnchor1); } public void setRelativeAnchorPoint2(float relx, float rely) { localAnchor2.set(relx, rely); b2.mAng.transpose().mulEqual(localAnchor2); } @Override void solvePosition() { if (enableLimit && limitState != 0) { float over = b2.ang - b1.ang - localAngle; if (over < minAngle) { over += 0.008F; over = ((over - minAngle) + b2.correctAngVel) - b1.correctAngVel; float torque = over * 0.2F * angM; float subAngleImpulse = angI; angI = MathUtils.min(angI + torque, 0.0F); torque = angI - subAngleImpulse; b1.positionCorrection(torque); b2.positionCorrection(-torque); } if (over > maxAngle) { over -= 0.008F; over = ((over - maxAngle) + b2.correctAngVel) - b1.correctAngVel; float torque = over * 0.2F * angM; float subAngleImpulse = angI; angI = MathUtils.max(angI + torque, 0.0F); torque = angI - subAngleImpulse; b1.positionCorrection(torque); b2.positionCorrection(-torque); } } Vector2f force = anchor2.sub(anchor1); force.subLocal(PTransformer.calcRelativeCorrectVelocity(b1, b2, relAnchor1, relAnchor2)); float length = force.length(); force.normalize(); force.mulLocal(Math.max(length * 0.2F - 0.002F, 0.0F)); mass.mulEqual(force); b1.positionCorrection(force.x, force.y, anchor1.x, anchor1.y); b2.positionCorrection(-force.x, -force.y, anchor2.x, anchor2.y); } @Override void solveVelocity(float dt) { Vector2f relVel = PTransformer.calcRelativeVelocity(b1, b2, relAnchor1, relAnchor2); Vector2f force = mass.mul(relVel).negate(); impulse.addLocal(force); b1.applyImpulse(force.x, force.y, anchor1.x, anchor1.y); b2.applyImpulse(-force.x, -force.y, anchor2.x, anchor2.y); if (enableMotor) { float angRelVel = b2.angVel - b1.angVel - motorSpeed; float torque = angM * angRelVel; float subMotorI = motI; motI = MathUtils.clamp(motI + torque, -motorTorque * dt, motorTorque * dt); torque = motI - subMotorI; b1.applyTorque(torque); b2.applyTorque(-torque); } if (enableLimit && limitState != 0) { float angRelVel = b2.angVel - b1.angVel - targetAngleSpeed; float torque = angM * angRelVel; float subLimitI = limI; if (limitState == -1) { limI = MathUtils.min(limI + torque, 0.0F); } else { if (limitState == 1) { limI = MathUtils.max(limI + torque, 0.0F); } } torque = limI - subLimitI; b1.applyTorque(torque); b2.applyTorque(-torque); } } @Override void update() { relAnchor1 = b1.mAng.mul(localAnchor1); relAnchor2 = b2.mAng.mul(localAnchor2); anchor1.set(relAnchor1.x + b1.pos.x, relAnchor1.y + b1.pos.y); anchor2.set(relAnchor2.x + b2.pos.x, relAnchor2.y + b2.pos.y); if (b1.rem || b2.rem || b1.fix && b2.fix) { rem = true; } } }
cping/LGame
Java/old/OpenGL-1.0(old_ver)/Loon-backend-Android/src/loon/physics/PHingeJoint.java
Java
apache-2.0
7,633
--- copyright: years: 2015, 2016 lastupdated: "2016-11-07" --- {:new_window: target="_blank"} {:shortdesc: .shortdesc} # {{site.data.keyword.Bluemix_local_notm}} {: #local} <!-- 10/30/16 Most sections are currently being updated and edited. Do not move full file for production --> {{site.data.keyword.Bluemix_local}} proporciona la potencia y la agilidad de la plataforma basada en nubes de {{site.data.keyword.Bluemix_notm}} para el centro de datos. Con {{site.data.keyword.Bluemix_local_notm}}, puede proteger las cargas de trabajo más sensibles detrás del cortafuegos de la empresa, mientras que permanecen conectadas de forma segura y en sincronización con {{site.data.keyword.Bluemix_notm}} público. {:shortdesc} IBM® utiliza operaciones de nube como un servicio para supervisar y mantener el entorno, de modo que puede centrarse en la construcción de apps y servicios que se ejecutan en la parte superior del entorno. {{site.data.keyword.IBM_notm}} también maneja actualizaciones a la plataforma, de modo que puede centrarse en la empresa. Los entornos de {{site.data.keyword.Bluemix_local_notm}} tienen los mismos estándares de seguridad que {{site.data.keyword.Bluemix_notm}} público en términos de seguridad operativa. Proporcione el hardware y la infraestructura, que le proporciona control sobre la infraestructura y la [seguridad](/docs/security/index.html#localplatformsecurity) física. El acceso de desarrollador al entorno de {{site.data.keyword.Bluemix_notm}} local está controlado por las políticas de LDAP, que puede configurar el equipo de {{site.data.keyword.Bluemix_notm}} al configurar el entorno. En el entorno local, utilizando la página de administración, puede [gestionar usuarios y permisos](/docs/admin/index.html#oc_useradmin). {{site.data.keyword.Bluemix_local_notm}} se suministra con todos los tiempos de ejecución de {{site.data.keyword.Bluemix_notm}} incluidos y a los 64 GB de memoria de cálculo. Además, hay un conjunto de servicios que están disponibles como servicios de {{site.data.keyword.Bluemix_local_notm}}. Revise la tabla siguiente para ver lo que se incluye y qué hay disponible para comprar. | **Tipo** | **Nombre** | **Descripción** | |----------|----------|-----------------| |Incluido | [Tiempos de ejecución de {{site.data.keyword.Bluemix_notm}}](/docs/cfapps/runtimes.html) | Utilice los tiempos de ejecución para que su app esté activa y en funcionamiento con rapidez, sin necesidad de configurar y gestionar las máquinas ni los sistemas operativos. Todos los tiempos de ejecución de {{site.data.keyword.Bluemix_notm}} están disponibles para utilizarlos en la instancia de {{site.data.keyword.Bluemix_notm}} local.| |Incluido | [{{site.data.keyword.autoscaling}}](/docs/services/Auto-Scaling/index.html)| Aumente o reduzca de forma dinámica la capacidad de cálculo de la app en función de políticas. Con este servicio, dispone de un uso ilimitado del entorno de {{site.data.keyword.Bluemix}} local.| |Opcional | [{{site.data.keyword.apiconnect_short}}](/docs/services/apiconnect/index.html) | {{site.data.keyword.apiconnect_long}} integra {{site.data.keyword.APIM}} e IBM StrongLoop en una única oferta que proporciona una solución completa para crear, ejecutar gestionar e imponer API y microservicios. | |Opcional | [{{site.data.keyword.cloudant}}](/docs/services/Cloudant/index.html#Cloudant) | {{site.data.keyword.cloudant}} proporciona acceso a una capa de datos JSON de NoSQL completamente gestionada que siempre está activa. Este servicio es compatible con CouchDB y se puede acceder a través de una interfaz HTTP fácil de utilizar para los modelos de aplicación web y móvil. Para obtener más información, consulte la [documentación](http://docs.cloudant.com/BluemixLocal.html){: new_window} completa y los [requisitos de hardware](http://docs.cloudant.com/BluemixLocalHardware.html){: new_window} para un entorno local. | |Opcional | [{{site.data.keyword.containershort}}](/docs/containers/container_index.html) | Ejecutar contenedores de Docker en {{site.data.keyword.Bluemix_notm}} local. Los contenedores son objetos de software virtuales que incluyen todos los elementos que una app necesita para ejecutarse. Un contenedor tiene las ventajas del aislamiento y asignación de recursos, pero es más portable y eficiente que, por ejemplo, una máquina virtual. Para obtener información sobre los requisitos de hardware, consulte [IBM {{site.data.keyword.containershort}} en {{site.data.keyword.Bluemix_notm}} Dedicado y Bluemix Local](/docs/containers/container_dl.html). | |Opcional | [{{site.data.keyword.datacshort}}](/docs/services/DataCache/index.html#data_cache) | Este servicio proporciona una cuadrícula de datos en memoria que da soporte a casos de ejemplo de memoria caché distribuidos para las apps. Incluye 50 GB de memoria caché en memoria. | | Opcional (Beta) | [Registro](/docs/monitoringandlogging/cfapps_ml_logs_dedicated_ov.html#container_ml_logs_dedicated_ov) | Proporciona registros para las apps de Cloud Foundry en la interfaz de usuario de {{site.data.keyword.Bluemix_notm}} y registros y paneles de control en los que pueden realizarse búsquedas en Kibana. | |Opcional | [{{site.data.keyword.mobilepush}}](/docs/services/mobilepush/index.html) | {{site.data.keyword.mobilepush}} es un servicio que puede utilizar para enviar notificaciones a un dispositivo iOS y Android. Las notificaciones pueden dirigirse a todos los usuarios de aplicaciones o a un conjunto específico de usuarios y dispositivos utilizando etiquetas. Puede administrar dispositivos, etiquetas y suscripciones. También puede utilizar un kit de desarrollo de software (SDK) y una interfaz de programa de aplicación (API) de aplicación REST (Representational State Transfer) para seguir desarrollando las aplicaciones cliente. | |Opcional | [{{site.data.keyword.sescashort}}](/docs/services/SessionCache/index.html#session_cache) | Para una mayor redundancia, {{site.data.keyword.sescashort}} proporciona una réplica de una sesión almacenada en la memoria caché. Por lo tanto en el caso de una caída de la red o una interrupción, la aplicación cliente mantiene el acceso a la sesión en la memoria caché. El servicio da soporte a casos de ejemplo de almacenamiento en caché de sesión para aplicaciones web y para móvil. | |Opcional | [{{site.data.keyword.iot_short}}](/docs/services/IoT/index.html) | Este servicio permite a las apps comunicarse y consumir datos recopilados por los dispositivos, sensores y pasarelas conectados. La oferta de base local incluye un entorno inicial que permite la ejecución de una versión privada de IBM {{site.data.keyword.iot_short}} dentro del entorno local con una capacidad de 100.000 aplicaciones o dispositivos conectados simultáneamente y 1,6 TB de intercambio de datos. | {: caption="Table 1. Local services and runtimes" caption-side="top"} {: #table01} Hay componentes opcionales que se pueden adquirir para escalar y ampliar la capacidad de los recursos y servicios. Puede adquirir cualquiera de estos componentes poniéndose en contacto con el equipo de ventas de; vaya a [Póngase en contacto con nosotros](https://console.ng.bluemix.net/?direct=classic/#/contactUs/cloudOEPaneId=contactUs) para obtener información acerca de cómo ponerse en contacto con un representante de ventas. Para aumentar el plan para un servicio, puede seleccionar el plan en el mosaico del servicio del catálogo. | **Nombre** | **Descripción** | |----------|-----------------| |{{site.data.keyword.Bluemix_notm}} 5 millones de llamadas de API de {{site.data.keyword.apiconnect_short}} Professional local | Un entorno que permite ejecutar una versión privada de {{site.data.keyword.apiconnect_short}} con una capacidad para 5 millones de llamadas de API al mes destinadas a proyectos de API de departamento. | |{{site.data.keyword.Bluemix_notm}} Aumento de 100 mil llamadas de API de {{site.data.keyword.apiconnect_short}} Professional local| Una extensión del entorno {{site.data.keyword.apiconnect_short}} Professional para proporcionar una capacidad adicional de 100 mil llamadas de API al mes. | |{{site.data.keyword.Bluemix_notm}} 25 millones de llamadas de API de {{site.data.keyword.apiconnect_short}} Enterprise local | Un entorno que permite ejecutar una versión privada de {{site.data.keyword.apiconnect_short}} con una capacidad para 25 millones de llamadas de API al mes destinadas a proyectos de API. | |{{site.data.keyword.Bluemix_notm}} Aumento de 100 mil llamadas de API de {{site.data.keyword.apiconnect_short}} Enterprise local | Una extensión del entorno {{site.data.keyword.apiconnect_short}} Enterprise para proporcionar una capacidad adicional de 100 mil llamadas de API al mes. | |Clúster {{site.data.keyword.cloudant}} de {{site.data.keyword.Bluemix_notm}} local | Un entorno que permite el despliegue de un clúster de 3 nodos del servicio {{site.data.keyword.cloudant}}. La capacidad de datos de los nodos la determina la infraestructura que haya proporcionado para el entorno local. | |Aumento de capacidad de 50 GB de Datos y Sesión de {{site.data.keyword.Bluemix_notm}} | Entorno que permite desplegar y ejecutar instancias de caché de datos y caché de sesión hasta una capacidad acumulativa de 50 GB. | |Aumento incremental de {{site.data.keyword.Bluemix_notm}} {{site.data.keyword.iot_short}} local | Un entorno adicional para la oferta de servicio base de {{site.data.keyword.iot_short}} local que permite ejecutar una versión privada de {{site.data.keyword.iot_short}} dentro del entorno local con una capacidad de 100.000 aplicaciones o dispositivos conectados simultáneamente y 0,5 TB de intercambio de datos. | |Instancia de complemento de {{site.data.keyword.IBM_notm}} {{site.data.keyword.mobilepush}} Local | Un entorno que permite el despliegue y la ejecución de instancias de {{site.data.keyword.mobilepush}} con capacidad para aceptar 300 solicitudes adicionales por segundo. | {: caption="Table 2. Optional services components for purchase" caption-side="top"} {: #table02} | **Nombre** | **Descripción** | |----------|-----------------| |Capacidad de 64 GB de los tiempos de ejecución de Local Cloud Foundry | Entorno de tiempos de ejecución de Cloud Foundry con 64 GB de capacidad de tiempo de ejecución. | |Aumento de la capacidad de 16 GB de los tiempos de ejecución de Local Cloud Foundry | Extensión del entorno de tiempos de ejecución de Cloud Foundry para proporcionar 16 GB adicionales de capacidad de tiempo de ejecución. | |Aumento de capacidad de 16 GB de {{site.data.keyword.containerlong}} local | Extensión del entorno de {{site.data.keyword.containerlong}} para proporcionar 16 GB adicionales de capacidad. | |Capacidad local de 64 GB de {{site.data.keyword.containerlong}} | Entorno de {{site.data.keyword.containerlong}} con 64 GB de capacidad. | {: caption="Table 3. Optional platform add-on components for purchase" caption-side="top"} {: #table03} **Nota**: Los componentes de {{site.data.keyword.Bluemix_notm}} local pueden iniciar una capacidad configurada específica, como gigabytes o transacciones por segundo. Dado que la capacidad actual en la práctica para cualquier configuración del servicio de nube varía en función de muchos factores, la capacidad real en la práctica puede ser superior o inferior a la capacidad configurada. ### Catálogo sindicado {: #cataloglocal} {{site.data.keyword.Bluemix_local_notm}} incluye un catálogo privado que aúna servicios aprobados de los despliegues públicos y locales. Incluso puede publicar y gestionar el acceso a sus propios servicios a través del catálogo de {{site.data.keyword.Bluemix_notm}}. Tiene la opción de decidir qué servicios públicos cumplen los requisitos de su empresa en función de sus criterios de privacidad de datos y de seguridad. Si es una instancia privada de un servicio de {{site.data.keyword.Bluemix_notm}} para el entorno local, verá una etiqueta "Local" con los nombres del servicio en la vista de administración del catálogo. De forma parecida, si es un servicio personalizado (es decir, para cuya creación se ha utilizado un intermediario de servicio) verá "Personalizado" listado con el nombre del servicio. El resto de servicios listados que no incluyen la etiqueta "local" o "personalizado" están disponibles mediante la sindicación desde {{site.data.keyword.Bluemix_notm}} público. Los servicios sindicados proporcionan la función para crear aplicaciones híbridas que constan de servicios públicos o privados. |Servicio |Disponible en la región EE.UU. sur |Disponible en la región Europa Reino Unido |Disponible en la región Australiana Sídney| |:----------|:------------------------------|:------------------|:------------------| |{{site.data.keyword.alchemyapishort}} |Sí |Sí |Sí| |{{site.data.keyword.alertnotificationshort}} |Sí |Sí |Sí | |{{site.data.keyword.apiconnect_short}} |Sí |Sí |Sí | |{{site.data.keyword.appseccloudshort}} |Sí |Sí |Sí | |{{site.data.keyword.apiconnect_short}} |Sí |Sí |Sí | |Comprobador de accesibilidad automatizado |Sí |Sí |Sí | |{{site.data.keyword.rules_short}} |Sí |Sí |Sí | |{{site.data.keyword.cloudant}} |Sí |Sí |Sí | |{{site.data.keyword.iotmapinsights_short}} |Sí |Sí |Sí | |{{site.data.keyword.conversationshort}} |Sí |Sí |Sí | |{{site.data.keyword.dashdbshort}} |Sí |Sí |Sí | |{{site.data.keyword.dataworks_short}} |Sí |Sí |No| |{{site.data.keyword.DB2OnCloud_short}} |Sí |Sí |Sí | |Comprobador de contenido digital |Sí |Sí |Sí | |{{site.data.keyword.documentconversionshort}} |Sí |Sí |Sí| |{{site.data.keyword.iotdriverinsights_short}} |Sí |Sí |Sí | |{{site.data.keyword.geospatialshort_Geospatial}} |Sí |Sí |Sí | |{{site.data.keyword.GlobalizationPipeline_short}} |Sí | Sí | Sí | |{{site.data.keyword.identitymixershort}} |Sí |Sí |Sí| |{{site.data.keyword.iot4auto_short}} |Sí |Sí |Sí | |{{site.data.keyword.iotelectronics}} |Sí |Sí |No | |{{site.data.keyword.iotinsurance_short}} |No |No |Sí | |{{site.data.keyword.twittershort}} |Sí |Sí |Sí| |{{site.data.keyword.languagetranslationshort}} |Sí |Sí |Sí | |{{site.data.keyword.languagetranslatorshort}} |Sí |Sí |Sí | |{{site.data.keyword.dwl_short}} |Sí |Sí |No | |{{site.data.keyword.eventhubshort}} |Sí |No |No| |{{site.data.keyword.messagehub}} |Sí |Sí |No| |{{site.data.keyword.manda}} |Sí |Sí |Sí | |{{site.data.keyword.amashort}} |Sí |Sí |Sí | |{{site.data.keyword.mqa}} |Sí |Sí |Sí | |{{site.data.keyword.mql}} |No |No |Sí | |{{site.data.keyword.nlclassifierlshort}} |Sí |Sí |Sí| |{{site.data.keyword.personalityinsightsshort}} |Sí |Sí |Sí| |{{site.data.keyword.pm_short}} |Sí |Sí |No | |{{site.data.keyword.mobilepush}} |Sí |Sí |Sí | |{{site.data.keyword.retrieveandrankshort}} |Sí |Sí |Sí| |{{site.data.keyword.runbook_short}} |Sí |Sí |Sí| |{{site.data.keyword.SecureGateway}} |Sí |Sí |Sí | |{{site.data.keyword.ssofull}} |Sí |No |No| |{{site.data.keyword.speechtotextshort}} |Sí |Sí |Sí| |{{site.data.keyword.streaminganalyticsshort}} |Sí |Sí |Sí | |{{site.data.keyword.texttospeechshort}} |Sí |Sí |Sí| |{{site.data.keyword.toneanalyzershort}} |Sí |Sí |Sí| |{{site.data.keyword.tradeoffanalyticsshort}} |Sí |Sí |Sí| |{{site.data.keyword.visualrecognitionshort}} |Sí |Sí |Sí| |{{site.data.keyword.iot_short}} |Sí |Sí |No| |{{site.data.keyword.weather_short}} |Sí |Sí |Sí| |{{site.data.keyword.workloadscheduler}} |Sí |Sí |Sí | {: caption="Table 4. Services available for syndication from {{site.data.keyword.Bluemix_notm}} Public by region" caption-side="top"} {: #table04} **Nota**: Los servicios de terceros no están incluidos en la tabla. Compruebe el catálogo para opciones de servicio de terceros. ## Arquitectura de {{site.data.keyword.Bluemix_local_notm}} {: #localarch} {{site.data.keyword.Bluemix_local_notm}} forma parte de una infraestructura virtualizada que está detrás del cortafuegos de la empresa, lo que le permite disponer de la infraestructura de nube de alto rendimiento y más segura. {{site.data.keyword.IBM_notm}} instala, supervisa de forma remota y gestiona {{site.data.keyword.Bluemix_local_notm}} en su centro de datos gracias a la tecnología [Relay](#localrelay) de {{site.data.keyword.IBM_notm}}. La arquitectura lógica de [Figure 1](#figure01) describe cómo {{site.data.keyword.Bluemix_notm}} configura el entorno local y cómo {{site.data.keyword.IBM_notm}} mantiene la instancia local: ![Arquitectura de {{site.data.keyword.Bluemix_local_notm}}](images/bmlocal_arch.png "Diagrama de la arquitectura local de Bluemix") Figura 1. Arquitectura de {{site.data.keyword.Bluemix_local_notm}} {: #figure01} La máquina virtual inicial (VM inicial) se ejecuta en la infraestructura virtualizada de la empresa detrás del cortafuegos de la empresa. La VM inicial crea una conexión de red de salida con el centro de operaciones de {{site.data.keyword.IBM_notm}} a través de la tecnología de relé de {{site.data.keyword.IBM_notm}}. La tecnología de relé realiza varias funciones que se describen en la siguiente sección [Relay (Relé)](#localrelay). Los componentes de la plataforma de {{site.data.keyword.Bluemix_notm}} y las funciones principales que dan soporte a los componentes de la plataforma, se ejecutan en una red de área local virtual aislada y privada (VLAN). {{site.data.keyword.Bluemix_local_notm}} utiliza una VLAN para la subred privada. El uso de una subred privada en lugar de una VLAN pública es más seguro y puede ayudar a evitar problemas de direccionamiento. El conjunto de funciones centrales que dan soporte a la plataforma son: <dl> <dt>Plataforma</dt> <dd>Como mínimo, la plataforma consta de componentes de Cloud Foundry y de algunos servicios de aplicaciones locales. {{site.data.keyword.Bluemix_notm}} proporciona entornos de cálculo basados en Cloud Foundry y en {{site.data.keyword.containerlong}}. Una empresa puede tener configurado uno de estos entornos de cálculo o ambos.<br> Una empresa también puede tener servicios de aplicaciones locales adicionales.<br> <p>Consulte [Componentes opcionales para su adquisición: Complementos de servicio](#table02) y [Componentes opcionales para su adquisición: Componentes de plataforma](#table03) para ver los servicios y las funciones de cálculo que se pueden añadir.</p> </dd> <dt>{{site.data.keyword.Bluemix_notm}} público</dt> <dd> Un entorno de {{site.data.keyword.Bluemix_local_notm}} puede tener una conexión de salida con una región pública de {{site.data.keyword.Bluemix_notm}}. Una conexión con una región pública habilita la sindicación de servicios públicos en el catálogo local. La sindicación del servicio {{site.data.keyword.Bluemix_notm}} público ofrece a los desarrolladores un método práctico para crear aplicaciones alojadas en el entorno {{site.data.keyword.Bluemix_local_notm}} de la empresa, así como para acceder a los servicios que se ejecutan en {{site.data.keyword.Bluemix_notm}} público. Consulte la lista de servicios de {{site.data.keyword.IBM_notm}} que se pueden sindicar desde {{site.data.keyword.Bluemix_notm}} público en la sección [Catálogo sindicado](#cataloglocal). </dd> <dt>{{site.data.keyword.IBM_notm}} Operations</dt> <dd> {{site.data.keyword.IBM_notm}} gestiona, supervisa y mantiene la plataforma local y los servicios locales, de modo que pueda centrarse en la creación de aplicaciones innovadores. El equipo de Servicios de soporte de operaciones (OSS) de {{site.data.keyword.IBM_notm}} lleva a cabo operaciones utilizando una conexión de túnel VPN entre la VM inicial y la red de {{site.data.keyword.IBM_notm}} Operations. </dd> <dt>Empresa</dt> <dd> El entorno de red de la empresa tiene un enlace de red bidireccional con {{site.data.keyword.Bluemix_local_notm}}. Esto permite que las aplicaciones alojadas en {{site.data.keyword.Bluemix_local_notm}} puedan acceder a los servicios y recursos de la empresa, incluidas fuentes de datos y servicios de empresa. El enlace de red también permite a {{site.data.keyword.Bluemix_local_notm}} utilizar su LDAP para la autenticación de desarrolladores y administradores. </dd> <dt>Servicios locales</dt> <dd>Dispone de un conjunto de servicios que se utilizan de forma privada en el entorno {{site.data.keyword.Bluemix_local_notm}}. Normalmente, se deciden los servicios que se desea para el entorno antes del despliegue por parte del equipo de {{site.data.keyword.IBM_notm}}. Para obtener una lista de servicios disponibles, vaya al apartado sobre [Servicios y tiempos de ejecución locales](#table01). </dd> <dt>DataPower Gateway</dt> <dd> Los dispositivos {{site.data.keyword.IBM_notm}} DataPower Gateway proporcionan acceso a los dominios de aplicaciones de {{site.data.keyword.Bluemix_notm}}. Estos dispositivos se conectan a la red intranet y a la red privada de {{site.data.keyword.Bluemix_notm}}, proporcionando una pasarela segura al despliegue de {{site.data.keyword.Bluemix_notm}}. Los desarrolladores que despliegan apps y servicios obtienen acceso desde la intranet a través de la pasarela. Los usuarios de la aplicación obtienen acceso a través de los dispositivos DataPower, así como los administradores. </dd> <dt>Security intelligence</dt> <dd><p>{{site.data.keyword.IBM_notm}} utiliza la plataforma QRadar Security Intelligence para ofrecer una arquitectura unificada para mejorar diversos componentes clave. Estos componentes incluyen información de seguridad y gestión de sucesos, gestión de registros, detección de anomalías, actividades forenses de incidencias y gestión de configuración y vulnerabilidades. {{site.data.keyword.Bluemix_notm}} también utiliza la información de seguridad de {{site.data.keyword.IBM_notm}} QRadar y la gestión de sucesos (SIEM) para supervisar acciones de usuarios privilegiados y los intentos de inicio de sesión tanto correctos como incorrectos de los desarrolladores de aplicaciones. Los informes de QRadar proporcionan al cliente visibilidad a través de la sección Informes y registros de la página Administración. Para obtener información sobre los informes de seguridad, consulte [Visualización de informes](/docs/admin/index.html#oc_report).</p> <p>{{site.data.keyword.IBM_notm}} BigFix garantiza que los arreglos de los sistemas operativos se aplican con la frecuencia adecuada. El proceso de aplicación de parches está automatizado, y la planificación se acuerda entre usted e IBM. Para obtener información sobre el mantenimiento y actualizaciones, consulte [Mantenimiento de su instancia local](index.html#maintainlocal).</p> </dd> </dl> Sus apps se despliegan dentro de contenedores virtuales que se ejecutan en máquinas virtuales de Cloud Foundry. Todos los componentes de Cloud Foundry, como los controladores de nube, los gestores de estado, direccionadores y agentes de ejecución de droplet (DEA) se despliegan cuando se configura {{site.data.keyword.Bluemix_notm}}. Los diversos componentes de gestión de {{site.data.keyword.Bluemix_notm}} también se incluyen en el despliegue de {{site.data.keyword.Bluemix_notm}}. Para obtener más información sobre las especificaciones de red y los requisitos de infraestructura, consulte [Requisitos de la infraestructura de {{site.data.keyword.Bluemix_local_notm}}](/docs/local/index.html#localinfra). ### Relay (Relé) {: #localrelay} Relay es el enlace seguro entre la red de la empresa e {{site.data.keyword.IBM_notm}} Cloud Operations. El tráfico sobre la conexión relay es una actividad automatizada para el servicio y mantenimiento de la plataforma {{site.data.keyword.Bluemix_local_notm}}, los recursos de cálculo y los servicios para su instancia. El tráfico sobre la conexión relay se pueden clasificar como se indica a continuación: * supervisión y sucesos * inteligencia y seguridad * despliegues y actualizaciones * determinación de problemas y arreglos * mantenimiento de emergencia <dl> <dt> Supervisión y sucesos </dt> <dd> Las funciones de supervisión y sucesos se despliegan en sus centros de datos. Los datos de la aplicación permanecen en el centro de datos.<br> El tráfico sobre la conexión relay incluye la prestación de supervisión que utiliza {{site.data.keyword.IBM_notm}} Operations para llevar a cabo la supervisión de estado y la determinación de problemas cuando sea necesario.<br> <p>No se incluyen datos confidenciales en la información de supervisión, lo que significa nada de contraseñas, datos de aplicación, registros de aplicación ni claves. El tráfico sobre relay incluye flujos entre VM inicial y el centro de operaciones de {{site.data.keyword.Bluemix_notm}}.</p> </dd> <dt> Security Intelligence </dt> <dd> {{site.data.keyword.IBM_notm}} utiliza la plataforma QRadar Security Intelligence para ofrecer una arquitectura unificada para mejorar diversos componentes clave. Estos componentes incluyen información de seguridad y gestión de sucesos, gestión de registros, detección de anomalías, actividades forenses de incidencias y gestión de configuración y vulnerabilidades.<br> <p>{{site.data.keyword.Bluemix_notm}} también utiliza la información de seguridad de {{site.data.keyword.IBM_notm}} QRadar y la gestión de sucesos (SIEM) para supervisar acciones de usuarios privilegiados y los intentos de inicio de sesión tanto correctos como incorrectos.</p> <p>Los informes de QRadar proporcionan al administrador de {{site.data.keyword.Bluemix_notm}} visibilidad sobre los sucesos y los datos de sucesos a través de la sección Informes y registros de la página Administración. Los informes de QRadar se generan de forma regular, ya sea diaria o mensualmente, según el tipo de informe. Todos los informes se conservan 90 días en la consola administrativa para su recuperación. Transcurridos 90 días, los informes están disponibles fuera de línea desde {{site.data.keyword.IBM_notm}} durante 9 meses. En total, los informes están disponibles para su recuperación un máximo de un año.</p> <p>No se incluyen datos de aplicaciones en el tráfico que consume QRadar. Los únicos datos que podrían considerarse como confidenciales son los ID de usuario de los informes sobre intentos de inicio de sesión y las direcciones IP de algunos componentes de {{site.data.keyword.Bluemix_notm}}. El tráfico a través de relé incluye los flujos entre el procesador de sucesos en QRadar de {{site.data.keyword.Bluemix_local_notm}} y una consola de QRadar del centro de {{site.data.keyword.IBM_notm}} Operations.</p> </dd> <dt> Actualizaciones en el despliegue y el mantenimiento </dt> <dd> Excepto por la instalación inicial de la VM inicial que se instala en la etapa temprana del proceso de despliegue, el despliegue de la mayoría de los demás componentes está automatizado mediante UrbanCode Deploy.<br> <p>Para la actividad de despliegue, UrbanCode Deploy se basa en [BOSH](https://bosh.cloudfoundry.org/){:new_window}; los componentes de BOSH se encuentran entre los primeros componentes desplegados desde VM inicial. Se utiliza la capacidad de entrega continua de UrbanCode Deploy para ofrecer actualizaciones de plataforma mediante un proceso coherente de pruebas y validaciones.</p> <p>Los scripts y paquetes se transfieren entre el centro de {{site.data.keyword.IBM_notm}} Operations y la plataforma de {{site.data.keyword.Bluemix_notm}} local a través de Relay.</p> </dd> <dt> Arreglos </dt> <dd> {{site.data.keyword.IBM_notm}} BigFix garantiza que las actualizaciones de seguridad de los sistemas operativos se aplican con la frecuencia adecuada. El proceso de aplicación de parches está automatizado, y la planificación se acuerda entre usted e IBM. </dd> <dt> Determinación de problemas y mantenimiento de emergencia </dt> <dd> {{site.data.keyword.IBM_notm}} proporciona una lista de los usuarios y los ID aprobados desde {{site.data.keyword.IBM_notm}} Operations que pueden acceder al entorno. Puede realizar una auditoría de los accesos al entorno desde la página Administración del entorno {{site.data.keyword.Bluemix_local_notm}}.<br> <p>Los usuarios de {{site.data.keyword.IBM_notm}} Operations solo accederán al entorno {{site.data.keyword.Bluemix_local_notm}} para ver detalles del estado de la plataforma. El equipo de operaciones nunca accede al código ni a los datos de la aplicación, y solo ejecuta los mandatos necesarios para la determinación de problemas para comprobar configuraciones o parámetros en casos de emergencia para llevar a cabo operaciones que no están automatizadas. Ninguno de estos mandatos transfiere datos confidenciales sobre la relé.</p> <p>El acceso al entorno local está protegido mediante la autenticación de dos factores durante los diversos pasos del proceso de conexión. Mediante la generación de un informe de seguridad puede saber quién ha accedido al entorno, incluido cuándo y por qué ha accedido.</p> <p>El tráfico sobre relé para la determinación de problemas y el mantenimiento de emergencia es tráfico SSH; se utiliza tráfico LDAP y Kerberos para autenticar a los usuarios de {{site.data.keyword.IBM_notm}}.<br> El entorno está completamente visible para usted, como administrador, para gestión de incidencias, problemas, cambios, capacidad y seguridad. Puede acceder a la información sobre su entorno usando la página de Administración. La tecnología Relay mantiene actualizada la página Administración con los datos de sucesos de la plataforma más recientes de QRadar. </p> </dd> </dl> ## Configuración de la instancia de {{site.data.keyword.Bluemix_local_notm}} {: #setuplocal} {{site.data.keyword.Bluemix_local_notm}} se ha diseñado para proporcionar una versión privada del producto {{site.data.keyword.Bluemix_notm}} público alojado en su propio hardware, gestionado por el usuario. Puede utilizar servicios y tiempos de ejecución de {{site.data.keyword.Bluemix_notm}} para satisfacer sus necesidades de cálculo en un entorno de nube seguro, alojado por el cliente y gestionado. {{site.data.keyword.IBM_notm}} le proporciona acceso a {{site.data.keyword.Bluemix_local_notm}} mediante un inicio de sesión protegido por contraseña. Puede acceder a los servicios, tiempos de ejecución y recursos asociados, y desplegar y eliminar apps {{site.data.keyword.Bluemix_notm}}. Revise los pasos siguientes para trabajar con el representante de {{site.data.keyword.IBM_notm}} para configurar la instancia local de {{site.data.keyword.Bluemix_notm}}. Para configurar su versión privada de {{site.data.keyword.Bluemix_notm}}: <ol> <li>Revise los requisitos de infraestructura de <a href="index.html#localinfra" title="Se abre en una nueva ventana">{{site.data.keyword.Bluemix_local_notm}}</a> para configurar la instancia local.</li> <li>Póngase en contacto con el representante designado de la cuenta de {{site.data.keyword.IBM_notm}} o con el equipo de <a href="https://console.ng.bluemix.net/?direct=classic/#/contactUs/cloudOEPaneId=contactUs" target="_blank">{{site.data.keyword.Bluemix_notm}}</a> para empezar a trabajar.</li> <li>Establezca su acuerdo de {{site.data.keyword.Bluemix_local_notm}} con {{site.data.keyword.IBM_notm}}, que incluye fechas de objetivo de entrega. <ol type="a"> <li>Trabaje con IBM sobre su configuración de una sola vez y sobre los cargos mensuales recurrentes para su instancia de {{site.data.keyword.Bluemix_notm}} Local. El cargo mensual se basa en los servicios locales que desee utilizar, más una suscripción a todos los servicios públicos de {{site.data.keyword.Bluemix_notm}}. Recibirá una factura por todo lo que utilice por encima del acuerdo de suscripción.</li> <li>Identifique los plazos límite para cada fase de la configuración de la instancia de {{site.data.keyword.Bluemix_local_notm}}.</li> </ol> </li> <li>Una vez que se cree la plataforma y la cuenta, identifique las personas de la organización para los roles necesarios para configurar y activar la instancia local. Para obtener más información sobre los roles que puede asignar, consulte el apartado sobre <a href="/docs/local/index.html#rolesresponsibilities" target="_blank">Roles y responsabilidades de {{site.data.keyword.Bluemix_notm}} local</a>. </li> <li>El usuario proporciona el hardware e {{site.data.keyword.IBM_notm}} le ayuda a definir y a establecer la conectividad de red entre su red corporativa y la instancia de {{site.data.keyword.Bluemix_local_notm}}. Para obtener más información sobre los requisitos de la infraestructura, consulte requisitos de la infraestructura de <a href="index.html#localinfra">{{site.data.keyword.Bluemix_local_notm}}</a>. <ol type="a"> <li>{{site.data.keyword.IBM_notm}} configura el acceso a la red y LDAP en función de lo que proporcione el usuario. Se ofrece acceso de administración a los contactos que designe el cliente. También debe designar un contacto para soporte y facturación.</li> <li>{{site.data.keyword.IBM_notm}} configura un catálogo sindicado en el entorno local para mostrar los servicios locales y muchos de los servicios públicos de {{site.data.keyword.Bluemix_notm}}.</li> <li>El cliente debe validar la configuración de la red y del cortafuegos, además del punto final LDAP y el acceso.</li> </ol> </li> </ol> Puede prever un proceso similar a la siguiente lista para el despliegue y la configuración iniciales de su entorno. Para obtener detalles sobre la persona responsable de cada tarea, consulte [Roles y responsabilidades](/docs/local/index.html#rolesresponsibilities). <ol> <li>Proporcione la configuración de VMware que cumpla las especificaciones para calcular recursos, la red y el almacenamiento. Para obtener más información sobre los requisitos de la infraestructura, consulte requisitos de la infraestructura de <a href="/docs/local/index.html#localinfra">{{site.data.keyword.Bluemix_notm}} local</a>.</li> <li>Proporcione las credenciales de clúster de vCenter que utilizará la máquina virtual inicial. Debe proporcionar la siguiente información: <ul> <li>Nombre del clúster VMware</li> <li>Credenciales del clúster vCenter incluidos el ID de usuario y la contraseña</li> <li>Nombre o nombres del almacén de datos (nombre del LUN de almacenamiento)</li> <li>ID de VLAN/grupo de puertos VMware</li> <li>Nombre de agrupación de recursos</li> </ul> </li> <li>Usted e {{site.data.keyword.IBM_notm}} trabajan conjuntamente para validar las credenciales que ha proporcionado en la tarea anterior.</li> <li>Debe proporcionar 7 direcciones IP en la red. Si tiene un proxy web protegido para permitir el acceso de salida a Internet para componentes internos de {{site.data.keyword.Bluemix_notm}}, debe proporcionar las credenciales para conectarse a él. <p>**Nota**: Si el proxy web no es seguro, no necesita proporcionar las credenciales. Además, tenga en cuenta que no todos los clientes de {{site.data.keyword.Bluemix_local_notm}} utilizan un proxy web.</p></li> <li>{{site.data.keyword.IBM_notm}} proporciona una lista blanca de los URL que deben estar permitidos a través del proxy web antes de iniciar el despliegue.<br /> <p>**Nota**: para garantizar que las aplicaciones nuevas y existentes puedan acceder a los recursos necesarios, es posible que deba realizar pasos adicionales para empaquetar los recursos con el paquete de compilación, o trabajar con el equipo de seguridad para crear una lista blanca con los URL necesarios para ejecutar las aplicaciones. Para obtener más información sobre cómo trabajar con paquetes de compilación de node.js y Liberty for Java, consulte <a href="../runtimes/nodejs/offlineMode.html">Modalidad fuera de línea para node.js</a> y <a href="../runtimes/liberty/offlineMode.html">Modalidad fuera de línea para Liberty for Java</a>.</p> </li> <li>Debe especificar los nombres de dominio para el despliegue, y los ID que desea utilizar. Obtendrá dos dominios definidos parcialmente al configurar la instancia local, y seleccione el prefijo para los dos dominios. Por ejemplo, seleccione el prefijo para <code>*mycompany*.bluemix.net</code> y <code>*mycompany*.mybluemix.net</code>. Y, a continuación, también puede seleccionar el dominio completo para crear un dominio personalizado.<br /> <p>Puede elegir tantos dominios personalizados como desee. Sin embargo, el usuario es responsable de los certificados para los dominios personalizados. Para obtener información sobre cómo crear el dominio personalizado, consulte <a href="../manageapps/updapps.html#domain">Creación y utilización de un dominio personalizado</a>.</p></li> <li>Puede elegir qué tecnología, IPSec o túnel OpenVPN utilizará para configurar el Relé para volver a conectarse al centro de operaciones de {{site.data.keyword.IBM_notm}}.</li> <li>{{site.data.keyword.IBM_notm}} instala e inicia la máquina virtual inicial dentro del clúster de {{site.data.keyword.Bluemix_notm}}. Si proporciona su propio VMware, un representante de {{site.data.keyword.IBM_notm}} ayuda al representante del cliente a completar esta tarea.</li> <li>{{site.data.keyword.IBM_notm}} configura el Relé para comunicarse de nuevo con el centro de operaciones de {{site.data.keyword.IBM_notm}}.</li> <li>El repositorio de máquina virtual inicial detiene los artefactos de compilación actualizados.</li> <li>Proporcione las credenciales correspondientes a {{site.data.keyword.IBM_notm}} para conectarse con la instancia de directorios LDAP corporativos.</li> <li>{{site.data.keyword.IBM_notm}} utiliza la automatización para desplegar la plataforma central de {{site.data.keyword.Bluemix_notm}}.</li> <li>{{site.data.keyword.IBM_notm}} despliega la plataforma principal que incluye los tipos de ejecución elásticos, la consola, la función de administración y la supervisión.</li> <li>{{site.data.keyword.IBM_notm}} configura el acceso administrativo al entorno.</li> <li>{{site.data.keyword.IBM_notm}} enlaza el catálogo sindicado desde el despliegue local a una instancia pública de {{site.data.keyword.Bluemix_notm}} para su uso de los servicios públicos. Hay disponible un conjunto de servicios públicos en la instancia local de forma predeterminada. Puede utilizar la página de administración para la gestión de catálogos para activar o desactivar los servicios para la instancia local.</li> <li>Puede empezar a utilizar la instancia local supervisada por el equipo de operaciones de {{site.data.keyword.IBM_notm}} para responder a las alertas.</li> </ol> Una vez que se configure la instancia de {{site.data.keyword.Bluemix_notm}}, puede supervisar y gestionar la instancia de {{site.data.keyword.Bluemix_notm}} utilizando la página Administración. Para obtener más información, consulte [Gestión de {{site.data.keyword.Bluemix_local_notm}} y dedicado](../admin/index.html#mng). Para obtener información sobre las actualizaciones y el mantenimiento, consulte [Mantenimiento de la instancia local](index.html#maintainlocal). ##Roles y responsabilidades {: #rolesresponsibilities} Si establece una cuenta de {{site.data.keyword.Bluemix_local_notm}}, puede identificar a las personas de su organización para los roles necesarios para configurar y activar la instancia. ###Roles La lista siguiente muestra los roles y responsabilidades de cliente que se asignan: <dl> <dt>**Contacto de suministro**</dt> <dd>Trabaja con el representante de {{site.data.keyword.IBM_notm}} en el establecimiento del entorno de {{site.data.keyword.Bluemix_local_notm}}, incluida la identificación de las personas adecuadas de la organización que trabajarán en cualquier aspecto del proyecto. La persona asignada a este rol supervisa la selección del patrón, las formas comerciales y la disposición de acceso a los recursos del cliente. El contacto de suministro es el contacto general para configurar la instancia local.</dd> <dt>**Responsable de suministro**</dt> <dd>Trabaja con el representante de {{site.data.keyword.IBM_notm}} para seleccionar una topología y opción de despliegue que se ajuste a sus requisitos de seguridad. La persona asignada a este rol trabaja con el asesor de suministro de {{site.data.keyword.IBM_notm}} para determinar qué patrones de despliegue consiguen los objetivos y las metas de conformidad.</dd> <dt>**Especialista en redes**</dt> <dd>Trabaja con el representante de {{site.data.keyword.IBM_notm}} en los planes de red para el despliegue de {{site.data.keyword.Bluemix_notm}}. La persona asignada a este rol revisa las especificaciones de red necesarias para {{site.data.keyword.IBM_notm}} y trabaja conjuntamente con {{site.data.keyword.IBM_notm}} en un plan de implementación. Al final de la fase de instalación y de verificación, la persona asignada a este rol concluirá que la configuración de red está en conformidad con los estándares corporativos.</dd> <dt>**Contacto de DevOps**</dt> <dd>Trabaja con el representante de {{site.data.keyword.IBM_notm}} para planificar y aplicar las actualizaciones de mantenimiento necesarias para la plataforma, servicios y tiempos de ejecución de {{site.data.keyword.Bluemix_notm}}. La persona asignada a este rol también trabaja con el representante de {{site.data.keyword.IBM_notm}} en la configuración de la instancia de {{site.data.keyword.Bluemix_local_notm}}.</dd> <dt>**Especialista IaaS**</dt> <dd>Trabaja con los representantes de {{site.data.keyword.IBM_notm}} en el plan de despliegue para VMware. Normalmente se trata de algún administrador de VMware en el centro de datos. La persona asignada a este rol revisa los <a href="../local/index.html#localinfra">requisitos de infraestructura de {{site.data.keyword.Bluemix_local_notm}}</a> y trabaja conjuntamente con {{site.data.keyword.IBM_notm}} en un plan de implementación. Al final del despliegue, la persona asignada a este rol concluye que el despliegue cumple los estándares corporativos en la capa IaaS.</dd> <dt>**Contacto de operaciones**</dt> <dd>Trabaja con el equipo de soporte de {{site.data.keyword.IBM_notm}} cuando sea necesario una vez el entorno está activo y en ejecución. Se trata de alguien con acceso de **Superusuario** a la consola de administración que puede aprobar y planificar actualizaciones de mantenimiento para el entorno {{site.data.keyword.Bluemix_notm}} y que está siempre disponible en el caso de que se produzca un incidente crítico. La persona asignada a este rol debe tener conocimientos técnicos del entorno {{site.data.keyword.Bluemix_notm}} y debe tener capacidad para establecer contacto con la persona de la organización con los conocimientos específicos del área que se vea afectada, incluidas, por ejemplo, las áreas de red o de seguridad. </dd> </dl> Los representantes de los clientes trabajan con los especialistas de {{site.data.keyword.IBM_notm}} que trabajan conjuntamente para asegurarse de que siempre tenga el soporte que necesita. Puede actualizar al nivel de soporte Premium para trabajar con un CSM (Client Success Manager) dedicado para su cuenta. Para obtener más información sobre los distintos niveles de soporte, consulte [Cómo obtener soporte](../support/index.html#contacting-support). El CSM completa los siguientes tipos de tareas: <ul> <li>Ofrece coordinación técnica entre usted e IBM.</li> <li>Coordina actualizaciones, ayuda de expertos de IBM y una habilitación inicial de un ingeniero de soporte de {{site.data.keyword.Bluemix_notm}}.</li> <li>Proporciona información sobre los tipos de soporte que están disponibles.</li> <li>Actúa como punto de escalada inicial, si es necesario.</li> </ul> El equipo de soporte y operaciones de {{site.data.keyword.Bluemix_notm}} que trabaja con usted en la instancia de {{site.data.keyword.Bluemix_notm}} puede acceder a su entorno local, pero solo por los siguientes motivos: <ul> <li>Para responder a las alertas y realizar tareas de mantenimiento operativo</li> <li>Para intentar reproducir un problema notificado en una incidencia de soporte</li> </ul> ###Responsabilidades Desde configurar su entorno hasta efectuar tareas de mantenimiento continuado, hay una gran variedad de tareas que deben llevar a cabo usted e IBM. En las tablas siguientes se describen las tareas necesarias, así como los encargados de llevar a cabo la tarea durante la fase inicial, de progresión y de finalización. La fase inicial se utiliza para establecer el entorno de {{site.data.keyword.Bluemix_local_notm}}. En este punto, ya ha revisado los [requisitos de la infraestructura local](../local/index.html#localinfra). Los objetivos principales de dicha fase son los siguientes: - Revisar el acuerdo financiero y establecer las fechas objetivo para la entrega. - Crear la plataforma {{site.data.keyword.Bluemix_notm}} y proporcionar acceso a tiempos de ejecución y servicios. - Definir y establecer la conectividad de red entre su red corporativa y las operaciones de {{site.data.keyword.Bluemix_notm}}. - Identificar y asignar roles al equipo de administración. | **Tarea** | **Detalles de la tarea** | **Parte responsable** | |----------|------------------|-----------------------| |Establecer estándares de conformidad | Identificar estándares gubernamentales, sectoriales y de propiedad corporativa necesarios para el entorno. | Cliente | |Crear un plan de seguridad y de integración de conformidad | Crear un plan de seguridad e integración que incluya costes, planificación y recursos necesarios para conseguir la conformidad de seguridad. | {{site.data.keyword.IBM_notm}} | |Aprobación de un plan de conformidad | Aprobar el plan de conformidad. | Cliente | |Crear una variación de tamaño para los entornos | Crear una variación de tamaño de los entornos en función de opciones predefinidas que tengan en cuenta los objetivos de alta disponibilidad y la recuperación en caso de error, así como el DEA inicial y el suministro de servicios necesario para dar soporte a las apps creadas con la plataforma. Usted e {{site.data.keyword.IBM_notm}} trabajan conjuntamente para definir, por ejemplo, qué bases de datos son necesarias, qué servicios se ofrecen en el catálogo sindicado del cliente, entre otros. | {{site.data.keyword.IBM_notm}} y el cliente comparten responsabilidades | |Seleccionar una arquitectura | Seleccionar una arquitectura basada en opciones predefinidas que tengan en cuenta requisitos de alta disponibilidad y de recuperación en caso de desastre. | {{site.data.keyword.IBM_notm}} | |Definir objetivos de recuperación en caso de error | Definir los requisitos de recuperación en caso de error para el entorno. | Cliente | |Crear un plan de recuperación en caso de error | Consultar y definir el plan de recuperación en caso de error. {{site.data.keyword.IBM_notm}} crea un modelo de recuperación en caso de error y le consulta dónde debe proporcionar comentarios y aprobar el plan. | {{site.data.keyword.IBM_notm}} y el cliente comparten responsabilidades | |Crear un plan de copia de seguridad y recuperación | Crear un plan de copia de seguridad y recuperación que defina la frecuencia y los requisitos para la distribución interna y externa de la copia de seguridad. {{site.data.keyword.IBM_notm}} realiza una copia de seguridad de componentes de plataforma, servicios de {{site.data.keyword.IBM_notm}}, metadatos de servicios (roles de usuarios), etc. Debe realizar una copia de seguridad de todos los datos específicos de app de los que sea responsable. | {{site.data.keyword.IBM_notm}} y el cliente comparten responsabilidades | |Identificar herramientas para la detección de sucesos y la determinación de problemas | Identificar herramientas de {{site.data.keyword.IBM_notm}} y de terceros utilizadas para la detección de sucesos y la determinación de problemas en el nivel de plataforma de {{site.data.keyword.Bluemix_notm}}. | {{site.data.keyword.IBM_notm}} | |Definir un plan de escalamiento | Definir el plan de escalamiento para seleccionar y resolver sucesos detectados desde los componentes de supervisión. | {{site.data.keyword.IBM_notm}} | |Firmar acuerdos de infraestructuras, plataformas y soporte | Firmar el acuerdo de suscripción, incluidos los términos y condiciones financieros del entorno. Firmar la suscripción de soporte. | Cliente | |Obtener un entorno | Conseguir recursos informáticos, de redes y almacenamiento. Para obtener más información sobre los requisitos de la infraestructura del entorno, consulte los [requisitos de la infraestructura local](../local/index.html#localinfra). | Cliente | |Instalar una solución VPN | Instalar una solución VPN bidireccional. | {{site.data.keyword.IBM_notm}} | |Instalar plataforma, aplicación, y componentes de supervisión y gestión | Instalar, configurar y verificar componentes de plataforma, como BOSH Director, Cloud Controller, Health Manager, mensajería, routers, DEA y proveedores de servicios y los componentes de supervisión definidos en el plan de escalamiento y detección de problemas. | {{site.data.keyword.IBM_notm}} | |Instalar y configurar componentes de seguridad | Instalar y configurar componentes de seguridad enlazados con el plan de supervisión y escalamiento, incluyendo {{site.data.keyword.IBM_notm}} QRadar, almacén de credenciales, sistema de prevención de intrusión, {{site.data.keyword.IBM_notm}} BigFix e {{site.data.keyword.IBM_notm}} Security Privileged Identity Management. | {{site.data.keyword.IBM_notm}} | |Configurar un servidor de inicio de sesión | Configurar el servidor de inicio de sesión para utilizarlo con el LDAP corporativo. | {{site.data.keyword.IBM_notm}} | |Instalar y configurar componentes personalizados | Instalar y configurar componentes personalizados que residen fuera del ámbito del producto y los servicios de {{site.data.keyword.Bluemix_notm}}. | Cliente | |Conectar el conducto de {{site.data.keyword.Bluemix_notm}} | Conectar la integración continua y el conducto de entrega continua de {{site.data.keyword.Bluemix_notm}} con repositorios de {{site.data.keyword.IBM_notm}}. | {{site.data.keyword.IBM_notm}} | |Personalizar componentes de soluciones externas | Personalizar equilibradores de carga para escenarios de recuperación en caso de error. | Cliente | |Hacer un seguimiento del estado de la seguridad, la conformidad y los controles de auditoría | Hacer un seguimiento del estado hasta el punto en que todas las herramientas y procesos estén en regla para conseguir la conformidad identificada. | Cliente | |Revisar la infraestructura física | Revisar las instalaciones físicas que alojan los componentes de la solución para detectar amenazas y revisar los controles de seguridad para proteger el centro de datos. | Cliente | |Inspeccionar el software de supervisión | Inspeccionar los componentes de supervisión y gestión, como se define en el plan de escalamiento y determinación de problemas. | Cliente | |Inspeccionar el SO | Inspeccionar y asegurarse de que la imagen del sistema operativo cumple los estándares de conformidad. {{site.data.keyword.IBM_notm}} proporciona acceso a la imagen del SO. | {{site.data.keyword.IBM_notm}} y el cliente comparten responsabilidades | {: caption="Table 5. Inception phase tasks" caption-side="top"} A continuación tenemos la fase de progresión. En la fase de progresión se describe la relación de colaboración entre usted e IBM. Los objetivos principales de esta fase son los siguientes: - Revisar la capacidad y coordinar los ajustes necesarios. - Revisar el mantenimiento y las mejoras en la plataforma. - Coordinar las actividades para la resolución de problemas y analizar las causas originarias. | **Tarea** | **Detalles de la tarea** | **Parte responsable** | |----------|------------------|-----------------------| |Revisar informes de capacidad semanalmente | Revisar los informes de capacidad semanalmente y tomar acciones de corrección, si procede. | Cliente | |Crear proyecciones mes a mes | Recopilar información y crear una proyección mes a mes de la capacidad y el consumo. | {{site.data.keyword.IBM_notm}} y el cliente comparten responsabilidades | |Revisar las proyecciones de capacidad | Revisar las proyecciones de capacidad relacionadas con sucesos externos que puedan afectar a la capacidad, así como la previsión de nuevos despliegues de apps. Trabajar con {{site.data.keyword.IBM_notm}} para revisar las proyecciones y efectuar una planificación según convenga. | {{site.data.keyword.IBM_notm}} y el cliente comparten responsabilidades | |Ajustar la capacidad | Añadir o eliminar capacidad a medida que cambien sus necesidades. | {{site.data.keyword.IBM_notm}} | |Publicar actualizaciones venideras y realizar mantenimiento | Crear documentación para el mantenimiento necesario de los componentes de {{site.data.keyword.IBM_notm}}. | {{site.data.keyword.IBM_notm}} | |Realizar tareas de mantenimiento | Trabajar con {{site.data.keyword.IBM_notm}} para planificar tareas de mantenimiento necesarias en un intervalo de 21 días. Puede proporcionar fechas que no le vayan bien en dicho período de 21 días, e {{site.data.keyword.IBM_notm}} trabajará para planificar el mantenimiento según convenga. | {{site.data.keyword.IBM_notm}} y el cliente comparten responsabilidades | |Abordar fallos de aprovisionamiento | Corregir fallos de aprovisionamiento, si se producen, de los servicios creados por el cliente desplegados en el catálogo. | {{site.data.keyword.IBM_notm}} | |Realizar exploraciones de red y de IP | Realizar exploraciones diarias y mensuales de red y de IP. | {{site.data.keyword.IBM_notm}} y el cliente comparten responsabilidades | |Proporcionar acceso a los registros de auditoría | Proporcionar acceso a todos los registros de auditoría de seguridad y administración. | {{site.data.keyword.IBM_notm}} y el cliente comparten responsabilidades | |Realizar pruebas | Realizar pruebas Key Controls over Operations (KCO) periódicas y pruebas de penetración de terceros. | {{site.data.keyword.IBM_notm}} y el cliente comparten responsabilidades | |Informes de estado, coordinación de auditorías y reuniones de conformidad | Efectuar informes de estado, coordinación de auditorías externas y representación en reuniones de estado de revisión de conformidad. | {{site.data.keyword.IBM_notm}} | |Verificación de necesidades empresariales y de ocupación | Efectuar verificaciones de ocupación trimestrales y verificaciones de necesidades empresariales continuadas para los representantes de {{site.data.keyword.IBM_notm}} que tienen acceso al entorno del cliente. | {{site.data.keyword.IBM_notm}} | |Resolución de vulnerabilidades de seguridad | Resolver vulnerabilidades de seguridad notificadas en la plataforma. | {{site.data.keyword.IBM_notm}} | {: caption="Table 6. Progression phase tasks" caption-side="top"} La etapa final de la finalización representa el final de la relación entre usted e {{site.data.keyword.IBM_notm}} {{site.data.keyword.Bluemix_notm}}. Las tareas principales de esta fase son las siguientes: * Finalización del acuerdo financiero * Eliminación de todas las conexiones de red * Reciclaje de la infraestructura | **Tarea** | **Detalles de la tarea** | **Parte responsable** | |----------|------------------|-----------------------| |Finalizar el acuerdo financiero | Debatir y acordar el contrato del acuerdo financiero. | {{site.data.keyword.IBM_notm}} y el cliente comparten responsabilidades | |Retirar el entorno | Cerrar el acceso y retirar las credenciales del entorno. | {{site.data.keyword.IBM_notm}} y el cliente comparten responsabilidades | |Finalizar el relé | Terminar la conexión del relé. | {{site.data.keyword.IBM_notm}} | |Reciclar la infraestructura | Reciclar la infraestructura de acuerdo con las directrices de la empresa. | Cliente | {: caption="Table 7. Completion phase tasks" caption-side="top"} ## Requisitos de la infraestructura de {{site.data.keyword.Bluemix_local_notm}} {: #localinfra} En {{site.data.keyword.Bluemix_local_notm}}, usted es el propietario de la seguridad física y de la infraestructura para alojar la instancia local. {{site.data.keyword.IBM_notm}} establece los siguientes requisitos mínimos para configurar {{site.data.keyword.Bluemix_local_notm}}. ### Hardware Aunque hay requisitos para el tipo y el tamaño del hardware disponible, puede elegir cualquier combinación que cumpla los requisitos totales de los recursos definidos. <dl> <dt>**Hardware VMware ESXi**</dt> <dd> ESXi es una capa de virtualización que se ejecuta en servidores físicos y que abstrae el procesador, la memoria, el almacenamiento y los recursos en varias máquinas virtuales. Elija cualquier combinación que cumpla los siguientes totales de recursos, con la condición de que el recuento mínimo de núcleos físicos por ESXi sea ocho. Las siguientes especificaciones son sólo para el tiempo de ejecución de núcleo de {{site.data.keyword.Bluemix_notm}}. <ul> <li>32 núcleos físicos a 2.0 o más GHz cada uno de ellos</li> <li>512 GB de memoria RAM física</li> <li>Tamaño total de almacenes de datos: 7,5 TB <ul> <li>7 TB de almacén de datos para alojar {{site.data.keyword.Bluemix_notm}}</li> <li>500 GB de almacén de datos para alojar la máquina virtual inicial</li> </ul> </li> </ul> <p><strong>Nota:</strong> Si utiliza varios almacenes de datos, utilice el mismo prefijo para cada uno de ellos.</p> </dd> <dt>**Alta disponibilidad**</dt> <dd> Para poder dar soporte a un solo error de nodo debe tener n+1 ESXi. Por ejemplo, si los 32 núcleos y 512 GB de memoria se cumplen utilizando servidores de dos núcleos 16x con 256 GB ESXi, necesitará tres de estos servidores para dar soporte al fallo completo de un nodo individual. <p><strong>Nota:</strong> El administrador de VMware del cliente puede optar por aplicar una migración tras error estricta de alta disponibilidad en el clúster para garantizar los recursos. Si decide continuar sin migración tras error de alta disponibilidad, puede cumplir el requisito mínimo de recursos de 32 núcleos y 512 GB.</p> </dd> <dt>**Red**</dt> <dd> Entre los requisitos recomendados se incluye un grupo de puertos accesibles para el cliente con siete direcciones IP de red del cliente que tienen acceso saliente a Internet en la misma subred. La máquina virtual inicial utiliza dos puertos, tres puertos son direcciones IP virtuales utilizadas para los dominios, y las últimas dos son direcciones IP públicas para el DataPowers. A continuación, defina una segunda VLAN privada sólo entre los ESXi utilizados para {{site.data.keyword.Bluemix_local_notm}}. Esta VLAN se muestra como un grupo de puertos en VMware. {{site.data.keyword.Bluemix_local_notm}} lo utiliza para la subred privada, que es más segura y puede ayudar a evitar problemas de direccionamiento.<br /> <p>Se utilizarán los puertos siguientes:</p> <ul> <li>Puerto 443 para la conexión de relé <p>**Nota**: Si elige utilizar un túnel IPSec en lugar de una OpenVPN, abra a continuación un puerto de cliente para esta conexión.</p></li> <li>Puerto 389 o SSL 636 para la conexión LDAP o Active Directory</li> </ul> <p>**Nota**: {{site.data.keyword.IBM_notm}} puede detectar si se ha perdido la conexión de red. En caso de que se pierda la conexión de red, {{site.data.keyword.IBM_notm}} se pondrá en contacto con usted y trabajará con el especialista de red para resolver el problema.</p> </dd> <dt>**Enlaces de red**</dt> <dd>Utilice dos o más interfaces de 1 a 10 Gbps, según la carga de trabajo esperada para el sistema.</dd> </dl> ### Configuración de servidor de vCenter Revise los siguientes requisitos relacionados con la versión, el centro de datos, la agrupación de recursos y el almacén de datos. <dl> <dt>**Versiones soportadas de VMware**</dt> <dd>vCenter y ESXi 5.1, 5.5 y 6.0</dd> <dt>**Tipos soportados de VMware**</dt> <dd>vSphere Enterprise<br /> vSphere Enterprise más, si tiene pensado utilizar conmutadores virtuales distribuidos</dd> <dt>**Centro de datos**</dt> <dd>Cree un centro de datos (si no hay ninguno).</dd> <dt>**Carpeta del centro de datos**</dt> <dd>Cree una carpeta de la máquina virtual con el mismo nombre que el clúster si no tiene pensado otorgar un acceso de administrador que se propague desde el centro de datos.</dd> <dt>**Clúster**</dt> <dd>Cree un clúster específicamente para {{site.data.keyword.Bluemix_local_notm}}. Un ejemplo del nombre del clúster sería `bluemix`.</dd> <dt>**Agrupación de recursos**</dt> <dd>Cree una agrupación de recursos en el clúster de {{site.data.keyword.Bluemix_local_notm}}. Un ejemplo del nombre de la agrupación de recursos sería `local`.</dd> </dt>**Almacenes de datos**</dt> <dd>Requiere 7,5 TB para el despliegue inicial de {{site.data.keyword.Bluemix_notm}}.<br /> <br /> **Nota**: Si utiliza más de un almacén de datos, asegúrese de que todos ellos empiezan con el mismo prefijo. Un ejemplo de varios nombres de almacén de datos con el mismo prefijo sería `almacén_datos_bluemix_01` y `almacén_datos_bluemix_02`.</dd> <dt>**Red**</dt> <dd>Debe tener una red accesible de cliente con capacidad de Internet de salida. La VLAN aloja la subred privada en la que se ejecutan los componentes del Bluemix local. Todo el tráfico se direcciona desde la subred privada a la subred del cliente. Se utiliza una IP de subred de cliente para todos los accesos al Bluemix local. A continuación, puede definir una segunda VLAN privada solo entre los ESXi que se utilizan para el Bluemix local. Esta VLAN se muestra como un grupo de puertos en VMware. El Bluemix local la utiliza para la subred privada, que es más segura y puede ayudar a evitar problemas de direccionamiento. <p>Si utiliza conmutadores distribuidos de vSphere (vDS), cree una carpeta para alogar los vDS, y colóquelos en la carpeta.</p> </dl> ### Ancho de banda de red para Relay El rendimiento recomendado es de 5 Mbps de subida y de 5 Mbps de bajada; puede esperar un uso de datos mensual de 10 GB. {{site.data.keyword.IBM_notm}} establece ventanas acordadas cuando se entregan paquetes de datos grandes, que pueden tener un tamaño de 4 GB. ### Permisos de VMware Establezca los siguientes roles y permisos. La propagación se establece para cada permiso. Si el permiso se propaga, pasa por la jerarquía de objetos. Sin embargo, los permisos de un objeto hijo siempre sustituyen los permisos que se propagan desde un objeto padre. <dl> <dt>**Servidor vCenter**</dt> <dd>Establezca el rol como de solo lectura y propagado.<br /> <br /> **Nota**: Este rol es necesario para recuperar estados de tareas de determinadas operaciones de disco.</dd> <dt>**Centro de datos**</dt> <dd>Crear el rol "{{site.data.keyword.Bluemix_notm}}" y otorgarle los permisos siguientes: <ul> <li>Para **Datastore**, establecer **Operaciones de archivo de bajo nivel** y **Actualizar archivos de máquina virtual**.</li> <li>Para **vApp**, establecer **Importar**.</li> <li>Para el grupo **dvPort**, establecer **Modificar**. Esto solo es para uso de vDS.</li> </ul> **Nota**: Este rol es necesario para poder dar soporte a las publicaciones de archivos en los almacenes de datos.</dd> <dt>**Clúster**</dt> <dd>Establezca el rol como administrador y propagado.</dd> <dt>**Almacenes de datos**</dt> <dd>Establezca el rol administrador y propagado para cada almacén de datos de {{site.data.keyword.Bluemix_notm}}.</dd> <dt>**Red**</dt> <dd><ul> <li>Para vSwitch, establecer grupos de puertos públicos y privados con el rol de administrador, no con el rol propagado.</li> <li>Para la carpeta padre vDS, establecer como sólo lectura y propagado.</li> <li>Para vDS, establecer grupos de puertos públicos y privados con el rol de administrador, no con el rol propagado.</li> </ul> </dd> </dl> ### Aumento de la agrupación de agentes de ejecución de gotas (DEA) Cada DEA está configurado con: - 16 o 32 GB de RAM - vCPU 2x o 4x - 150 o 300 GB de almacenamiento Por ejemplo, si el tamaño de host ESXi es de 256 GB de memoria con 16x núcleos, se añaden ocho DEA. Si el tamaño de host ESXi es de 64 GB de memoria con 8x núcleos, se deben añadir dos ESXi y cuatro DEA. Se necesita 1,5 TB más de almacenamiento para cada cuatro DEA. Este ejemplo se basa en un DEA configurado con 32 GB de RAM, 4x vCPU y 300 GB de almacenamiento. ## Mantenimiento de la instancia local {: #maintainlocal} {{site.data.keyword.IBM_notm}} mantiene e instala actualizaciones y arreglos en los tiempos de ejecución y servicios de {{site.data.keyword.Bluemix_notm}}, como {{site.data.keyword.IBM_notm}} considere adecuado. Es posible que los servicios no estén disponibles durante las ventanas de mantenimiento. Además, {{site.data.keyword.IBM_notm}} trabaja con usted para planificar actualizaciones de mantenimiento para la plataforma {{site.data.keyword.Bluemix_notm}}. ### Mantenimiento de {{site.data.keyword.Bluemix_notm}} Se requieren los siguientes tipos de mantenimiento para {{site.data.keyword.Bluemix_local_notm}}: <dl> <dt>**Mantenimiento estándar para servicios**</dt> <dd>Los servicios utilizan ventanas de mantenimiento estándar y predefinidas, lo cual podría hacer que los servicios no estén disponibles. {{site.data.keyword.IBM_notm}} no requiere aprobación del cliente para realizar el mantenimiento de servicios, aunque intenta minimizar el impacto en los servicios.<br /> <br /> {{site.data.keyword.IBM_notm}} envía mensajes de difusión general detallando los cambios planificados para cada ventana de mantenimiento en la página Estado.<br /> <br /> **Importante**: algunos servicios pueden no estar disponible durante el periodo de mantenimiento.</dd> <dt>**Mantenimiento estándar para la plataforma de {{site.data.keyword.Bluemix_notm}}**</dt> <dd>Las actualizaciones de mantenimiento se aplican en función de la coordinación entre el usuario e {{site.data.keyword.IBM_notm}} dentro de un periodo de 21 días. Usted proporciona a {{site.data.keyword.IBM_notm}} ventanas de mantenimiento y fechas u horas específicas aprobadas previamente que pueden no funcionar para usted, e {{site.data.keyword.IBM_notm}} trabaja para planificar actualizaciones durante o alrededor de las fechas seleccionadas.<br /> <p>Vaya a **ADMINISTRACIÓN > INFORMACIÓN DEL SISTEMA** para ver las actualizaciones de mantenimiento planificadas y pendientes. Para obtener más información sobre cómo establecer las ventanas aprobadas previamente y las fechas no disponibles y para visualizar o aprobar actualizaciones de mantenimiento planificadas, consulte <a href="../admin/index.html#oc_schedulemaintenance">Actualizaciones de mantenimiento</a>.</p></dd> </dl> **Importante**: {{site.data.keyword.IBM_notm}} se reserva el derecho de interrumpir servicios para aplicar mantenimiento emergencia si es necesario. {{site.data.keyword.IBM_notm}} puede modificar las horas de mantenimiento planificadas, pero le notificará de cualquier cambio, así como la información de mantenimiento de emergencia. Si hay un problema después de una actualización de mantenimiento, acuerda con el soporte de {{site.data.keyword.Bluemix_notm}} si le conviene permitir que {{site.data.keyword.IBM_notm}} retrotraiga la actualización. Si así se acuerda, {{site.data.keyword.IBM_notm}} retrotrae la actualización para restaurar el entorno al estado anterior. ### Mantenimiento de infraestructuras de cliente {: #inframaintenance} {{site.data.keyword.Bluemix_local_notm}} se despliega en el hipervisor ESXi, y la aplicación vCenter se utiliza para gestionar de forma centralizada las máquinas virtuales y los hosts ESXi. {{site.data.keyword.Bluemix_notm}} admite las tres últimas versiones de ESXi y vCenter, incluidas todas las actualizaciones y los parches intermedios. Siempre encontrará las últimas versiones admitidas en la documentación de [Requisitos de infraestructura local](../local/index.html#localinfra). **Importante**: si despliega {{site.data.keyword.Bluemix_local_notm}} en el hipervisor ESXi, las actualizaciones y los parches de ESXi pueden interferir en la disponibilidad del entorno local, incluidas todas las aplicaciones y servicios que se ejecuten en el entorno. Debe notificarlo a {{site.data.keyword.Bluemix_notm}} mediante una incidencia de soporte antes de completar o una actualización y parche para garantizar que la interrupción no alerte por error al equipo de operaciones. Si tiene asignado un CSM (client success manager), pueden trabajar conjuntamente para comunicar la programación de la actualización. A fin de garantizar que la instancia local es compatible con las últimas versiones admitidas, el equipo de operaciones de {{site.data.keyword.Bluemix_notm}} supervisa el entorno para determinar que versiones no admitidas pueden no coincidir con las últimas actualizaciones del entorno de {{site.data.keyword.Bluemix_notm}} Local. Algunas actualizaciones de {{site.data.keyword.Bluemix_notm}}, como las actualizaciones de la versión de Cloud Foundry, requieren actualizar el software de ESXi o vCenter. El equipo de soporte de {{site.data.keyword.Bluemix_notm}} le indicará qué actualizaciones debe hacer y cuándo debe hacerlas. Se le asignará un periodo determinado de tiempo para realizar la actualización. {{site.data.keyword.Bluemix_notm}} realiza todos los esfuerzos necesarios para que los entornos sean compatibles con las últimas versiones de ESXi y vCenter. Sin embargo, puede haber breves periodos de tiempo en los que las versiones más recientes de ESXi y vCenter no se admitan. Consulte en la documentación los [requisitos de la infraestructura local](/docs/local/index.html#localinfra) para obtener información sobre las últimas versiones compatibles antes de llevar a cabo alguna actualización. ## Respuesta y soporte de incidencias para {{site.data.keyword.Bluemix_local_notm}} {: #incidentresponse} ### Problemas detectados por el cliente Si detecta un problema que necesite la atención de operaciones y soporte de {{site.data.keyword.IBM_notm}} puede ponerse en contacto con el soporte mediante diversos métodos. Para obtener información sobre cómo contactar con el soporte, consulte [Cómo obtener soporte](../support/index.html#contacting-bluemix-support-local). Según la naturaleza del problema, el usuario, IBM o ambos pueden trabajar para solucionarlo. ### Incidencias críticas detectadas por IBM Las incidencias críticas son urgentes, cortes de servicio inesperados y problemas de estabilidad que afectan a su entorno o sus usuarios. Si {{site.data.keyword.IBM_notm}} detecta una incidencia crítica en su entorno, se le envía una notificación en la página **Estado**. También se puede revisar la página Estado para buscar problemas conocidos para la plataforma o sus servicios. Para obtener más información sobre la página Estado, consulte [Visualización de estado](../admin/index.html#oc_status). Si quiere integrar sus notificaciones con un servicio web que admita ganchos (hooks), consulte [Notificaciones y suscripciones de sucesos](/docs/admin/index.html#oc_eventsubscription) para obtener información sobre cómo ampliar las funciones de notificación. ![Proceso de respuesta de incidencias](images/incidentresponseprocess.png "Proceso de respuesta de incidencias") Figura 2. Proceso de respuesta de incidencias Según la naturaleza del problema, el usuario, IBM o ambos pueden trabajar para solucionarlo. Si tiene alguna pregunta relativa a la incidencia, o si necesita que un representante de {{site.data.keyword.IBM_notm}} le ayude a resolver el problema, puede abrir una incidencia de soporte. Para obtener información sobre cómo contactar con el soporte, consulte [Cómo obtener soporte](../support/index.html#contacting-bluemix-support-local). **Nota**: Las incidencias de soporte de gravedad 1 se supervisan 24 horas al día, 7 días por semana. Otras incidencias se procesan desde las 22:00 del domingo (GMT) hasta las 00:00 del sábado (GMT). Para obtener más información sobre la gravedad de las incidencias de soporte y cómo trabajar con soporte, consulte <a href="/docs/support/index.html#contacting-bluemix-support-local">Contacto con soporte</a>. ## Recuperación tras desastre para {{site.data.keyword.Bluemix_local_notm}} {: #dr} La recuperación tras desastre para {{site.data.keyword.Bluemix_short}} local puede configurarse de forma parecida a la forma en que funciona cuando utiliza {{site.data.keyword.Bluemix_short}} público. {{site.data.keyword.Bluemix_short}} público proporciona una plataforma disponible de forma continua para la innovación con varias medidas libre de errores para garantizar que las organizaciones, los espacios y las apps estén siempre disponibles. El despliegue de apps en varias regiones geográficas permite la disponibilidad continua, que protege frente a la pérdida no planificada y simultánea de varios componentes de hardware o software, o la pérdida de todo un centro de datos, de modo que, incluso en el caso de un desastre natural en una ubicación geográfica, las instancias distribuidas de la app de {{site.data.keyword.Bluemix_notm}} público, situadas en ubicaciones geográficas alternativas, seguirán estando disponibles. {: shortdesc} La recuperación en caso de error de {{site.data.keyword.Bluemix_short}} local es posible gracias a la disponibilidad continua de sus apps, la alta disponibilidad inherente de la plataforma y la capacidad de restaurar la instancia en caso de error. Es responsable de habilitar una disponibilidad continua de sus apps desplegándolas en varias regiones. La alta disponibilidad está integrada en el nivel de la plataforma mediante tecnologías incluidas en Cloud Foundry y otros componentes. También puede trabajar conjuntamente con {{site.data.keyword.IBM_notm}} para asegurarse de que se ha hecho una copia de seguridad correcta de sus datos en el caso de que necesite restaurar su instancia en cualquier momento. ### Habilitación de la disponibilidad continua para {{site.data.keyword.Bluemix_local_notm}} {: #enabling} De forma predeterminada, {{site.data.keyword.Bluemix_notm}} público se despliega en varias ubicaciones geográficas. Sin embargo, debe llevar a cabo lo siguiente para habilitar las instancias de {{site.data.keyword.Bluemix_local_notm}} distribuidas globalmente: * Asegúrese de que los desarrolladores están desplegando apps en más de una región, ya sea a través de un proceso manual o automatizado. Las regiones seleccionadas deben estar a una distancia de más de 200 km entre ellas para garantizar que, en caso de desastre natural, ambas ubicaciones geográficas no se vean afectadas. * Configure un equilibrador de carga global, como Akamai o Dyn, para que apunten a apps en al menos dos regiones distintas. **Nota**: No todos los servicios de {{site.data.keyword.Bluemix_notm}} admiten la distribución regional. Al construir una app, si desea lograr la distribución geográfica, también debe asegurarse de que los servicios que se utilizan en la app tienen la sincronización de datos como característica clave. #### Despliegue de apps de {{site.data.keyword.Bluemix_local_notm}} en varias ubicaciones geográficas {: #deploying} Para efectuar un despliegue en una segunda ubicación o en varias ubicaciones, debe seguir un proceso similar al que siguió para habilitar la ubicación geográfica primaria: 1. Habilite un nuevo entorno local para alojar instancias adicionales de las apps. Para crear un nuevo entorno, póngase en contacto con el equipo de ventas de {{site.data.keyword.IBM_notm}} para iniciar el proceso. Para obtener más información sobre cómo configurar una instancia local, consulte [Configuración de {{site.data.keyword.Bluemix_local_notm}}](../local/index.html#setuplocal). Debe iniciar sesión por separado para acceder a cada entorno. Cada ubicación física de los entornos alojados debe estar a una distancia mínima de 200 km de la ubicación original para garantizar la disponibilidad. 2. Obtenga el nombre de dominio exclusivo en el que se alojará la nueva app desplegada. Por ejemplo, si el dominio original es *mycompany.caeast.bluemix.net*, puede crear un nuevo entorno local con un nuevo dominio como *mycompany.cawest.bluemix.net* y realizar el despliegue en el nuevo dominio. 3. Efectúe un despliegue en la nueva ubicación cada vez que despliegue la app original. Para obtener más información sobre el despliegue, consulte [Carga de una app](/docs/starters/upload_app.html). #### Habilitación de un equilibrador de carga global para {{site.data.keyword.Bluemix_local_notm}} {: #glb} Un equilibrador de carga global no solo garantiza una disponibilidad continua y es necesario para la recuperación en caso de error, sino que también presenta varias ventajas adicionales: * Dirige a los usuarios a la región más próxima de {{site.data.keyword.Bluemix_notm}} de forma predeterminada * Efectúa un enrutamiento en función del rendimiento * Dirige de forma selectiva un porcentaje de tráfico a una nueva versión de una app * Proporciona migración tras error de sitio en función de la comprobación del estado de la región * Proporciona migración tras error de sitio en función de la comprobación del estado de la app * Utiliza un direccionamiento ponderado entre los puntos finales Puede elegir un equilibrador de carga global como Akamai o Dyn. Para obtener más información sobre cómo utilizar Akamai como equilibrador de carga global, consulte [Gestión de tráfico global](https://www.akamai.com/us/en/solutions/products/web-performance/global-traffic-management.jsp){: new_window}. Para obtener más información sobre cómo utilizar Dyn como equilibrador de carga global, consulte [4 Reasons Businesses Are Taking Global Load Balancing to the Cloud](http://dyn.com/blog/4-reasons-businesses-are-taking-global-load-balancing-to-the-cloud/){: new_window}. ### Alta disponibilidad {: #ha} Además de habilitar una disponibilidad continua, {{site.data.keyword.Bluemix_notm}} también proporciona alta disponibilidad en la plataforma mediante tecnologías integradas en Cloud Foundry y otros componentes. Estas tecnologías incluyen: <dl> <dt>Escalabilidad de DEA en Cloud Foundry</dt> <dd>Un <a href="https://docs.cloudfoundry.org/concepts/architecture/execution-agent.html" target="_blank">agente de ejecución de gotas (DEA)</a> de Cloud Foundry efectúa comprobaciones de estado en las apps que se ejecutan en él. Si se produce algún problema con la app o con el propio DEA, despliega instancias adicionales de la app en un DEA alternativo para solucionar el problema. Para obtener más información, consulte <a href="https://docs.cloudfoundry.org/concepts/high-availability.html" target="_blank">Configuración de CF para la alta disponibilidad con redundancia</a>. <p>Para asegurar la alta disponibilidad de las aplicaciones, serán necesarios suficientes recursos de cálculo para equilibrar la carga y también pueden ser necesarios recursos de cálculo adicionales para dar soporte a una posible anomalía. Si es necesario escalar el entorno aumentando la agrupación de DEA para que esté preparada para una anomalía o abordar un pico en la carga para las instancias de la app, puede trabajar con el representante de IBM para solicitar DEA adicionales y asegurarse de que tiene el hardware apropiado para dar soporte a los recursos añadidos. </p> </dd> <dt>Copia de seguridad de metadatos</dt> <dd>Se realiza una copia de seguridad de los metadatos en una ubicación secundaria, normalmente en una máquina virtual local. Si es posible, debe replicar la copia de seguridad a su propio entorno a una distancia mínima de 200 km.</dd> </dl> ## Restauración de la instancia local {: #restorelocal} Se hace una copia de seguridad de forma regular de los valores, los metadatos y las configuraciones de {{site.data.keyword.Bluemix_local_notm}} para prepararse ante cualquier interrupción no planificada del entorno. Los datos de cuya copia de seguridad es responsable incluyen datos de app, datos de servicios de bases de datos en la nube y almacenes de objetos. Como parte de la copia de seguridad de los datos, que incluye metadatos del sistema y configuraciones, {{site.data.keyword.IBM_notm}} lleva a cabo las tareas siguientes: <ul> <li>Cifra todas las copias de seguridad y gestiona las claves de cifrado</li> <li>Supervisa y gestiona la actividad de copia de seguridad</li> <li>Proporciona los archivos de copia de seguridad cifrados</li> <li>Restaura los datos solicitados</li> <li>Gestiona conflictos de planificación entre operaciones de copia de seguridad y de gestión de arreglos</li> </ul> Puesto que la protección de datos privados es crítica, {{site.data.keyword.IBM_notm}} necesita su colaboración cuando se trabaja con la gestión de archivos de copia de seguridad, de modo que los archivos no se traspasen fuera de sus centros de datos. Específicamente, {{site.data.keyword.IBM_notm}} le solicita que complete las tareas siguientes: <ul> <li>Mover una copia de los datos de copia de seguridad cifrados fuera del sitio, como lo haría para cualesquiera otros datos de copia de seguridad que gestione.</li> <li>Proporcionar los archivos de copia de seguridad al administrador de {{site.data.keyword.IBM_notm}} en caso de cualquier necesidad de restauración.</li> </ul> # rellinks ## general * [Descubrir: {{site.data.keyword.Bluemix_local_notm}}](http://www.ibm.com/cloud-computing/bluemix/hybrid/local/) * [Novedades de {{site.data.keyword.Bluemix_notm}}](/docs/whatsnew/index.html) * [{{site.data.keyword.Bluemix_notm}} glosario](/docs/overview/glossary/index.html) * [Gestión de {{site.data.keyword.Bluemix_local_notm}} y {{site.data.keyword.Bluemix_notm}} dedicado](../admin/index.html#mng) * [Cómo obtener soporte](/docs/support/index.html#getting-customer-support)
patsmith-ibm/docs
local/nl/es/index.md
Markdown
apache-2.0
81,977
// Copyright 2021 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.mediapipe.solutioncore; /** Interface for the customizable MediaPipe solution error listener. */ public interface ErrorListener { void onError(String message, RuntimeException e); }
google/mediapipe
mediapipe/java/com/google/mediapipe/solutioncore/ErrorListener.java
Java
apache-2.0
805
'use strict'; /** * Requirements * @ignore */ const Base = require('../Base.js').Base; const Context = require('../application/Context.js').Context; const CliLogger = require('../cli/CliLogger.js').CliLogger; const assertParameter = require('../utils/assert.js').assertParameter; const co = require('co'); const chalk = require('chalk'); /** * @memberOf application */ class Runner extends Base { /** * @param {Context} context */ constructor(context, cliLogger, commands) { super(); //Check params assertParameter(this, 'context', context, true, Context); assertParameter(this, 'cliLogger', cliLogger, true, CliLogger); // Add initial values this._context = context; this._cliLogger = cliLogger; this._commands = []; // Create commands if (Array.isArray(commands)) { for (const command of commands) { this._commands.push(this.context.di.create((typeof command === 'function') ? command : command.type)); } } } /** * @inheritDoc */ static get injections() { /* istanbul ignore next */ return { 'parameters': [Context, CliLogger, 'application/Runner.commands'] }; } /** * @inheritDoc */ static get className() { return 'application/Runner'; } /** * @type {Context} */ get context() { return this._context; } /** * @type {Context} */ get cliLogger() { return this._cliLogger; } /** * @type {array} */ get commands() { return this._commands; } /* istanbul ignore next */ /** * @returns {Promise} */ help() { this.cliLogger.info('Usage:'); this.cliLogger.info(' entoj command [action] [options]'); this.cliLogger.info(''); this.cliLogger.info('Options:'); this.cliLogger.info(' --environment=[development]'); this.cliLogger.info(' Use the build settings from the given environment'); this.cliLogger.info(''); this.cliLogger.info('Commands:'); const data = []; let isFirstCommand = true; for (const command of this._commands) { if (!isFirstCommand) { data.push({}); } isFirstCommand = false; data.push( { command: String.fromCharCode(6) + ' ' + command.help.name, description: chalk.white(command.help.description) }); let isFirstAction = true; if (command.help.actions && command.help.actions.length) { for (const action of command.help.actions) { if (!isFirstAction) { data.push({}); } isFirstAction = false; /* let parameters = ''; if (action.options) { for (const option of action.options) { if (option.type == 'optional' || option.type == 'named') { parameters+= chalk.dim('['); } if (option.type == 'named') { parameters+= chalk.yellow('--'); } parameters+= chalk.yellow(option.name); if (option.type == 'named') { parameters+= chalk.yellow('=' + (option.value || option.name)); } if (option.type == 'optional' || option.type == 'named') { parameters+= chalk.dim(']'); } parameters+= ' '; } } */ data.push( { command: String.fromCharCode(6) + ' ' + action.name, description: chalk.white(action.description) }); if (action.options) { for (const option of action.options) { let command = String.fromCharCode(6) + ' '; if (option.type == 'named') { command+= chalk.yellow('--'); } command+= chalk.yellow(option.name); data.push( { command: command, description: chalk.white(option.description) }); } } } } } this.cliLogger.table(data); } /** * @returns {Promise} */ run() { const scope = this; let handled = false; this._context.parameters._ = this._context.parameters._ || []; this._context.parameters.command = this._context.parameters._.length ? this._context.parameters._.shift() : false; this._context.parameters.action = this._context.parameters._.length ? this._context.parameters._.shift() : false; const promise = co(function *() { for (const command of scope._commands) { const result = yield command.execute(scope._context.parameters); if (result !== false) { handled = true; } } if (!handled) { scope.cliLogger.error('No command handled request'); scope.help(); } return true; }).catch(function(error) { scope.cliLogger.error(error); }); return promise; } } /** * Exports * @ignore */ module.exports.Runner = Runner;
entoj/entoj-core
source/application/Runner.js
JavaScript
apache-2.0
6,456
package cn.jin.utils; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * md5加密工具类 * Created by Jin on 2016/3/7. * desc: */ public class MD5Util { public static String encrypt(String data){ byte[] hash; try { hash = MessageDigest.getInstance("MD5").digest(data.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Huh, MD5 should be supported?", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Huh, UTF-8 should be supported?", e); } StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { if ((b & 0xFF) < 0x10) hex.append("0"); hex.append(Integer.toHexString(b & 0xFF)); } return hex.toString(); } public static String encrypt(byte[] data){ byte[] hash; try { hash = MessageDigest.getInstance("MD5").digest(data); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Huh, MD5 should be supported?", e); } StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { if ((b & 0xFF) < 0x10) hex.append("0"); hex.append(Integer.toHexString(b & 0xFF)); } return hex.toString(); } }
Jeff518/JinBase
jinlib/src/main/java/cn/jin/utils/MD5Util.java
Java
apache-2.0
1,456
/* * Copyright 2003 - 2020 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.esjp.ui.rest.dto; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; @EFapsUUID("32c1f972-30c2-414f-8a48-a0cd29362ab9") @EFapsApplication("eFaps-WebApp") public enum ValueType { READ_ONLY, INPUT, SNIPPLET, UPLOAD, UPLOADMULTIPLE, ENUM, STATUS, RADIO, AUTOCOMPLETE, DATE, DROPDOWN }
eFaps/eFaps-WebApp-Install
src/main/efaps/ESJP/org/efaps/esjp/ui/rest/dto/ValueType.java
Java
apache-2.0
1,004
/** * Copyright 2011 Caleb Richardson * * 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.outerspacecat.util; import com.google.common.base.Optional; import javax.annotation.concurrent.ThreadSafe; /** * Defines methods for caching. * * @author Caleb Richardson * @param <K> the type of the cache keys * @param <V> the type of the cache values */ @ThreadSafe public interface Cache<K, V> { /** * Retrieves the value mapped by {@code k}. * * @param k the key whose associated value is to be returned. Must be non * {@code null}. * @return the value mapped by {@code k}. Never {@code null}. */ Optional<V> get ( K k ); /** * Creates or updates a mapping in this cache. If a mapping for the specified * key already exists, then the old mapping will be removed, and a new mapping * will be created. * * @param k the key for the mapping. Must be non {@code null}. * @param v the value for the mapping. Must be non {@code null}. */ void put ( K k, V v ); /** * Invalidates the mapping specified by {@code k}. * * @param k the key for the mapping to invalidate. Must be non {@code null}. */ void invalidate ( K k ); /** * Clears this cache. */ void clear (); }
calebrichardson/spiff
src/main/java/com/outerspacecat/util/Cache.java
Java
apache-2.0
1,772
package pl.touk.nussknacker.engine.management.sample.transformer import pl.touk.nussknacker.engine.api.{CustomStreamTransformer, LazyParameter, MethodToInvoke, ParamName} case object NoneReturnTypeTransformer extends CustomStreamTransformer { @MethodToInvoke(returnType = classOf[Void]) def execute(@ParamName("expression") expression: LazyParameter[java.lang.Boolean]): Unit = {} }
TouK/nussknacker
engine/flink/management/dev-model/src/main/scala/pl/touk/nussknacker/engine/management/sample/transformer/NoneReturnTypeTransformer.scala
Scala
apache-2.0
389
package com.nitorcreations.puggly.domain; import org.springframework.http.HttpHeaders; import javax.servlet.http.HttpServletResponse; public class LoggedResponse extends PugglyValue { public HttpHeaders headers; public int status; public String contentType; public String body; public LoggedResponse() { headers = new HttpHeaders(); } public LoggedResponse(HttpServletResponse response, String body) { this.body = body; this.contentType = response.getContentType(); this.status = response.getStatus(); this.headers = HeaderParser.getHeaders(response); } @Override public String toString() { return "[status=" + status + (headers.isEmpty() ? "" : "\n" + HeaderParser.headerString(headers)) + "\n> contentType=" + (contentType == null ? "<null>" : contentType) + "\n> body=" + (body == null ? "<null>" : body) + "]"; } }
NitorCreations/Puggly
src/main/java/com/nitorcreations/puggly/domain/LoggedResponse.java
Java
apache-2.0
981
<ion-view view-title="Menu"> <div class="tabs-striped tabs-color-royal"> <ul class="tabs"> <li ng-class="{active:isSelected(1)}" class="tab-item"> <a ng-click="select(1)">The Menu</a></li> <li ng-class="{active:isSelected(2)}" class="tab-item"> <a ng-click="select(2)">Appetizers</a></li> <li ng-class="{active:isSelected(3)}" class="tab-item"> <a ng-click="select(3)">Mains</a></li> <li ng-class="{active:isSelected(4)}" class="tab-item"> <a ng-click="select(4)">Desserts</a></li> </ul> </div> <ion-content> <ion-list> <ion-item ng-repeat="dish in dishes | filter:{category: filtText}" href="#/app/menu/{{dish.id}}" class="item-thumbnail-left"> <img ng-src="{{baseURL+dish.image}}"> <h2>{{dish.name}} <span style="font-size:75%">{{dish.price | currency}}</span> <span class="badge badge-assertive">{{dish.label}}</span></h2> <p>{{dish.description}}</p> <ion-option-button class="button-assertive icon ion-plus-circled" ng-click="addFavorite(dish.id)"> </ion-option-button> </ion-item> </ion-list> </ion-content> </ion-view>
sotiris920/Restaurant_Multiplatform_Mobile_Application
www/templates/menu.html
HTML
apache-2.0
1,165
# Copyright 2016-2019 IBM Corp. 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. """ Commands for virtual functions. """ from __future__ import absolute_import import click import zhmcclient from .zhmccli import cli from ._helper import print_properties, print_resources, abort_if_false, \ options_to_properties, original_options, COMMAND_OPTIONS_METAVAR, \ click_exception, add_options, LIST_OPTIONS from ._cmd_partition import find_partition def find_vfunction( cmd_ctx, client, cpc_or_name, partition_name, vfunction_name): """ Find a virtual function by name and return its resource object. """ partition = find_partition(cmd_ctx, client, cpc_or_name, partition_name) try: vfunction = partition.virtual_functions.find(name=vfunction_name) except zhmcclient.Error as exc: raise click_exception(exc, cmd_ctx.error_format) return vfunction @cli.group('vfunction', options_metavar=COMMAND_OPTIONS_METAVAR) def vfunction_group(): """ Command group for managing virtual functions (DPM mode only). The only virtual functions that can be managed with the commands in this group are those of the zEDC accelerator adapter, and only on CPCs that are in DPM mode. In addition to the command-specific options shown in this help text, the general options (see 'zhmc --help') can also be specified right after the 'zhmc' command name. """ @vfunction_group.command('list', options_metavar=COMMAND_OPTIONS_METAVAR) @click.argument('CPC', type=str, metavar='CPC') @click.argument('PARTITION', type=str, metavar='PARTITION') @add_options(LIST_OPTIONS) @click.pass_obj def vfunction_list(cmd_ctx, cpc, partition, **options): """ List the virtual functions in a partition. In addition to the command-specific options shown in this help text, the general options (see 'zhmc --help') can also be specified right after the 'zhmc' command name. """ cmd_ctx.execute_cmd(lambda: cmd_vfunction_list(cmd_ctx, cpc, partition, options)) @vfunction_group.command('show', options_metavar=COMMAND_OPTIONS_METAVAR) @click.argument('CPC', type=str, metavar='CPC') @click.argument('PARTITION', type=str, metavar='PARTITION') @click.argument('VFUNCTION', type=str, metavar='VFUNCTION') @click.pass_obj def vfunction_show(cmd_ctx, cpc, partition, vfunction): """ Show the details of a virtual function. In addition to the command-specific options shown in this help text, the general options (see 'zhmc --help') can also be specified right after the 'zhmc' command name. """ cmd_ctx.execute_cmd(lambda: cmd_vfunction_show(cmd_ctx, cpc, partition, vfunction)) @vfunction_group.command('create', options_metavar=COMMAND_OPTIONS_METAVAR) @click.argument('CPC', type=str, metavar='CPC') @click.argument('PARTITION', type=str, metavar='PARTITION') @click.option('--name', type=str, required=True, help='The name of the new virtual function. Must be unique ' 'within the virtual functions of the partition') @click.option('--description', type=str, required=False, help='The description of the new virtual function. ' 'Default: empty') @click.option('--adapter', type=str, required=True, help='The name of the adapter backing the virtual function.') @click.option('--device-number', type=str, required=False, help='The device number to be used for the new virtual ' 'function. Default: auto-generated') @click.pass_obj def vfunction_create(cmd_ctx, cpc, partition, **options): """ Create a virtual function in a partition. This assigns a virtual function of an adapter to a partition, creating a named virtual function resource within that partition. In addition to the command-specific options shown in this help text, the general options (see 'zhmc --help') can also be specified right after the 'zhmc' command name. """ cmd_ctx.execute_cmd(lambda: cmd_vfunction_create(cmd_ctx, cpc, partition, options)) @vfunction_group.command('update', options_metavar=COMMAND_OPTIONS_METAVAR) @click.argument('CPC', type=str, metavar='CPC') @click.argument('PARTITION', type=str, metavar='PARTITION') @click.argument('VFUNCTION', type=str, metavar='VFUNCTION') @click.option('--name', type=str, required=False, help='The new name of the virtual function. Must be unique ' 'within the virtual functions of the partition.') @click.option('--description', type=str, required=False, help='The new description of the virtual function.') @click.option('--adapter', type=str, required=False, help='The name of the new adapter (in the same CPC) that will ' 'back the virtual function.') @click.option('--device-number', type=str, required=False, help='The new device number to be used for the virtual ' 'function.') @click.pass_obj def vfunction_update(cmd_ctx, cpc, partition, vfunction, **options): """ Update the properties of a virtual function. Only the properties will be changed for which a corresponding option is specified, so the default for all options is not to change properties. In addition to the command-specific options shown in this help text, the general options (see 'zhmc --help') can also be specified right after the 'zhmc' command name. """ cmd_ctx.execute_cmd(lambda: cmd_vfunction_update(cmd_ctx, cpc, partition, vfunction, options)) @vfunction_group.command('delete', options_metavar=COMMAND_OPTIONS_METAVAR) @click.argument('CPC', type=str, metavar='CPC') @click.argument('PARTITION', type=str, metavar='PARTITION') @click.argument('VFUNCTION', type=str, metavar='VFUNCTION') @click.option('-y', '--yes', is_flag=True, callback=abort_if_false, expose_value=False, help='Skip prompt to confirm deletion of the virtual function.', prompt='Are you sure you want to delete this virtual function ?') @click.pass_obj def vfunction_delete(cmd_ctx, cpc, partition, vfunction): """ Delete a virtual function. In addition to the command-specific options shown in this help text, the general options (see 'zhmc --help') can also be specified right after the 'zhmc' command name. """ cmd_ctx.execute_cmd(lambda: cmd_vfunction_delete(cmd_ctx, cpc, partition, vfunction)) def cmd_vfunction_list(cmd_ctx, cpc_name, partition_name, options): # pylint: disable=missing-function-docstring client = zhmcclient.Client(cmd_ctx.session) partition = find_partition(cmd_ctx, client, cpc_name, partition_name) try: vfunctions = partition.virtual_functions.list() except zhmcclient.Error as exc: raise click_exception(exc, cmd_ctx.error_format) show_list = [ 'name', 'cpc', 'partition', ] if not options['names_only']: show_list.extend([ # No additional standard properties ]) if options['uri']: show_list.extend([ 'element-uri', ]) cpc_additions = {} partition_additions = {} for vfunction in vfunctions: cpc_additions[vfunction.uri] = cpc_name partition_additions[vfunction.uri] = partition_name additions = { 'cpc': cpc_additions, 'partition': partition_additions, } try: print_resources(cmd_ctx, vfunctions, cmd_ctx.output_format, show_list, additions, all=options['all']) except zhmcclient.Error as exc: raise click_exception(exc, cmd_ctx.error_format) def cmd_vfunction_show(cmd_ctx, cpc_name, partition_name, vfunction_name): # pylint: disable=missing-function-docstring client = zhmcclient.Client(cmd_ctx.session) vfunction = find_vfunction(cmd_ctx, client, cpc_name, partition_name, vfunction_name) try: vfunction.pull_full_properties() except zhmcclient.Error as exc: raise click_exception(exc, cmd_ctx.error_format) print_properties(cmd_ctx, vfunction.properties, cmd_ctx.output_format) def cmd_vfunction_create(cmd_ctx, cpc_name, partition_name, options): # pylint: disable=missing-function-docstring client = zhmcclient.Client(cmd_ctx.session) partition = find_partition(cmd_ctx, client, cpc_name, partition_name) name_map = { # The following options are handled in this function: 'adapter': None, } org_options = original_options(options) properties = options_to_properties(org_options, name_map) adapter_name = org_options['adapter'] try: adapter = partition.manager.cpc.adapters.find(name=adapter_name) except zhmcclient.NotFound: raise click_exception("Could not find adapter '{a}' in CPC '{c}'.". format(a=adapter_name, c=cpc_name), cmd_ctx.error_format) properties['adapter-uri'] = adapter.uri try: new_vfunction = partition.virtual_functions.create(properties) except zhmcclient.Error as exc: raise click_exception(exc, cmd_ctx.error_format) cmd_ctx.spinner.stop() click.echo("New virtual function '{f}' has been created.". format(f=new_vfunction.properties['name'])) def cmd_vfunction_update(cmd_ctx, cpc_name, partition_name, vfunction_name, options): # pylint: disable=missing-function-docstring client = zhmcclient.Client(cmd_ctx.session) vfunction = find_vfunction(cmd_ctx, client, cpc_name, partition_name, vfunction_name) name_map = { # The following options are handled in this function: 'adapter': None, } org_options = original_options(options) properties = options_to_properties(org_options, name_map) if org_options['adapter'] is not None: adapter_name = org_options['adapter'] try: adapter = vfunction.manager.partition.manager.cpc.adapters.find( name=adapter_name) except zhmcclient.NotFound: raise click_exception("Could not find adapter '{a}' in CPC '{c}'.". format(a=adapter_name, c=cpc_name), cmd_ctx.error_format) properties['adapter-uri'] = adapter.uri if not properties: cmd_ctx.spinner.stop() click.echo("No properties specified for updating virtual function " "{f}.".format(f=vfunction_name)) return try: vfunction.update_properties(properties) except zhmcclient.Error as exc: raise click_exception(exc, cmd_ctx.error_format) cmd_ctx.spinner.stop() if 'name' in properties and properties['name'] != vfunction_name: click.echo("Virtual function '{f}' has been renamed to '{fn}' and was " "updated.".format(f=vfunction_name, fn=properties['name'])) else: click.echo("Virtual function '{f}' has been updated.". format(f=vfunction_name)) def cmd_vfunction_delete(cmd_ctx, cpc_name, partition_name, vfunction_name): # pylint: disable=missing-function-docstring client = zhmcclient.Client(cmd_ctx.session) vfunction = find_vfunction(cmd_ctx, client, cpc_name, partition_name, vfunction_name) try: vfunction.delete() except zhmcclient.Error as exc: raise click_exception(exc, cmd_ctx.error_format) cmd_ctx.spinner.stop() click.echo("Virtual function '{f}' has been deleted.". format(f=vfunction_name))
zhmcclient/zhmccli
zhmccli/_cmd_vfunction.py
Python
apache-2.0
12,466
/* * Copyright 2015 Higher Frequency Trading * * http://chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.queue.impl; import net.openhft.chronicle.queue.ExcerptTailer; import net.openhft.chronicle.wire.ByteableLongArrayValues; import org.jetbrains.annotations.NotNull; import static net.openhft.chronicle.queue.impl.Indexer.IndexOffset.toAddress0; import static net.openhft.chronicle.queue.impl.Indexer.IndexOffset.toAddress1; import static net.openhft.chronicle.queue.impl.SingleChronicleQueue.UNINITIALISED; /** * this class is not thread safe - first CAS has to be implemented * * @author Rob Austin. */ public class Indexer { // 1 << 20 ( is 1MB ), a long is 8 Bytes, if we were to just store the longs // in 1Mb this would give use 1 << 17 longs. public static final long NUMBER_OF_ENTRIES_IN_EACH_INDEX = 1 << 17; private final SingleChronicleQueue chronicle; private final ThreadLocal<ByteableLongArrayValues> array; public Indexer(@NotNull final SingleChronicleQueue chronicle) { this.array = WireUtil.newLongArrayValuesPool(chronicle.wireType()); this.chronicle = chronicle; } /** * Scans through every excerpts and records every 64th addressForRead in the index2index' * * @ */ public synchronized void index() { final ExcerptTailer tailer = chronicle.createTailer(); for (long i = 0; i <= chronicle.lastIndex(); i++) { final long index = i; tailer.readDocument(wireIn -> { long address = wireIn.bytes().position() - 4; recordAddress(index, address); wireIn.bytes().skip(wireIn.bytes().remaining()); }); } } /** * records every 64th addressForRead in the index2index * * @param index the index of the Excerpts which we are going to record * @param address the addressForRead of the Excerpts which we are going to record */ private void recordAddress(long index, long address) { if (index % 64 != 0) return; final ByteableLongArrayValues array = this.array.get(); final long index2Index = chronicle.indexToIndex(); chronicle.wire().readDocument(index2Index, rootIndex -> { rootIndex.read("index").int64array(array, longArrayValues -> { }); long secondaryAddress = array.getValueAt(toAddress0(index)); if (secondaryAddress == UNINITIALISED) { array.setValueAt(index, secondaryAddress = chronicle.newIndex()); } chronicle.wire().readDocument(secondaryAddress, secondaryIndex -> { secondaryIndex.read("index").int64array(array, longArrayValues -> { }); array.setValueAt(toAddress1(index), address); }, null); }, null); } public enum IndexOffset { ; // none static long toAddress0(long index) { long siftedIndex = index >> (17L + 6L); long mask = (1L << 17L) - 1L; long maskedShiftedIndex = mask & siftedIndex; // convert to an offset return maskedShiftedIndex * 8L; } static long toAddress1(long index) { long siftedIndex = index >> (6L); long mask = (1L << 17L) - 1L; long maskedShiftedIndex = mask & siftedIndex; // convert to an offset return maskedShiftedIndex * 8L; } @NotNull public static String toBinaryString(long i) { StringBuilder sb = new StringBuilder(); for (int n = 63; n >= 0; n--) { sb.append(((i & (1L << n)) != 0 ? "1" : "0")); } return sb.toString(); } @NotNull public static String toScale() { StringBuilder units = new StringBuilder(); StringBuilder tens = new StringBuilder(); for (int n = 64; n >= 1; n--) { units.append((0 == (n % 10)) ? "|" : n % 10); } for (int n = 64; n >= 1; n--) { tens.append((0 == (n % 10)) ? n / 10 : " "); } return units.toString() + "\n" + tens.toString(); } } }
OpenHFT/Chronicle-Queue
chronicle-sandbox/src/main/java/net/openhft/chronicle/queue/impl/Indexer.java
Java
apache-2.0
4,826
// @link http://schemas.triniti.io/json-schema/triniti/ovp/event/transcription-completed/1-0-0.json# import Fb from '@gdbots/pbj/FieldBuilder'; import Format from '@gdbots/pbj/enums/Format'; import GdbotsPbjxEventV1Mixin from '@gdbots/schemas/gdbots/pbjx/mixin/event/EventV1Mixin'; import Message from '@gdbots/pbj/Message'; import Schema from '@gdbots/pbj/Schema'; import T from '@gdbots/pbj/types'; export default class TranscriptionCompletedV1 extends Message { /** * @private * * @returns {Schema} */ static defineSchema() { return new Schema(this.SCHEMA_ID, this, [ Fb.create('event_id', T.TimeUuidType.create()) .required() .build(), Fb.create('occurred_at', T.MicrotimeType.create()) .build(), /* * Multi-tenant apps can use this field to track the tenant id. */ Fb.create('ctx_tenant_id', T.StringType.create()) .pattern('^[\\w\\/\\.:-]+$') .build(), Fb.create('ctx_causator_ref', T.MessageRefType.create()) .build(), Fb.create('ctx_correlator_ref', T.MessageRefType.create()) .build(), Fb.create('ctx_user_ref', T.MessageRefType.create()) .build(), /* * The "ctx_app" refers to the application used to send the command which * in turn resulted in this event being published. */ Fb.create('ctx_app', T.MessageType.create()) .anyOfCuries([ 'gdbots:contexts::app', ]) .build(), /* * The "ctx_cloud" is usually copied from the command that resulted in this * event being published. This means the value most likely refers to the cloud * that received the command originally, not the machine processing the event. */ Fb.create('ctx_cloud', T.MessageType.create()) .anyOfCuries([ 'gdbots:contexts::cloud', ]) .build(), Fb.create('ctx_ip', T.StringType.create()) .format(Format.IPV4) .overridable(true) .build(), Fb.create('ctx_ipv6', T.StringType.create()) .format(Format.IPV6) .overridable(true) .build(), Fb.create('ctx_ua', T.TextType.create()) .overridable(true) .build(), /* * An optional message/reason for the event being created. * Consider this like a git commit message. */ Fb.create('ctx_msg', T.TextType.create()) .build(), /* * Tags is a map that categorizes data or tracks references in * external systems. The tags names should be consistent and descriptive, * e.g. fb_user_id:123, salesforce_customer_id:456. */ Fb.create('tags', T.StringType.create()) .asAMap() .pattern('^[\\w\\/\\.:-]+$') .build(), /* * A reference to the video asset that was transcribed. */ Fb.create('node_ref', T.NodeRefType.create()) .required() .build(), Fb.create('transcribe_job_name', T.StringType.create()) .pattern('^[\\w-]+$') .build(), Fb.create('transcribe_job_region', T.StringType.create()) .maxLength(20) .format(Format.SLUG) .build(), Fb.create('language_code', T.StringType.create()) .pattern('^[\\w-]+$') .build(), /* * How long in seconds it took to produce a transcribed artifact. */ Fb.create('time_taken', T.SmallIntType.create()) .build(), ], this.MIXINS, ); } } const M = TranscriptionCompletedV1; M.prototype.SCHEMA_ID = M.SCHEMA_ID = 'pbj:triniti:ovp:event:transcription-completed:1-0-0'; M.prototype.SCHEMA_CURIE = M.SCHEMA_CURIE = 'triniti:ovp:event:transcription-completed'; M.prototype.SCHEMA_CURIE_MAJOR = M.SCHEMA_CURIE_MAJOR = 'triniti:ovp:event:transcription-completed:v1'; M.prototype.MIXINS = M.MIXINS = [ 'gdbots:pbjx:mixin:event:v1', 'gdbots:pbjx:mixin:event', 'gdbots:common:mixin:taggable:v1', 'gdbots:common:mixin:taggable', ]; GdbotsPbjxEventV1Mixin(M); Object.freeze(M); Object.freeze(M.prototype);
triniti/schemas
build/js/src/triniti/ovp/event/TranscriptionCompletedV1.js
JavaScript
apache-2.0
4,253
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov, [email protected] * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package ed.ext.org.mozilla.javascript; /** * Object that can allows assignments to the result of function calls. */ public interface RefCallable extends Callable { /** * Perform function call in reference context. * The args array reference should not be stored in any object that is * can be GC-reachable after this method returns. If this is necessary, * for example, to implement {@link Ref} methods, then store args.clone(), * not args array itself. * * @param cx the current Context for this thread * @param thisObj the JavaScript <code>this</code> object * @param args the array of arguments */ public Ref refCall(Context cx, Scriptable thisObj, Object[] args); }
babble/babble
src/main/ed/ext/org/mozilla/javascript/RefCallable.java
Java
apache-2.0
2,390
<div class="row"> <div class="columns medium-6 large-4"> <div class="sf_colsIn"> </div> </div> <div class="columns medium-6 large-8"> <div class="sf_colsIn"> </div> </div> </div>
osmak/sitefinity-multistore
MultistoreSite/ResourcePackages/Foundation/GridSystem/Templates/grid-4+8.html
HTML
apache-2.0
230
\documentclass{article} \usepackage{mathpartir} \author{ Reinier Maas \\ 4131495 \and Adolfo Ochagavía \\ 4045483 } \title{CCO - Assignment 1} \begin{document} \maketitle % See docs on http://www.ccs.neu.edu/course/csg264/latex/mathpartir/mathpartir.pdf \section{Readme} \subsection*{Structure of the code} \begin{itemize} \item \texttt{bin}: the code of the four command line utilities required by the assignment. \item \texttt{lib}: the implementation of the command line utilities as a library, so that they can be unit-tested. \item \texttt{test}: unit and end to end tests (use \texttt{make test} and \texttt{make e2e-test} to run them). \item \texttt{uu-cco}: a fork of the \texttt{uu-cco} library, with a \texttt{ioRun'} function that makes it easier to unit test our components. \item \texttt{readme}: the latex code used to typeset this document (use \texttt{make latex} to generate the diagrams and typeset the document). \end{itemize} \subsection*{Building} Provided you have \texttt{stack} and \texttt{uuagc} installed on your system, you can use the make commands to build the project (concretely, \texttt{make build}). The project should probably build as well when using cabal, though we haven't tested it. \section{Type system} \subsection*{Basic terms} \[ \inferrule[Program]{\ }{program\ P\ in\ L : Program\ L} \] \[ \inferrule[Platform]{\ }{platform\ M : Platform\ M} \] \[ \inferrule[Interpreter]{\ }{interpreter\ I\ for\ L\ in\ M : Interpreter\ L\ M} \] \[ \inferrule[Compiler]{\ }{compiler\ C\ from\ I\ to\ O\ in\ M\ :\ Compiler\ I\ O\ M} \] \subsection*{Subtyping} \[ \inferrule[InterpreterIsProgram]{i : Interpreter\ L\ M}{i : Program\ M} \] \[ \inferrule[InterpreterIsPlatform]{i : Interpreter\ L\ M}{i : Platform\ L} \] \[ \inferrule[CompilerIsProgram]{c : Compiler\ I\ O\ M}{c : Program\ M} \] \subsection*{Recursive terms} \[ \inferrule[ExecuteProgram]{p : Program\ L \qquad m : Platform\ L}{execute\ p\ on\ m : Execute} \] \[ \inferrule[ExecuteCompiling]{c : Compiling\ O\ M \qquad m : Platform\ M}{execute\ c\ on\ m : Program\ O} \] \[ \inferrule[ExecuteCompilingOnAnyPlatform]{c : Compiling\ O\ M \qquad m : Platform\ O}{execute\ c\ on\ m : Execute} \] \[ \inferrule[Compile]{p : Program\ L \qquad c : Compiler\ L\ O\ M}{compile\ p\ with\ c\ end : Compiling\ O\ M} \] \section{Generated pictures} Note: you can generate \texttt{diagrams.tex} by running \texttt{make e2e-test}. \begin{scriptsize} \input{diagrams.tex} \end{scriptsize} \end{document}
aochagavia/CompilerConstruction
tdiagrams/readme/readme.tex
TeX
apache-2.0
2,515
<!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <head> <title>Universe - College Education Responsive Template</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Description for my template"> <meta name="author" content="Esmet"> <meta charset="UTF-8"> <link href='http://fonts.googleapis.com/css?family=Raleway:400,100,200,300,500,600,700,800' rel='stylesheet' type='text/css'> <!-- CSS Bootstrap & Custom --> <link href="bootstrap/css/bootstrap.css" rel="stylesheet" media="screen"> <link href="css/font-awesome.min.css" rel="stylesheet" media="screen"> <link href="css/animate.css" rel="stylesheet" media="screen"> <link href="style.css" rel="stylesheet" media="screen"> <!-- Favicons --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="images/ico/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="images/ico/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="images/ico/apple-touch-icon-57-precomposed.png"> <link rel="shortcut icon" href="images/ico/favicon.ico"> <!-- JavaScripts --> <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <script src="js/modernizr.js"></script> <!--[if lt IE 8]> <div style=' clear: both; text-align:center; position: relative;'> <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx?ocid=ie6_countdown_bannercode"><img src="http://storage.ie6countdown.com/assets/100/images/banners/warning_bar_0000_us.jpg" border="0" alt="" /></a> </div> <![endif]--> </head> <body> <!-- This one in here is responsive menu for tablet and mobiles --> <div class="responsive-navigation visible-sm visible-xs"> <a href="#" class="menu-toggle-btn"> <i class="fa fa-bars"></i> </a> <div class="responsive_menu"> <ul class="main_menu"> <li><a href="index.html">Home</a></li> <li><a href="#">Events</a> <ul> <li><a href="events-grid.html">Events Grid</a></li> <li><a href="events-list.html">Events List</a></li> <li><a href="event-single.html">Event Details</a></li> </ul> </li> <li><a href="#">Courses</a> <ul> <li><a href="courses.html">Course List</a></li> <li><a href="course-single.html">Course Single</a></li> </ul> </li> <li><a href="#">Blog Entries</a> <ul> <li><a href="blog.html">Blog Grid</a></li> <li><a href="blog-single.html">Blog Single</a></li> <li><a href="blog-disqus.html">Blog Disqus</a></li> </ul> </li> <li><a href="">Pages</a> <ul> <li><a href="archives.html">Archives</a></li> <li><a href="shortcodes.html">Shortcodes</a></li> <li><a href="gallery.html">Our Gallery</a></li> </ul> </li> <li><a href="contact.html">Contact</a></li> </ul> <!-- /.main_menu --> <ul class="social_icons"> <li><a href="#"><i class="fa fa-facebook"></i></a></li> <li><a href="#"><i class="fa fa-twitter"></i></a></li> <li><a href="#"><i class="fa fa-pinterest"></i></a></li> <li><a href="#"><i class="fa fa-google-plus"></i></a></li> <li><a href="#"><i class="fa fa-rss"></i></a></li> </ul> <!-- /.social_icons --> </div> <!-- /.responsive_menu --> </div> <!-- /responsive_navigation --> <header class="site-header"> <div class="container"> <div class="row"> <div class="col-md-4 header-left"> <p><i class="fa fa-phone"></i> +01 2334 853</p> <p><i class="fa fa-envelope"></i> <a href="mailto:[email protected]">[email protected]</a></p> </div> <!-- /.header-left --> <div class="col-md-4"> <div class="logo"> <a href="index.html" title="Universe" rel="home"> <img src="images/logo.png" alt="Universe"> </a> </div> <!-- /.logo --> </div> <!-- /.col-md-4 --> <div class="col-md-4 header-right"> <ul class="small-links"> <li><a href="#">About Us</a></li> <li><a href="#">Contact</a></li> <li><a href="#">Apply Now</a></li> </ul> <div class="search-form"> <form name="search_form" method="get" action="#" class="search_form"> <input type="text" name="s" placeholder="Search the site..." title="Search the site..." class="field_search"> </form> </div> </div> <!-- /.header-right --> </div> </div> <!-- /.container --> <div class="nav-bar-main" role="navigation"> <div class="container"> <nav class="main-navigation clearfix visible-md visible-lg" role="navigation"> <ul class="main-menu sf-menu"> <li><a href="index.html">Home</a></li> <li><a href="#">Events</a> <ul class="sub-menu"> <li><a href="events-grid.html">Events Grid</a></li> <li><a href="events-list.html">Events List</a></li> <li><a href="event-single.html">Events Details</a> </ul> </li> <li><a href="#">Courses</a> <ul class="sub-menu"> <li><a href="courses.html">Courses List</a></li> <li><a href="course-single.html">Course Single</a></li> </ul> </li> <li><a href="#">Blog Entries</a> <ul class="sub-menu"> <li><a href="blog.html">Blog Grid</a></li> <li><a href="blog-single.html">Blog Single</a></li> <li><a href="blog-disqus.html">Blog Disqus</a></li> </ul> </li> <li class="active"><a href="#">Pages</a> <ul class="sub-menu"> <li><a href="archives.html">Archives</a></li> <li><a href="shortcodes.html">Shortcodes</a></li> <li><a href="gallery.html">Our Gallery</a></li> </ul> </li> <li><a href="contact.html">Contact</a></li> </ul> <!-- /.main-menu --> <ul class="social-icons pull-right"> <li><a href="#" data-toggle="tooltip" title="Facebook"><i class="fa fa-facebook"></i></a></li> <li><a href="#" data-toggle="tooltip" title="Twitter"><i class="fa fa-twitter"></i></a></li> <li><a href="#" data-toggle="tooltip" title="Pinterest"><i class="fa fa-pinterest"></i></a></li> <li><a href="#" data-toggle="tooltip" title="Google+"><i class="fa fa-google-plus"></i></a></li> <li><a href="#" data-toggle="tooltip" title="RSS"><i class="fa fa-rss"></i></a></li> </ul> <!-- /.social-icons --> </nav> <!-- /.main-navigation --> </div> <!-- /.container --> </div> <!-- /.nav-bar-main --> </header> <!-- /.site-header --> <!-- Being Page Title --> <div class="container"> <div class="page-title clearfix"> <div class="row"> <div class="col-md-12"> <h6><a href="index.html">Home</a></h6> <h6><span class="page-active">Archives</span></h6> </div> </div> </div> </div> <div class="container"> <div class="row"> <!-- Here begin Main Content --> <div class="col-md-8"> <div class="row"> <div class="col-md-12"> <div class="widget-main"> <div class="widget-inner"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, excepturi ullam officia debitis blanditiis eos omnis asperiores eaque mollitia consequatur in aspernatur delectus ab accusantium itaque dolores alias provident veritatis repellendus culpa nemo vel accusamus! Ullam sint deserunt est quas.</p> <h3 class="archive-title">Latest 10 Posts</h3> <ul class="archive-list"> <li><a href="#">Aenean eleifend est a ligula dictum, a dapibus est mollis.</a></li> <li><a href="#">Proin ut sem ut lectus fringilla varius.</a></li> <li><a href="#">Nulla sit amet mi ac neque lobortis consectetur.</a></li> <li><a href="#">Sed hendrerit erat eget volutpat feugiat.</a></li> <li><a href="#">Aenean eu mauris quis magna pretium dictum a a metus.</a></li> <li><a href="#">Nunc posuere felis sit amet lectus cursus feugiat.</a></li> <li><a href="#">Maecenas ultricies augue pellentesque justo lacinia pulvinar.</a></li> <li><a href="#">Phasellus ac odio fermentum, feugiat nunc et, porttitor sapien.</a></li> <li><a href="#">Suspendisse a nisl nec nisl sagittis dictum.</a></li> <li><a href="#">Morbi aliquet purus vitae dolor commodo dictum.</a></li> </ul> <h3 class="archive-title">Archives by Month:</h3> <ul class="archive-list"> <li><a href="#">January 2014</a></li> <li><a href="#">December 2013</a></li> <li><a href="#">November 2013</a></li> <li><a href="#">October 2013</a></li> <li><a href="#">September 2013</a></li> <li><a href="#">August 2013</a></li> <li><a href="#">July 2013</a></li> </ul> <h3 class="archive-title">Archives by Categories:</h3> <ul class="archive-list"> <li><a href="#">Business</a></li> <li><a href="#">Famliy</a></li> <li><a href="#">Government</a></li> <li><a href="#">Health</a></li> <li><a href="#">Science</a></li> <li><a href="#">Student Achievements</a></li> <li><a href="#">Tech & Engineering</a></li> </ul> </div> <!-- /.widget-inner --> </div> <!-- /.widget-main --> </div> <!-- /.col-md-12 --> </div> <!-- /.row --> </div> <!-- /.col-md-8 --> <!-- Here begin Sidebar --> <div class="col-md-4"> <div class="widget-main"> <div class="widget-inner"> <div class="search-form-widget"> <form name="search_form" method="get" action="#" class="search_form"> <input type="text" name="s" placeholder="Type and click enter to search..." title="Type and click enter to search..." class="field_search"> </form> </div> </div> <!-- /.widget-inner --> </div> <!-- /.widget-main --> <div class="widget-main"> <div class="widget-main-title"> <h4 class="widget-title">Our Gallery</h4> </div> <div class="widget-inner"> <div class="gallery-small-thumbs clearfix"> <div class="thumb-small-gallery"> <a class="fancybox" rel="gallery1" href="images/gallery/gallery1.jpg" title="Gallery Tittle One"> <img src="images/gallery/gallery-small-thumb1.jpg" alt="" /> </a> </div> <div class="thumb-small-gallery"> <a class="fancybox" rel="gallery1" href="images/gallery/gallery2.jpg" title="Gallery Tittle One"> <img src="images/gallery/gallery-small-thumb2.jpg" alt="" /> </a> </div> <div class="thumb-small-gallery"> <a class="fancybox" rel="gallery1" href="images/gallery/gallery3.jpg" title="Gallery Tittle One"> <img src="images/gallery/gallery-small-thumb3.jpg" alt="" /> </a> </div> <div class="thumb-small-gallery"> <a class="fancybox" rel="gallery1" href="images/gallery/gallery4.jpg" title="Gallery Tittle One"> <img src="images/gallery/gallery-small-thumb4.jpg" alt="" /> </a> </div> <div class="thumb-small-gallery"> <a class="fancybox" rel="gallery1" href="images/gallery/gallery5.jpg" title="Gallery Tittle One"> <img src="images/gallery/gallery-small-thumb5.jpg" alt="" /> </a> </div> <div class="thumb-small-gallery"> <a class="fancybox" rel="gallery1" href="images/gallery/gallery6.jpg" title="Gallery Tittle One"> <img src="images/gallery/gallery-small-thumb6.jpg" alt="" /> </a> </div> <div class="thumb-small-gallery"> <a class="fancybox" rel="gallery1" href="images/gallery/gallery7.jpg" title="Gallery Tittle One"> <img src="images/gallery/gallery-small-thumb7.jpg" alt="" /> </a> </div> <div class="thumb-small-gallery"> <a class="fancybox" rel="gallery1" href="images/gallery/gallery8.jpg" title="Gallery Tittle One"> <img src="images/gallery/gallery-small-thumb8.jpg" alt="" /> </a> </div> </div> <!-- /.galler-small-thumbs --> </div> <!-- /.widget-inner --> </div> <!-- /.widget-main --> </div> <!-- /.col-md-4 --> </div> <!-- /.row --> </div> <!-- /.container --> <!-- begin The Footer --> <footer class="site-footer"> <div class="container"> <div class="row"> <div class="col-md-3"> <div class="footer-widget"> <h4 class="footer-widget-title">Contact Us</h4> <p>The simple contact form below comes packed within this theme. </br></br>Mailing address:</br>877 Filbert Street</br> Chester, PA 19013</p> </div> </div> <div class="col-md-2 col-sm-4"> <div class="footer-widget"> <h4 class="footer-widget-title">Favourites</h4> <ul class="list-links"> <li><a href="#">A to Z Index</a></li> <li><a href="#">Admissions</a></li> <li><a href="#">Bookstore</a></li> <li><a href="#">Catalog / Classes</a></li> <li><a href="#">Dining</a></li> <li><a href="#">Financial Aid</a></li> <li><a href="#">Graduation</a></li> </ul> </div> </div> <div class="col-md-2 col-sm-4"> <div class="footer-widget"> <h4 class="footer-widget-title">Resources For</h4> <ul class="list-links"> <li><a href="#">Future Students</a></li> <li><a href="#">Current Students</a></li> <li><a href="#">Faculty/Staff</a></li> <li><a href="#">International</a></li> <li><a href="#">Postdocs</a></li> <li><a href="#">Alumni</a></li> </ul> </div> </div> <div class="col-md-2 col-sm-4"> <div class="footer-widget"> <h4 class="footer-widget-title">Study</h4> <ul class="list-links"> <li><a href="#">Courses</a></li> <li><a href="#">Apply Now</a></li> <li><a href="#">Scholarships</a></li> <li><a href="#">FAQs</a></li> <li><a href="#">International student enquiries</a></li> </ul> </div> </div> <div class="col-md-3"> <div class="footer-widget"> <ul class="footer-media-icons"> <li><a href="#" class="fa fa-facebook"></a></li> <li><a href="#" class="fa fa-twitter"></a></li> <li><a href="#" class="fa fa-google-plus"></a></li> <li><a href="#" class="fa fa-youtube"></a></li> <li><a href="#" class="fa fa-linkedin"></a></li> <li><a href="#" class="fa fa-instagram"></a></li> <li><a href="#" class="fa fa-apple"></a></li> <li><a href="#" class="fa fa-rss"></a></li> </ul> </div> </div> </div> <!-- /.row --> <div class="bottom-footer"> <div class="row"> <div class="col-md-5"> <p class="small-text">&copy; Copyright 2014. Universe designed by <a href="#">Esmeth</a></p> </div> <!-- /.col-md-5 --> <div class="col-md-7"> <ul class="footer-nav"> <li><a href="index.html">Home</a></li> <li><a href="courses.html">Courses</a></li> <li><a href="events-list.html">Events</a></li> <li><a href="blog.html">Blog</a></li> <li><a href="shortcodes.html">Shortcodes</a></li> <li><a href="contact.html">Contact</a></li> </ul> </div> <!-- /.col-md-7 --> </div> <!-- /.row --> </div> <!-- /.bottom-footer --> </div> <!-- /.container --> </footer> <!-- /.site-footer --> <script src="bootstrap/js/bootstrap.min.js"></script> <script src="js/plugins.js"></script> <script src="js/custom.js"></script> </body> </html>
iclockwork/percy
web/src/main/webapp/res/universe/archives.html
HTML
apache-2.0
21,672
<!doctype html> <html class="default no-js"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>&quot;stats/base/dists/chisquare/entropy/docs/types/index.d&quot; | stdlib</title> <meta name="description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing."> <meta name="author" content="stdlib"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <!-- Icons --> <link rel="apple-touch-icon" sizes="180x180" href="../apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="../favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../favicon-16x16.png"> <link rel="manifest" href="../manifest.json"> <link rel="mask-icon" href="../safari-pinned-tab.svg" color="#5bbad5"> <meta name="theme-color" content="#ffffff"> <!-- Facebook Open Graph --> <meta property="og:type" content="website"> <meta property="og:site_name" content="stdlib"> <meta property="og:url" content="https://stdlib.io/"> <meta property="og:title" content="A standard library for JavaScript and Node.js."> <meta property="og:description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing."> <meta property="og:locale" content="en_US"> <meta property="og:image" content=""> <!-- Twitter --> <meta name="twitter:card" content="A standard library for JavaScript and Node.js."> <meta name="twitter:site" content="@stdlibjs"> <meta name="twitter:url" content="https://stdlib.io/"> <meta name="twitter:title" content="stdlib"> <meta name="twitter:description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing."> <meta name="twitter:image" content=""> <link rel="stylesheet" href="../assets/css/main.css"> <link rel="stylesheet" href="../assets/css/theme.css"> </head> <body> <header> <div class="tsd-page-toolbar"> <div class="container"> <div class="table-wrap"> <div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base=".."> <div class="field"> <label for="tsd-search-field" class="tsd-widget search no-caption">Search</label> <input id="tsd-search-field" type="text" /> </div> <ul class="results"> <li class="state loading">Preparing search index...</li> <li class="state failure">The search index is not available</li> </ul> <a href="../index.html" class="title"><img src="../logo_white.svg" alt="stdlib"></a> </div> <div class="table-cell" id="tsd-widgets"> <div id="tsd-filter"> <a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a> <div class="tsd-filter-group"> <div class="tsd-select" id="tsd-filter-visibility"> <span class="tsd-select-label">All</span> <ul class="tsd-select-list"> <li data-value="public">Public</li> <li data-value="protected">Public/Protected</li> <li data-value="private" class="selected">All</li> </ul> </div> <input type="checkbox" id="tsd-filter-inherited" checked /> <label class="tsd-widget" for="tsd-filter-inherited">Inherited</label> <input type="checkbox" id="tsd-filter-only-exported" /> <label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label> </div> </div> <a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a> </div> </div> </div> </div> <div class="tsd-page-title"> <div class="container"> <ul class="tsd-breadcrumb"> <li> <a href="../globals.html">Globals</a> </li> <li> <a href="_stats_base_dists_chisquare_entropy_docs_types_index_d_.html">&quot;stats/base/dists/chisquare/entropy/docs/types/index.d&quot;</a> </li> </ul> <h1>External module &quot;stats/base/dists/chisquare/entropy/docs/types/index.d&quot;</h1> </div> </div> </header> <div class="container container-main"> <div class="row"> <div class="col-8 col-content"> <section class="tsd-panel-group tsd-index-group"> <h2>Index</h2> <section class="tsd-panel tsd-index-panel"> <div class="tsd-index-content"> <section class="tsd-index-section tsd-is-not-exported"> <h3>Functions</h3> <ul class="tsd-index-list"> <li class="tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported"><a href="_stats_base_dists_chisquare_entropy_docs_types_index_d_.html#entropy" class="tsd-kind-icon">entropy</a></li> </ul> </section> </div> </section> </section> <section class="tsd-panel-group tsd-member-group tsd-is-not-exported"> <h2>Functions</h2> <section class="tsd-panel tsd-member tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported"> <a name="entropy" class="tsd-anchor"></a> <h3>entropy</h3> <ul class="tsd-signatures tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported"> <li class="tsd-signature tsd-kind-icon">entropy<span class="tsd-signature-symbol">(</span>k<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span></li> </ul> <ul class="tsd-descriptions"> <li class="tsd-description"> <aside class="tsd-sources"> <ul> <li>Defined in <a href="https://github.com/stdlib-js/stdlib/blob/61b1a8a068/lib/node_modules/@stdlib/stats/base/dists/chisquare/entropy/docs/types/index.d.ts#L47">lib/node_modules/@stdlib/stats/base/dists/chisquare/entropy/docs/types/index.d.ts:47</a></li> </ul> </aside> <div class="tsd-comment tsd-typography"> <div class="lead"> <p>Returns the differential entropy of a chi-squared distribution (in nats).</p> </div> <a href="#notes" id="notes" style="color: inherit; text-decoration: none;"> <h2>Notes</h2> </a> <ul> <li>If provided <code>k &lt;= 0</code>, the function returns <code>NaN</code>.</li> </ul> </div> <h4 class="tsd-parameters-title">Parameters</h4> <ul class="tsd-parameters"> <li> <h5>k: <span class="tsd-signature-type">number</span></h5> <div class="tsd-comment tsd-typography"> <p>degrees of freedom</p> </div> </li> </ul> <h4 class="tsd-returns-title">Returns <span class="tsd-signature-type">number</span> </h4> <p>entropy</p> <h4 class="tsd-example-title">Example</h4> <div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> v = entropy( <span class="hljs-number">9.0</span> ); <span class="hljs-comment">// returns ~2.786</span></code></pre> </div> <h4 class="tsd-example-title">Example</h4> <div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> v = entropy( <span class="hljs-number">1.0</span> ); <span class="hljs-comment">// returns ~0.784</span></code></pre> </div> <h4 class="tsd-example-title">Example</h4> <div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> v = entropy( <span class="hljs-number">-0.2</span> ); <span class="hljs-comment">// returns NaN</span></code></pre> </div> <h4 class="tsd-example-title">Example</h4> <div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> v = entropy( <span class="hljs-literal">NaN</span> ); <span class="hljs-comment">// returns NaN</span></code></pre> </div> </li> </ul> </section> </section> </div> <div class="col-4 col-menu menu-sticky-wrap menu-highlight"> <nav class="tsd-navigation primary"> <ul> <li class="globals "> <a href="../globals.html"><em>Packages</em></a> </li> <li class="current tsd-kind-external-module"> <a href="_stats_base_dists_chisquare_entropy_docs_types_index_d_.html">&quot;stats/base/dists/chisquare/entropy/docs/types/index.d&quot;</a> </li> </ul> </nav> <nav class="tsd-navigation secondary menu-sticky"> <ul class="before-current"> <li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported"> <a href="_stats_base_dists_chisquare_entropy_docs_types_index_d_.html#entropy" class="tsd-kind-icon">entropy</a> </li> </ul> </nav> </div> </div> </div> <footer> <div class="container"> <h2>Legend</h2> <div class="tsd-legend-group"> <ul class="tsd-legend"> <li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li> <li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li> <li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li> <li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li> <li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li> <li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li> <li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li> <li class="tsd-kind-type-alias tsd-has-type-parameter"><span class="tsd-kind-icon">Type alias with type parameter</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li> <li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li> <li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li> <li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li> <li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li> <li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li> <li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li> <li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li> <li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li> <li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li> <li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li> <li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li> <li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li> </ul> </div> </div> <div class="bottom-nav center border-top"> <a href="https://www.patreon.com/athan">Donate</a> / <a href="/docs/api/">Docs</a> / <a href="https://gitter.im/stdlib-js/stdlib">Chat</a> / <a href="https://twitter.com/stdlibjs">Twitter</a> / <a href="https://github.com/stdlib-js/stdlib">Contribute</a> </div> </footer> <div class="overlay"></div> <script src="../assets/js/main.js"></script> <script src="../assets/js/theme.js"></script> <script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-105890493-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
stdlib-js/www
public/docs/ts/latest/modules/_stats_base_dists_chisquare_entropy_docs_types_index_d_.html
HTML
apache-2.0
14,334
package it.reply.workflowmanager.cdi.orchestrator.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Qualifier; /** * Qualifier for CDI {@link EntityManager}. * */ @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) public @interface PlatformPersistenceUnit { }
ConceptReplyIT/workflow-manager
workflow-manager-cdi/src/main/java/it/reply/workflowmanager/cdi/orchestrator/annotations/PlatformPersistenceUnit.java
Java
apache-2.0
499
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: Apache License, Version 2.0 * See the LICENSE file in the root directory or visit http://www.apache.org/licenses/LICENSE-2.0 */ package org.hibernate.sqm.query.expression.function; import org.hibernate.sqm.SemanticQueryWalker; import org.hibernate.sqm.domain.BasicType; import org.hibernate.sqm.query.expression.SqmExpression; /** * @author Steve Ebersole */ public class AvgFunctionSqmExpression extends AbstractAggregateFunctionSqmExpression implements AggregateFunctionSqmExpression { public static final String NAME = "avg"; public AvgFunctionSqmExpression(SqmExpression argument, boolean distinct, BasicType resultType) { super( argument, distinct, resultType ); } @Override public String getFunctionName() { return NAME; } @Override public <T> T accept(SemanticQueryWalker<T> walker) { return walker.visitAvgFunction( this ); } }
johnaoahra80/hibernate-semantic-query
src/main/java/org/hibernate/sqm/query/expression/function/AvgFunctionSqmExpression.java
Java
apache-2.0
936
name "nyan-cat" maintainer "Sean OMeara" maintainer_email "[email protected]" license "apache2" description "Installs/Configures nyan-cat" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "0.1.4" depends 'line'
someara/nyan-cat-cookbook
metadata.rb
Ruby
apache-2.0
288
package com.org.scgroup.simplerequest.hanlder; import com.org.scgroup.simplerequest.IRequest; import com.org.scgroup.simplerequest.IRequestCallback; import com.org.scgroup.simplerequest.IRequestService; public interface IExecutorHanlder { <RESULT> void executeRequest(IRequestService service, IRequest<RESULT> request, IRequestCallback<RESULT> callback); void shutdown(); boolean shouldShutdownWhenEmpty(); }
ductranit/SimpleRequest
SimpleRequest/src/com/org/scgroup/simplerequest/hanlder/IExecutorHanlder.java
Java
apache-2.0
414
package com.fasterxml.jackson.datatype.jsr310; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; import static org.hamcrest.core.StringContains.containsString; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collection; @RunWith(Parameterized.class) public class TestLocalDateSerializationWithCustomFormatter { private final DateTimeFormatter formatter; public TestLocalDateSerializationWithCustomFormatter(DateTimeFormatter formatter) { this.formatter = formatter; } @Test public void testSerialization() throws Exception { LocalDate date = LocalDate.now(); assertThat(serializeWith(date, formatter), containsString(date.format(formatter))); } private String serializeWith(LocalDate date, DateTimeFormatter f) throws Exception { ObjectMapper mapper = new ObjectMapper().registerModule(new SimpleModule() .addSerializer(new LocalDateSerializer(f))); return mapper.writeValueAsString(date); } @Test public void testDeserialization() throws Exception { LocalDate date = LocalDate.now(); assertThat(deserializeWith(date.format(formatter), formatter), equalTo(date)); } private LocalDate deserializeWith(String json, DateTimeFormatter f) throws Exception { ObjectMapper mapper = new ObjectMapper().registerModule(new SimpleModule() .addDeserializer(LocalDate.class, new LocalDateDeserializer(f))); return mapper.readValue("\"" + json + "\"", LocalDate.class); } @Parameters public static Collection<Object[]> customFormatters() { Collection<Object[]> formatters = new ArrayList<>(); formatters.add(new Object[]{DateTimeFormatter.BASIC_ISO_DATE}); formatters.add(new Object[]{DateTimeFormatter.ISO_DATE}); formatters.add(new Object[]{DateTimeFormatter.ISO_LOCAL_DATE}); formatters.add(new Object[]{DateTimeFormatter.ISO_ORDINAL_DATE}); formatters.add(new Object[]{DateTimeFormatter.ISO_WEEK_DATE}); formatters.add(new Object[]{DateTimeFormatter.ofPattern("MM/dd/yyyy")}); return formatters; } }
kevinjom/jackson-modules-java8
datetime/src/test/java/com/fasterxml/jackson/datatype/jsr310/TestLocalDateSerializationWithCustomFormatter.java
Java
apache-2.0
2,637
/* * Copyright 2014 Guillaume Masclet <[email protected]>. * * 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.elasticlib.common.bson; import java.math.BigDecimal; import java.time.Instant; import static java.util.Collections.unmodifiableMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import static org.elasticlib.common.bson.ValueReading.readMap; import org.elasticlib.common.hash.Guid; import org.elasticlib.common.hash.Hash; import org.elasticlib.common.value.Value; /** * A binary reader. Converts a JSON-like binary structure into a map. */ public class BsonReader { private final Map<String, Value> map; /** * Constructor. * * @param bytes A JSON-like binary structure. */ public BsonReader(byte[] bytes) { map = unmodifiableMap(readMap(new ByteArrayReader(bytes), bytes.length)); } /** * Returns <tt>true</tt> if decoded structure contains a mapping for the specified key. * * @param key key whose presence in decoded structure is to be tested * @return <tt>true</tt> if this map contains a mapping for the specified key */ public boolean containsKey(String key) { return map.containsKey(key); } /** * Returns a sorted {@link Set} of the keys contained in decoded structure. * * @return A set. */ public Set<String> keyset() { return map.keySet(); } /** * Returns decoded structure as a map of values. * * @return A set. */ public Map<String, Value> asMap() { return map; } /** * Returns the value to which the specified key is mapped in decoded structure. Fails if decoded structure does not * contain a mapping for the specified key or if the value is actually not a hash. * * @param key The key whose associated value is to be returned. * @return A hash. */ public Hash getHash(String key) { return get(key).asHash(); } /** * Returns the value to which the specified key is mapped in decoded structure. Fails if decoded structure does not * contain a mapping for the specified key or if the value is actually not a GUID. * * @param key The key whose associated value is to be returned. * @return A GUID. */ public Guid getGuid(String key) { return get(key).asGuid(); } /** * Returns the value to which the specified key is mapped in decoded structure. Fails if decoded structure does not * contain a mapping for the specified key or if the value is actually not a byte array. * * @param key The key whose associated value is to be returned. * @return A byte array. */ public byte[] getByteArray(String key) { return get(key).asByteArray(); } /** * Returns the value to which the specified key is mapped in decoded structure. Fails if decoded structure does not * contain a mapping for the specified key or if the value is actually not a boolean. * * @param key The key whose associated value is to be returned. * @return A boolean. */ public boolean getBoolean(String key) { return get(key).asBoolean(); } /** * Returns the value to which the specified key is mapped in decoded structure. Fails if decoded structure does not * contain a mapping for the specified key or if the value is actually not a long. * * @param key The key whose associated value is to be returned. * @return A long. */ public long getLong(String key) { return get(key).asLong(); } /** * Returns the value to which the specified key is mapped in decoded structure. Fails if decoded structure does not * contain a mapping for the specified key or if the value is actually not a big decimal. * * @param key The key whose associated value is to be returned. * @return A big decimal. */ public BigDecimal getBigDecimal(String key) { return get(key).asBigDecimal(); } /** * Returns the value to which the specified key is mapped in decoded structure. Fails if decoded structure does not * contain a mapping for the specified key or if the value is actually not a string. * * @param key The key whose associated value is to be returned. * @return A string. */ public String getString(String key) { return get(key).asString(); } /** * Returns the value to which the specified key is mapped in decoded structure. Fails if decoded structure does not * contain a mapping for the specified key or if the value is actually not an instant. * * @param key The key whose associated value is to be returned. * @return An instant. */ public Instant getInstant(String key) { return get(key).asInstant(); } /** * Returns the value to which the specified key is mapped in decoded structure. Fails if decoded structure does not * contain a mapping for the specified key or if the value is actually not a map. * * @param key The key whose associated value is to be returned. * @return A map. */ public Map<String, Value> getMap(String key) { return get(key).asMap(); } /** * Returns the value to which the specified key is mapped in decoded structure. Fails if decoded structure does not * contain a mapping for the specified key or if the value is actually not a list. * * @param key The key whose associated value is to be returned. * @return A list. */ public List<Value> getList(String key) { return get(key).asList(); } /** * Returns the value to which the specified key is mapped in decoded structure. Fails if decoded structure does not * contain a mapping for the specified key. * * @param key The key whose associated value is to be returned. * @return A Value. */ public Value get(String key) { if (!map.containsKey(key)) { throw new NoSuchElementException(); } return map.get(key); } }
elasticlib/elasticlib
elasticlib-common/src/main/java/org/elasticlib/common/bson/BsonReader.java
Java
apache-2.0
6,725
/* * (c) Copyright 2018 Palantir Technologies 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.palantir.atlasdb.keyvalue.impl; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Multimap; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import com.google.common.util.concurrent.ListenableFuture; import com.palantir.atlasdb.keyvalue.api.BatchColumnRangeSelection; import com.palantir.atlasdb.keyvalue.api.CandidateCellForSweeping; import com.palantir.atlasdb.keyvalue.api.CandidateCellForSweepingRequest; import com.palantir.atlasdb.keyvalue.api.Cell; import com.palantir.atlasdb.keyvalue.api.CheckAndSetCompatibility; import com.palantir.atlasdb.keyvalue.api.CheckAndSetRequest; import com.palantir.atlasdb.keyvalue.api.ClusterAvailabilityStatus; import com.palantir.atlasdb.keyvalue.api.ColumnRangeSelection; import com.palantir.atlasdb.keyvalue.api.ColumnSelection; import com.palantir.atlasdb.keyvalue.api.KeyAlreadyExistsException; import com.palantir.atlasdb.keyvalue.api.KeyValueService; import com.palantir.atlasdb.keyvalue.api.RangeRequest; import com.palantir.atlasdb.keyvalue.api.RowColumnRangeIterator; import com.palantir.atlasdb.keyvalue.api.RowResult; import com.palantir.atlasdb.keyvalue.api.TableReference; import com.palantir.atlasdb.keyvalue.api.TimestampRangeDelete; import com.palantir.atlasdb.keyvalue.api.Value; import com.palantir.atlasdb.logging.KvsProfilingLogger; import com.palantir.atlasdb.logging.KvsProfilingLogger.LoggingFunction; import com.palantir.atlasdb.logging.LoggingArgs; import com.palantir.common.base.ClosableIterator; import com.palantir.util.paging.TokenBackedBasicResultsPage; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Supplier; public final class ProfilingKeyValueService implements KeyValueService { private final KeyValueService delegate; public static ProfilingKeyValueService create(KeyValueService delegate) { return new ProfilingKeyValueService(delegate); } /** * @param delegate the KeyValueService to be profiled * @param slowLogThresholdMillis sets the threshold for slow log, Defaults to using a 1 second slowlog. * @return ProfilingKeyValueService that profiles the delegate KeyValueService * @deprecated in favour of ProfilingKeyValueService#create(KeyValueService delegate). Use {@link * KvsProfilingLogger#setSlowLogThresholdMillis(long)} to configure the slow logging threshold. */ @Deprecated public static ProfilingKeyValueService create(KeyValueService delegate, long slowLogThresholdMillis) { KvsProfilingLogger.setSlowLogThresholdMillis(slowLogThresholdMillis); return create(delegate); } private ProfilingKeyValueService(KeyValueService delegate) { this.delegate = delegate; } private static BiConsumer<LoggingFunction, Stopwatch> logCellsAndSize( String method, TableReference tableRef, int numCells, long sizeInBytes) { long startTime = System.currentTimeMillis(); return (logger, stopwatch) -> logger.log( "Call to KVS.{} at time {}, on table {} for {} cells of overall size {} bytes took {} ms.", LoggingArgs.method(method), LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableRef(tableRef), LoggingArgs.cellCount(numCells), LoggingArgs.sizeInBytes(sizeInBytes), LoggingArgs.durationMillis(stopwatch)); } private static BiConsumer<LoggingFunction, Stopwatch> logTime(String method) { long startTime = System.currentTimeMillis(); return (logger, stopwatch) -> logger.log( "Call to KVS.{} at time {}, took {} ms.", LoggingArgs.method(method), LoggingArgs.startTimeMillis(startTime), LoggingArgs.durationMillis(stopwatch)); } private static BiConsumer<LoggingFunction, Stopwatch> logTimeAndTable(String method, TableReference tableRef) { long startTime = System.currentTimeMillis(); return (logger, stopwatch) -> logger.log( "Call to KVS.{} at time {}, on table {} took {} ms.", LoggingArgs.method(method), LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableRef(tableRef), LoggingArgs.durationMillis(stopwatch)); } private static BiConsumer<LoggingFunction, Stopwatch> logTimeAndTableCount(String method, int tableCount) { long startTime = System.currentTimeMillis(); return (logger, stopwatch) -> logger.log( "Call to KVS.{} at time {}, for {} tables took {} ms.", LoggingArgs.method(method), LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableCount(tableCount), LoggingArgs.durationMillis(stopwatch)); } private static BiConsumer<LoggingFunction, Stopwatch> logTimeAndTableRange( String method, TableReference tableRef, RangeRequest range) { long startTime = System.currentTimeMillis(); return (logger, stopwatch) -> logger.log( "Call to KVS.{} at time {}, on table {} with range {} took {} ms.", LoggingArgs.method(method), LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableRef(tableRef), LoggingArgs.range(tableRef, range), LoggingArgs.durationMillis(stopwatch)); } private static BiConsumer<LoggingFunction, Stopwatch> logTimeAndTableRows( String method, TableReference tableRef, Iterable<byte[]> rows) { long startTime = System.currentTimeMillis(); return (logger, stopwatch) -> logger.log( "Call to KVS.{} at time {}, on table {} for (estimated) {} rows took {} ms.", LoggingArgs.method(method), LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableRef(tableRef), LoggingArgs.rowCount(Ints.saturatedCast(rows.spliterator().estimateSize())), LoggingArgs.durationMillis(stopwatch)); } private static BiConsumer<LoggingFunction, Map<Cell, Value>> logCellResultSize(long overhead) { return (logger, result) -> { long sizeInBytes = 0; for (Map.Entry<Cell, Value> entry : result.entrySet()) { sizeInBytes += Cells.getApproxSizeOfCell(entry.getKey()) + entry.getValue().getContents().length + overhead; } logger.log("and returned {} bytes.", LoggingArgs.sizeInBytes(sizeInBytes)); }; } @Override public void addGarbageCollectionSentinelValues(TableReference tableRef, Iterable<Cell> cells) { long startTime = System.currentTimeMillis(); maybeLog( () -> delegate.addGarbageCollectionSentinelValues(tableRef, cells), (logger, stopwatch) -> logger.log( "Call to KVS.addGarbageCollectionSentinelValues at time {}, on table {} over {} cells took {}" + " ms.", LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableRef(tableRef), LoggingArgs.cellCount(Iterables.size(cells)), LoggingArgs.durationMillis(stopwatch))); } @Override public void createTable(TableReference tableRef, byte[] tableMetadata) { maybeLog(() -> delegate.createTable(tableRef, tableMetadata), logTimeAndTable("createTable", tableRef)); } @Override public void createTables(Map<TableReference, byte[]> tableRefToTableMetadata) { maybeLog( () -> delegate.createTables(tableRefToTableMetadata), logTimeAndTableCount( "createTables", tableRefToTableMetadata.keySet().size())); } @Override public void delete(TableReference tableRef, Multimap<Cell, Long> keys) { maybeLog( () -> delegate.delete(tableRef, keys), logCellsAndSize("delete", tableRef, keys.keySet().size(), byteSize(keys))); } @Override public void deleteRange(TableReference tableRef, RangeRequest range) { maybeLog(() -> delegate.deleteRange(tableRef, range), logTimeAndTableRange("deleteRange", tableRef, range)); } @Override public void deleteRows(TableReference tableRef, Iterable<byte[]> rows) { maybeLog(() -> delegate.deleteRows(tableRef, rows), logTimeAndTableRows("deleteRows", tableRef, rows)); } @Override public void deleteAllTimestamps(TableReference tableRef, Map<Cell, TimestampRangeDelete> deletes) { maybeLog( () -> delegate.deleteAllTimestamps(tableRef, deletes), logTimeAndTable("deleteAllTimestamps", tableRef)); } @Override public void dropTable(TableReference tableRef) { maybeLog(() -> delegate.dropTable(tableRef), logTimeAndTable("dropTable", tableRef)); } @Override public void dropTables(Set<TableReference> tableRefs) { maybeLog(() -> delegate.dropTables(tableRefs), logTimeAndTableCount("dropTable", tableRefs.size())); } @Override public Map<Cell, Value> get(TableReference tableRef, Map<Cell, Long> timestampByCell) { long startTime = System.currentTimeMillis(); return KvsProfilingLogger.maybeLog( () -> delegate.get(tableRef, timestampByCell), (logger, stopwatch) -> logger.log( "Call to KVS.get at time {}, on table {}, requesting {} cells took {} ms ", LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableRef(tableRef), LoggingArgs.cellCount(timestampByCell.size()), LoggingArgs.durationMillis(stopwatch)), logCellResultSize(4L)); } @Override public Set<TableReference> getAllTableNames() { return maybeLog(delegate::getAllTableNames, logTime("getAllTableNames")); } @Override public Multimap<Cell, Long> getAllTimestamps(TableReference tableRef, Set<Cell> cells, long timestamp) { return maybeLog( () -> delegate.getAllTimestamps(tableRef, cells, timestamp), logCellsAndSize("getAllTimestamps", tableRef, cells.size(), cells.size() * Longs.BYTES)); } @Override public Collection<? extends KeyValueService> getDelegates() { return ImmutableList.of(delegate); } @Override public Map<RangeRequest, TokenBackedBasicResultsPage<RowResult<Value>, byte[]>> getFirstBatchForRanges( TableReference tableRef, Iterable<RangeRequest> rangeRequests, long timestamp) { return maybeLog( () -> delegate.getFirstBatchForRanges(tableRef, rangeRequests, timestamp), logTimeAndTable("getFirstBatchForRanges", tableRef)); } @Override public Map<Cell, Long> getLatestTimestamps(TableReference tableRef, Map<Cell, Long> timestampByCell) { return maybeLog( () -> delegate.getLatestTimestamps(tableRef, timestampByCell), logCellsAndSize("getLatestTimestamps", tableRef, timestampByCell.size(), byteSize(timestampByCell))); } @Override public byte[] getMetadataForTable(TableReference tableRef) { return maybeLog(() -> delegate.getMetadataForTable(tableRef), logTimeAndTable("getMetadataForTable", tableRef)); } @Override public Map<TableReference, byte[]> getMetadataForTables() { return maybeLog(delegate::getMetadataForTables, logTime("getMetadataForTables")); } @Override public ClosableIterator<RowResult<Value>> getRange( TableReference tableRef, RangeRequest rangeRequest, long timestamp) { return maybeLog( () -> delegate.getRange(tableRef, rangeRequest, timestamp), logTimeAndTableRange("getRange", tableRef, rangeRequest)); } @Override public ClosableIterator<RowResult<Set<Long>>> getRangeOfTimestamps( TableReference tableRef, RangeRequest rangeRequest, long timestamp) { return maybeLog( () -> delegate.getRangeOfTimestamps(tableRef, rangeRequest, timestamp), logTimeAndTableRange("getRangeOfTimestamps", tableRef, rangeRequest)); } @Override public ClosableIterator<List<CandidateCellForSweeping>> getCandidateCellsForSweeping( TableReference tableRef, CandidateCellForSweepingRequest request) { return maybeLog( () -> delegate.getCandidateCellsForSweeping(tableRef, request), logTime("getCandidateCellsForSweeping")); } @Override public Map<Cell, Value> getRows( TableReference tableRef, Iterable<byte[]> rows, ColumnSelection columnSelection, long timestamp) { long startTime = System.currentTimeMillis(); return KvsProfilingLogger.maybeLog( () -> delegate.getRows(tableRef, rows, columnSelection, timestamp), (logger, stopwatch) -> logger.log( "Call to KVS.getRows at time {}, on table {} requesting {} columns from {} rows took {} ms ", LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableRef(tableRef), LoggingArgs.columnCount(columnSelection), LoggingArgs.rowCount(Iterables.size(rows)), LoggingArgs.durationMillis(stopwatch)), logCellResultSize(0L)); } @Override public void multiPut(Map<TableReference, ? extends Map<Cell, byte[]>> valuesByTable, long timestamp) { long startTime = System.currentTimeMillis(); maybeLog(() -> delegate.multiPut(valuesByTable, timestamp), (logger, stopwatch) -> { int totalCells = 0; long totalBytes = 0; for (Map<Cell, byte[]> values : valuesByTable.values()) { totalCells += values.size(); totalBytes += byteSize(values); } logger.log( "Call to KVS.multiPut at time {}, on {} tables putting {} total cells of {} total bytes took {}" + " ms.", LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableCount(valuesByTable.keySet().size()), LoggingArgs.cellCount(totalCells), LoggingArgs.sizeInBytes(totalBytes), LoggingArgs.durationMillis(stopwatch)); }); } @Override public void put(TableReference tableRef, Map<Cell, byte[]> values, long timestamp) { maybeLog( () -> delegate.put(tableRef, values, timestamp), logCellsAndSize("put", tableRef, values.keySet().size(), byteSize(values))); } @Override public void putMetadataForTable(TableReference tableRef, byte[] metadata) { maybeLog( () -> delegate.putMetadataForTable(tableRef, metadata), logTimeAndTable("putMetadataForTable", tableRef)); } @Override public void putMetadataForTables(Map<TableReference, byte[]> tableRefToMetadata) { maybeLog( () -> delegate.putMetadataForTables(tableRefToMetadata), logTimeAndTableCount( "putMetadataForTables", tableRefToMetadata.keySet().size())); } @Override public void putUnlessExists(TableReference tableRef, Map<Cell, byte[]> values) throws KeyAlreadyExistsException { maybeLog( () -> delegate.putUnlessExists(tableRef, values), logCellsAndSize("putUnlessExists", tableRef, values.keySet().size(), byteSize(values))); } @Override public void setOnce(TableReference tableRef, Map<Cell, byte[]> values) { maybeLog( () -> delegate.setOnce(tableRef, values), logCellsAndSize("setOnce", tableRef, values.keySet().size(), byteSize(values))); } @Override public CheckAndSetCompatibility getCheckAndSetCompatibility() { return delegate.getCheckAndSetCompatibility(); } @Override public void checkAndSet(CheckAndSetRequest request) { maybeLog( () -> delegate.checkAndSet(request), logCellsAndSize("checkAndSet", request.table(), 1, request.newValue().length)); } @Override public void putWithTimestamps(TableReference tableRef, Multimap<Cell, Value> values) { maybeLog( () -> delegate.putWithTimestamps(tableRef, values), logCellsAndSize("putWithTimestamps", tableRef, values.keySet().size(), byteSize(values))); } @Override public void close() { maybeLog(delegate::close, logTime("close")); } @Override public void truncateTable(TableReference tableRef) { maybeLog(() -> delegate.truncateTable(tableRef), logTimeAndTable("truncateTable", tableRef)); } @Override public void truncateTables(Set<TableReference> tableRefs) { maybeLog(() -> delegate.truncateTables(tableRefs), logTimeAndTableCount("truncateTables", tableRefs.size())); } @Override public void compactInternally(TableReference tableRef) { maybeLog(() -> delegate.compactInternally(tableRef), logTimeAndTable("compactInternally", tableRef)); } @Override public ClusterAvailabilityStatus getClusterAvailabilityStatus() { return maybeLog(delegate::getClusterAvailabilityStatus, logTime("getClusterAvailabilityStatus")); } @Override public boolean isInitialized() { return maybeLog(delegate::isInitialized, logTime("isInitialized")); } @Override public void compactInternally(TableReference tableRef, boolean inMaintenanceMode) { long startTime = System.currentTimeMillis(); maybeLog(() -> delegate.compactInternally(tableRef, inMaintenanceMode), (logger, stopwatch) -> { if (inMaintenanceMode) { // Log differently in maintenance mode - if a compactInternally is slow this might be bad in normal // operational hours, but is probably okay in maintenance mode. logger.log( "Call to KVS.compactInternally (in maintenance mode) at time {}, on table {} took {} ms.", LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableRef(tableRef), LoggingArgs.durationMillis(stopwatch)); } else { logger.log( "Call to KVS.{} at time {}, on table {} took {} ms.", LoggingArgs.method("compactInternally"), LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableRef(tableRef), LoggingArgs.durationMillis(stopwatch)); } }); } @Override public Map<byte[], RowColumnRangeIterator> getRowsColumnRange( TableReference tableRef, Iterable<byte[]> rows, BatchColumnRangeSelection batchColumnRangeSelection, long timestamp) { long startTime = System.currentTimeMillis(); return maybeLog( () -> delegate.getRowsColumnRange(tableRef, rows, batchColumnRangeSelection, timestamp), (logger, stopwatch) -> logger.log( "Call to KVS.getRowsColumnRange at time {}, on table {} for {} rows with range {} took {} ms.", LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableRef(tableRef), LoggingArgs.rowCount(Iterables.size(rows)), LoggingArgs.batchColumnRangeSelection(batchColumnRangeSelection), LoggingArgs.durationMillis(stopwatch))); } @Override public RowColumnRangeIterator getRowsColumnRange( TableReference tableRef, Iterable<byte[]> rows, ColumnRangeSelection columnRangeSelection, int cellBatchHint, long timestamp) { long startTime = System.currentTimeMillis(); return maybeLog( () -> delegate.getRowsColumnRange(tableRef, rows, columnRangeSelection, cellBatchHint, timestamp), (logger, stopwatch) -> logger.log( "Call to KVS.getRowsColumnRange - CellBatch at time {}, on table {} for {} rows with range {} " + "and batch hint {} took {} ms.", LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableRef(tableRef), LoggingArgs.rowCount(Iterables.size(rows)), LoggingArgs.columnRangeSelection(columnRangeSelection), LoggingArgs.batchHint(cellBatchHint), LoggingArgs.durationMillis(stopwatch))); } private <T> T maybeLog(Supplier<T> action, BiConsumer<LoggingFunction, Stopwatch> logger) { return KvsProfilingLogger.maybeLog(action, logger); } private void maybeLog(Runnable runnable, BiConsumer<LoggingFunction, Stopwatch> logger) { KvsProfilingLogger.maybeLog(runnable, logger); } private static <T> long byteSize(Map<Cell, T> values) { long sizeInBytes = 0; for (Map.Entry<Cell, T> valueEntry : values.entrySet()) { sizeInBytes += Cells.getApproxSizeOfCell(valueEntry.getKey()); T value = valueEntry.getValue(); if (value instanceof byte[]) { sizeInBytes += ((byte[]) value).length; } else if (value instanceof Long) { sizeInBytes += Longs.BYTES; } } return sizeInBytes; } private static <T> long byteSize(Multimap<Cell, T> values) { long sizeInBytes = 0; for (Cell cell : values.keySet()) { sizeInBytes += Cells.getApproxSizeOfCell(cell) + values.get(cell).size(); } return sizeInBytes; } @Override public boolean shouldTriggerCompactions() { return delegate.shouldTriggerCompactions(); } @Override public List<byte[]> getRowKeysInRange(TableReference tableRef, byte[] startRow, byte[] endRow, int maxResults) { return maybeLog( () -> delegate.getRowKeysInRange(tableRef, startRow, endRow, maxResults), logTimeAndTable("getRowKeysInRange", tableRef)); } @Override public ListenableFuture<Map<Cell, Value>> getAsync(TableReference tableRef, Map<Cell, Long> timestampByCell) { long startTime = System.currentTimeMillis(); return KvsProfilingLogger.maybeLogAsync( () -> delegate.getAsync(tableRef, timestampByCell), (logger, stopwatch) -> logger.log( "Call to KVS.getAsync", LoggingArgs.startTimeMillis(startTime), LoggingArgs.tableRef(tableRef), LoggingArgs.cellCount(timestampByCell.size()), LoggingArgs.durationMillis(stopwatch)), logCellResultSize(4L)); } }
palantir/atlasdb
atlasdb-client/src/main/java/com/palantir/atlasdb/keyvalue/impl/ProfilingKeyValueService.java
Java
apache-2.0
24,182
/* * 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 de.unioninvestment.eai.portal.portlet.crud.scripting.domain.container.rest; import static java.util.Collections.unmodifiableList; import groovy.lang.Closure; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.DefaultHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.vaadin.data.Container.Filter; import de.unioninvestment.eai.portal.portlet.crud.config.GroovyScript; import de.unioninvestment.eai.portal.portlet.crud.config.ReSTAttributeConfig; import de.unioninvestment.eai.portal.portlet.crud.config.ReSTChangeConfig; import de.unioninvestment.eai.portal.portlet.crud.config.ReSTChangeMethodConfig; import de.unioninvestment.eai.portal.portlet.crud.config.ReSTContainerConfig; import de.unioninvestment.eai.portal.portlet.crud.config.ReSTFormatConfig; import de.unioninvestment.eai.portal.portlet.crud.domain.exception.BusinessException; import de.unioninvestment.eai.portal.portlet.crud.domain.exception.InvalidConfigurationException; import de.unioninvestment.eai.portal.portlet.crud.domain.exception.TechnicalCrudPortletException; import de.unioninvestment.eai.portal.portlet.crud.domain.model.GenericContainerRow; import de.unioninvestment.eai.portal.portlet.crud.domain.model.GenericContainerRowId; import de.unioninvestment.eai.portal.portlet.crud.domain.model.ReSTContainer; import de.unioninvestment.eai.portal.portlet.crud.domain.model.ReSTDelegate; import de.unioninvestment.eai.portal.portlet.crud.domain.model.authentication.Realm; import de.unioninvestment.eai.portal.portlet.crud.domain.support.AuditLogger; import de.unioninvestment.eai.portal.portlet.crud.scripting.model.ScriptRow; import de.unioninvestment.eai.portal.support.scripting.ScriptBuilder; import de.unioninvestment.eai.portal.support.vaadin.container.Column; import de.unioninvestment.eai.portal.support.vaadin.container.GenericItem; import de.unioninvestment.eai.portal.support.vaadin.container.MetaData; import de.unioninvestment.eai.portal.support.vaadin.container.UpdateContext; public class ReSTDelegateImpl implements ReSTDelegate { static final class ConstantStringProvider extends Closure<Object> { private final String string; private static final long serialVersionUID = 1L; ConstantStringProvider(Object owner, String newQueryUrl) { super(owner); this.string = newQueryUrl; } public String doCall() { return string; } } private static final List<Object[]> EMPTY_RESULT = unmodifiableList(new LinkedList<Object[]>()); private static final Logger LOGGER = LoggerFactory .getLogger(ReSTDelegateImpl.class); private ReSTContainerConfig config; private ScriptBuilder scriptBuilder; private MetaData metaData; HttpClient httpClient = new DefaultHttpClient(); PayloadParser parser; PayloadCreator creator; private ReSTContainer container; private Closure<Object> baseUrlProvider; private Closure<Object> queryUrlProvider; private AuditLogger auditLogger; public ReSTDelegateImpl(ReSTContainerConfig containerConfig, ReSTContainer container, Realm realm, ScriptBuilder scriptBuilder, AuditLogger auditLogger) { this.config = containerConfig; this.container = container; this.scriptBuilder = scriptBuilder; this.auditLogger = auditLogger; this.metaData = extractMetaData(); this.parser = createParser(); this.creator = createCreator(); this.baseUrlProvider = scriptBuilder.buildClosure(config.getBaseUrl()); this.queryUrlProvider = scriptBuilder.buildClosure(config.getQuery() .getUrl()); if (realm != null && httpClient instanceof DefaultHttpClient) { // for Testing => DefaultHttpClient cannot be fully mocked due to // final methods realm.applyBasicAuthentication((DefaultHttpClient) httpClient); } } private PayloadCreator createCreator() { if (config.getFormat() == ReSTFormatConfig.JSON) { return new JsonCreator(container, scriptBuilder); } else if (config.getFormat() == ReSTFormatConfig.XML) { return new XmlCreator(container, scriptBuilder); } else { throw new TechnicalCrudPortletException("Unknown ReST format: " + config.getFormat()); } } private PayloadParser createParser() { if (config.getFormat() == ReSTFormatConfig.JSON) { return new JsonParser(config, scriptBuilder); } else if (config.getFormat() == ReSTFormatConfig.XML) { return new XmlParser(config, scriptBuilder); } else { throw new TechnicalCrudPortletException("Unknown ReST format: " + config.getFormat()); } } private MetaData extractMetaData() { List<ReSTAttributeConfig> attributes = config.getQuery().getAttribute(); List<Column> columns = new ArrayList<Column>(attributes.size()); for (ReSTAttributeConfig attribute : attributes) { columns.add(new Column(attribute.getName(), attribute.getType(), attribute.isReadonly(), attribute.isRequired(), attribute .isPrimaryKey(), null)); } boolean insertSupported = config.getInsert() != null; boolean updateSupported = config.getUpdate() != null; boolean deleteSupported = config.getDelete() != null; return new MetaData(columns, insertSupported, updateSupported, deleteSupported, false, false); } @Override public MetaData getMetaData() { return metaData; } @Override public List<Object[]> getRows() { String queryUrl = (String) queryUrlProvider.call(); if (StringUtils.isBlank(queryUrl)) { return EMPTY_RESULT; } HttpGet request = createQueryRequest(); try { HttpResponse response = httpClient.execute(request); expectAnyStatusCode(response, HttpStatus.SC_OK); return parser.getRows(response); } catch (ClientProtocolException e) { LOGGER.error("Error during restful query", e); throw new BusinessException("portlet.crud.error.rest.io", e.getMessage()); } catch (IOException e) { LOGGER.error("Error during restful query", e); throw new BusinessException("portlet.crud.error.rest.io", e.getMessage()); } finally { request.releaseConnection(); } } private HttpGet createQueryRequest() { String queryUrl = queryUrlProvider.call().toString(); URI uri = createURI(queryUrl); HttpGet request = new HttpGet(uri); String mimetype = creator.getMimeType(); if (config.getMimetype() != null) { mimetype = config.getMimetype(); } request.addHeader("Accept", mimetype); return request; } private URI createURI(String postfix) { String uri = postfix; if (baseUrlProvider != null) { Object baseUrl = baseUrlProvider.call(); if (baseUrl != null) { uri = baseUrl.toString() + postfix; } } try { return URI.create(uri); } catch (IllegalArgumentException e) { throw new InvalidConfigurationException( "portlet.crud.error.config.rest.invalidUrl", uri); } } @Override public void setFilters(Filter[] filters) { throw new UnsupportedOperationException( "Server side filtering is not supported by the ReST backend"); } @Override public void update(List<GenericItem> items, UpdateContext context) { context.requireRefresh(); try { for (GenericItem item : items) { if (item.isNewItem() || item.isModified()) { ReSTChangeConfig changeConfig = findChangeConfig(item); ReSTChangeMethodConfig method = findRequestMethod(item); if (method == ReSTChangeMethodConfig.POST) { sendPostRequest(item, changeConfig); } else { sendPutRequest(item, changeConfig); } } else if (item.isDeleted()) { sendDeleteRequest(item); } } } catch (ClientProtocolException e) { LOGGER.error("Error during restful operation", e); throw new BusinessException("portlet.crud.error.rest.io", e.getMessage()); } catch (IOException e) { LOGGER.error("Error during restful operation", e); throw new BusinessException("portlet.crud.error.rest.io", e.getMessage()); } } private ReSTChangeConfig findChangeConfig(GenericItem item) { ReSTChangeConfig changeConfig = item.isNewItem() ? config.getInsert() : config.getUpdate(); return changeConfig; } private ReSTChangeMethodConfig findRequestMethod(GenericItem item) { ReSTChangeMethodConfig method = null; if (item.isNewItem()) { method = config.getInsert().getMethod(); if (method == null) { method = ReSTChangeMethodConfig.POST; } } else { method = config.getUpdate().getMethod(); if (method == null) { method = ReSTChangeMethodConfig.PUT; } } return method; } private void sendPostRequest(GenericItem item, ReSTChangeConfig changeConfig) throws IOException, ClientProtocolException { byte[] content = creator.create(item, changeConfig.getValue(), config.getCharset()); URI uri = createURI(item, changeConfig.getUrl()); HttpPost request = new HttpPost(uri); ContentType contentType = createContentType(); request.setEntity(new ByteArrayEntity(content, contentType)); try { HttpResponse response = httpClient.execute(request); auditLogger.auditReSTRequest(request.getMethod(), uri.toString(), new String(content, config.getCharset()), response .getStatusLine().toString()); expectAnyStatusCode(response, HttpStatus.SC_CREATED, HttpStatus.SC_NO_CONTENT); } finally { request.releaseConnection(); } } private void sendPutRequest(GenericItem item, ReSTChangeConfig changeConfig) throws ClientProtocolException, IOException { byte[] content = creator.create(item, changeConfig.getValue(), config.getCharset()); URI uri = createURI(item, changeConfig.getUrl()); HttpPut request = new HttpPut(uri); ContentType contentType = createContentType(); request.setEntity(new ByteArrayEntity(content, contentType)); try { HttpResponse response = httpClient.execute(request); auditLogger.auditReSTRequest(request.getMethod(), uri.toString(), new String(content, config.getCharset()), response .getStatusLine().toString()); expectAnyStatusCode(response, HttpStatus.SC_OK, HttpStatus.SC_NO_CONTENT); } finally { request.releaseConnection(); } } private void expectAnyStatusCode(HttpResponse response, int... acceptedStatusCodes) { StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); for (int i = 0; i < acceptedStatusCodes.length; i++) { if (acceptedStatusCodes[i] == statusCode) { return; } } throw new BusinessException("portlet.crud.error.rest.wrongStatus", statusCode, statusLine.getReasonPhrase()); } private ContentType createContentType() { String mimetype = creator.getMimeType(); if (config.getMimetype() != null) { mimetype = config.getMimetype(); } return ContentType.create(mimetype, config.getCharset()); } private void sendDeleteRequest(GenericItem item) throws ClientProtocolException, IOException { URI uri = createURI(item, config.getDelete().getUrl()); HttpDelete request = new HttpDelete(uri); try { HttpResponse response = httpClient.execute(request); auditLogger.auditReSTRequest(request.getMethod(), uri.toString(), response.getStatusLine().toString()); expectAnyStatusCode(response, HttpStatus.SC_OK, HttpStatus.SC_ACCEPTED, // marked for deletion HttpStatus.SC_NO_CONTENT); } finally { request.releaseConnection(); } } private URI createURI(GenericItem item, GroovyScript uriScript) { GenericContainerRowId containerRowId = new GenericContainerRowId( item.getId(), container.getPrimaryKeyColumns()); GenericContainerRow containerRow = new GenericContainerRow( containerRowId, item, container, false, true); ScriptRow row = new ScriptRow(containerRow); Object postfix = scriptBuilder.buildClosure(uriScript).call(row); return createURI(postfix.toString()); } public void setBaseUrl(final String newBaseUrl) { this.baseUrlProvider = new ConstantStringProvider(null, newBaseUrl); } public void setQueryUrl(final String newQueryUrl) { this.queryUrlProvider = new ConstantStringProvider(null, newQueryUrl); } }
Union-Investment/Crud2Go
eai-portal-support-scripting/src/main/java/de/unioninvestment/eai/portal/portlet/crud/scripting/domain/container/rest/ReSTDelegateImpl.java
Java
apache-2.0
13,370
<div class="property-pane animate-slide" ng-show="false" ng-class="{'pane-collasped': !editor.internal.enabled}"> <div class="jfc-container"> <div class="jfc-box"> <div class="pull-left align-middle header-bar jfc-width-10"> <button class="btn icon icon-back" ng-click="editor.toggleEditor()"></button> </div> <div class="align-middle align-center header-bar align-center menu-heading"> <div class="beta">Playbook</div> </div> </div> </div> <div ng-show="editor.internal.editconfig" class="jfc-container after-spacer"> <div class="jfc-box"> <div class="cell menu-heading"> <div> <h2 class="medium">Chart Configuration</h2> </div> </div> </div> </div> <div ng-if="editor.internal.editconfig" class="jfc-container jfc-width-96 after-spacer" ng-controller="ConfigController"> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Name</span> </span> <span class="cell"> <span> <uitext ng-model="editor.name"></uitext> </span> </span> </label> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Prefix</span> </span> <span class="cell"> <span> <uitext ng-model="editor.idPrefix"></uitext> </span> </span> </label> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Portal</span> </span> <span class="cell"> <span> <uiselect ng-model="editor.portal" list="application.portalList" displayField="portalNm" valuefield="portalValueField"></uiselect> </span> </span> </label> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Environment</span> </span> <span class="cell"> <span> <uiselect ng-model="editor.environment" list="application.environmentList" valuefield="environmentValueField"></uiselect> </span> </span> </label> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Module</span> </span> <span class="cell after-spacer"> <span> <uiselect ng-model="editor.project" list="application.projectList" valuefield="projectValueField"></uiselect> </span> </span> </label> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Owner</span> </span> <span class="cell"> <span> <uitext ng-model="editor.owner"></uitext> </span> </span> </label> </div> <div class="jfc-container jfc-toolbar"> <div class="jfc-box"> <div class="cell menu-heading"> <div> <h2 class="medium">Chart Item Properties</h2> </div> </div> </div> <div class="jfc-box"> <div class="jfc-container"> <div class="cell align-middle align-left"> <div> <button class="btn btn-medium" ng-click="exportChartJson()"> <i class="icon icon-database medium"></i> <span class="medium">Export</span> </button> </div> </div> <div class="cell align-middle align-right"> <div> <button ng-if="editor.chartList.length == 0" class="btn btn-medium" ng-click="addChartItem()"> <i class="icon icon-add medium"></i> <span class="medium">Begin</span> </button> <button ng-if="editor.editList.length > 0 && editor.editList[0].type != 'End'" class="btn btn-medium" ng-click="addOption()"> <i class="icon icon-add medium"></i> <span class="medium">Option</span> </button> <button ng-if="editor.editList.length > 0 && editor.editList[0].type == 'Actor'" class="btn btn-medium" ng-click="addActor()"> <i class="icon icon-add medium"></i> <span class="medium">Actor</span> </button> </div> </div> </div> </div> </div> <div class="jfc-container jfc-list" ng-show="editor.editList.length > 0"> <uichartitem ng-repeat="item in editor.editList" ng-mouseenter="showAllCustomiseTool($event, true)" ng-mouseleave="showAllCustomiseTool($event, false)" ng-click="selectItem(item)" ng-class="{'jfc-list-item-selected':(item.id === editor.internal.selected.id)}"></uichartitem> <div class="jfc-container"> <div class="cell align-middle align-left"> <div> <button class="btn btn-medium" ng-click="exportChartJson()"> <i class="icon icon-database medium"></i> <span class="medium">Export</span> </button> </div> </div> <div class="cell align-middle align-right"> <div> <button ng-if="editor.chartList.length == 0" class="btn btn-medium" ng-click="addChartItem()"> <i class="icon icon-add medium"></i> <span class="medium">Begin</span> </button> <button ng-if="editor.editList.length > 0 && editor.editList[0].type != 'End'" class="btn btn-medium" ng-click="addOption()"> <i class="icon icon-add medium"></i> <span class="medium">Option</span> </button> <button ng-if="editor.editList.length > 0 && editor.editList[0].type == 'Actor'" class="btn btn-medium" ng-click="addActor()"> <i class="icon icon-add medium"></i> <span class="medium">Actor</span> </button> </div> </div> </div> </div> <div class="jfc-container jfc-list"> <div class="jfc-box"> <div class="cell menu-heading"> <div> <h2 class="medium">Editor Hints</h2> </div> </div> </div> <div class="jfc-box"> <div class="cell"> <div> <ul> <li> Move Cursor on to the chart item or its properties to view the customization options like <i class="icon icon-config medium"></i> <i class="icon icon-stop medium"></i> <i class="icon icon-add-option medium"></i> <i class="icon icon-add-actor medium"></i> </li> <li>Click <i class="icon icon-config medium"></i> to change Chart Title.</li> <li>Click <i class="icon icon-add-option medium"></i> options to add new item.</li> <li>Click <i class="icon icon-add-actor medium"></i> options to add new actor to the selected chart item.</li> <li>Select Type[Begin/Actor/Activity/End] to convert to Actor, Activity or End.</li> </ul> </div> </div> </div> </div> </div> <div id="chartcanvas" style="right: 0;" ng-controller="SceneController"> <div id="chartTitle" class="large mono bold"> <span ng-bind="editor.name"></span> <i class="icon icon-edit medium" ng-click="editor.config.toggle()"></i> </div> <div id="chartscene"> <span style="display:hidden;" ng-init="xIndex = $index;yInit=0;initRepeatValues($index, 0);" ng-repeat-start="itemHolder in editor.parsedList"></span> <div ng-repeat-start="item in itemHolder" id="{{item.id}}" class="card-holder" ng-init="yIndex = $index;rearrangeChart(item, xIndex, $index, yInit, editor.parsedList)" ng-style="item.internal.style" ng-mouseover="showCustomiseTool($event, true)" ng-mouseleave="showCustomiseTool($event, false)"> <div class="customise-tool jfc-hide"> <div ng-style="{'width': (item.type == 'Actor' ? '140px' : '105px')}"> <button ng-click="manageConfig(false)"> <i class="icon icon-config large"></i> </button> <button ng-click="deleteCard()"> <i class="icon icon-trash large"></i> </button> <button ng-if="item.type == 'Actor'" ng-click="addActor()"> <i class="icon icon-add-actor large"></i> </button> <button ng-click="addOption()"> <i class="icon icon-add-option large"></i> </button> <button class="edit-card" ng-click="selectCard($event, item, editor.parsedList, editor)"> <i class="icon icon-edit large"></i> </button> <div class="card-info small">#<span ng-bind="item.id | stripparent"></span></div> </div> </div> <div class="card" ng-click="" ng-class="item.internal.class"> <div ng-if="item.type == 'Activity'" class="title"> <span class="fa fa-task"></span> <span ng-bind="item.name"></span> </div> <div ng-if="item.type == 'Begin' || item.type == 'End'" class="content card-special"> <div> <div class="jfc-width-20"> <i ng-if="item.type == 'Begin'" class="icon icon-flag-start x-large"></i> <i ng-if="item.type == 'End'" class="icon icon-flag-end x-large"></i> </div> <div> <div class="medium special-title"><span ng-bind="item.name"></span></div> <div class="small" ng-bind-html="item.description | formattext"></div> </div> </div> </div> <div ng-if="item.type == 'Activity'" class="content"> {{item.description}} </div> <div ng-if="item.type == 'Actor'" class="actors jfc-width-100"> <div class="actor" ng-repeat="actor in item.actors" id="{{actor.id}}"> <div></div> <div> <div class="medium">{{actor.name}}</div> <div class="small">{{actor.email}}</div> <div class="small">{{actor.contact}}</div> </div> </div> </div> <div class="options"> <div ng-repeat="subitem in item.options" id="{{subitem.id}}" ng-mouseover="highlightRelation(this, true)" ng-mouseleave="highlightRelation(this, false)"> <div> <span class="jfc-width-80">{{subitem.name}}</span> <span class="jfc-width-20 fa fa-play"></span> </div> </div> </div> </div> </div> <div ng-repeat="subitem in item.options" id="{{subitem.id}}-arrow-{{subitem.charts}}" ng-init="rearrangeOption(subitem, item, xIndex, yIndex, $index, yInit, editor.parsedList)" ng-class="subitem.internal.class" ng-style="subitem.internal.style" style="width: 78px; left: 0px; top: 92.1875px;"> <div> <div class="arrow-tail"></div> </div> <div> <div></div> <div></div> </div> <div> <div class="arrow-straight-tail"></div> <div class="arrow-head"> <div></div> </div> </div> </div> <span style="display:hidden;" ng-repeat-end></span> <span style="display:hidden;" ng-repeat-end></span> </div> </div> <!-- Edit Chart Item --> <uianchoredmodal id="chartItemModal" show="editor.item.edit" uistyle="editor.item.style" anchor="editor.item.anchor" title="editor.item.title" overlayclick="editor.item.toggle" notes="editor.item.notes"> <div class="jfc-container" ng-show="editor.editList.length > 0"> <uichartitem ng-repeat="item in editor.editList" ng-mouseenter="showAllCustomiseTool($event, true)" ng-mouseleave="showAllCustomiseTool($event, false)" ng-click="selectItem(item)" ng-class="{'jfc-list-item-selected':(item.id === editor.internal.selected.id)}"></uichartitem> <div class="jfc-container"> <div class="cell align-middle align-left"> <div> <button class="btn btn-medium" ng-click="exportChartJson()"> <i class="icon icon-database medium"></i> <span class="medium">Save</span> </button> <button class="btn btn-medium" ng-click="exportChartJson(true)"> <i class="icon icon-database medium"></i> <span class="medium">Save As</span> </button> </div> </div> <div class="cell align-middle align-right"> <div> <button ng-if="editor.chartList.length == 0" class="btn btn-medium" ng-click="addChartItem()"> <i class="icon icon-add medium"></i> <span class="medium">Begin</span> </button> <button ng-if="editor.editList.length > 0 && editor.editList[0].type != 'End'" class="btn btn-medium" ng-click="addOption();editor.item.handleOption(editor.editList[0]);"> <i class="icon icon-add medium"></i> <span class="medium">Option</span> </button> <button ng-if="editor.editList.length > 0 && editor.editList[0].type == 'Actor'" class="btn btn-medium" ng-click="addActor()"> <i class="icon icon-add medium"></i> <span class="medium">Actor</span> </button> </div> </div> </div> </div> </uianchoredmodal> <!-- /Edit Chart Item --> <!-- Edit Chart Configuration --> <uianchoredmodal show="editor.config.edit" uistyle="editor.config.style" anchor="editor.config.anchor" title="editor.config.title" overlayclick="editor.config.toggle" notes="editor.config.notes"> <div class="jfc-container jfc-width-96 before-spacer after-spacer" ng-controller="ConfigController"> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Name</span> </span> <span class="cell"> <span> <uitext ng-model="editor.name"></uitext> </span> </span> </label> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Prefix</span> </span> <span class="cell"> <span> <uitext ng-model="editor.idPrefix"></uitext> </span> </span> </label> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Portal</span> </span> <span class="cell"> <span> <uiselect ng-model="editor.portal" list="application.portalList" displayField="portalNm" valuefield="portalValueField"></uiselect> </span> </span> </label> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Environment</span> </span> <span class="cell"> <span> <uiselect ng-model="editor.environment" list="application.environmentList" displayField="environmentNm" valuefield="environmentValueField"></uiselect> </span> </span> </label> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Module</span> </span> <span class="cell after-spacer"> <span> <uiselect ng-model="editor.project" list="application.projectList" displayField="moduleNm" valuefield="projectValueField"></uiselect> </span> </span> </label> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Owner</span> </span> <span class="cell"> <span> <uitext ng-model="editor.owner"></uitext> </span> </span> </label> <label class="jfc-box align-left"> <span class="cell medium after-spacer before-spacer align-middle"> <span>Occurence</span> </span> <span class="cell"> <span> <span class="jfc-container"> <span class="jfc-box align-left"> <span class="cell medium align-middle align-right"> <button class="btn icon icon-add no-padding" ng-click="editor.occurence = editor.occurence + 1"></button> </span> <span class="cell medium align-middle"> <uitext class="inline_block" ng-model="editor.occurence"></uitext> </span> <span class="cell medium align-middle align-left"> <button class="btn icon icon-minus no-padding" ng-click="if(editor.occurence > 0){editor.occurence--;}"></button> </span> </span> </span> </span> </span> </label> </div> </uianchoredmodal> <!-- Edit Chart Configuration -->
CarreraPHP/jfc
ngapp/app/view/Admin.html
HTML
apache-2.0
19,764
/* * 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.samza.table.retry; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import net.jodah.failsafe.RetryPolicy; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Predicate; import org.apache.samza.context.Context; import org.apache.samza.storage.kv.Entry; import org.apache.samza.table.AsyncReadWriteTable; import org.apache.samza.table.remote.TableReadFunction; import org.apache.samza.table.remote.TableWriteFunction; import org.apache.samza.table.utils.TableMetricsUtil; import static org.apache.samza.table.BaseReadWriteTable.Func1; import static org.apache.samza.table.retry.FailsafeAdapter.failsafe; /** * A composable asynchronous retriable table implementation that supports features * defined in {@link TableRetryPolicy}. * * @param <K> the type of the key in this table * @param <V> the type of the value in this table */ public class AsyncRetriableTable<K, V> implements AsyncReadWriteTable<K, V> { private final String tableId; private final AsyncReadWriteTable<K, V> table; private final RetryPolicy readRetryPolicy; private final RetryPolicy writeRetryPolicy; private final ScheduledExecutorService retryExecutor; @VisibleForTesting RetryMetrics readRetryMetrics; @VisibleForTesting RetryMetrics writeRetryMetrics; public AsyncRetriableTable(String tableId, AsyncReadWriteTable<K, V> table, TableRetryPolicy readRetryPolicy, TableRetryPolicy writeRetryPolicy, ScheduledExecutorService retryExecutor, TableReadFunction readFn, TableWriteFunction writeFn) { Preconditions.checkNotNull(tableId, "null tableId"); Preconditions.checkNotNull(table, "null table"); Preconditions.checkNotNull(retryExecutor, "null retryExecutor"); Preconditions.checkArgument(readRetryPolicy != null || writeRetryPolicy != null, "both readRetryPolicy and writeRetryPolicy are null"); this.tableId = tableId; this.table = table; this.retryExecutor = retryExecutor; if (readRetryPolicy != null && readFn != null) { Predicate<Throwable> readRetryPredicate = readRetryPolicy.getRetryPredicate(); readRetryPolicy.withRetryPredicate((ex) -> readFn.isRetriable(ex) || readRetryPredicate.test(ex)); this.readRetryPolicy = FailsafeAdapter.valueOf(readRetryPolicy); } else { this.readRetryPolicy = null; } if (writeRetryPolicy != null && writeFn != null) { Predicate<Throwable> writeRetryPredicate = writeRetryPolicy.getRetryPredicate(); writeRetryPolicy.withRetryPredicate((ex) -> writeFn.isRetriable(ex) || writeRetryPredicate.test(ex)); this.writeRetryPolicy = FailsafeAdapter.valueOf(writeRetryPolicy); } else { this.writeRetryPolicy = null; } } @Override public CompletableFuture<V> getAsync(K key, Object... args) { return doRead(() -> table.getAsync(key, args)); } @Override public CompletableFuture<Map<K, V>> getAllAsync(List<K> keys, Object ... args) { return doRead(() -> table.getAllAsync(keys, args)); } @Override public <T> CompletableFuture<T> readAsync(int opId, Object... args) { return doRead(() -> table.readAsync(opId, args)); } @Override public CompletableFuture<Void> putAsync(K key, V value, Object... args) { return doWrite(() -> table.putAsync(key, value, args)); } @Override public CompletableFuture<Void> putAllAsync(List<Entry<K, V>> entries, Object ... args) { return doWrite(() -> table.putAllAsync(entries, args)); } @Override public CompletableFuture<Void> deleteAsync(K key, Object... args) { return doWrite(() -> table.deleteAsync(key, args)); } @Override public CompletableFuture<Void> deleteAllAsync(List<K> keys, Object ... args) { return doWrite(() -> table.deleteAllAsync(keys, args)); } @Override public <T> CompletableFuture<T> writeAsync(int opId, Object... args) { return doWrite(() -> table.writeAsync(opId, args)); } @Override public void init(Context context) { table.init(context); TableMetricsUtil metricsUtil = new TableMetricsUtil(context, this, tableId); if (readRetryPolicy != null) { readRetryMetrics = new RetryMetrics("reader", metricsUtil); } if (writeRetryPolicy != null) { writeRetryMetrics = new RetryMetrics("writer", metricsUtil); } } @Override public void flush() { table.flush(); } @Override public void close() { table.close(); } private <T> CompletableFuture<T> doRead(Func1<T> func) { return readRetryPolicy != null ? failsafe(readRetryPolicy, readRetryMetrics, retryExecutor).getStageAsync(() -> func.apply()) : func.apply(); } private <T> CompletableFuture<T> doWrite(Func1<T> func) { return writeRetryPolicy != null ? failsafe(writeRetryPolicy, writeRetryMetrics, retryExecutor).getStageAsync(() -> func.apply()) : func.apply(); } }
prateekm/samza
samza-core/src/main/java/org/apache/samza/table/retry/AsyncRetriableTable.java
Java
apache-2.0
5,841
'use strict' var registerPromiseWorker = require('../register') registerPromiseWorker(function (msg) { return msg }) self.addEventListener('activate', function (event) { // activate right now event.waitUntil(self.clients.claim()) })
nolanlawson/promise-worker
test/worker-echo-sw.js
JavaScript
apache-2.0
242
/* * #%L * GarethHealy :: Game of Life :: Core * %% * Copyright (C) 2013 - 2018 Gareth Healy * %% * 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. * #L% */ package com.garethahealy.springboot.gameoflife.core.services; import java.util.List; import com.garethahealy.springboot.gameoflife.core.entities.Cell; import com.garethahealy.springboot.gameoflife.core.entities.GameBoard; import com.garethahealy.springboot.gameoflife.core.enums.Rules; import com.garethahealy.springboot.gameoflife.core.transformers.JsonTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service public class DefaultBoardService extends AbstractBoardService { private static final Logger LOG = LoggerFactory.getLogger(DefaultBoardService.class); public DefaultBoardService() { this(48, 48); } public DefaultBoardService(Integer width, Integer height) { super(new GameBoard(width, height), new JsonTransformer()); } @Override protected void takeTurn(Cell current) { Integer aliveNeighbours = 0; List<Integer[]> cords = current.getAdjacentCoordinates(); for (Integer[] xyCords : cords) { Integer x = xyCords[0]; Integer y = xyCords[1]; Cell found = board.getCellAt(x, y); if (found != null && found.isAlive()) { aliveNeighbours++; } } LOG.debug("aliveNeighbours: {} / {}", aliveNeighbours, current.toString()); if (current.isAlive()) { if (aliveNeighbours < 2) { current.kill(Rules.UNDER_POPULATION); } else if (aliveNeighbours.equals(2) || aliveNeighbours.equals(3)) { current.resurrect(Rules.LIVE_ON); } else if (aliveNeighbours > 3) { current.kill(Rules.OVERCROWDING); } } else if (current.isDead()) { if (aliveNeighbours.equals(3)) { current.resurrect(Rules.REPRODUCTION); } } else { throw new IllegalArgumentException("Cell is not alive or dead: " + current.toString()); } } }
garethahealy/game-of-life
gof-core/src/main/java/com/garethahealy/springboot/gameoflife/core/services/DefaultBoardService.java
Java
apache-2.0
2,755
/* * * 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.zephyr.schema.normalizer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class DateFormatNormalizer implements Normalizer { private final String incomingFormat; private final String outgoingFormat; private TimeZone timezone; private Locale incomingLocale; private Locale outgoingLocale; public static final String ISO_8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; /** * If no timezone information is in <code>incomingFormat</code> than the systems default TimeZone will be used. * * @param incomingFormat * @param outgoingFormat */ public DateFormatNormalizer(String incomingFormat, String outgoingFormat) { this.incomingFormat = incomingFormat; this.outgoingFormat = outgoingFormat; } public void setTimeZone(String timeZoneCode) { this.timezone = TimeZone.getTimeZone(timeZoneCode); } @Override public String normalize(String value) throws NormalizationException { try { DateFormat in = getLocaleDateFormat(incomingFormat, incomingLocale); if (this.timezone != null) in.setTimeZone(this.timezone); in.setLenient(false); Date date = in.parse(value); DateFormat out = getLocaleDateFormat(outgoingFormat, outgoingLocale); out.setTimeZone(TimeZone.getTimeZone("GMT")); return out.format(date); } catch (Throwable t) { throw new NormalizationException(t); } } /** * Returns the DateFormat * * @param incomingFormat * @param locale * @return */ private DateFormat getLocaleDateFormat(String incomingFormat, Locale locale) { return (locale != null) ? new SimpleDateFormat(incomingFormat, locale) : new SimpleDateFormat(incomingFormat); } public void setIncomingLocale(Locale incomingLocale) { this.incomingLocale = incomingLocale; } public void setOutgoingLocale(Locale outgoingLocale) { this.outgoingLocale = outgoingLocale; } public String getIncomingFormat() { return incomingFormat; } public String getOutgoingFormat() { return outgoingFormat; } public TimeZone getTimezone() { return timezone; } public Locale getIncomingLocale() { return incomingLocale; } public Locale getOutgoingLocale() { return outgoingLocale; } }
Sotera/zephyr
zephyr-core/src/main/java/org/zephyr/schema/normalizer/DateFormatNormalizer.java
Java
apache-2.0
3,375
/*License (MIT) Copyright © 2013 Matt Diamond 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. */ (function(window){ var WORKER_PATH = '../Scripts/AudioRecorder/js/recorderjs/recorderWorker.js'; var Recorder = function(source, cfg){ var config = cfg || {}; var bufferLen = config.bufferLen || 4096; this.context = source.context; if(!this.context.createScriptProcessor){ this.node = this.context.createJavaScriptNode(bufferLen, 2, 2); } else { this.node = this.context.createScriptProcessor(bufferLen, 2, 2); } var worker = new Worker(config.workerPath || WORKER_PATH); worker.postMessage({ command: 'init', config: { sampleRate: this.context.sampleRate } }); var recording = false, currCallback; this.node.onaudioprocess = function(e){ if (!recording) return; worker.postMessage({ command: 'record', buffer: [ e.inputBuffer.getChannelData(0), e.inputBuffer.getChannelData(1) ] }); } this.configure = function(cfg){ for (var prop in cfg){ if (cfg.hasOwnProperty(prop)){ config[prop] = cfg[prop]; } } } this.record = function(){ recording = true; } this.stop = function(){ recording = false; } this.clear = function(){ worker.postMessage({ command: 'clear' }); } this.getBuffers = function(cb) { currCallback = cb || config.callback; worker.postMessage({ command: 'getBuffers' }); } this.exportWAV = function(cb, type){ currCallback = cb || config.callback; type = type || config.type || 'audio/wav'; if (!currCallback) throw new Error('Callback not set'); worker.postMessage({ command: 'exportWAV', type: type }); } this.exportMonoWAV = function(cb, type){ currCallback = cb || config.callback; type = type || config.type || 'audio/wav'; if (!currCallback) throw new Error('Callback not set'); worker.postMessage({ command: 'exportMonoWAV', type: type }); } worker.onmessage = function(e){ var blob = e.data; currCallback(blob); } source.connect(this.node); this.node.connect(this.context.destination); // if the script node is not connected to an output the "onaudioprocess" event is not triggered in chrome. }; Recorder.setupDownload = function(blob, filename){ var url = (window.URL || window.webkitURL).createObjectURL(blob); var link = document.getElementById("save"); link.href = url; //link.download = filename || 'output.wav'; } window.Recorder = Recorder; })(window);
andycarmona/Uni-AppKids
UniAppSpel/Scripts/AudioRecorder/js/recorderjs/recorder.js
JavaScript
apache-2.0
3,721
<?php /** * DO NOT EDIT THIS FILE! * * This file was automatically generated from external sources. * * Any manual change here will be lost the next time the SDK * is updated. You've been warned! */ namespace DTS\eBaySDK\PostOrder\Types; use DTS\eBaySDK\StatusCodeTrait; use DTS\eBaySDK\HttpHeadersTrait; /** * * @property \DTS\eBaySDK\PostOrder\Types\Error[] $error * @property \DTS\eBaySDK\PostOrder\Types\ErrorDetailV3[] $errors * @property \DTS\eBaySDK\PostOrder\Types\ErrorDetailV3[] $warnings */ class GetReturnFilesRestResponse extends \DTS\eBaySDK\PostOrder\Types\GetFileResponse { use StatusCodeTrait; use HttpHeadersTrait; /** * @var array Properties belonging to objects of this class. */ private static $propertyTypes = [ 'error' => [ 'type' => 'DTS\eBaySDK\PostOrder\Types\Error', 'repeatable' => true, 'attribute' => false, 'elementName' => 'error' ], 'errors' => [ 'type' => 'DTS\eBaySDK\PostOrder\Types\ErrorDetailV3', 'repeatable' => true, 'attribute' => false, 'elementName' => 'errors' ], 'warnings' => [ 'type' => 'DTS\eBaySDK\PostOrder\Types\ErrorDetailV3', 'repeatable' => true, 'attribute' => false, 'elementName' => 'warnings' ] ]; /** * @param array $values Optional properties and values to assign to the object. * @param int $statusCode Status code * @param array $headers HTTP Response headers. */ public function __construct(array $values = [], $statusCode = 200, array $headers = []) { list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values); parent::__construct($parentValues); if (!array_key_exists(__CLASS__, self::$properties)) { self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes); } $this->setValues(__CLASS__, $childValues); $this->statusCode = (int)$statusCode; $this->setHeaders($headers); } }
davidtsadler/ebay-sdk-php
src/PostOrder/Types/GetReturnFilesRestResponse.php
PHP
apache-2.0
2,166
--- layout: article title: "Inspect and Manage Your Cookies" seotitle: "Inspect and Manage Your Cookies in the Chrome DevTools Resources Panel" description: "TBD description." introduction: "TBD introduction." article: written_on: 2015-04-14 updated_on: 2015-04-14 order: 2 authors: - megginkearney priority: 0 collection: manage-data key-takeaways: tldr-tbd: - TBD tldr. remember: note-tbd: - TBD note. --- {% wrap content %} TBD. Cover the content here: https://developer.chrome.com/devtools/docs/resource-panel#cookies {% include modules/takeaway.liquid list=page.key-takeaways.tldr-tbd %} ### TBD TBD. {% include modules/remember.liquid title="Remember" list=page.remember.note-tbd %} {% include modules/nextarticle.liquid %} {% endwrap %}
1234-/WebFundamentals
src/_langs/en/tools/iterate/manage-data/cookies.markdown
Markdown
apache-2.0
771
/*! * Start Bootstrap - Agency Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ body { overflow-x: hidden; font-family: "Roboto Slab","Helvetica Neue",Helvetica,Arial,sans-serif; color: #{{ site.color.secondary-dark }}; } .text-muted { color: #777; } .text-primary { color: #{{ site.color.primary }}; } p { font-size: 14px; line-height: 1.75; } p.large { font-size: 16px; } a, a:hover, a:focus, a:active, a.active { outline: 0; } a { color: #{{ site.color.primary }}; } a:hover, a:focus, a:active, a.active { color: #{{ site.color.secondary }}; } h1, h2, h3, h4, h5, h6 { text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 700; } .img-centered { margin: 0 auto; } .bg-light-gray { background-color: #f7f7f7; } .bg-darkest-gray { background-color: #222; } .btn-primary { border-color: #{{ site.color.primary }}; text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 700; color: #fff; background-color: #{{ site.color.primary }}; } .btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open .dropdown-toggle.btn-primary { border-color: #{{ site.color.primary }}; color: #fff; background-color: #{{ site.color.secondary }}; } .btn-primary:active, .btn-primary.active, .open .dropdown-toggle.btn-primary { background-image: none; } .btn-primary.disabled, .btn-primary[disabled], fieldset[disabled] .btn-primary, .btn-primary.disabled:hover, .btn-primary[disabled]:hover, fieldset[disabled] .btn-primary:hover, .btn-primary.disabled:focus, .btn-primary[disabled]:focus, fieldset[disabled] .btn-primary:focus, .btn-primary.disabled:active, .btn-primary[disabled]:active, fieldset[disabled] .btn-primary:active, .btn-primary.disabled.active, .btn-primary[disabled].active, fieldset[disabled] .btn-primary.active { border-color: #{{ site.color.primary }}; background-color: #{{ site.color.primary }}; } .btn-primary .badge { color: #{{ site.color.primary }}; background-color: #fff; } .btn-xl { padding: 20px 40px; border-color: #{{ site.color.primary }}; border-radius: 3px; text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 18px; font-weight: 700; color: #fff; background-color: #{{ site.color.primary }}; } .btn-xl:hover, .btn-xl:focus, .btn-xl:active, .btn-xl.active, .open .dropdown-toggle.btn-xl { border-color: #{{ site.color.primary }}; color: #fff; background-color: #{{ site.color.secondary }}; } .btn-xl:active, .btn-xl.active, .open .dropdown-toggle.btn-xl { background-image: none; } .btn-xl.disabled, .btn-xl[disabled], fieldset[disabled] .btn-xl, .btn-xl.disabled:hover, .btn-xl[disabled]:hover, fieldset[disabled] .btn-xl:hover, .btn-xl.disabled:focus, .btn-xl[disabled]:focus, fieldset[disabled] .btn-xl:focus, .btn-xl.disabled:active, .btn-xl[disabled]:active, fieldset[disabled] .btn-xl:active, .btn-xl.disabled.active, .btn-xl[disabled].active, fieldset[disabled] .btn-xl.active { border-color: #{{ site.color.primary }}; background-color: #{{ site.color.primary }}; } .btn-xl .badge { color: #{{ site.color.primary }}; background-color: #fff; } .navbar-default { border-color: transparent; background-color: #222; } .navbar-default .navbar-brand { font-family: "Kaushan Script","Helvetica Neue",Helvetica,Arial,cursive; color: #{{ site.color.primary }}; } .navbar-default .navbar-brand:hover, .navbar-default .navbar-brand:focus, .navbar-default .navbar-brand:active, .navbar-default .navbar-brand.active { color: #{{ site.color.secondary }}; } .navbar-default .navbar-collapse { border-color: rgba(255,255,255,.02); } .navbar-default .navbar-toggle { border-color: #{{ site.color.primary }}; background-color: #{{ site.color.primary }}; } .navbar-default .navbar-toggle .icon-bar { background-color: #fff; } .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus { background-color: #{{ site.color.primary }}; } .navbar-default .nav li a { text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 400; letter-spacing: 1px; color: #fff; } .navbar-default .nav li a:hover, .navbar-default .nav li a:focus { outline: 0; color: #{{ site.color.primary }}; } .navbar-default .navbar-nav>.active>a { border-radius: 0; color: #fff; background-color: #{{ site.color.primary }}; } .navbar-default .navbar-nav>.active>a:hover, .navbar-default .navbar-nav>.active>a:focus { color: #fff; background-color: #{{ site.color.secondary }}; } @media(min-width:768px) { .navbar-default { padding: 25px 0; border: 0; background-color: transparent; -webkit-transition: padding .3s; -moz-transition: padding .3s; transition: padding .3s; } .navbar-default .navbar-brand { font-size: 2em; -webkit-transition: all .3s; -moz-transition: all .3s; transition: all .3s; } .navbar-default .navbar-nav>.active>a { border-radius: 3px; } .navbar-default.navbar-shrink { padding: 10px 0; background-color: #222; } .navbar-default.navbar-shrink .navbar-brand { font-size: 1.5em; } } header { text-align: center; color: #fff; background-attachment: scroll; background-image: url(../img/header-bg.jpg); background-position: center center; background-repeat: none; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } header .intro-text { padding-top: 100px; padding-bottom: 50px; } header .intro-text .intro-lead-in { margin-bottom: 25px; font-family: "Droid Serif","Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 22px; font-style: italic; line-height: 22px; } header .intro-text .intro-heading { margin-bottom: 25px; text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 50px; font-weight: 700; line-height: 50px; } @media(min-width:768px) { header .intro-text { padding-top: 100px; padding-bottom: 200px; } header .intro-text .intro-lead-in { margin-bottom: 25px; font-family: "Droid Serif","Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 40px; font-style: italic; line-height: 40px; } header .intro-text .intro-heading { margin-bottom: 50px; text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 75px; font-weight: 700; line-height: 75px; } } section { padding: 10px 0; margin: 0 0; } section h2.section-heading { margin-top: 0; margin-bottom: 15px; font-size: 40px; } section h3.section-subheading { margin-bottom: 75px; text-transform: none; font-family: "Droid Serif","Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 16px; font-style: italic; font-weight: 400; } @media(min-width:768px) { section { padding: 150px 0; } } .service-heading { margin: 15px 0; text-transform: none; } #portfolio .portfolio-item { right: 0; margin: 0 0 15px; } #portfolio .portfolio-item .portfolio-link { display: block; position: relative; margin: 0 auto; max-width: 400px; } #portfolio .portfolio-item .portfolio-link .portfolio-hover { position: absolute; width: 100%; height: 100%; opacity: 0; -webkit-transition: all ease .5s; -moz-transition: all ease .5s; transition: all ease .5s; background: rgba(254,209,54,.9); /* Fallback when no plugin support */ background: rgba({{ site.color.primary | hex_to_rgb | join: ',' }}, .9); } #portfolio .portfolio-item .portfolio-link .portfolio-hover:hover { opacity: 1; } #portfolio .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content { position: absolute; top: 50%; width: 100%; height: 20px; margin-top: -12px; text-align: center; font-size: 20px; color: #fff; } #portfolio .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content i { margin-top: -12px; } #portfolio .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content h3, #portfolio .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content h4 { margin: 0; } #portfolio .portfolio-item .portfolio-caption { margin: 0 auto; padding: 25px; max-width: 400px; text-align: center; background-color: #fff; } #portfolio .portfolio-item .portfolio-caption h4 { margin: 0; text-transform: none; } #portfolio .portfolio-item .portfolio-caption p { margin: 0; font-family: "Droid Serif","Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 16px; font-style: italic; } #portfolio * { z-index: 2; } @media(min-width:767px) { #portfolio .portfolio-item { margin: 0 0 30px; } } .timeline { position: relative; padding: 0; list-style: none; } .timeline:before { content: ""; position: absolute; top: 0; bottom: 0; left: 40px; width: 2px; margin-left: -1.5px; background-color: #f1f1f1; } .timeline>li { position: relative; margin-bottom: 50px; min-height: 50px; } .timeline>li:before, .timeline>li:after { content: " "; display: table; } .timeline>li:after { clear: both; } .timeline>li .timeline-panel { float: right; position: relative; width: 100%; padding: 0 20px 0 100px; text-align: left; } .timeline>li .timeline-panel:before { right: auto; left: -15px; border-right-width: 15px; border-left-width: 0; } .timeline>li .timeline-panel:after { right: auto; left: -14px; border-right-width: 14px; border-left-width: 0; } .timeline>li .timeline-image { z-index: 100; position: absolute; left: 0; width: 80px; height: 80px; margin-left: 0; border: 7px solid #f1f1f1; border-radius: 100%; text-align: center; color: #fff; background-color: #{{ site.color.primary }}; } .timeline>li .timeline-image h4 { margin-top: 12px; font-size: 10px; line-height: 14px; } .timeline>li.timeline-inverted>.timeline-panel { float: right; padding: 0 20px 0 100px; text-align: left; } .timeline>li.timeline-inverted>.timeline-panel:before { right: auto; left: -15px; border-right-width: 15px; border-left-width: 0; } .timeline>li.timeline-inverted>.timeline-panel:after { right: auto; left: -14px; border-right-width: 14px; border-left-width: 0; } .timeline>li:last-child { margin-bottom: 0; } .timeline .timeline-heading h4 { margin-top: 0; color: inherit; } .timeline .timeline-heading h4.subheading { text-transform: none; } .timeline .timeline-body>p, .timeline .timeline-body>ul { margin-bottom: 0; } @media(min-width:768px) { .timeline:before { left: 50%; } .timeline>li { margin-bottom: 100px; min-height: 100px; } .timeline>li .timeline-panel { float: left; width: 41%; padding: 0 20px 20px 30px; text-align: right; } .timeline>li .timeline-image { left: 50%; width: 100px; height: 100px; margin-left: -50px; } .timeline>li .timeline-image h4 { margin-top: 16px; font-size: 13px; line-height: 18px; } .timeline>li.timeline-inverted>.timeline-panel { float: right; padding: 0 30px 20px 20px; text-align: left; } } @media(min-width:992px) { .timeline>li { min-height: 150px; } .timeline>li .timeline-panel { padding: 0 20px 20px; } .timeline>li .timeline-image { width: 150px; height: 150px; margin-left: -75px; } .timeline>li .timeline-image h4 { margin-top: 30px; font-size: 18px; line-height: 26px; } .timeline>li.timeline-inverted>.timeline-panel { padding: 0 20px 20px; } } @media(min-width:1200px) { .timeline>li { min-height: 170px; } .timeline>li .timeline-panel { padding: 0 20px 20px 100px; } .timeline>li .timeline-image { width: 170px; height: 170px; margin-left: -85px; } .timeline>li .timeline-image h4 { margin-top: 40px; } .timeline>li.timeline-inverted>.timeline-panel { padding: 0 100px 20px 20px; } } .team-member { margin-bottom: 50px; text-align: center; } .team-member img { margin: 0 auto; border: 7px solid #fff; } .team-member h4 { margin-top: 25px; margin-bottom: 0; text-transform: none; } .team-member p { margin-top: 0; } aside.clients img { margin: 50px auto; } section#contact { background-color: #222; background-image: url(../img/map-image.png); background-position: center; background-repeat: no-repeat; } section#contact .section-heading { color: #fff; } section#contact .form-group { margin-bottom: 25px; } section#contact .form-group input, section#contact .form-group textarea { padding: 20px; } section#contact .form-group input.form-control { height: auto; } section#contact .form-group textarea.form-control { height: 236px; } section#contact .form-control:focus { border-color: #{{ site.color.primary }}; box-shadow: none; } section#contact::-webkit-input-placeholder { text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 700; color: #bbb; } section#contact:-moz-placeholder { text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 700; color: #bbb; } section#contact::-moz-placeholder { text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 700; color: #bbb; } section#contact:-ms-input-placeholder { text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 700; color: #bbb; } section#contact .text-danger { color: #e74c3c; } footer { padding: 25px 0; text-align: center; } footer span.copyright { text-transform: uppercase; text-transform: none; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; line-height: 40px; } footer ul.quicklinks { margin-bottom: 0; text-transform: uppercase; text-transform: none; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; line-height: 40px; } ul.social-buttons { margin-bottom: 0; } ul.social-buttons li a { display: block; width: 40px; height: 40px; border-radius: 100%; font-size: 20px; line-height: 40px; outline: 0; color: #fff; background-color: #222; -webkit-transition: all .3s; -moz-transition: all .3s; transition: all .3s; } ul.social-buttons li a:hover, ul.social-buttons li a:focus, ul.social-buttons li a:active { background-color: #{{ site.color.primary }}; } .btn:focus, .btn:active, .btn.active, .btn:active:focus { outline: 0; } .portfolio-modal .modal-content { padding: 100px 0; min-height: 100%; border: 0; border-radius: 0; text-align: center; background-clip: border-box; -webkit-box-shadow: none; box-shadow: none; } .portfolio-modal .modal-content h2 { margin-bottom: 15px; font-size: 3em; } .portfolio-modal .modal-content p { margin-bottom: 30px; } .portfolio-modal .modal-content p.item-intro { margin: 20px 0 30px; font-family: "Droid Serif","Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 16px; font-style: italic; } .portfolio-modal .modal-content ul.list-inline { margin-top: 0; margin-bottom: 30px; } .portfolio-modal .modal-content img { margin-bottom: 30px; } .portfolio-modal .close-modal { position: absolute; top: 25px; right: 25px; width: 75px; height: 75px; background-color: transparent; cursor: pointer; } .portfolio-modal .close-modal:hover { opacity: .3; } .portfolio-modal .close-modal .lr { z-index: 1051; width: 1px; height: 75px; margin-left: 35px; background-color: #222; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); } .portfolio-modal .close-modal .lr .rl { z-index: 1052; width: 1px; height: 75px; background-color: #222; -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } ::-moz-selection { text-shadow: none; background: #{{ site.color.primary }}; } ::selection { text-shadow: none; background: #{{ site.color.primary }}; } img::selection { background: 0 0; } img::-moz-selection { background: 0 0; } body { webkit-tap-highlight-color: #{{ site.color.primary }}; }
abcsds/Pinguica
_includes/css/agency.css
CSS
apache-2.0
17,530
<!-- ~ Copyright [2015] [Alexander Dridiger - [email protected]] ~ ~ 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. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>API Help (Apache Commons Lang 3.3.2 API)</title> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="API Help (Apache Commons Lang 3.3.2 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="overview-tree.html">Tree</a></li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li class="navBarCell1Rev">Help</li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?help-doc.html" target="_top">Frames</a></li> <li><a href="help-doc.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">How This API Document Is Organized</h1> <div class="subTitle">This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.</div> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <h2>Overview</h2> <p>The <a href="overview-summary.html">Overview</a> page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.</p> </li> <li class="blockList"> <h2>Package</h2> <p>Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain six categories:</p> <ul> <li>Interfaces (italic)</li> <li>Classes</li> <li>Enums</li> <li>Exceptions</li> <li>Errors</li> <li>Annotation Types</li> </ul> </li> <li class="blockList"> <h2>Class/Interface</h2> <p>Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:</p> <ul> <li>Class inheritance diagram</li> <li>Direct Subclasses</li> <li>All Known Subinterfaces</li> <li>All Known Implementing Classes</li> <li>Class/interface declaration</li> <li>Class/interface description</li> </ul> <ul> <li>Nested Class Summary</li> <li>Field Summary</li> <li>Constructor Summary</li> <li>Method Summary</li> </ul> <ul> <li>Field Detail</li> <li>Constructor Detail</li> <li>Method Detail</li> </ul> <p>Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.</p> </li> <li class="blockList"> <h2>Annotation Type</h2> <p>Each annotation type has its own separate page with the following sections:</p> <ul> <li>Annotation Type declaration</li> <li>Annotation Type description</li> <li>Required Element Summary</li> <li>Optional Element Summary</li> <li>Element Detail</li> </ul> </li> <li class="blockList"> <h2>Enum</h2> <p>Each enum has its own separate page with the following sections:</p> <ul> <li>Enum declaration</li> <li>Enum description</li> <li>Enum Constant Summary</li> <li>Enum Constant Detail</li> </ul> </li> <li class="blockList"> <h2>Use</h2> <p>Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class or package. Given a class or interface A, its Use page includes subclasses of A, fields declared as A, methods that return A, and methods and constructors with parameters of type A. You can access this page by first going to the package, class or interface, then clicking on the "Use" link in the navigation bar.</p> </li> <li class="blockList"> <h2>Tree (Class Hierarchy)</h2> <p>There is a <a href="overview-tree.html">Class Hierarchy</a> page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with <code>java.lang.Object</code>. The interfaces do not inherit from <code>java.lang.Object</code>.</p> <ul> <li>When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.</li> <li>When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.</li> </ul> </li> <li class="blockList"> <h2>Deprecated API</h2> <p>The <a href="deprecated-list.html">Deprecated API</a> page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.</p> </li> <li class="blockList"> <h2>Index</h2> <p>The <a href="index-all.html">Index</a> contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.</p> </li> <li class="blockList"> <h2>Prev/Next</h2> <p>These links take you to the next or previous class, interface, package, or related page.</p> </li> <li class="blockList"> <h2>Frames/No Frames</h2> <p>These links show and hide the HTML frames. All pages are available with or without frames.</p> </li> <li class="blockList"> <h2>All Classes</h2> <p>The <a href="allclasses-noframe.html">All Classes</a> link shows all classes and interfaces except non-static nested types.</p> </li> <li class="blockList"> <h2>Serialized Form</h2> <p>Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See also" section of the class description.</p> </li> <li class="blockList"> <h2>Constant Field Values</h2> <p>The <a href="constant-values.html">Constant Field Values</a> page lists the static final fields and their values.</p> </li> </ul> <em>This help file applies to API documentation generated using the standard doclet.</em></div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="overview-tree.html">Tree</a></li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li class="navBarCell1Rev">Help</li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?help-doc.html" target="_top">Frames</a></li> <li><a href="help-doc.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2001&#x2013;2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
drisoftie/AsyncActions
actions/AsyncActions/src/main/libs/doc/commons-lang3-3.3.2/help-doc.html
HTML
apache-2.0
9,396
/* * Copyright 2011 - 2013 NTB University of Applied Sciences in Technology * Buchs, Switzerland, http://www.ntb.ch/inf * * 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.deepjava.runtime.mpc555.driver; import org.deepjava.runtime.mpc555.IntbMpc555HB; import org.deepjava.unsafe.US; /* CHANGES: * 14.04.2009 NTB/SP creation */ /** * SPI Driver for the Maxim512 Digital to Analog Converter.<br> * PCS0 on the SPI is used. * */ public class MAX512 implements IntbMpc555HB { public final static int chnA = 0; public final static int chnB = 1; public final static int chnC = 2; private static short disDACs = 0; /** * Disable one channel. * @param ch the desired channel ({@link #chnA}, {@link #chnB}, {@link #chnC}) */ public static void disable(int ch){ disDACs |= 0x0800 << ch; US.PUT2(TRANRAM + 2 * ch,disDACs); } /** * Enable a disabled channel. * @param ch the desired channel ({@link #chnA}, {@link #chnB}, {@link #chnC}) */ public static void enable(int ch){ disDACs &= ~(0x0800 << ch); US.PUT2(TRANRAM + 2 * ch,disDACs); } /** * Write a value to the DAC. * @param ch the desired channel ({@link #chnA}, {@link #chnB}, {@link #chnC}) * @param val the desired output value */ public static void write(int ch, byte val){ US.PUT2(TRANRAM + 2 * ch, (disDACs | (0x0100 << ch)| (0xFF & val))); // Write data to transmit ram } /** * Initializes the SPI. */ public static void init(){ US.PUT2(SPCR1, 0x0); //disable QSPI US.PUT1(PQSPAR, 0x0B); // use PCS0, MOSI, MISO for QSPI US.PUT1(DDRQS, 0x0E); //SCK, MOSI, PCS's outputs; MISO is input US.PUT2(PORTQS, 0xFF); //all Pins, in case QSPI disabled, are high US.PUT2(SPCR0, 0x8014); // QSPI is master, 16 bits per transfer, inactive state of SCLK is high (CPOL=1), data changed on leading edge (CPHA=1), clock = 1 MHz US.PUT2(SPCR2, 0x4200); // no interrupts, wraparound mode, NEWQP=0, ENDQP=7 US.PUT1(COMDRAM, 0x6E); //Cont off, BITS of SPCR0, DT from SPCR1, CS0 low US.PUT1(COMDRAM + 1, 0x6E); //Cont off, BITS of SPCR0, DT from SPCR1, CS0 low US.PUT1(COMDRAM + 2, 0x6E); //Cont off, BITS of SPCR0, DT from SPCR1, CS0 low US.PUT2(SPCR1, 0x08010); //enable QSPI, delay 13us after transfer } }
deepjava/runtime-library
src/org/deepjava/runtime/mpc555/driver/MAX512.java
Java
apache-2.0
2,864
package com.sequenceiq.cloudbreak.service.publicendpoint; import java.security.KeyPair; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.sequenceiq.cloudbreak.auth.ThreadBasedUserCrnProvider; import com.sequenceiq.cloudbreak.certificate.PkiUtil; import com.sequenceiq.cloudbreak.cmtemplate.CmTemplateProcessor; import com.sequenceiq.cloudbreak.cmtemplate.configproviders.hue.HueRoles; import com.sequenceiq.cloudbreak.domain.SecurityConfig; import com.sequenceiq.cloudbreak.domain.stack.Stack; import com.sequenceiq.cloudbreak.domain.stack.cluster.Cluster; import com.sequenceiq.cloudbreak.domain.stack.instance.InstanceMetaData; import com.sequenceiq.cloudbreak.domain.stack.loadbalancer.LoadBalancer; import com.sequenceiq.cloudbreak.service.LoadBalancerConfigService; import com.sequenceiq.cloudbreak.service.cluster.ClusterService; import com.sequenceiq.cloudbreak.service.environment.EnvironmentClientService; import com.sequenceiq.cloudbreak.service.securityconfig.SecurityConfigService; import com.sequenceiq.cloudbreak.service.stack.LoadBalancerPersistenceService; import com.sequenceiq.common.api.type.LoadBalancerType; import com.sequenceiq.environment.api.v1.environment.model.response.DetailedEnvironmentResponse; @Service public class GatewayPublicEndpointManagementService extends BasePublicEndpointManagementService { private static final Logger LOGGER = LoggerFactory.getLogger(GatewayPublicEndpointManagementService.class); @Inject private EnvironmentClientService environmentClientService; @Inject private SecurityConfigService securityConfigService; @Inject private ClusterService clusterService; @Inject private LoadBalancerPersistenceService loadBalancerPersistenceService; @Inject private LoadBalancerConfigService loadBalancerConfigService; public boolean isCertRenewalTriggerable(Stack stack) { return manageCertificateAndDnsInPem() && stack != null && stack.getCluster() != null; } public boolean generateCertAndSaveForStackAndUpdateDnsEntry(Stack stack) { boolean success = false; if (isCertRenewalTriggerable(stack)) { if (StringUtils.isEmpty(stack.getSecurityConfig().getUserFacingCert())) { success = generateCertAndSaveForStack(stack); } updateDnsEntryForCluster(stack); updateDnsEntryForLoadBalancers(stack); } else { LOGGER.info("External FQDN and valid certificate creation is disabled."); } return success; } public String updateDnsEntry(Stack stack, String gatewayIp) { LOGGER.info("Update dns entry"); String accountId = ThreadBasedUserCrnProvider.getAccountId(); DetailedEnvironmentResponse environment = environmentClientService.getByCrn(stack.getEnvironmentCrn()); Set<String> hueHostGroups = getHueHostGroups(stack); if (StringUtils.isEmpty(gatewayIp)) { Optional<InstanceMetaData> gateway = Optional.ofNullable(stack.getPrimaryGatewayInstance()); if (gateway.isEmpty()) { LOGGER.info("No running gateway or all node is terminated, we skip the dns entry deletion."); return null; } else { gatewayIp = gateway.get().getPublicIpWrapper(); } } String endpointName = getEndpointNameForStack(stack); LOGGER.info("Creating DNS entry with endpoint name: '{}', environment name: '{}' and gateway IP: '{}'", endpointName, environment.getName(), gatewayIp); List<String> ips = List.of(gatewayIp); boolean success = getDnsManagementService().createOrUpdateDnsEntryWithIp(accountId, endpointName, environment.getName(), false, ips); if (success) { try { String fullQualifiedDomainName = getDomainNameProvider() .getFullyQualifiedEndpointName(hueHostGroups, endpointName, environment); if (fullQualifiedDomainName != null) { LOGGER.info("Dns entry updated: ip: {}, FQDN: {}", gatewayIp, fullQualifiedDomainName); return fullQualifiedDomainName; } } catch (Exception e) { LOGGER.info("Cannot generate fqdn: {}", e.getMessage(), e); } } return null; } public Set<String> getHueHostGroups(Stack stack) { return new CmTemplateProcessor(stack.getCluster().getBlueprint().getBlueprintText()) .getHostGroupsWithComponent(HueRoles.HUE_SERVER); } public boolean updateDnsEntryForLoadBalancers(Stack stack) { boolean success = false; if (manageCertificateAndDnsInPem() && stack != null) { Optional<LoadBalancer> loadBalancerOptional = getLoadBalancerWithEndpoint(stack); if (loadBalancerOptional.isEmpty()) { LOGGER.error("Unable find appropriate load balancer in stack. Load balancer public domain name will not be registered."); } else { success = registerLoadBalancersDnsEntries(loadBalancerOptional.get(), stack.getEnvironmentCrn(), getHueHostGroups(stack)); } } else { LOGGER.debug("DNS registration in PEM service not enabled for load balancer."); success = true; } return success; } private boolean registerLoadBalancersDnsEntries(LoadBalancer loadBalancer, String environmentCrn, Set<String> hueHostGroups) { boolean success = false; LOGGER.info("Updating load balancer DNS entries"); String accountId = ThreadBasedUserCrnProvider.getAccountId(); DetailedEnvironmentResponse environment = environmentClientService.getByCrn(environmentCrn); String endpoint = loadBalancer.getEndpoint(); if (loadBalancer.getDns() != null && loadBalancer.getHostedZoneId() != null) { LOGGER.info("Creating load balancer DNS entry with endpoint name: '{}', environment name: '{}' and cloud DNS: '{}'", endpoint, environment.getName(), loadBalancer.getDns()); success = getDnsManagementService().createOrUpdateDnsEntryWithCloudDns(accountId, endpoint, environment.getName(), loadBalancer.getDns(), loadBalancer.getHostedZoneId()); } else if (loadBalancer.getIp() != null) { LOGGER.info("Creating load balancer DNS entry with endpoint name: '{}', environment name: '{}' and IP: '{}'", endpoint, environment.getName(), loadBalancer.getIp()); success = getDnsManagementService().createOrUpdateDnsEntryWithIp(accountId, endpoint, environment.getName(), false, List.of(loadBalancer.getIp())); } else { LOGGER.warn("Could not find IP or cloud DNS info for load balancer with endpoint {} ." + "DNS registration will be skipped.", loadBalancer.getEndpoint()); } if (success) { setLoadBalancerFqdn(hueHostGroups, loadBalancer, endpoint, environment, accountId); } return success; } private void setLoadBalancerFqdn(Set<String> hueHostGroups, LoadBalancer loadBalancer, String endpoint, DetailedEnvironmentResponse env, String accountId) { loadBalancer.setFqdn(getDomainNameProvider().getFullyQualifiedEndpointName(hueHostGroups, endpoint, env)); loadBalancerPersistenceService.save(loadBalancer); LOGGER.info("Set load balancer's FQDN to {}.", loadBalancer.getFqdn()); } public String deleteDnsEntry(Stack stack, String environmentName) { String accountId = ThreadBasedUserCrnProvider.getAccountId(); if (StringUtils.isEmpty(environmentName)) { DetailedEnvironmentResponse environment = environmentClientService.getByCrn(stack.getEnvironmentCrn()); environmentName = environment.getName(); } Optional<InstanceMetaData> gateway = Optional.ofNullable(stack.getPrimaryGatewayInstance()); if (!gateway.isPresent()) { LOGGER.info("No running gateway or all node is terminated, we skip the dns entry deletion."); return null; } String ip = gateway.get().getPublicIpWrapper(); if (ip == null) { return null; } String endpointName = getEndpointNameForStack(stack); LOGGER.info("Deleting DNS entry with endpoint name: '{}', environment name: '{}' and gateway IP: '{}'", endpointName, environmentName, ip); getDnsManagementService().deleteDnsEntryWithIp(accountId, endpointName, environmentName, false, List.of(ip)); return ip; } public void deleteLoadBalancerDnsEntry(Stack stack, String environmentName) { Optional<LoadBalancer> loadBalancerOptional = getLoadBalancerWithEndpoint(stack); if (loadBalancerOptional.isEmpty()) { LOGGER.warn("Unable to find appropriate load balancer in stack. Load balancer public domain name will not be deleted."); } else { String accountId = ThreadBasedUserCrnProvider.getAccountId(); if (StringUtils.isEmpty(environmentName)) { DetailedEnvironmentResponse environment = environmentClientService.getByCrn(stack.getEnvironmentCrn()); environmentName = environment.getName(); } LoadBalancer loadBalancer = loadBalancerOptional.get(); String endpoint = loadBalancer.getEndpoint(); if (loadBalancer.getDns() != null && loadBalancer.getHostedZoneId() != null) { LOGGER.info("Deleting load balancer DNS entry with endpoint name: '{}', environment name: '{}' and cloud DNS: '{}'", endpoint, environmentName, loadBalancer.getDns()); getDnsManagementService().deleteDnsEntryWithCloudDns(accountId, endpoint, environmentName, loadBalancer.getDns(), loadBalancer.getHostedZoneId()); } else if (loadBalancer.getIp() != null) { LOGGER.info("Deleting load balancer DNS entry with endpoint name: '{}', environment name: '{}' and IP: '{}'", endpoint, environmentName, loadBalancer.getIp()); getDnsManagementService().deleteDnsEntryWithIp(accountId, endpoint, environmentName, false, List.of(loadBalancer.getIp())); } } } public boolean renewCertificate(Stack stack) { boolean certGeneratedSuccessfully = true; if (isCertRenewalTriggerable(stack)) { LOGGER.info("Renew certificate for stack: '{}'", stack.getName()); certGeneratedSuccessfully = generateCertAndSaveForStack(stack); if (certGeneratedSuccessfully) { LOGGER.info("Generate cert was successful update dns entry for cluster"); updateDnsEntryForCluster(stack); } } return certGeneratedSuccessfully; } private boolean generateCertAndSaveForStack(Stack stack) { boolean result = false; LOGGER.info("Acquire certificate from PEM service and save for stack"); String accountId = ThreadBasedUserCrnProvider.getAccountId(); SecurityConfig securityConfig = stack.getSecurityConfig(); Set<String> hueHostGroups = getHueHostGroups(stack); try { KeyPair keyPair = getKeyPairForStack(stack); String endpointName = getEndpointNameForStack(stack); Set<String> loadBalancerEndpoints = getLoadBalancerNamesForStack(stack); DetailedEnvironmentResponse environment = environmentClientService.getByCrn(stack.getEnvironmentCrn()); String environmentName = environment.getName(); String commonName = getDomainNameProvider().getCommonName(endpointName, environment); String fullyQualifiedEndpointName = getDomainNameProvider().getFullyQualifiedEndpointName( hueHostGroups, endpointName, environment); List<String> subjectAlternativeNames = new ArrayList<>(); subjectAlternativeNames.add(commonName); subjectAlternativeNames.add(fullyQualifiedEndpointName); for (String loadBalancerEndpoint : loadBalancerEndpoints) { String loadBalancerEndpointName = getDomainNameProvider().getFullyQualifiedEndpointName( hueHostGroups, loadBalancerEndpoint, environment); subjectAlternativeNames.add(loadBalancerEndpointName); } LOGGER.info("Acquiring certificate with common name:{} and SANs: {}", commonName, String.join(",", subjectAlternativeNames)); PKCS10CertificationRequest csr = PkiUtil.csr(keyPair, commonName, subjectAlternativeNames); List<String> certs = getCertificateCreationService().create(accountId, endpointName, environmentName, csr, stack.getResourceCrn()); securityConfig.setUserFacingCert(String.join("", certs)); securityConfigService.save(securityConfig); result = true; } catch (Exception e) { LOGGER.info("The certification could not be generated by Public Endpoint Management service: " + e.getMessage(), e); } return result; } private KeyPair getKeyPairForStack(Stack stack) { KeyPair keyPair; SecurityConfig securityConfig = stack.getSecurityConfig(); if (StringUtils.isEmpty(securityConfig.getUserFacingKey())) { keyPair = PkiUtil.generateKeypair(); securityConfig.setUserFacingKey(PkiUtil.convert(keyPair.getPrivate())); securityConfigService.save(securityConfig); } else { keyPair = PkiUtil.fromPrivateKeyPem(securityConfig.getUserFacingKey()); if (keyPair == null) { keyPair = PkiUtil.generateKeypair(); } } return keyPair; } public String updateDnsEntryForCluster(Stack stack) { String fqdn = updateDnsEntry(stack, null); if (fqdn != null) { Cluster cluster = stack.getCluster(); cluster.setFqdn(fqdn); clusterService.save(cluster); LOGGER.info("The '{}' domain name has been generated, registered through PEM service and saved for the cluster.", fqdn); } return fqdn; } private String getEndpointNameForStack(Stack stack) { return stack.getPrimaryGatewayInstance().getShortHostname(); } @VisibleForTesting Set<String> getLoadBalancerNamesForStack(Stack stack) { return loadBalancerPersistenceService.findByStackId(stack.getId()).stream() .filter(lb -> StringUtils.isNotEmpty(lb.getEndpoint())) .map(LoadBalancer::getEndpoint) .collect(Collectors.toSet()); } private Optional<LoadBalancer> getLoadBalancerWithEndpoint(Stack stack) { Optional<LoadBalancer> loadBalancerOptional; Set<LoadBalancer> loadBalancers = loadBalancerPersistenceService.findByStackId(stack.getId()); if (loadBalancers.isEmpty()) { LOGGER.info("No load balancers in stack {}", stack.getId()); loadBalancerOptional = Optional.empty(); } else { loadBalancerOptional = loadBalancerConfigService.selectLoadBalancer(loadBalancers, LoadBalancerType.PUBLIC); if (loadBalancerOptional.isEmpty()) { LOGGER.error("Unable to determine load balancer type. Load balancer public domain name will not be registered."); } else if (Strings.isNullOrEmpty(loadBalancerOptional.get().getEndpoint())) { LOGGER.error("No endpoint set for load balancer. Can't register domain."); loadBalancerOptional = Optional.empty(); } else { LOGGER.debug("Found load balancer {}", loadBalancerOptional.get().getEndpoint()); } } return loadBalancerOptional; } }
hortonworks/cloudbreak
core/src/main/java/com/sequenceiq/cloudbreak/service/publicendpoint/GatewayPublicEndpointManagementService.java
Java
apache-2.0
16,394
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Agency - Start Bootstrap Theme</title> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/agency.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <link href="http://fonts.googleapis.com/css?family=Jockey+One|Merriweather:400,300italic,300,700italic,700,400italic,900,900italic" rel="stylesheet" type="text/css"> </head> <body id="page-top" class="index"> <!-- Navigation --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand page-scroll" href="#page-top">Hicham Idiomas</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="hidden active"> <a href="#page-top"></a> </li> <li> <a class="page-scroll" href="#services">IDIOMAS</a> </li> <li> <a class="page-scroll" href="#portfolio">SERVIÇOS</a> </li> <li> <a class="page-scroll" href="#about">O PROFESSOR</a> </li> <li> <a class="page-scroll" href="#team">DEPOIMENTOS</a> </li> <li> <a class="page-scroll" href="#contact">PACOTES</a> </li> <li> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <!-- Header --> <header> <div class="container"> <div class="intro-text"> <div class="intro-heading">HICHAM IDIOMAS</div> <div class="intro-lead-in">Experimente o mundo em uma nova língua</div> <a href="#services" class="page-scroll btn btn-xl">Tell Me More</a> </div> </div> </header> <!-- Services Section --> <section id="services"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">POR QUE ESTUDAR UMA NOVA LÍNGUA?</h2> <h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3> </div> </div> <div class="row text-center"> <div class="col-md-5 col-md-offset-0 margins"> <img src="img/franceR.png" width="100" class="img-rounded"/> <h4 class="service-heading">Francês</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> <div class="col-md-5 col-md-offset-0"> <img src="img/germanyR.png" width="100"/> <h4 class="service-heading">Alemão</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> </div> </div> </section> <!-- Portfolio Grid Section --> <section id="portfolio" class="bg-light-gray"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">o QUE OFERECEMOS</h2> <h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3> </div> <div class="col-md-offset-0 text-center col-md-4"> <img src="img/ICON-foco.png" width="100" class="img-rounded"> <h4 class="service-heading">Foco nos seus objetivos</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> <div class="col-md-offset-0 text-center col-md-4"> <img src="img/ICON-livro.png" width="100" class="img-rounded"> <h4 class="service-heading">Material didático moderno</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> <div class="col-md-offset-0 text-center col-md-4"> <img src="img/ICON-grupo.png" width="100" class="img-rounded"> <h4 class="service-heading">Aulas individuais ou em grupo</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> <div class="col-md-offset-0 text-center col-md-4"> <img src="img/ICON-hora.png" width="100" class="img-rounded"> <h4 class="service-heading">Horários flexíveis</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> <div class="col-md-offset-0 text-center col-md-4"> <img src="img/ICON-mapa.png" width="100" class="img-rounded"> <h4 class="service-heading">Localização de fácil acesso</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> <div class="col-md-offset-0 text-center col-md-4"> <img src="img/ICON-certif.png" width="100" class="img-rounded"> <h4 class="service-heading">Certificados de conclusão</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> </div> <div class="row"> </div> </div> </section> <!-- About Section --> <section id="about" class="professor"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">CONHEÇA O PROFESSOR</h2> <h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3> </div> </div> <div class="row"> <div class="col-md-4"> <p><i>Lorem ipsum.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc massa libero, sollicitudin eget imperdiet in, vestibulum non justo. Sed in mi aliquet purus volutpat bibendum. Praesent vel imperdiet diam, vel finibus diam. Nullam placerat risus dui, quis elementum velit condimentum at. Donec lorem lacus, convallis at libero ac, varius vehicula risus. Sed finibus magna eget leo commodo, vehicula maximus dui cursus. Vestibulum blandit massa placerat, tincidunt odio ac, consectetur ipsum.</i></p> <p><i><i>Lorem ipsum.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc massa libero, sollicitudin eget imperdiet in, vestibulum non justo. Sed in mi aliquet purus volutpat bibendum. Praesent vel imperdiet diam, vel finibus diam. Nullam placerat risus dui, quis elementum velit condimentum at. Donec lorem lacus, convallis at libero ac, varius vehicula risus. Sed finibus magna eget leo commodo, vehicula maximus dui cursus. Vestibulum blandit massa placerat, tincidunt odio ac, consectetur ipsum.</i><br></i></p> <p><i><i><i><i>&nbsp;Donec lorem lacus, convallis at libero ac, varius vehicula risus. Sed finibus magna eget leo commodo, vehicula maximus dui cursus. Vestibulum blandit massa placerat, tincidunt odio ac, consectetur ipsum.</i></i><br></i></i></p> </div> <div class="col-md-4 col-md-offset-2"> <img src="img/person.jpg" class="photo" width="550"/> </div> </div> </div> <div class="row"></div> </section> <!-- Team Section --> <section id="team" class="bg-light-gray"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">VEJA O QUE NOSSOS ALUNOS ESTÃO DIZENDO<br></h2> </div> </div> <div class="row"> <div class="col-sm-4"> <div class="team-member"> <img src="img/team/1.jpg" class="img-responsive img-circle" alt=""> <h4>Kay Garland</h4> <p class="text-muted">Lead Designer</p> <ul class="list-inline social-buttons"> <li> <a href="#"><i class="fa fa-twitter"></i></a> </li> <li> <a href="#"><i class="fa fa-facebook"></i></a> </li> <li> <a href="#"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> </div> <div class="col-sm-4"> <div class="team-member"> <img src="img/team/2.jpg" class="img-responsive img-circle" alt=""> <h4>Larry Parker</h4> <p class="text-muted">Lead Marketer</p> <ul class="list-inline social-buttons"> <li> <a href="#"><i class="fa fa-twitter"></i></a> </li> <li> <a href="#"><i class="fa fa-facebook"></i></a> </li> <li> <a href="#"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> </div> <div class="col-sm-4"> <div class="team-member"> <img src="img/team/3.jpg" class="img-responsive img-circle" alt=""> <h4>Diana Pertersen</h4> <p class="text-muted">Lead Developer</p> <ul class="list-inline social-buttons"> <li> <a href="#"><i class="fa fa-twitter"></i></a> </li> <li> <a href="#"><i class="fa fa-facebook"></i></a> </li> <li> <a href="#"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> </div> </div> <div class="row"> <div class="col-lg-8 col-lg-offset-2 text-center"> <p class="large text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut eaque, laboriosam veritatis, quos non quis ad perspiciatis, totam corporis ea, alias ut unde.</p> </div> </div> </div> </section> <!-- Clients Aside --> <aside class="clients"> <div class="container"> <div class="row"> <div class="col-md-3 col-sm-6"> <a href="#"> <img src="img/logos/creative-market.jpg" class="img-responsive img-centered" alt=""> </a> </div> </div> </div> </aside> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Contact Us</h2> <h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3> </div> </div> <div class="row"> <div class="col-lg-12"> <form name="sentMessage" id="contactForm" novalidate> <div class="row"> <div class="col-md-6"> <div class="form-group"> <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number."> <p class="help-block text-danger"></p> </div> </div> <div class="col-md-6"> <div class="form-group"> <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea> <p class="help-block text-danger"></p> </div> </div> <div class="clearfix"></div> <div class="col-lg-12 text-center"> <div id="success"></div> <button type="submit" class="btn btn-xl">Send Message</button> </div> </div> </form> </div> </div> </div> </section> <footer> <div class="container"> <div class="row"> <div class="col-md-4"> <span class="copyright">Copyright &copy; Your Website 2014</span> </div> <div class="col-md-4"> <ul class="list-inline social-buttons"> <li> <a href="#"><i class="fa fa-twitter"></i></a> </li> <li> <a href="#"><i class="fa fa-facebook"></i></a> </li> <li> <a href="#"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> <div class="col-md-4"> <ul class="list-inline quicklinks"> <li> <a href="#">Privacy Policy</a> </li> <li> <a href="#">Terms of Use</a> </li> </ul> </div> </div> </div> </footer> <!-- Portfolio Modals --> <!-- Use the modals below to showcase details about your portfolio projects! --> <!-- Portfolio Modal 1 --> <div class="portfolio-modal modal fade" id="portfolioModal1" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive" src="img/portfolio/roundicons-free.png" alt=""> <p>Use this area to describe your project. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est blanditiis dolorem culpa incidunt minus dignissimos deserunt repellat aperiam quasi sunt officia expedita beatae cupiditate, maiores repudiandae, nostrum, reiciendis facere nemo!</p> <p><strong>Want these icons in this portfolio item sample?</strong>You can download 60 of them for free, courtesy of <a href="https://getdpd.com/cart/hoplink/18076?referrer=bvbo4kax5k8ogc">RoundIcons.com</a>, or you can purchase the 1500 icon set <a href="https://getdpd.com/cart/hoplink/18076?referrer=bvbo4kax5k8ogc">here</a>.</p> <ul class="list-inline"> <li>Date: July 2014</li> <li>Client: Round Icons</li> <li>Category: Graphic Design</li> </ul> <button type="button" class="btn btn-primary" data-dismiss="modal"> <i class="fa fa-times"></i> Close Project </button> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 2 --> <div class="portfolio-modal modal fade" id="portfolioModal2" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <h2>Project Heading</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/startup-framework-preview.png" alt=""> <p><a href="http://designmodo.com/startup/?u=787">Startup Framework</a> is a website builder for professionals. Startup Framework contains components and complex blocks (PSD+HTML Bootstrap themes and templates) which can easily be integrated into almost any design. All of these components are made in the same style, and can easily be integrated into projects, allowing you to create hundreds of solutions for your future projects.</p> <p>You can preview Startup Framework <a href="http://designmodo.com/startup/?u=787">here</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"> <i class="fa fa-times"></i> Close Project </button> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 3 --> <div class="portfolio-modal modal fade" id="portfolioModal3" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/treehouse-preview.png" alt=""> <p>Treehouse is a free PSD web template built by <a href="https://www.behance.net/MathavanJaya">Mathavan Jaya</a>. This is bright and spacious design perfect for people or startup companies looking to showcase their apps or other projects.</p> <p>You can download the PSD template in this portfolio sample item at <a href="http://freebiesxpress.com/gallery/treehouse-free-psd-web-template/">FreebiesXpress.com</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"> <i class="fa fa-times"></i> Close Project </button> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 4 --> <div class="portfolio-modal modal fade" id="portfolioModal4" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/golden-preview.png" alt=""> <p>Start Bootstrap's Agency theme is based on Golden, a free PSD website template built by <a href="https://www.behance.net/MathavanJaya">Mathavan Jaya</a>. Golden is a modern and clean one page web template that was made exclusively for Best PSD Freebies. This template has a great portfolio, timeline, and meet your team sections that can be easily modified to fit your needs.</p> <p>You can download the PSD template in this portfolio sample item at <a href="http://freebiesxpress.com/gallery/golden-free-one-page-web-template/">FreebiesXpress.com</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"> <i class="fa fa-times"></i> Close Project </button> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 5 --> <div class="portfolio-modal modal fade" id="portfolioModal5" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/escape-preview.png" alt=""> <p>Escape is a free PSD web template built by <a href="https://www.behance.net/MathavanJaya">Mathavan Jaya</a>. Escape is a one page web template that was designed with agencies in mind. This template is ideal for those looking for a simple one page solution to describe your business and offer your services.</p> <p>You can download the PSD template in this portfolio sample item at <a href="http://freebiesxpress.com/gallery/escape-one-page-psd-web-template/">FreebiesXpress.com</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"> <i class="fa fa-times"></i> Close Project </button> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 6 --> <div class="portfolio-modal modal fade" id="portfolioModal6" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/dreams-preview.png" alt=""> <p>Dreams is a free PSD web template built by <a href="https://www.behance.net/MathavanJaya">Mathavan Jaya</a>. Dreams is a modern one page web template designed for almost any purpose. It’s a beautiful template that’s designed with the Bootstrap framework in mind.</p> <p>You can download the PSD template in this portfolio sample item at <a href="http://freebiesxpress.com/gallery/dreams-free-one-page-web-template/">FreebiesXpress.com</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"> <i class="fa fa-times"></i> Close Project </button> </div> </div> </div> </div> </div> </div> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="js/classie.js"></script> <script src="js/cbpAnimatedHeader.js"></script> <!-- Contact Form JavaScript --> <script src="js/jqBootstrapValidation.js"></script> <script src="js/contact_me.js"></script> <!-- Custom Theme JavaScript --> <script src="js/agency.js"></script> </body> </html>
hichamidiomas/hichamidiomas.github.io
_pgbackup/index_1423972345.html
HTML
apache-2.0
31,485
--- author: leifmadsen comments: true date: 2011-10-26 16:36:49+00:00 layout: post slug: astricon-presentation-today-at-1140am title: AstriCon presentation today at 11:40am wordpress_id: 373 categories: - Asterisk tags: - asterisk.distributed device state - astricon - presentation - queues --- I'll be speaking at AstriCon today (and tomorrow) about building a distributed call centre. The presentation will be 35 minutes long and will contain a set of slides that moves you from an existing traditional PBX system up through a distributed model (which happens to use a call centre as the example system). A PDF of the presentation along with the configuration files from the demo will be available on my website after the presentation. I'll post links to the files on my blog here shortly after the presentation finishes. Hope to see you there!
leifmadsen/blog
content/post/2011-10-26-astricon-presentation-today-at-1140am.markdown
Markdown
apache-2.0
850
const CLS = require('continuation-local-storage'); const createNameSpace = CLS.createNamespace; const getNameSpace = CLS.getNamespace; const knex = require('../core/database'); const uuidV4 = require('uuid/v4'); let kNAMESPACE = 'pwa'; // create the NameSpace createNameSpace(kNAMESPACE); var TransactionInfo = {}; /** * Starts a database transaction & adds that as a facade scoped object under the key 'database' */ // TransactionInfo.startTransaction = async function(cb) { // return knex.transaction(function(transaction) { // let session = getNameSpace(kNAMESPACE); // return session.runAndReturn(function() { // session.set('database', transaction); // return cb(); // }); // }); // }; TransactionInfo.startTransaction = async function(cb) { return knex.transaction(function(transaction) { let session = getNameSpace(kNAMESPACE); return session.runAndReturn(function() { // Add knex transaction object session.set('transaction', transaction); // Add transactionID for async logging session.set('transactionID', uuidV4()); return cb(); }); }); }; /** * Reads a facade scoped object. */ TransactionInfo.getFacadeScopedObject = function(key) { let session = getNameSpace(kNAMESPACE); return session.get(key); }; /** * Sets a facade scoped object. */ TransactionInfo.setFacadeScopedObject = function(key, object) { let session = getNameSpace(kNAMESPACE); session.set(key, object); }; TransactionInfo.bindEmitter = function(obj) { let session = getNameSpace(kNAMESPACE); session.bindEmitter(obj); }; module.exports = TransactionInfo;
sinnott74/PWA
server/src/core/TransactionInfo.js
JavaScript
apache-2.0
1,634
<?php if (! defined("BASEPATH")) exit('No direct access allowed'); class Template extends MY_Controller { var $userdata = ''; function __construct() { parent::__construct(); $utype = $this->session->userdata('usertype'); $uid = $this->session->userdata('userid'); $this->userdata = $this->userdetails($uid, $utype); } public function index($data) { $this->load_template($data); } public function load_template($data) { $this->load->view('flat_template', $data); } public function load_lecturer_template($data) { foreach ($this->userdata[0] as $key => $value) { $data[$key] = $value; } $this->load->view('lecturer_template', $data); } } ?>
karsanrichard/southern_cross
application/modules/template/controllers/template.php
PHP
apache-2.0
682
{{set . "title" .app.Title}} {{$dateFormat := "2006/01/02 15:04"}} {{template "header.html" .}} <section class="app-detail"> <div id="data-app-id" data-app-id="{{.app.Id}}"></div> <h1><a class="app-detail__ttl" href="{{url "AppControllerWithValidation.GetApp" .app.Id}}">{{with $field := field "app.Title" .}}{{$field.Value}}{{end}}</a></h1> <div class="app-detail__description">{{with $field := field "app.Description" .}} {{nl2br $field.Value}}{{end}} <!-- /.app-detail__description --></div> <div id="app-bundle" class="app-detail__bundle"> <div class="app-detail__bundle__tab"> {{set . "bundles" .apkBundles}} {{set . "bundleLabel" "apk"}} {{template "partialBundleList.html" .}} <!-- /.app-detail__bundle__tab --></div> <div class="app-detail__bundle__tab"> {{set . "bundles" .ipaBundles}} {{set . "bundleLabel" "ipa"}} {{template "partialBundleList.html" .}} <!-- /.app-detail__bundle__tab --></div> <!-- /.app-detail__bundle --></div> {{/* <div class="data-box">{{with $field := field "app.Description" .}} <div class="data-box__description"> {{nl2br $field.Value}} <!-- /.data-box__description --></div>{{end}}{{with $field := field "app.CreatedAt" .}} <div class="data-box__date">{{$field.Value.Format $dateFormat}}</div>{{end}} <!-- /.data-box --></div> */}} <div class="app-detail__btn-area"> <a class="btn--create-bundle" href="{{url "AppControllerWithValidation.GetCreateBundle" .app.Id}}" data-icon="&#xf14C;">ファイルを追加</a> <!-- /.app-detail__btn-area --></div> <div class="members"> <h2 class="members__ttl">チームメンバー</h2>{{$email := .tokeninfo.Email}} <ul id="member-list" class="members__list">{{range .authorities}} <li {{if eq .Email $email}}class="members__item--self"{{else}}class="members__item"{{end}} data-authority-id="{{.Id}}"> <a class="members__item__delete" href="javascript:void()" data-icon="&#xf14E;"><span>削除</span></a> <span class="members__item__email">{{.Email}}</span> <!-- /.members__item --></li>{{end}} <li class="members__item--add"> <a id="member-list-add" class="members__add-btn" href="javascript:void()" data-icon="&#xf14C;">メンバーの追加</a> <!-- /.members__item--add --></li> <!-- /.members__list --></ul> <!-- /.members --></div> <div class="api-token"> <h2 class="api-token__ttl">APIトークン</h2> <div class="api-token__token"> <form action="{{url "AppControllerWithValidation.PostRefreshToken" .app.Id}}" method="POST">{{with $field := field "app.ApiToken" .}} <input type="text" value="{{$field.Value}}" />{{end}}{{with $field := field "app.Id" .}} <input type="hidden" name="{{$field.Name}}" value="{{$field.Value}}" />{{end}} <input type="submit" class="btn--refresh-token" value="トークン再発行" /> </form> <!-- /.api-token__token --></div> <ul class="api-token__notice"> <li>アプリケーション開発者は上記のAPIトークンを利用してファイルをアップロードできます。</li> <li>詳しくは<a href="{{url "ApiController.GetDocument"}}">APIドキュメント</a>をご覧ください。</li> <!-- /.api-token__notice --></ul> <!-- /.api-token --></div> <div class="app-detail__btn-area"> <a class="btn--update-app" href="{{url "AppControllerWithValidation.GetUpdateApp" .app.Id}}" data-icon="&#xf04D;">プロジェクトの編集</a> <a class="btn--delete-app" href="{{url "AppControllerWithValidation.PostDeleteApp" .app.Id}}" data-icon="&#xf056;">プロジェクトの削除</a> <!-- /.app-detail__btn-area --></div> <!-- /.app-detail --></section> {{template "footer.html" .}}
kayac/alphawing
app/views/AppControllerWithValidation/GetApp.html
HTML
apache-2.0
3,520
/* jshint node:true */ 'use strict'; /*! * Node.js client/server library for the E1.31 (sACN) protocol * Hugo Hromic - http://github.com/hhromic * * Copyright 2016 Hugo Hromic * * 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. */ // DMP layer private constants var _VECTOR = 0x02; var _TYPE = 0xa1; var _FIRST_ADDRESS = 0x0000; var _ADDRESS_INCREMENT = 0x0001; // DMP layer object constructor function DMPLayer(buffer) { if (this instanceof DMPLayer === false) { return new DMPLayer(buffer); } this._buffer = buffer; this.update(); } // init all fields to default values DMPLayer.prototype.init = function init(numSlots) { var length = this.getLength(); this._buffer.fill(0x00); this._buffer.writeUInt16BE(0x7000 | length, 0); // flength this._buffer.writeUInt8(_VECTOR, 2); this._buffer.writeUInt8(_TYPE, 3); this._buffer.writeUInt16BE(_FIRST_ADDRESS, 4); this._buffer.writeUInt16BE(_ADDRESS_INCREMENT, 6); this._buffer.writeUInt16BE(numSlots + 1, 8); // propertyValueCount this.update(); }; // update object fields from internal buffer DMPLayer.prototype.update = function update() { this.flength = this._buffer.readUInt16BE(0); this.vector = this._buffer.readUInt8(2); this.type = this._buffer.readUInt8(3); this.firstAddress = this._buffer.readUInt16BE(4); this.addressIncrement = this._buffer.readUInt16BE(6); this.propertyValueCount = this._buffer.readUInt16BE(8); this.propertyValues = this._buffer.slice(10); }; // get the bytes length of this DMP layer DMPLayer.prototype.getLength = function getLength() { return this._buffer.length; }; // get DMX slots data from this DMP layer DMPLayer.prototype.getSlotsData = function getSlotsData() { return this.propertyValues.slice(1); }; // set DMX slots data on this DMP layer DMPLayer.prototype.setSlotsData = function setSlotsData(slotsData) { slotsData.copy(this.propertyValues, 1, 0, this.propertyValueCount - 1); }; // check if this DMP layer is valid DMPLayer.prototype.isValid = function isValid() { return this.vector === _VECTOR && this.type === _TYPE && this.firstAddress === _FIRST_ADDRESS && this.addressIncrement === _ADDRESS_INCREMENT; }; // module exports module.exports = DMPLayer;
hhromic/e131-node
lib/e131/dmp_layer.js
JavaScript
apache-2.0
2,736
# # curl -L https://www.opscode.com/chef/install.sh | bash # # Cookbook Name:: phpapp # Recipe:: default # # Copyright 2016, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # #include_recipe "mysql" include_recipe "apache2" include_recipe "apache2::default" # #include_recipe "php" include_recipe "apache2::mod_php5" #recipe[selinux::disabled] package ["git"] do action :install end package ["mercurial"] do action :install end template ("/etc/hosts") do source ("hosts.erb") owner "root" group "root" mode 0644 variables( hosts: '127.0.0.1', hostname: node['aplicativo']['nombre'], ) end ## template para acceso desde afuera al puerto 80 ## template ("/etc/sysconfig/iptables") do source ("iptables.erb") owner "root" group "root" mode 0600 end # directory(node[:phpprueba][:app_root]) # web_app("wsj") do # server_name("wsj") # docroot("/var/wsj/web") # template('vhost.conf.erb') # end yum_package 'mysql-libs' do action :purge version "5.1.66-2.el6_3" end yum_package 'ca-certificates' do action :upgrade #options "--disablerepo=epel" end yum_package 'nano' do action :install #options "--disablerepo=epel" end cookbook_file '/tmp/mysql57-community-release-el6-8.noarch.rpm' do source 'mysql57-community-release-el6-8.noarch.rpm' owner 'root' group 'root' mode '0755' not_if { File.exist?("/tmp/mysql57-community-release-el6-8.noarch.rpm") } action :create end cookbook_file '/tmp/epel-release-6-8.noarch.rpm' do source 'epel-release-6-8.noarch.rpm' owner 'root' group 'root' mode '0755' not_if { File.exist?("/tmp/epel-release-6-8.noarch.rpm") } action :create end cookbook_file '/tmp/latest.rpm' do source 'latest.rpm' owner 'root' group 'root' mode '0755' not_if { File.exist?("/tmp/latest.rpm") } action :create end cookbook_file '/etc/yum.repos.d/remi.repo' do source 'remi.repo' owner 'root' group 'root' mode '0755' not_if { File.exist?("/etc/yum.repos.d/remi.repo") } action :create end execute 'instalando rpm mysql' do #command "npm install -g n && n 0.12.4" command "yum -y localinstall /tmp/mysql57-community-release-el6-8.noarch.rpm" user "root" group "root" not_if { File.exist?("/etc/yum.repos.d/mysql-community.repo") } action :run end execute 'instalando rpm epel' do #command "npm install -g n && n 0.12.4" command "yum -y localinstall /tmp/epel-release-6-8.noarch.rpm" user "root" group "root" not_if { File.exist?("/etc/yum.repos.d/epel.repo") } action :run end execute 'instalando rpm latest' do #command "npm install -g n && n 0.12.4" command "yum -y localinstall /tmp/latest.rpm" user "root" group "root" #not_if { File.exist?("/etc/yum.repos.d/latest.repo") } not_if { File.exist?("/etc/yum.repos.d/webtatic.repo") } action :run end mysql_client 'default' do action :create end pass = node['bd']['clave-acceso'] mysql_service "default" do port '3306' version '5.7' initial_root_password "#{pass}" #package_version '5.6.32-1ubuntu14.04' #package_version "5.6.31-0ubuntu0.14.04.2" #package_version "5.5.50-0ubuntu0.14.04.1" action [:create, :start] end package "php" do action :install end # package "php-mysql" do # action :install # end #service "apache2" do # supports :restart => true # action :start # subscribes :reload,"package[php-mysql]" , :immediately #end service "apache2" do supports :restart => true action :start subscribes :reload,"package[php]" , :immediately end package "php-curl" do action :install end service "apache2" do supports :restart => true action :start subscribes :reload,"package[php-curl]" , :immediately end package "php-intl" do action :install end service "apache2" do supports :restart => true action :start subscribes :reload,"package[php-intl]" , :immediately end package "php-gd" do action :install end service "apache2" do supports :restart => true action :start subscribes :reload,"package[php-gd]" , :immediately end package "php-xml" do action :install end service "apache2" do supports :restart => true action :start subscribes :reload,"package[php-xml]" , :immediately end package "php-mbstring" do action :install end service "apache2" do supports :restart => true action :start subscribes :reload,"package[php-mbstring]" , :immediately end package "php-dom" do action :install end service "apache2" do supports :restart => true action :start subscribes :reload,"package[php-dom]" , :immediately end package "php-process" do action :install end service "apache2" do supports :restart => true action :start subscribes :reload,"package[php-process]" , :immediately end package "php-pdo" do action :install end service "apache2" do supports :restart => true action :start subscribes :reload,"package[php-pdo]" , :immediately end package "php-mysql" do action :install end service "apache2" do supports :restart => true action :start subscribes :reload,"package[php-mysql]" , :immediately end #package ["apache2-utils"] do # action :install #end execute 'instalando composer' do #command "npm install -g n && n 0.12.4" command "cd /tmp && php -r \"copy('https://getcomposer.org/installer', 'composer-setup.php');\" && php composer-setup.php && mv /tmp/composer.phar /vagrant/" user "root" group "root" not_if { File.exist?("/vagrant/composer.phar") } action :run end #ver el tamaño por var se seteo template ("/etc/php.ini") do source ("php.erb") owner "root" group "root" mode 0640 end # #ver el nombreservidor por seteo # # template ("/etc/httpd/conf/httpd.conf") do # # source ("httpd.erb") # # owner "root" # # group "root" # # mode 0640 # # end nombre_aplicativo = node['aplicativo']['nombre'] template ("/etc/httpd/sites-available/sylius.conf") do source ("sylius.erb") owner "root" group "apache" mode 0750 variables(aplicativo: nombre_aplicativo) #verify 'file /var/#{nombre_aplicativo} |grep ": directory" ' end execute 'enable sylius' do command "cd /etc/httpd/sites-enabled/ && ln -s ../sites-available/sylius.conf sylius.conf " user "root" #ignore_failure true #not_if { File.exist?("etc/apache2/conf-enabled/phpmyadmin.conf") } not_if 'file /etc/httpd/sites-enabled/sylius.conf |grep symbolic ' action :run end execute 'enable variable term' do command "echo 'export TERM=linux' > ~/.bash_profile && source ~/.bash_profile" user "root" group "root" #ignore_failure true #not_if { File.exist?("etc/apache2/conf-enabled/phpmyadmin.conf") } #not_if 'file /etc/httpd/sites-enabled/sylius.conf ' action :run end # hola = node['prueba']['directorio'] # execute 'enable sylius' do # command "cd /tmp && mkdir #{hola}" # user "root" # group "root" # #ignore_failure true # #not_if { File.exist?("etc/apache2/conf-enabled/phpmyadmin.conf") } # #not_if 'file /etc/httpd/sites-enabled/sylius.conf ' # action :run # end execute 'modulo rewrite' do command " a2enmod rewrite " user "root" #ignore_failure true #not_if { File.exist?("etc/apache2/conf-enabled/phpmyadmin.conf") } action :run end service "apache2" do supports :restart => true action :enable subscribes :restart,"modulo rewrite" , :immediately end package "php-mcrypt" do action :install end package ["npm"] do action :install end # execute 'mcryp' do # command "php5enmod mcrypt " # user "root" # action :run # end # package ["phpmyadmin"] do # action :install # end # service "apache2" do # supports :restart => true # action :enable # subscribes :restart,"package[phpmyadmin]" , :immediately # end # template ("/usr/share/phpMyAdmin/.htaccess") do # source (".htaccess.erb") # owner "root" # group "root" # mode 0755 # end # cookbook_file '/tmp/create_tables.sql' do # source 'create_tables.sql' # owner 'root' # group 'root' # mode '0755' # not_if { File.exist?("/tmp/create_tables.sql") } # action :create # end # pass = node['bd']['clave-acceso'] # execute 'crea bd phpmyadmin ' do # command " mysql -u root -p#{pass} -h 127.0.0.1 < /tmp/create_tables.sql " # user "root" # #ignore_failure true # #not_if { File.exist?("etc/apache2/conf-enabled/phpmyadmin.conf") } # action :run # end # cookbook_file '/tmp/user_pma.sql' do # source 'user_pma.sql' # owner 'root' # group 'root' # mode '0755' # not_if { File.exist?("/tmp/user_pma.sql") } # action :create # end # pass = node['bd']['clave-acceso'] # template ("/tmp/user_pma.sql") do # source ("user_pma.sql.erb") # owner "root" # group "root" # mode 0750 # variables(server: "localhost",clave: pass) # #verify 'file /var/#{nombre_aplicativo} |grep ": directory" ' # end # pass = node['bd']['clave-acceso'] # execute 'crea crea usuario pma y accesos a phpmyadmin (BD)' do # command " mysql -u root -p#{pass} -h 127.0.0.1 < /tmp/user_pma.sql " # user "root" # #ignore_failure true # #not_if { File.exist?("etc/apache2/conf-enabled/phpmyadmin.conf") } # not_if 'mysql -uroot -p#{pass} -h 127.0.0.1 -e"SELECT User FROM mysql.user;" |grep pma' # action :run # end # pass = node['bd']['clave-acceso'] # template ("/etc/phpMyAdmin/config-db.php") do # source ("config-db.php.erb") # owner "root" # group "apache" # variables(clave: pass) # mode 0640 # end
AyeJavier/chef-sylius
cookbooks/phpapp/recipes/default.rb
Ruby
apache-2.0
9,441
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>Catcher - ScalaTest 2.2.2-SNAPSHOT - org.scalactic.Catcher</title> <meta name="description" content="Catcher - ScalaTest 2.2.2 - SNAPSHOT - org.scalactic.Catcher" /> <meta name="keywords" content="Catcher ScalaTest 2.2.2 SNAPSHOT org.scalactic.Catcher" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../lib/jquery.js" id="jquery-js"></script> <script type="text/javascript" src="../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../lib/template.js"></script> <script type="text/javascript" src="../../lib/tools.tooltip.js"></script> <script type="text/javascript"> if(top === self) { var url = '../../index.html'; var hash = 'org.scalactic.Catcher$'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-71294502-3', 'auto'); ga('send', 'pageview'); </script> </head> <body class="value"> <!-- Top of doc.scalactic.org [javascript] --> <script type="text/javascript"> var rnd = window.rnd || Math.floor(Math.random()*10e6); var pid204569 = window.pid204569 || rnd; var plc204569 = window.plc204569 || 0; var abkw = window.abkw || ''; var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204569;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204569+';place='+(plc204569++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER'; document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>'); </script> <div id="definition"> <a href="Catcher.html" title="Go to companion"><img src="../../lib/object_to_class_big.png" /></a> <p id="owner"><a href="../package.html" class="extype" name="org">org</a>.<a href="package.html" class="extype" name="org.scalactic">scalactic</a></p> <h1><a href="Catcher.html" title="Go to companion">Catcher</a></h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">object</span> </span> <span class="symbol"> <span class="name">Catcher</span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="comment cmt"><p>Companion object for <code>Catcher</code> that provides a factory method for creating <code>Throwable</code> extractors. </p></div><dl class="attributes block"> <dt>Source</dt><dd><a href="https://github.com/scalatest/scalatest/tree/release-2.2.2-for-scala-2.11-and-2.10/src/main/scala/org/scalactic/Catcher.scala" target="_blank">Catcher.scala</a></dd></dl><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="org.scalactic.Catcher"><span>Catcher</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li> </ol> <a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:AnyRef):Boolean"></a> <a id="!=(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:AnyRef):Boolean"></a> <a id="==(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="org.scalactic.Catcher#apply" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="apply(partial:PartialFunction[Throwable,Boolean]):org.scalactic.Catcher"></a> <a id="apply(PartialFunction[Throwable,Boolean]):Catcher"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">apply</span><span class="params">(<span name="partial">partial: <span class="extype" name="scala.PartialFunction">PartialFunction</span>[<span class="extype" name="scala.Throwable">Throwable</span>, <span class="extype" name="scala.Boolean">Boolean</span>]</span>)</span><span class="result">: <a href="Catcher.html" class="extype" name="org.scalactic.Catcher">Catcher</a></span> </span> </h4> <p class="shortcomment cmt">Creates and returns a new <code>Catcher</code> that uses the passed partial function to determine matches.</p><div class="fullcomment"><div class="comment cmt"><p>Creates and returns a new <code>Catcher</code> that uses the passed partial function to determine matches. </p></div><dl class="paramcmts block"><dt class="param">partial</dt><dd class="cmt"><p>the partial function that is used by returned extractor to determine matches </p></dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </html>
scalatest/scalatest-website
public/scaladoc/2.2.2/org/scalactic/Catcher$.html
HTML
apache-2.0
23,756
use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::time::{SystemTime, UNIX_EPOCH}; use domain::wallet::Tags; use domain::anoncreds::schema::SchemaId; use domain::anoncreds::credential_definition::CredentialDefinitionId; use errors::prelude::*; use services::wallet::{WalletService, WalletRecord}; use api::{WalletHandle, PoolHandle, CommandHandle}; use commands::{Command, CommandExecutor}; use commands::ledger::LedgerCommand; use domain::cache::{GetCacheOptions, PurgeOptions}; use api::next_command_handle; const CRED_DEF_CACHE: &str = "cred_def_cache"; const SCHEMA_CACHE: &str = "schema_cache"; pub enum CacheCommand { GetSchema(PoolHandle, WalletHandle, String, // submitter_did SchemaId, // id GetCacheOptions, // options Box<dyn Fn(IndyResult<String>) + Send>), GetSchemaContinue( WalletHandle, IndyResult<(String, String)>, // ledger_response GetCacheOptions, // options CommandHandle, // cb_id ), GetCredDef(PoolHandle, WalletHandle, String, // submitter_did CredentialDefinitionId, // id GetCacheOptions, // options Box<dyn Fn(IndyResult<String>) + Send>), GetCredDefContinue( WalletHandle, IndyResult<(String, String)>, // ledger_response GetCacheOptions, // options CommandHandle, // cb_id ), PurgeSchemaCache(WalletHandle, PurgeOptions, // options Box<dyn Fn(IndyResult<()>) + Send>), PurgeCredDefCache(WalletHandle, PurgeOptions, // options Box<dyn Fn(IndyResult<()>) + Send>), } pub struct CacheCommandExecutor { wallet_service: Rc<WalletService>, pending_callbacks: RefCell<HashMap<CommandHandle, Box<dyn Fn(IndyResult<String>)>>>, } macro_rules! check_cache { ($cache: ident, $options: ident, $cb: ident) => { if let Some(cache) = $cache { let min_fresh = $options.min_fresh.unwrap_or(-1); if min_fresh >= 0 { let ts = match CacheCommandExecutor::get_seconds_since_epoch() { Ok(ts) => ts, Err(err) => { return $cb(Err(err)) } }; if ts - min_fresh <= cache.get_tags().unwrap_or(&Tags::new()).get("timestamp").unwrap_or(&"-1".to_string()).parse().unwrap_or(-1) { return $cb(Ok(cache.get_value().unwrap_or("").to_string())) } } else { return $cb(Ok(cache.get_value().unwrap_or("").to_string())) } } }; } impl CacheCommandExecutor { pub fn new(wallet_service: Rc<WalletService>) -> CacheCommandExecutor { CacheCommandExecutor { wallet_service, pending_callbacks: RefCell::new(HashMap::new()), } } pub fn execute(&self, command: CacheCommand) { match command { CacheCommand::GetSchema(pool_handle, wallet_handle, submitter_did, id, options, cb) => { debug!(target: "non_secrets_command_executor", "GetSchema command received"); self.get_schema(pool_handle, wallet_handle, &submitter_did, &id, options, cb); } CacheCommand::GetSchemaContinue(wallet_handle, ledger_response, options, cb_id) => { debug!(target: "non_secrets_command_executor", "GetSchemaContinue command received"); self._get_schema_continue(wallet_handle, ledger_response, options, cb_id); } CacheCommand::GetCredDef(pool_handle, wallet_handle, submitter_did, id, options, cb) => { debug!(target: "non_secrets_command_executor", "GetCredDef command received"); self.get_cred_def(pool_handle, wallet_handle, &submitter_did, &id, options, cb); } CacheCommand::GetCredDefContinue(wallet_handle, ledger_response, options, cb_id) => { debug!(target: "non_secrets_command_executor", "GetCredDefContinue command received"); self._get_cred_def_continue(wallet_handle, ledger_response, options, cb_id); } CacheCommand::PurgeSchemaCache(wallet_handle, options, cb) => { debug!(target: "non_secrets_command_executor", "PurgeSchemaCache command received"); cb(self.purge_schema_cache(wallet_handle, options)); } CacheCommand::PurgeCredDefCache(wallet_handle, options, cb) => { debug!(target: "non_secrets_command_executor", "PurgeCredDefCache command received"); cb(self.purge_cred_def_cache(wallet_handle, options)); } } } fn get_schema(&self, pool_handle: PoolHandle, wallet_handle: WalletHandle, submitter_did: &str, id: &SchemaId, options: GetCacheOptions, cb: Box<dyn Fn(IndyResult<String>) + Send>) { trace!("get_schema >>> pool_handle: {:?}, wallet_handle: {:?}, submitter_did: {:?}, id: {:?}, options: {:?}", pool_handle, wallet_handle, submitter_did, id, options); let cache = self.get_record_from_cache(wallet_handle, &id.0, &options, SCHEMA_CACHE); let cache = try_cb!(cache, cb); check_cache!(cache, options, cb); if options.no_update.unwrap_or(false) { return cb(Err(IndyError::from(IndyErrorKind::LedgerItemNotFound))); } let cb_id = next_command_handle(); self.pending_callbacks.borrow_mut().insert(cb_id, cb); CommandExecutor::instance().send( Command::Ledger( LedgerCommand::GetSchema( pool_handle, Some(submitter_did.to_string()), id.clone(), Box::new(move |ledger_response| { CommandExecutor::instance().send( Command::Cache( CacheCommand::GetSchemaContinue( wallet_handle, ledger_response, options.clone(), cb_id, ) ) ).unwrap(); }) ) ) ).unwrap(); } fn _delete_and_add_record(&self, wallet_handle: WalletHandle, options: GetCacheOptions, schema_id: &str, schema_json: &str, which_cache: &str) -> IndyResult<()> { if !options.no_store.unwrap_or(false) { let mut tags = Tags::new(); let ts = match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(ts) => ts.as_secs() as i32, Err(err) => { warn!("Cannot get time: {:?}", err); 0 } }; tags.insert("timestamp".to_string(), ts.to_string()); let _ignore = self.wallet_service.delete_record(wallet_handle, which_cache, &schema_id); self.wallet_service.add_record(wallet_handle, which_cache, &schema_id, &schema_json, &tags)? } Ok(()) } fn _get_schema_continue(&self, wallet_handle: WalletHandle, ledger_response: IndyResult<(String, String)>, options: GetCacheOptions, cb_id: CommandHandle) { let cb = self.pending_callbacks.borrow_mut().remove(&cb_id).expect("FIXME INVALID STATE"); let (schema_id, schema_json) = try_cb!(ledger_response, cb); match self._delete_and_add_record(wallet_handle, options, &schema_id, &schema_json, SCHEMA_CACHE) { Ok(_) => cb(Ok(schema_json)), Err(err) => cb(Err(IndyError::from_msg(IndyErrorKind::InvalidState, format!("get_schema_continue failed: {:?}", err)))) } } fn get_cred_def(&self, pool_handle: PoolHandle, wallet_handle: WalletHandle, submitter_did: &str, id: &CredentialDefinitionId, options: GetCacheOptions, cb: Box<dyn Fn(IndyResult<String>) + Send>) { trace!("get_cred_def >>> pool_handle: {:?}, wallet_handle: {:?}, submitter_did: {:?}, id: {:?}, options: {:?}", pool_handle, wallet_handle, submitter_did, id, options); let cache = self.get_record_from_cache(wallet_handle, &id.0, &options, CRED_DEF_CACHE); let cache = try_cb!(cache, cb); check_cache!(cache, options, cb); if options.no_update.unwrap_or(false) { return cb(Err(IndyError::from(IndyErrorKind::LedgerItemNotFound))); } let cb_id = next_command_handle(); self.pending_callbacks.borrow_mut().insert(cb_id, cb); CommandExecutor::instance().send( Command::Ledger( LedgerCommand::GetCredDef( pool_handle, Some(submitter_did.to_string()), id.clone(), Box::new(move |ledger_response| { CommandExecutor::instance().send( Command::Cache( CacheCommand::GetCredDefContinue( wallet_handle, ledger_response, options.clone(), cb_id, ) ) ).unwrap(); }) ) ) ).unwrap(); } fn get_record_from_cache(&self, wallet_handle: WalletHandle, id: &str, options: &GetCacheOptions, which_cache: &str) -> Result<Option<WalletRecord>, IndyError> { if !options.no_cache.unwrap_or(false) { let options_json = json!({ "retrieveType": false, "retrieveValue": true, "retrieveTags": true, }).to_string(); match self.wallet_service.get_record(wallet_handle, which_cache, &id, &options_json) { Ok(record) => Ok(Some(record)), Err(err) => if err.kind() == IndyErrorKind::WalletItemNotFound { Ok(None) } else { Err(err) } } } else { Ok(None) } } fn _get_cred_def_continue(&self, wallet_handle: WalletHandle, ledger_response: IndyResult<(String, String)>, options: GetCacheOptions, cb_id: CommandHandle) { let cb = self.pending_callbacks.borrow_mut().remove(&cb_id).expect("FIXME INVALID STATE"); let (cred_def_id, cred_def_json) = try_cb!(ledger_response, cb); match self._delete_and_add_record(wallet_handle, options, &cred_def_id, &cred_def_json, CRED_DEF_CACHE) { Ok(_) => cb(Ok(cred_def_json)), Err(err) => cb(Err(IndyError::from_msg(IndyErrorKind::InvalidState, format!("get_cred_def_continue failed: {:?}", err)))) } } fn get_seconds_since_epoch() -> Result<i32, IndyError> { match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(ts) => Ok(ts.as_secs() as i32), Err(err) => { error!("Cannot get time: {:?}", err); Err(IndyError::from_msg(IndyErrorKind::InvalidState, format!("Cannot get time: {:?}", err))) } } } fn build_query_json(max_age: i32) -> Result<String, IndyError> { if max_age >= 0 { let ts = CacheCommandExecutor::get_seconds_since_epoch()?; Ok(json!({"timestamp": {"$lt": ts - max_age}}).to_string()) } else { Ok("{}".to_string()) } } fn purge_schema_cache(&self, wallet_handle: WalletHandle, options: PurgeOptions) -> IndyResult<()> { trace!("purge_schema_cache >>> wallet_handle: {:?}, options: {:?}", wallet_handle, options); let max_age = options.max_age.unwrap_or(-1); let query_json = CacheCommandExecutor::build_query_json(max_age)?; let options_json = json!({ "retrieveType": false, "retrieveValue": false, "retrieveTags": false, }).to_string(); let mut search = self.wallet_service.search_records( wallet_handle, SCHEMA_CACHE, &query_json, &options_json, )?; while let Some(record) = search.fetch_next_record()? { self.wallet_service.delete_record(wallet_handle, SCHEMA_CACHE, record.get_id())?; } trace!("purge_schema_cache <<< res: ()"); Ok(()) } fn purge_cred_def_cache(&self, wallet_handle: WalletHandle, options: PurgeOptions) -> IndyResult<()> { trace!("purge_cred_def_cache >>> wallet_handle: {:?}, options: {:?}", wallet_handle, options); let max_age = options.max_age.unwrap_or(-1); let query_json = CacheCommandExecutor::build_query_json(max_age)?; let options_json = json!({ "retrieveType": false, "retrieveValue": false, "retrieveTags": false, }).to_string(); let mut search = self.wallet_service.search_records( wallet_handle, CRED_DEF_CACHE, &query_json, &options_json, )?; while let Some(record) = search.fetch_next_record()? { self.wallet_service.delete_record(wallet_handle, CRED_DEF_CACHE, record.get_id())?; } trace!("purge_cred_def_cache <<< res: ()"); Ok(()) } }
peacekeeper/indy-sdk
libindy/src/commands/cache.rs
Rust
apache-2.0
14,119
package com.sequenceiq.cloudbreak.controller.v4; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.transaction.Transactional; import javax.transaction.Transactional.TxType; import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import com.sequenceiq.authorization.annotation.AccountIdNotNeeded; import com.sequenceiq.authorization.annotation.CheckPermissionByAccount; import com.sequenceiq.authorization.annotation.CheckPermissionByResourceCrn; import com.sequenceiq.authorization.annotation.CheckPermissionByResourceName; import com.sequenceiq.authorization.annotation.InternalOnly; import com.sequenceiq.authorization.annotation.ResourceCrn; import com.sequenceiq.authorization.annotation.ResourceName; import com.sequenceiq.authorization.resource.AuthorizationResourceAction; import com.sequenceiq.cloudbreak.api.endpoint.v4.autoscales.AutoscaleV4Endpoint; import com.sequenceiq.cloudbreak.api.endpoint.v4.autoscales.base.ScalingStrategy; import com.sequenceiq.cloudbreak.api.endpoint.v4.autoscales.request.UpdateStackV4Request; import com.sequenceiq.cloudbreak.api.endpoint.v4.autoscales.response.AuthorizeForAutoscaleV4Response; import com.sequenceiq.cloudbreak.api.endpoint.v4.autoscales.response.AutoscaleStackV4Responses; import com.sequenceiq.cloudbreak.api.endpoint.v4.autoscales.response.CertificateV4Response; import com.sequenceiq.cloudbreak.api.endpoint.v4.autoscales.response.ClusterProxyConfiguration; import com.sequenceiq.cloudbreak.api.endpoint.v4.autoscales.response.LimitsConfigurationResponse; import com.sequenceiq.cloudbreak.api.endpoint.v4.connector.responses.AutoscaleRecommendationV4Response; import com.sequenceiq.cloudbreak.api.endpoint.v4.dto.NameOrCrn; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.request.UpdateClusterV4Request; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.AutoscaleStackV4Response; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.StackStatusV4Response; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.StackV4Response; import com.sequenceiq.cloudbreak.auth.security.internal.AccountId; import com.sequenceiq.cloudbreak.auth.security.internal.TenantAwareParam; import com.sequenceiq.cloudbreak.cloud.model.AutoscaleRecommendation; import com.sequenceiq.cloudbreak.conf.LimitConfiguration; import com.sequenceiq.cloudbreak.converter.v4.clustertemplate.AutoscaleRecommendationToAutoscaleRecommendationV4ResponseConverter; import com.sequenceiq.cloudbreak.converter.v4.stacks.StackToAutoscaleStackV4ResponseConverter; import com.sequenceiq.cloudbreak.core.flow2.cluster.provision.service.ClusterProxyService; import com.sequenceiq.cloudbreak.domain.stack.Stack; import com.sequenceiq.cloudbreak.service.ClusterCommonService; import com.sequenceiq.cloudbreak.service.StackCommonService; import com.sequenceiq.cloudbreak.service.blueprint.BlueprintService; import com.sequenceiq.cloudbreak.service.stack.StackService; import com.sequenceiq.cloudbreak.structuredevent.CloudbreakRestRequestThreadLocalService; import com.sequenceiq.distrox.v1.distrox.StackOperations; @Controller @Transactional(TxType.NEVER) public class AutoscaleV4Controller implements AutoscaleV4Endpoint { private static final Logger LOGGER = LoggerFactory.getLogger(AutoscaleV4Controller.class); @Inject private StackService stackService; @Inject private StackOperations stackOperations; @Inject private CloudbreakRestRequestThreadLocalService restRequestThreadLocalService; @Inject private StackCommonService stackCommonService; @Inject private ClusterCommonService clusterCommonService; @Inject private ClusterProxyService clusterProxyService; @Inject private BlueprintService blueprintService; @Inject private StackToAutoscaleStackV4ResponseConverter stackToAutoscaleStackV4ResponseConverter; @Inject private AutoscaleRecommendationToAutoscaleRecommendationV4ResponseConverter autoscaleRecommendationToAutoscaleRecommendationV4ResponseConverter; @Inject private LimitConfiguration limitConfiguration; @Override @CheckPermissionByResourceCrn(action = AuthorizationResourceAction.SCALE_DATAHUB) public void putStack(@TenantAwareParam @ResourceCrn String crn, String userId, @Valid UpdateStackV4Request updateRequest) { stackCommonService.putInDefaultWorkspace(crn, updateRequest); } @Override @CheckPermissionByResourceCrn(action = AuthorizationResourceAction.SCALE_DATAHUB) public void putStackStartInstancesByCrn(@TenantAwareParam @ResourceCrn String crn, @Valid UpdateStackV4Request updateRequest) { stackCommonService.putStartInstancesInDefaultWorkspace(NameOrCrn.ofCrn(crn), restRequestThreadLocalService.getRequestedWorkspaceId(), updateRequest, ScalingStrategy.STOPSTART); } @Override @CheckPermissionByResourceName(action = AuthorizationResourceAction.SCALE_DATAHUB) public void putStackStartInstancesByName(@ResourceName String name, @Valid UpdateStackV4Request updateRequest) { stackCommonService.putStartInstancesInDefaultWorkspace(NameOrCrn.ofName(name), restRequestThreadLocalService.getRequestedWorkspaceId(), updateRequest, ScalingStrategy.STOPSTART); } @Override @CheckPermissionByResourceCrn(action = AuthorizationResourceAction.SCALE_DATAHUB) public void putCluster(@TenantAwareParam @ResourceCrn String crn, String userId, @Valid UpdateClusterV4Request updateRequest) { clusterCommonService.put(crn, updateRequest); } @Override @CheckPermissionByResourceCrn(action = AuthorizationResourceAction.SCALE_DATAHUB) public void decommissionInstancesForClusterCrn(@TenantAwareParam @ResourceCrn String clusterCrn, Long workspaceId, List<String> instanceIds, Boolean forced) { stackCommonService.deleteMultipleInstancesInWorkspace(NameOrCrn.ofCrn(clusterCrn), restRequestThreadLocalService.getRequestedWorkspaceId(), new HashSet(instanceIds), forced); } @Override @CheckPermissionByResourceCrn(action = AuthorizationResourceAction.SCALE_DATAHUB) public AutoscaleStackV4Response getAutoscaleClusterByCrn(@TenantAwareParam @ResourceCrn String crn) { Stack stack = stackService.getByCrnInWorkspace(crn, restRequestThreadLocalService.getRequestedWorkspaceId()); return stackToAutoscaleStackV4ResponseConverter.convert(stack); } @Override @CheckPermissionByResourceName(action = AuthorizationResourceAction.SCALE_DATAHUB) public AutoscaleStackV4Response getAutoscaleClusterByName(@ResourceName String name) { Stack stack = stackService.getByNameInWorkspace(name, restRequestThreadLocalService.getRequestedWorkspaceId()); return stackToAutoscaleStackV4ResponseConverter.convert(stack); } @Override @InternalOnly public AutoscaleStackV4Response getInternalAutoscaleClusterByName(String name, @AccountId String accountId) { return getAutoscaleClusterByName(name); } @Override @InternalOnly public void decommissionInternalInstancesForClusterCrn(@TenantAwareParam @ResourceCrn String clusterCrn, List<String> instanceIds, Boolean forced) { LOGGER.info("decommissionInternalInstancesForClusterCrn. forced={}, clusterCrn={}, instanceIds=[{}]", forced, clusterCrn, instanceIds); stackCommonService.deleteMultipleInstancesInWorkspace(NameOrCrn.ofCrn(clusterCrn), restRequestThreadLocalService.getRequestedWorkspaceId(), new HashSet(instanceIds), forced); } @Override @CheckPermissionByResourceCrn(action = AuthorizationResourceAction.SCALE_DATAHUB) public void stopInstancesForClusterCrn(@TenantAwareParam @ResourceCrn String clusterCrn, @NotEmpty List<String> instanceIds, Boolean forced, ScalingStrategy scalingStrategy) { LOGGER.info("stopInstancesForClusterCrn. ScalingStrategy={}, forced={}, clusterCrn={}, instanceIds=[{}]", scalingStrategy, forced, clusterCrn, instanceIds); stackCommonService.stopMultipleInstancesInWorkspace(NameOrCrn.ofCrn(clusterCrn), restRequestThreadLocalService.getRequestedWorkspaceId(), new HashSet(instanceIds), forced); } @Override @CheckPermissionByResourceName(action = AuthorizationResourceAction.SCALE_DATAHUB) public void stopInstancesForClusterName(@ResourceName String clusterName, @NotEmpty List<String> instanceIds, Boolean forced, ScalingStrategy scalingStrategy) { LOGGER.info("stopInstancesForClusterName: ScalingStrategy={}, forced={}, clusterName={}, instanceIds=[{}]", scalingStrategy, forced, clusterName, instanceIds); stackCommonService.stopMultipleInstancesInWorkspace(NameOrCrn.ofName(clusterName), restRequestThreadLocalService.getRequestedWorkspaceId(), new HashSet<>(instanceIds), forced); } @Override @CheckPermissionByAccount(action = AuthorizationResourceAction.POWERUSER_ONLY) public AutoscaleStackV4Responses getAllForAutoscale() { Set<AutoscaleStackV4Response> allForAutoscale = stackCommonService.getAllForAutoscale(); return new AutoscaleStackV4Responses(new ArrayList<>(allForAutoscale)); } @Override @InternalOnly public StackV4Response get(@TenantAwareParam String crn) { return stackCommonService.getByCrn(crn, Collections.emptySet()); } @Override @InternalOnly public StackStatusV4Response getStatusByCrn(@TenantAwareParam String crn) { return stackOperations.getStatus(crn); } @Override @InternalOnly public AuthorizeForAutoscaleV4Response authorizeForAutoscale(@TenantAwareParam String crn, String userId, String tenant, String permission) { AuthorizeForAutoscaleV4Response response = new AuthorizeForAutoscaleV4Response(); try { restRequestThreadLocalService.setCloudbreakUserByUsernameAndTenant(userId, tenant); // TODO check permission explicitly Stack stack = stackService.getByCrn(crn); response.setSuccess(true); } catch (RuntimeException ignore) { response.setSuccess(false); } return response; } @Override @InternalOnly public CertificateV4Response getCertificate(@TenantAwareParam String crn) { return stackCommonService.getCertificate(crn); } @Override @AccountIdNotNeeded @InternalOnly public ClusterProxyConfiguration getClusterProxyconfiguration() { return clusterProxyService.getClusterProxyConfigurationForAutoscale(); } @Override @AccountIdNotNeeded @InternalOnly public LimitsConfigurationResponse getLimitsConfiguration() { return new LimitsConfigurationResponse(limitConfiguration.getNodeCountLimit()); } @Override @InternalOnly public AutoscaleRecommendationV4Response getRecommendation(@TenantAwareParam String crn) { Stack stack = stackService.getByCrn(crn); String blueprintName = stack.getCluster().getBlueprint().getName(); Long workspaceId = stack.getWorkspace().getId(); AutoscaleRecommendation autoscaleRecommendation = blueprintService.getAutoscaleRecommendation(workspaceId, blueprintName); return autoscaleRecommendationToAutoscaleRecommendationV4ResponseConverter.convert(autoscaleRecommendation); } @Override @CheckPermissionByResourceName(action = AuthorizationResourceAction.DESCRIBE_CLUSTER_TEMPLATE) public AutoscaleRecommendationV4Response getRecommendation(Long workspaceId, @ResourceName String blueprintName) { AutoscaleRecommendation autoscaleRecommendation = blueprintService.getAutoscaleRecommendation( restRequestThreadLocalService.getRequestedWorkspaceId(), blueprintName); return autoscaleRecommendationToAutoscaleRecommendationV4ResponseConverter.convert(autoscaleRecommendation); } }
hortonworks/cloudbreak
core/src/main/java/com/sequenceiq/cloudbreak/controller/v4/AutoscaleV4Controller.java
Java
apache-2.0
12,233
package z.z.w.test.demo ; import java.util.concurrent.locks.ReadWriteLock ; import java.util.concurrent.locks.ReentrantReadWriteLock ; class Data3 { private int data ; // 共享数据 private ReadWriteLock rwl = new ReentrantReadWriteLock() ; public void get() { rwl.readLock().lock() ;// 取到读锁 try { System.out.println( Thread.currentThread().getName() + "准备读取数据++++++++++++++" ) ; try { Thread.sleep( ( long ) ( Math.random() * 1000 ) ) ; } catch ( InterruptedException e ) { e.printStackTrace() ; } System.out.println( Thread.currentThread().getName() + "读取" + data ) ; } finally { rwl.readLock().unlock() ;// 释放读锁 } } public void set( int data ) { rwl.writeLock().lock() ;// 取到写锁 try { System.out.println( Thread.currentThread().getName() + "准备写入数据................" ) ; try { Thread.sleep( ( long ) ( Math.random() * 1000 ) ) ; } catch ( InterruptedException e ) { e.printStackTrace() ; } this.data = data ; System.out.println( Thread.currentThread().getName() + "写入" + this.data ) ; } finally { rwl.writeLock().unlock() ;// 释放写锁 } } } /************************************************************************** * <pre> * FileName: z.z.w.test.ReadWriteLockTest.java * Desc: * @author: Z_Z.W - [email protected] * @version: 2015年8月4日 下午2:39:56 * LastChange: 2015年8月4日 下午2:39:56 * History: * </pre> **************************************************************************/ public class ReadWriteLockTest3 { /** * Create by : 2015年8月4日 下午2:39:56 * * @param args */ public static void main( String[] args ) { System.out.println( Thread.currentThread().getName() + "准备=====================" ) ; for ( int i = 0 ; i < 4 ; i++ ) new Thread( new Runnable() { @Override public void run() { System.out.println( Thread.currentThread().getName() + "准备" ) ; final Data data = new Data() ; for ( int i = 0 ; i < 3 ; i++ ) new Thread( new Runnable() { @Override public void run() { for ( int j = 0 ; j < 5 ; j++ ) data.set( ( int ) ( Math.random() * 10000 ) ) ; } } ).start() ; for ( int i = 0 ; i < 3 ; i++ ) new Thread( new Runnable() { @Override public void run() { for ( int j = 0 ; j < 5 ; j++ ) data.get() ; } } ).start() ; System.out.println( Thread.currentThread().getName() + "結束" ) ; } } ).start() ; System.out.println( Thread.currentThread().getName() + "結束======================" ) ; } }
myhongkongzhen/pro-common
src/test/java/z/z/w/test/demo/ReadWriteLockTest3.java
Java
apache-2.0
2,776
package org.domeos.framework.api.model.deployment.related; /** * Created by xxs on 16/4/5. */ public enum HostEnv { PROD, TEST }
domeos/server
src/main/java/org/domeos/framework/api/model/deployment/related/HostEnv.java
Java
apache-2.0
136
/* * Copyright 2012-2017 Amazon Technologies, 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://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.auth; import java.util.HashMap; import java.util.Map; import com.amazonaws.ClientConfiguration; /** * Session credentials provider factory to share providers across potentially * many clients. */ public class SessionCredentialsProviderFactory { /** * Key object for the cache combines the access key and the service * endpoint. */ private static final class Key { private final String awsAccessKeyId; private final String serviceEndpoint; public Key(String awsAccessKeyId, String serviceEndpoint) { this.awsAccessKeyId = awsAccessKeyId; this.serviceEndpoint = serviceEndpoint; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((awsAccessKeyId == null) ? 0 : awsAccessKeyId.hashCode()); result = prime * result + ((serviceEndpoint == null) ? 0 : serviceEndpoint.hashCode()); return result; } @Override public boolean equals(Object obj) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; Key other = (Key) obj; if ( awsAccessKeyId == null ) { if ( other.awsAccessKeyId != null ) return false; } else if ( !awsAccessKeyId.equals(other.awsAccessKeyId) ) return false; if ( serviceEndpoint == null ) { if ( other.serviceEndpoint != null ) return false; } else if ( !serviceEndpoint.equals(other.serviceEndpoint) ) return false; return true; } } private static final Map<Key, STSSessionCredentialsProvider> cache = new HashMap<SessionCredentialsProviderFactory.Key, STSSessionCredentialsProvider>(); /** * Gets a session credentials provider for the long-term credentials and * service endpoint given. These are shared globally to support reuse of * session tokens. * * @param longTermCredentials * The long-term AWS account credentials used to initiate a * session. * @param serviceEndpoint * The service endpoint for the service the session credentials * will be used to access. * @param stsClientConfiguration * Client configuration for the {@link AWSSecurityTokenService} * used to fetch session credentials. */ public static synchronized STSSessionCredentialsProvider getSessionCredentialsProvider(AWSCredentials longTermCredentials, String serviceEndpoint, ClientConfiguration stsClientConfiguration) { Key key = new Key(longTermCredentials.getAWSAccessKeyId(), serviceEndpoint); if ( !cache.containsKey(key) ) { cache.put(key, new STSSessionCredentialsProvider(longTermCredentials, stsClientConfiguration)); } return cache.get(key); } }
dagnir/aws-sdk-java
aws-java-sdk-sts/src/main/java/com/amazonaws/auth/SessionCredentialsProviderFactory.java
Java
apache-2.0
3,932
<!DOCTYPE html> <html dir="ltr" lang="en-US"> <head> <!-- Document Meta =====================================--> <meta charset="UTF-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="author" content="CodexCoder"> <meta name="description" content="AppsWorld Is Onepage Application Marketing Landing page"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <!-- Document Title ======================================--> <title>AppsWorld :: Default</title> <!-- Project Stylesheets ==========================================--> <link rel="stylesheet" type="text/css" href="dependencies/loaders.css/loaders.css"> <link rel="stylesheet" type="text/css" href="dependencies/bootstrap/dist/css/bootstrap.css"> <link rel="stylesheet" type="text/css" href="dependencies/fontawesome/css/font-awesome.css"> <link rel="stylesheet" type="text/css" href="dependencies/swiper/dist/css/swiper.css"> <link rel="stylesheet" type="text/css" href="dependencies/formstone/dist/css/lightbox.css"> <link rel="stylesheet" type="text/css" href="dependencies/animate.css/animate.css"> <link rel="stylesheet" type="text/css" href="assets/stylesheets/app.css"> <!-- Google Fonts --> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic,700italic|Montserrat:400,700"> </head> <body class="blog" > <div id="preloader"> <div id="loader"> <div class="loader-inner ball-scale-multiple"><div></div><div></div><div></div></div> </div><!-- /#loader --> </div><!-- /#preloader --> <!-- Navigations ==============================--> <nav id="navigation" class="navigation-style-1"> <div class="container"> <div class="nav-header"> <a href="index.html" class="site-name" id="logo"> <img src="assets/images/logo.png" alt="Apps World"> <!-- <h1>AppsWorld</h1> --> </a> <div id="nav-socials"> <a href="#facebook"><i class="fa fa-facebook"></i></a> <a href="#dribbble"><i class="fa fa-dribbble"></i></a> <a href="#twitter"><i class="fa fa-twitter"></i></a> </div> <div id="nav-trigger" class="nav-trigger style-1"> <a href="#"><i class="fa fa-bars"></i></a> </div><!-- /#nav-trigger --> </div><!-- /.nav-header --> <ul class="site-navigation"> <li><a href="#banner"><i class="fa fa-home"></i>Home</a></li> <li><a href="#our-achievement"><i class="fa fa-user"></i>Achievement</a></li> <li><a href="#why"><i class="fa fa-download"></i>Why Us</a></li> <li><a href="#download"><i class="fa fa-briefcase"></i>Downloads</a></li> <li><a href="#feature"><i class="fa fa-file-image-o"></i>Features</a></li> <li><a href="#pricng"><i class="fa fa-usd"></i>Pricing</a></li> <li><a href="#testimonial"><i class="fa fa-edit"></i>Testimonials</a></li> <li><a href="#screenshots"><i class="fa fa-plane"></i>Screenshots</a></li> <li><a href="#blog"><i class="fa fa-envelope-o"></i>Blog</a></li> <li><a href="#blog"><i class="fa fa-envelope-o"></i>contact</a></li> <li class="has-submenu"> <a href="#"><i class="fa fa-envelope-o"></i>Sub Menu</a> <ul class="submenu"> <li><a href="#">Sub Item 1</a></li> <li><a href="#">Sub Item 2</a></li> <li><a href="#">Sub Item 3</a></li> </ul> </li> </ul><!-- /.site-navigation --> </div><!-- /.container --> </nav><!-- /#navigation --> <!-- Blog Header ==============================--> <section id="blog-header" class="aw-page-header transparent" data-type="background" data-parallax="yes" data-speed="50" data-src="assets/images/download-bg.jpg"> <div class="overlay section-padding"> <div class="container"> <div class="aw-header-content"> <h1 class="text-uppercase text-center">App's News</h1> <ol id="breadcrumbs" class="aw-bredcrumb text-center"> <li><a class="bread-link bread-home" href="#" title="Home">Home</a></li> <li><a href="#" title="Uncategorized">Uncategorized</a></li> <li class="item-current item-1241">Template: Sticky</li> </ol> </div><!-- /.aw-header-content --> </div><!-- /.container --> </div><!-- /.overlay --> </section><!-- /#blog-header --> <div id="blog-container" class="top-padding-100"> <div class="container"> <div class="row"> <div class="col-md-8"> <!-- Blog Posts ==============================--> <div class="aw-single-post"> <!-- Standard Post --> <article id="post-1" class="aw-post"> <img src="assets/images/post-thumb.jpg" alt="Post Item" class="aw-post-thumb"> <div class="aw-post-content"> <h2 class="title">Lorem ipsum dolor sit amet, consectetur adipis...</h2> <div class="aw-post-full-content"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime dolore unde nihil laudantium, minus iusto, aspernatur. Aliquam soluta provident dolor ea eaque sunt ipsum, voluptatem fuga cum voluptatum quos, voluptas possimus vero debitis veritatis neque, perferendis deserunt vel, praesentium explicabo quis temporibus. Hic voluptatum quo beatae, officia rerum. Mollitia, rem.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id reiciendis officia tempore. Temporibus impedit cupiditate delectus. Impedit dolores provident incidunt, labore error, debitis repellendus dolore.</p> <blockquote> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae saepe obcaecati quaerat, quas laboriosam sapiente molestias deleniti perspiciatis, aut maxime iusto, quis cumque fugiat nam? </blockquote> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Optio facere eligendi quaerat nam saepe nemo, porro nesciunt quod quibusdam nisi autem praesentium neque. Odio modi veritatis quae eveniet, ducimus nemo pariatur iure doloremque nisi et culpa eligendi, excepturi vero odit architecto facilis eaque unde illum nulla cupiditate. Nostrum magnam autem ipsam ratione, perferendis officiis tempora. Suscipit nesciunt eos animi fuga, cum molestiae amet quam delectus illum commodi cupiditate, in id earum deserunt corporis optio blanditiis ad magnam cumque inventore dolores eveniet, minima! Soluta ratione repudiandae blanditiis enim qui eum impedit, eveniet et, minus quas, obcaecati laudantium earum ullam! At, suscipit.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint nostrum non voluptatibus delectus eum hic, dignissimos inventore magnam esse, omnis enim, vero rerum atque distinctio repellendus eligendi dolore deleniti, corporis blanditiis quae. Qui, maiores voluptas nihil sed earum ipsum illum quisquam eius, nemo quos praesentium consequatur obcaecati ullam accusantium aut.</p> </div><!-- /.aw-post-full-content --> <div class="top-padding-20"></div> <div class="meta"> <ul> <li> <i class="fa fa-clock-o"></i> 27 May, 2015 </li> <li> <i class="fa fa-user"></i> Khandaker </li> <li> <i class="fa fa-comments-o"></i> <a href="#">09 Comments</a> </li> </ul> </div><!-- /.meta --> <div class="post-share"> <span class="share-text">Share: </span> <ul> <li> <a href="#"> <i class="fa fa-facebook"></i> <span>Share On Facebook</span> </a> </li> <li> <a href="#"> <i class="fa fa-twitter"></i> <span>Tweet on Twitter</span> </a> </li> <li> <a href="#"> <i class="fa fa-pinterest "></i> <span>Pin on Pinterest</span> </a> </li> <li> <a href="#"> <i class="fa fa-linkedin"></i> <span>Share on Linkedin</span> </a> </li> <li> <a href="#"> <i class="fa fa-google-plus"></i> <span>Share it on Google+</span> </a> </li> </ul> </div><!-- /.share --> </div><!-- /.aw-post-content --> </article><!-- /#post-1.aw-post --> <div class="aw-post-author"> <div class="author-img"> <img src="assets/images/user.jpg" alt="Post Author"> </div><!-- /.author-img --> <div class="author-details"> <h3>Khandaker Rasel</h3> <div class="bio"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat delectus consectetur odit blanditiis. Optio in similique eos sint a at illum. Explicabo dolorem, ab voluptatum! </div><!-- /.bio --> </div><!-- /.author-details --> </div><!-- /.aw-post-author --> <div class="aw-comments"> <h2 class="comment-title">68 Comments</h2> <ol class="commentslist"> <li> <article> <div class="comment-author-img"> <img src="assets/images/user.jpg" alt="Comment Author"> </div><!-- /.comment-author-img --> <div class="comment-details"> <div class="comment-meta"> <h3>Khandaker Rasel</h3> <div class="time"><a href="#">06 June 2014 at 10.30</a></div> </div><!-- /.comment-meta --> <div class="comment-content"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Praesentium, eligendi ad. Vel obcaecati nulla vero dolor, repellat praesentium rerum, ab ipsam ea. Nemo, fugiat, repellendus. </div><!-- /.comment-content --> </div><!-- /.comment-details --> <a href="#" class="comment-reply-link">Reply</a> </article><!-- #comment-## --> </li> <li> <article> <div class="comment-author-img"> <img src="assets/images/user.jpg" alt="Comment Author"> </div><!-- /.comment-author-img --> <div class="comment-details"> <div class="comment-meta"> <h3>Khandaker Rasel</h3> <div class="time"><a href="#">06 June 2014 at 10.30</a></div> </div><!-- /.comment-meta --> <div class="comment-content"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Praesentium, eligendi ad. Vel obcaecati nulla vero dolor, repellat praesentium rerum, ab ipsam ea. Nemo, fugiat, repellendus. </div><!-- /.comment-content --> </div><!-- /.comment-details --> <a href="#" class="comment-reply-link">Reply</a> </article><!-- #comment-## --> <ul class="children"> <li> <article> <div class="comment-author-img"> <img src="assets/images/user.jpg" alt="Comment Author"> </div><!-- /.comment-author-img --> <div class="comment-details"> <div class="comment-meta"> <h3>Khandaker Rasel</h3> <div class="time"><a href="#">06 June 2014 at 10.30</a></div> </div><!-- /.comment-meta --> <div class="comment-content"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Praesentium, eligendi ad. Vel obcaecati nulla vero dolor, repellat praesentium rerum, ab ipsam ea. Nemo, fugiat, repellendus. </div><!-- /.comment-content --> </div><!-- /.comment-details --> <a href="#" class="comment-reply-link">Reply</a> </article><!-- #comment-## --> </li> <ul class="children"> <li> <article> <div class="comment-author-img"> <img src="assets/images/user.jpg" alt="Comment Author"> </div><!-- /.comment-author-img --> <div class="comment-details"> <div class="comment-meta"> <h3>Khandaker Rasel</h3> <div class="time"><a href="#">06 June 2014 at 10.30</a></div> </div><!-- /.comment-meta --> <div class="comment-content"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Praesentium, eligendi ad. Vel obcaecati nulla vero dolor, repellat praesentium rerum, ab ipsam ea. Nemo, fugiat, repellendus. </div><!-- /.comment-content --> </div><!-- /.comment-details --> <a href="#" class="comment-reply-link">Reply</a> </article><!-- #comment-## --> </li> </ul> </ul> </li> <li> <article> <div class="comment-author-img"> <img src="assets/images/user.jpg" alt="Comment Author"> </div><!-- /.comment-author-img --> <div class="comment-details"> <div class="comment-meta"> <h3>Khandaker Rasel</h3> <div class="time"><a href="#">06 June 2014 at 10.30</a></div> </div><!-- /.comment-meta --> <div class="comment-content"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Praesentium, eligendi ad. Vel obcaecati nulla vero dolor, repellat praesentium rerum, ab ipsam ea. Nemo, fugiat, repellendus. </div><!-- /.comment-content --> </div><!-- /.comment-details --> <a href="#" class="comment-reply-link">Reply</a> </article><!-- #comment-## --> </li> <li> <article> <div class="comment-author-img"> <img src="assets/images/user.jpg" alt="Comment Author"> </div><!-- /.comment-author-img --> <div class="comment-details"> <div class="comment-meta"> <h3>Khandaker Rasel</h3> <div class="time"><a href="#">06 June 2014 at 10.30</a></div> </div><!-- /.comment-meta --> <div class="comment-content"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Praesentium, eligendi ad. Vel obcaecati nulla vero dolor, repellat praesentium rerum, ab ipsam ea. Nemo, fugiat, repellendus. </div><!-- /.comment-content --> </div><!-- /.comment-details --> <a href="#" class="comment-reply-link">Reply</a> </article><!-- #comment-## --> </li> </ol><!-- /.commentslist --> </div><!-- /.aw-comments --> <div class="comment-respond"> <h3 class="comment-reply-title">Leave A Comment</h3> <form action="#" class="comment-form"> <input type="text" name="name" id="name" placeholder="Your Name"> <input type="email" name="email" id="email" placeholder="Your Email"> <input type="url" name="website" id="website" placeholder="Your Website"> <textarea name="comment" id="comment" cols="30" rows="5" placeholder="Your Comments"></textarea> <div class="form-submit"> <input type="submit" value="Submit" /> </div><!-- /.form-submit --> </form> </div><!-- /.comment-respond --> </div><!-- /.aw-blog-posts --> </div><!-- /.col-md-8 --> <div class="col-md-4"> <!-- Blog Posts ==============================--> <div id="secondary" class="widget-area" role="complementary"> <aside id="archives-3" class="widget widget_archive"> <h1 class="widget-title">Archives</h1> <ul> <li><a href="http://office.wordpress.dev/appsworld/2015/06/">June 2015</a></li> <li><a href="http://office.wordpress.dev/appsworld/2013/03/">March 2013</a></li> <li><a href="http://office.wordpress.dev/appsworld/2013/01/">January 2013</a></li> <li><a href="http://office.wordpress.dev/appsworld/2012/12/">December 2012</a></li> <li><a href="http://office.wordpress.dev/appsworld/2012/11/">November 2012</a></li> </ul> </aside> <aside id="calendar-2" class="widget widget_calendar"> <div id="calendar_wrap"> <table id="wp-calendar"> <caption>June 2015</caption> <thead> <tr> <th scope="col" title="Monday">M</th> <th scope="col" title="Tuesday">T</th> <th scope="col" title="Wednesday">W</th> <th scope="col" title="Thursday">T</th> <th scope="col" title="Friday">F</th> <th scope="col" title="Saturday">S</th> <th scope="col" title="Sunday">S</th> </tr> </thead> <tfoot> <tr> <td colspan="3" id="prev"><a href="http://office.wordpress.dev/appsworld/2013/03/">« Mar</a></td> <td class="pad">&nbsp;</td> <td colspan="3" id="next" class="pad">&nbsp;</td> </tr> </tfoot> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td><a href="http://office.wordpress.dev/appsworld/2015/06/06/" title="Hello world!">6</a></td> <td>7</td> </tr> <tr> <td>8</td> <td>9</td> <td>10</td> <td>11</td> <td>12</td> <td>13</td> <td>14</td> </tr> <tr> <td id="today">15</td> <td>16</td> <td>17</td> <td>18</td> <td>19</td> <td>20</td> <td>21</td> </tr> <tr> <td>22</td> <td>23</td> <td>24</td> <td>25</td> <td>26</td> <td>27</td> <td>28</td> </tr> <tr> <td>29</td> <td>30</td> <td class="pad" colspan="5">&nbsp;</td> </tr> </tbody> </table> </div> </aside> <aside id="tag_cloud-2" class="widget widget_tag_cloud"> <h1 class="widget-title">Tags</h1> <div class="tagcloud"> <a href="http://office.wordpress.dev/appsworld/tag/8bit/" class="tag-link-43" title="1 topic" style="font-size: 8pt;">8BIT</a> <a href="http://office.wordpress.dev/appsworld/tag/articles/" class="tag-link-44" title="1 topic" style="font-size: 8pt;">Articles</a> <a href="http://office.wordpress.dev/appsworld/tag/dowork/" class="tag-link-45" title="1 topic" style="font-size: 8pt;">dowork</a> <a href="http://office.wordpress.dev/appsworld/tag/fail/" class="tag-link-46" title="1 topic" style="font-size: 8pt;">Fail</a> <a href="http://office.wordpress.dev/appsworld/tag/ftw/" class="tag-link-47" title="1 topic" style="font-size: 8pt;">FTW</a> <a href="http://office.wordpress.dev/appsworld/tag/fun/" class="tag-link-48" title="1 topic" style="font-size: 8pt;">Fun</a> <a href="http://office.wordpress.dev/appsworld/tag/love/" class="tag-link-49" title="1 topic" style="font-size: 8pt;">Love</a> <a href="http://office.wordpress.dev/appsworld/tag/mothership/" class="tag-link-50" title="1 topic" style="font-size: 8pt;">Mothership</a> <a href="http://office.wordpress.dev/appsworld/tag/mustread/" class="tag-link-51" title="1 topic" style="font-size: 8pt;">Must Read</a> <a href="http://office.wordpress.dev/appsworld/tag/nailedit/" class="tag-link-52" title="1 topic" style="font-size: 8pt;">Nailed It</a> <a href="http://office.wordpress.dev/appsworld/tag/pictures/" class="tag-link-53" title="1 topic" style="font-size: 8pt;">Pictures</a> <a href="http://office.wordpress.dev/appsworld/tag/success/" class="tag-link-54" title="1 topic" style="font-size: 8pt;">Success</a> <a href="http://office.wordpress.dev/appsworld/tag/swagger/" class="tag-link-55" title="1 topic" style="font-size: 8pt;">Swagger</a> <a href="http://office.wordpress.dev/appsworld/tag/tags/" class="tag-link-56" title="1 topic" style="font-size: 8pt;">Tags</a> <a href="http://office.wordpress.dev/appsworld/tag/unseen/" class="tag-link-57" title="1 topic" style="font-size: 8pt;">Unseen</a> <a href="http://office.wordpress.dev/appsworld/tag/wordpress/" class="tag-link-58" title="1 topic" style="font-size: 8pt;">WordPress</a> </div> </aside> <aside id="search-3" class="widget widget_search"> <form role="search" method="get" class="search-form" action="http://office.wordpress.dev/appsworld/"> <label> <span class="screen-reader-text">Search for:</span> <input type="search" class="search-field" placeholder="Search …" value="" name="s" title="Search for:"> </label> <input type="submit" class="search-submit" value="Search"> </form> </aside> <aside id="recent-posts-3" class="widget widget_recent_entries"> <h1 class="widget-title">Recent Posts</h1> <ul> <li> <a href="http://office.wordpress.dev/appsworld/2015/06/06/hello-world/">Hello world!</a> </li> <li> <a href="http://office.wordpress.dev/appsworld/2013/03/15/tiled-gallery/">Tiled Gallery</a> </li> <li> <a href="http://office.wordpress.dev/appsworld/2013/03/15/twitter-embeds/">Twitter Embeds</a> </li> <li> <a href="http://office.wordpress.dev/appsworld/2013/03/15/featured-image-vertical/">Featured Image (Vertical)</a> </li> <li> <a href="http://office.wordpress.dev/appsworld/2013/03/15/featured-image-horizontal/">Featured Image (Horizontal)</a> </li> </ul> </aside> <aside id="recent-comments-3" class="widget widget_recent_comments"> <h1 class="widget-title">Recent Comments</h1> <ul id="recentcomments"> <li class="recentcomments"><span class="comment-author-link"><a href="https://wordpress.org/" rel="external nofollow" class="url">Mr WordPress</a></span> on <a href="http://office.wordpress.dev/appsworld/2015/06/06/hello-world/#comment-1">Hello world!</a> </li> <li class="recentcomments"><span class="comment-author-link"><a href="http://chrisam.es/" rel="external nofollow" class="url">Chris Ames</a></span> on <a href="http://office.wordpress.dev/appsworld/page-comments/#comment-2">Page Comments</a> </li> <li class="recentcomments"><span class="comment-author-link"><a href="http://jarederickson.com/" rel="external nofollow" class="url">Jared Erickson</a></span> on <a href="http://office.wordpress.dev/appsworld/2013/01/05/non-breaking-text/#comment-31">Super/Duper/Long/NonBreaking/Path/Name/To/A/File/That/Is/Way/Deep/Down/In/Some/Mysterious/Remote/Desolate/Part/Of/The/Operating/System/To/A/File/That/Just/So/Happens/To/Be/Strangely/Named/Supercalifragilisticexpialidocious.txt</a> </li> <li class="recentcomments"><span class="comment-author-link"><a href="http://chrisam.es" rel="external nofollow" class="url">Chris Ames</a></span> on <a href="http://office.wordpress.dev/appsworld/2013/01/06/no-content/#comment-30">No Content</a> </li> <li class="recentcomments"><span class="comment-author-link"><a href="http://tommcfarlin.com/" rel="external nofollow" class="url">Tom McFarlin</a></span> on <a href="http://office.wordpress.dev/appsworld/2013/01/04/password-protected/#comment-29">Protected: Password Protected (the password is “enter”)</a> </li> </ul> </aside> <aside id="categories-3" class="widget widget_categories"> <h1 class="widget-title">Categories</h1> <ul> <li class="cat-item cat-item-2"><a href="http://office.wordpress.dev/appsworld/category/alignment/" title="Posts in this category test image and text alignment.">Alignment</a></li> <li class="cat-item cat-item-3"><a href="http://office.wordpress.dev/appsworld/category/post-format-aside/" title="Posts in this category test the aside post format.">Aside</a></li> <li class="cat-item cat-item-4"><a href="http://office.wordpress.dev/appsworld/category/post-format-audio/" title="Posts in this category test the audio post format.">Audio</a></li> <li class="cat-item cat-item-5"><a href="http://office.wordpress.dev/appsworld/category/captions/" title="Posts in this category test image captions.">Captions</a></li> <li class="cat-item cat-item-6"><a href="http://office.wordpress.dev/appsworld/category/post-format-chat/" title="Posts in this category test the chat post format.">Chat</a></li> <li class="cat-item cat-item-37"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-01/" title="This is a description for the Child Category 01.">Child Category 01</a></li> <li class="cat-item cat-item-38"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-02/" title="This is a description for the Child Category 02.">Child Category 02</a></li> <li class="cat-item cat-item-39"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-03/" title="This is a description for the Child Category 03.">Child Category 03</a></li> <li class="cat-item cat-item-40"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-04/" title="This is a description for the Child Category 04.">Child Category 04</a></li> <li class="cat-item cat-item-41"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-05/" title="This is a description for the Child Category 05.">Child Category 05</a></li> <li class="cat-item cat-item-7"><a href="http://office.wordpress.dev/appsworld/category/codex/" title="Posts in this category contain Codex references.">Codex</a></li> <li class="cat-item cat-item-8"><a href="http://office.wordpress.dev/appsworld/category/comments/" title="Posts in this category test comments.">Comments</a></li> <li class="cat-item cat-item-9"><a href="http://office.wordpress.dev/appsworld/category/content/" title="Posts in this category test post content.">Content</a></li> <li class="cat-item cat-item-10"><a href="http://office.wordpress.dev/appsworld/category/corner-case/" title="Posts in this category test odd corner cases, using uncovered by rare user workflows.">Corner Case</a></li> <li class="cat-item cat-item-11"><a href="http://office.wordpress.dev/appsworld/category/embeds/" title="Posts in this category test various embed codes.">Embeds</a></li> <li class="cat-item cat-item-12"><a href="http://office.wordpress.dev/appsworld/category/excerpt/" title="Posts in this category test post excerpts.">Excerpt</a></li> <li class="cat-item cat-item-13"><a href="http://office.wordpress.dev/appsworld/category/featured-images/" title="Posts in this category test featured images.">Featured Images</a></li> <li class="cat-item cat-item-14"><a href="http://office.wordpress.dev/appsworld/category/formatting/" title="Posts in this category test various formatting scenarios.">Formatting</a></li> <li class="cat-item cat-item-15"><a href="http://office.wordpress.dev/appsworld/category/post-format-gallery/" title="Posts in this category test the gallery post format.">Gallery</a></li> <li class="cat-item cat-item-42"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-03/grandchild-category/" title="This is a description for the Grandchild Category.">Grandchild Category</a></li> <li class="cat-item cat-item-16"><a href="http://office.wordpress.dev/appsworld/category/images/" title="Posts in this category test images in various ways.">Images</a></li> <li class="cat-item cat-item-17"><a href="http://office.wordpress.dev/appsworld/category/jetpack/" title="Posts in this category test Jetpack features.">Jetpack</a></li> <li class="cat-item cat-item-18"><a href="http://office.wordpress.dev/appsworld/category/post-format-link/" title="Posts in this category test the link post format.">Link</a></li> <li class="cat-item cat-item-19"><a href="http://office.wordpress.dev/appsworld/category/lists/" title="Posts in this category test various list scenarios.">Lists</a></li> <li class="cat-item cat-item-20"><a href="http://office.wordpress.dev/appsworld/category/markup/" title="Posts in this category test markup tags and styles.">Markup</a></li> <li class="cat-item cat-item-21"><a href="http://office.wordpress.dev/appsworld/category/more-tag/" title="Posts in this category test the more tag feature.">More Tag</a></li> <li class="cat-item cat-item-22"><a href="http://office.wordpress.dev/appsworld/category/parent-category/" title="This is a parent category. It will contain child categories">Parent Category</a></li> <li class="cat-item cat-item-23"><a href="http://office.wordpress.dev/appsworld/category/password/" title="Posts in this category test the post password feature.">Password</a></li> <li class="cat-item cat-item-24"><a href="http://office.wordpress.dev/appsworld/category/pingbacks/" title="Posts in this category test pingbacks.">Pingbacks</a></li> <li class="cat-item cat-item-25"><a href="http://office.wordpress.dev/appsworld/category/post-formats/" title="Posts in this category test post formats.">Post Formats</a></li> <li class="cat-item cat-item-26"><a href="http://office.wordpress.dev/appsworld/category/post-format-quote/" title="Posts in this category test the quote post format.">Quote</a></li> <li class="cat-item cat-item-27"><a href="http://office.wordpress.dev/appsworld/category/shortcodes/" title="Posts in this category test various shortcodes.">Shortcodes</a></li> <li class="cat-item cat-item-28"><a href="http://office.wordpress.dev/appsworld/category/standard/" title="Posts in this category test the standard post format.">Standard</a></li> <li class="cat-item cat-item-29"><a href="http://office.wordpress.dev/appsworld/category/post-format-status/" title="Posts in this category test the status post format.">Status</a></li> <li class="cat-item cat-item-30"><a href="http://office.wordpress.dev/appsworld/category/sticky/">Sticky</a></li> <li class="cat-item cat-item-31"><a href="http://office.wordpress.dev/appsworld/category/titles/" title="Posts in this category test post title scenarios.">Titles</a></li> <li class="cat-item cat-item-32"><a href="http://office.wordpress.dev/appsworld/category/trackbacks/" title="Posts in this category test trackbacks.">Trackbacks</a></li> <li class="cat-item cat-item-33"><a href="http://office.wordpress.dev/appsworld/category/twitter/" title="Posts in this category test various Twitter features.">Twitter</a></li> <li class="cat-item cat-item-1"><a href="http://office.wordpress.dev/appsworld/category/uncategorized/">Uncategorized</a></li> <li class="cat-item cat-item-34"><a href="http://office.wordpress.dev/appsworld/category/unpublished/" title="Posts in this category test unpublished posts.">Unpublished</a></li> <li class="cat-item cat-item-35"><a href="http://office.wordpress.dev/appsworld/category/post-format-video/" title="Posts in this category test the video post format.">Video</a></li> <li class="cat-item cat-item-36"><a href="http://office.wordpress.dev/appsworld/category/videopress/" title="Posts in this category test VideoPress features.">VideoPress</a></li> </ul> </aside> <aside id="nav_menu-2" class="widget widget_nav_menu"> <div class="menu-testing-menu-container"> <ul id="menu-testing-menu" class="menu"> <li id="menu-item-1355" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1355"><a href="http://office.wordpress.dev/appsworld/about/">About</a></li> <li id="menu-item-1303" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1303"><a href="#">Pages</a> <ul class="sub-menu"> <li id="menu-item-1356" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1356"><a href="http://office.wordpress.dev/appsworld/amazon-store/">Amazon Store</a></li> <li id="menu-item-1357" class="menu-item menu-item-type-post_type menu-item-object-page current_page_parent menu-item-1357"><a href="http://office.wordpress.dev/appsworld/blog/">Blog</a></li> <li id="menu-item-1358" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1358"><a href="http://office.wordpress.dev/appsworld/home-2/">Home</a></li> <li id="menu-item-1359" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1359"><a href="http://office.wordpress.dev/appsworld/page-comments/">Page Comments</a></li> <li id="menu-item-1360" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1360"><a href="http://office.wordpress.dev/appsworld/page-comments-disabled/">Page Comments Disabled</a></li> <li id="menu-item-1361" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1361"><a href="http://office.wordpress.dev/appsworld/page-image-alignment/">Page Image Alignment</a></li> <li id="menu-item-1362" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1362"><a href="http://office.wordpress.dev/appsworld/page-markup-and-formatting/">Page Markup And Formatting</a></li> </ul> </li> <li id="menu-item-1304" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1304"><a href="#">Categories</a> <ul class="sub-menu"> <li id="menu-item-1305" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1305"><a href="http://office.wordpress.dev/appsworld/category/alignment/">Alignment</a></li> <li id="menu-item-1306" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1306"><a href="http://office.wordpress.dev/appsworld/category/comments/">Comments</a></li> <li id="menu-item-1307" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1307"><a href="http://office.wordpress.dev/appsworld/category/corner-case/">Corner Case</a></li> <li id="menu-item-1308" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1308"><a href="http://office.wordpress.dev/appsworld/category/embeds/">Embeds</a></li> <li id="menu-item-1309" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1309"><a href="http://office.wordpress.dev/appsworld/category/excerpt/">Excerpt</a></li> <li id="menu-item-1310" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1310"><a href="http://office.wordpress.dev/appsworld/category/featured-images/">Featured Images</a></li> <li id="menu-item-1311" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1311"><a href="http://office.wordpress.dev/appsworld/category/formatting/">Formatting</a></li> <li id="menu-item-1312" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1312"><a href="http://office.wordpress.dev/appsworld/category/images/">Images</a></li> <li id="menu-item-1313" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1313"><a href="http://office.wordpress.dev/appsworld/category/jetpack/">Jetpack</a></li> <li id="menu-item-1314" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1314"><a href="http://office.wordpress.dev/appsworld/category/lists/">Lists</a></li> <li id="menu-item-1315" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1315"><a href="http://office.wordpress.dev/appsworld/category/markup/">Markup</a></li> <li id="menu-item-1316" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1316"><a href="http://office.wordpress.dev/appsworld/category/more-tag/">More Tag</a></li> <li id="menu-item-1317" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1317"><a href="http://office.wordpress.dev/appsworld/category/password/">Password</a></li> <li id="menu-item-1318" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1318"><a href="http://office.wordpress.dev/appsworld/category/post-formats/">Post Formats</a></li> <li id="menu-item-1319" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1319"><a href="http://office.wordpress.dev/appsworld/category/shortcodes/">Shortcodes</a></li> <li id="menu-item-1339" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1339"><a href="http://office.wordpress.dev/appsworld/category/sticky/">Sticky</a></li> <li id="menu-item-1320" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1320"><a href="http://office.wordpress.dev/appsworld/category/titles/">Titles</a></li> <li id="menu-item-1321" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1321"><a href="http://office.wordpress.dev/appsworld/category/unpublished/">Unpublished</a></li> </ul> </li> <li id="menu-item-1322" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1322"><a href="#">Depth</a> <ul class="sub-menu"> <li id="menu-item-1323" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1323"><a href="#">Level 01</a> <ul class="sub-menu"> <li id="menu-item-1324" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1324"><a href="#">Level 02</a> <ul class="sub-menu"> <li id="menu-item-1325" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1325"><a href="#">Level 03</a> <ul class="sub-menu"> <li id="menu-item-1326" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1326"><a href="#">Level 04</a> <ul class="sub-menu"> <li id="menu-item-1327" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1327"><a href="#">Level 05</a> <ul class="sub-menu"> <li id="menu-item-1328" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1328"><a href="#">Level 06</a> <ul class="sub-menu"> <li id="menu-item-1329" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1329"><a href="#">Level 07</a> <ul class="sub-menu"> <li id="menu-item-1330" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1330"><a href="#">Level 08</a> <ul class="sub-menu"> <li id="menu-item-1331" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1331"><a href="#">Level 09</a> <ul class="sub-menu"> <li id="menu-item-1332" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1332"><a href="#">Level 10</a></li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> <li id="menu-item-1333" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1333"><a href="#">Advanced</a> <ul class="sub-menu"> <li id="menu-item-1335" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1335"><a title="Custom Title Attribute" href="#">Menu Title Attribute</a></li> <li id="menu-item-1336" class="custom-menu-css-class menu-item menu-item-type-custom menu-item-object-custom menu-item-1336"><a href="#">Menu CSS Class</a></li> <li id="menu-item-1334" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1334"><a href="#">Menu Description</a></li> <li id="menu-item-1337" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1337"><a target="_blank" href="http://apple.com">New Window / Tab</a></li> </ul> </li> </ul> </div> </aside> <aside id="monster-widget-placeholder-1" class="widget widget_archive"> <h1 class="widget-title">Archives List</h1> <ul> <li><a href="http://office.wordpress.dev/appsworld/2015/06/">June 2015</a>&nbsp;(1)</li> <li><a href="http://office.wordpress.dev/appsworld/2013/03/">March 2013</a>&nbsp;(7)</li> <li><a href="http://office.wordpress.dev/appsworld/2013/01/">January 2013</a>&nbsp;(14)</li> <li><a href="http://office.wordpress.dev/appsworld/2012/12/">December 2012</a>&nbsp;(12)</li> <li><a href="http://office.wordpress.dev/appsworld/2012/11/">November 2012</a>&nbsp;(2)</li> </ul> </aside> <aside id="monster-widget-placeholder-2" class="widget widget_archive"> <h1 class="widget-title">Archives Dropdown</h1> <label class="screen-reader-text" for="archives-dropdown--1">Archives Dropdown</label> <select id="archives-dropdown--1" name="archive-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;"> <option value="">Select Month</option> <option value="http://office.wordpress.dev/appsworld/2015/06/"> June 2015 &nbsp;(1)</option> <option value="http://office.wordpress.dev/appsworld/2013/03/"> March 2013 &nbsp;(7)</option> <option value="http://office.wordpress.dev/appsworld/2013/01/"> January 2013 &nbsp;(14)</option> <option value="http://office.wordpress.dev/appsworld/2012/12/"> December 2012 &nbsp;(12)</option> <option value="http://office.wordpress.dev/appsworld/2012/11/"> November 2012 &nbsp;(2)</option> </select> </aside> <aside id="monster-widget-placeholder-3" class="widget widget_calendar"> <h1 class="widget-title">Calendar</h1> <div id="calendar_wrap"> <table id="wp-calendar"> <caption>June 2015</caption> <thead> <tr> <th scope="col" title="Monday">M</th> <th scope="col" title="Tuesday">T</th> <th scope="col" title="Wednesday">W</th> <th scope="col" title="Thursday">T</th> <th scope="col" title="Friday">F</th> <th scope="col" title="Saturday">S</th> <th scope="col" title="Sunday">S</th> </tr> </thead> <tfoot> <tr> <td colspan="3" id="prev"><a href="http://office.wordpress.dev/appsworld/2013/03/">« Mar</a></td> <td class="pad">&nbsp;</td> <td colspan="3" id="next" class="pad">&nbsp;</td> </tr> </tfoot> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td><a href="http://office.wordpress.dev/appsworld/2015/06/06/" title="Hello world!">6</a></td> <td>7</td> </tr> <tr> <td>8</td> <td>9</td> <td>10</td> <td>11</td> <td>12</td> <td>13</td> <td>14</td> </tr> <tr> <td id="today">15</td> <td>16</td> <td>17</td> <td>18</td> <td>19</td> <td>20</td> <td>21</td> </tr> <tr> <td>22</td> <td>23</td> <td>24</td> <td>25</td> <td>26</td> <td>27</td> <td>28</td> </tr> <tr> <td>29</td> <td>30</td> <td class="pad" colspan="5">&nbsp;</td> </tr> </tbody> </table> </div> </aside> <aside id="monster-widget-placeholder-4" class="widget widget_categories"> <h1 class="widget-title">Categories List</h1> <ul> <li class="cat-item cat-item-2"><a href="http://office.wordpress.dev/appsworld/category/alignment/" title="Posts in this category test image and text alignment.">Alignment</a> (3) </li> <li class="cat-item cat-item-3"><a href="http://office.wordpress.dev/appsworld/category/post-format-aside/" title="Posts in this category test the aside post format.">Aside</a> (2) </li> <li class="cat-item cat-item-4"><a href="http://office.wordpress.dev/appsworld/category/post-format-audio/" title="Posts in this category test the audio post format.">Audio</a> (2) </li> <li class="cat-item cat-item-5"><a href="http://office.wordpress.dev/appsworld/category/captions/" title="Posts in this category test image captions.">Captions</a> (2) </li> <li class="cat-item cat-item-6"><a href="http://office.wordpress.dev/appsworld/category/post-format-chat/" title="Posts in this category test the chat post format.">Chat</a> (2) </li> <li class="cat-item cat-item-7"><a href="http://office.wordpress.dev/appsworld/category/codex/" title="Posts in this category contain Codex references.">Codex</a> (3) </li> <li class="cat-item cat-item-8"><a href="http://office.wordpress.dev/appsworld/category/comments/" title="Posts in this category test comments.">Comments</a> (6) </li> <li class="cat-item cat-item-9"><a href="http://office.wordpress.dev/appsworld/category/content/" title="Posts in this category test post content.">Content</a> (11) </li> <li class="cat-item cat-item-10"><a href="http://office.wordpress.dev/appsworld/category/corner-case/" title="Posts in this category test odd corner cases, using uncovered by rare user workflows.">Corner Case</a> (4) </li> <li class="cat-item cat-item-11"><a href="http://office.wordpress.dev/appsworld/category/embeds/" title="Posts in this category test various embed codes.">Embeds</a> (2) </li> <li class="cat-item cat-item-12"><a href="http://office.wordpress.dev/appsworld/category/excerpt/" title="Posts in this category test post excerpts.">Excerpt</a> (2) </li> <li class="cat-item cat-item-13"><a href="http://office.wordpress.dev/appsworld/category/featured-images/" title="Posts in this category test featured images.">Featured Images</a> (3) </li> <li class="cat-item cat-item-14"><a href="http://office.wordpress.dev/appsworld/category/formatting/" title="Posts in this category test various formatting scenarios.">Formatting</a> (2) </li> <li class="cat-item cat-item-15"><a href="http://office.wordpress.dev/appsworld/category/post-format-gallery/" title="Posts in this category test the gallery post format.">Gallery</a> (2) </li> <li class="cat-item cat-item-16"><a href="http://office.wordpress.dev/appsworld/category/images/" title="Posts in this category test images in various ways.">Images</a> (7) </li> <li class="cat-item cat-item-17"><a href="http://office.wordpress.dev/appsworld/category/jetpack/" title="Posts in this category test Jetpack features.">Jetpack</a> (3) </li> <li class="cat-item cat-item-18"><a href="http://office.wordpress.dev/appsworld/category/post-format-link/" title="Posts in this category test the link post format.">Link</a> (3) </li> <li class="cat-item cat-item-19"><a href="http://office.wordpress.dev/appsworld/category/lists/" title="Posts in this category test various list scenarios.">Lists</a> (2) </li> <li class="cat-item cat-item-20"><a href="http://office.wordpress.dev/appsworld/category/markup/" title="Posts in this category test markup tags and styles.">Markup</a> (2) </li> <li class="cat-item cat-item-21"><a href="http://office.wordpress.dev/appsworld/category/more-tag/" title="Posts in this category test the more tag feature.">More Tag</a> (2) </li> <li class="cat-item cat-item-22"><a href="http://office.wordpress.dev/appsworld/category/parent-category/" title="This is a parent category. It will contain child categories">Parent Category</a> (1) <ul class="children"> <li class="cat-item cat-item-37"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-01/" title="This is a description for the Child Category 01.">Child Category 01</a> (1) </li> <li class="cat-item cat-item-38"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-02/" title="This is a description for the Child Category 02.">Child Category 02</a> (1) </li> <li class="cat-item cat-item-39"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-03/" title="This is a description for the Child Category 03.">Child Category 03</a> (1) <ul class="children"> <li class="cat-item cat-item-42"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-03/grandchild-category/" title="This is a description for the Grandchild Category.">Grandchild Category</a> (1) </li> </ul> </li> <li class="cat-item cat-item-40"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-04/" title="This is a description for the Child Category 04.">Child Category 04</a> (1) </li> <li class="cat-item cat-item-41"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-05/" title="This is a description for the Child Category 05.">Child Category 05</a> (1) </li> </ul> </li> <li class="cat-item cat-item-23"><a href="http://office.wordpress.dev/appsworld/category/password/" title="Posts in this category test the post password feature.">Password</a> (2) </li> <li class="cat-item cat-item-24"><a href="http://office.wordpress.dev/appsworld/category/pingbacks/" title="Posts in this category test pingbacks.">Pingbacks</a> (4) </li> <li class="cat-item cat-item-25"><a href="http://office.wordpress.dev/appsworld/category/post-formats/" title="Posts in this category test post formats.">Post Formats</a> (13) </li> <li class="cat-item cat-item-26"><a href="http://office.wordpress.dev/appsworld/category/post-format-quote/" title="Posts in this category test the quote post format.">Quote</a> (2) </li> <li class="cat-item cat-item-27"><a href="http://office.wordpress.dev/appsworld/category/shortcodes/" title="Posts in this category test various shortcodes.">Shortcodes</a> (2) </li> <li class="cat-item cat-item-28"><a href="http://office.wordpress.dev/appsworld/category/standard/" title="Posts in this category test the standard post format.">Standard</a> (2) </li> <li class="cat-item cat-item-29"><a href="http://office.wordpress.dev/appsworld/category/post-format-status/" title="Posts in this category test the status post format.">Status</a> (2) </li> <li class="cat-item cat-item-30"><a href="http://office.wordpress.dev/appsworld/category/sticky/">Sticky</a> (1) </li> <li class="cat-item cat-item-31"><a href="http://office.wordpress.dev/appsworld/category/titles/" title="Posts in this category test post title scenarios.">Titles</a> (5) </li> <li class="cat-item cat-item-32"><a href="http://office.wordpress.dev/appsworld/category/trackbacks/" title="Posts in this category test trackbacks.">Trackbacks</a> (4) </li> <li class="cat-item cat-item-33"><a href="http://office.wordpress.dev/appsworld/category/twitter/" title="Posts in this category test various Twitter features.">Twitter</a> (2) </li> <li class="cat-item cat-item-1"><a href="http://office.wordpress.dev/appsworld/category/uncategorized/">Uncategorized</a> (3) </li> <li class="cat-item cat-item-34"><a href="http://office.wordpress.dev/appsworld/category/unpublished/" title="Posts in this category test unpublished posts.">Unpublished</a> (1) </li> <li class="cat-item cat-item-35"><a href="http://office.wordpress.dev/appsworld/category/post-format-video/" title="Posts in this category test the video post format.">Video</a> (3) </li> <li class="cat-item cat-item-36"><a href="http://office.wordpress.dev/appsworld/category/videopress/" title="Posts in this category test VideoPress features.">VideoPress</a> (2) </li> </ul> </aside> <aside id="monster-widget-placeholder-5" class="widget widget_categories"> <h1 class="widget-title">Categories Dropdown</h1> <label class="screen-reader-text" for="cat">Categories Dropdown</label> <select name="cat" id="cat" class="postform"> <option value="-1">Select Category</option> <option class="level-0" value="2">Alignment&nbsp;&nbsp;(3)</option> <option class="level-0" value="3">Aside&nbsp;&nbsp;(2)</option> <option class="level-0" value="4">Audio&nbsp;&nbsp;(2)</option> <option class="level-0" value="5">Captions&nbsp;&nbsp;(2)</option> <option class="level-0" value="6">Chat&nbsp;&nbsp;(2)</option> <option class="level-0" value="7">Codex&nbsp;&nbsp;(3)</option> <option class="level-0" value="8">Comments&nbsp;&nbsp;(6)</option> <option class="level-0" value="9">Content&nbsp;&nbsp;(11)</option> <option class="level-0" value="10">Corner Case&nbsp;&nbsp;(4)</option> <option class="level-0" value="11">Embeds&nbsp;&nbsp;(2)</option> <option class="level-0" value="12">Excerpt&nbsp;&nbsp;(2)</option> <option class="level-0" value="13">Featured Images&nbsp;&nbsp;(3)</option> <option class="level-0" value="14">Formatting&nbsp;&nbsp;(2)</option> <option class="level-0" value="15">Gallery&nbsp;&nbsp;(2)</option> <option class="level-0" value="16">Images&nbsp;&nbsp;(7)</option> <option class="level-0" value="17">Jetpack&nbsp;&nbsp;(3)</option> <option class="level-0" value="18">Link&nbsp;&nbsp;(3)</option> <option class="level-0" value="19">Lists&nbsp;&nbsp;(2)</option> <option class="level-0" value="20">Markup&nbsp;&nbsp;(2)</option> <option class="level-0" value="21">More Tag&nbsp;&nbsp;(2)</option> <option class="level-0" value="22">Parent Category&nbsp;&nbsp;(1)</option> <option class="level-1" value="37">&nbsp;&nbsp;&nbsp;Child Category 01&nbsp;&nbsp;(1)</option> <option class="level-1" value="38">&nbsp;&nbsp;&nbsp;Child Category 02&nbsp;&nbsp;(1)</option> <option class="level-1" value="39">&nbsp;&nbsp;&nbsp;Child Category 03&nbsp;&nbsp;(1)</option> <option class="level-2" value="42">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Grandchild Category&nbsp;&nbsp;(1)</option> <option class="level-1" value="40">&nbsp;&nbsp;&nbsp;Child Category 04&nbsp;&nbsp;(1)</option> <option class="level-1" value="41">&nbsp;&nbsp;&nbsp;Child Category 05&nbsp;&nbsp;(1)</option> <option class="level-0" value="23">Password&nbsp;&nbsp;(2)</option> <option class="level-0" value="24">Pingbacks&nbsp;&nbsp;(4)</option> <option class="level-0" value="25">Post Formats&nbsp;&nbsp;(13)</option> <option class="level-0" value="26">Quote&nbsp;&nbsp;(2)</option> <option class="level-0" value="27">Shortcodes&nbsp;&nbsp;(2)</option> <option class="level-0" value="28">Standard&nbsp;&nbsp;(2)</option> <option class="level-0" value="29">Status&nbsp;&nbsp;(2)</option> <option class="level-0" value="30">Sticky&nbsp;&nbsp;(1)</option> <option class="level-0" value="31">Titles&nbsp;&nbsp;(5)</option> <option class="level-0" value="32">Trackbacks&nbsp;&nbsp;(4)</option> <option class="level-0" value="33">Twitter&nbsp;&nbsp;(2)</option> <option class="level-0" value="1">Uncategorized&nbsp;&nbsp;(3)</option> <option class="level-0" value="34">Unpublished&nbsp;&nbsp;(1)</option> <option class="level-0" value="35">Video&nbsp;&nbsp;(3)</option> <option class="level-0" value="36">VideoPress&nbsp;&nbsp;(2)</option> </select> </aside> <aside id="monster-widget-placeholder-6" class="widget widget_pages"> <h1 class="widget-title">Pages</h1> <ul> <li class="page_item page-item-1086"><a href="http://office.wordpress.dev/appsworld/about/">About</a></li> <li class="page_item page-item-1062"><a href="http://office.wordpress.dev/appsworld/amazon-store/">Amazon Store</a></li> <li class="page_item page-item-1066 current_page_parent"><a href="http://office.wordpress.dev/appsworld/blog/">Blog</a></li> <li class="page_item page-item-7"><a href="http://office.wordpress.dev/appsworld/home/">Home</a></li> <li class="page_item page-item-1064"><a href="http://office.wordpress.dev/appsworld/home-2/">Home</a></li> <li class="page_item page-item-1077"><a href="http://office.wordpress.dev/appsworld/page-comments/">Page Comments</a></li> <li class="page_item page-item-1075"><a href="http://office.wordpress.dev/appsworld/page-comments-disabled/">Page Comments Disabled</a></li> <li class="page_item page-item-1080"><a href="http://office.wordpress.dev/appsworld/page-image-alignment/">Page Image Alignment</a></li> <li class="page_item page-item-1083"><a href="http://office.wordpress.dev/appsworld/page-markup-and-formatting/">Page Markup And Formatting</a></li> <li class="page_item page-item-1088 page_item_has_children"><a href="http://office.wordpress.dev/appsworld/parent-page/">Parent Page</a> <ul class="children"> <li class="page_item page-item-1090"><a href="http://office.wordpress.dev/appsworld/parent-page/child-page-01/">Child Page 01</a></li> <li class="page_item page-item-1092"><a href="http://office.wordpress.dev/appsworld/parent-page/child-page-02/">Child Page 02</a></li> <li class="page_item page-item-1094 page_item_has_children"><a href="http://office.wordpress.dev/appsworld/parent-page/child-page-03/">Child Page 03</a> <ul class="children"> <li class="page_item page-item-1102"><a href="http://office.wordpress.dev/appsworld/parent-page/child-page-03/grandchild-page/">Grandchild Page</a></li> </ul> </li> <li class="page_item page-item-1096"><a href="http://office.wordpress.dev/appsworld/parent-page/child-page-04/">Child Page 04</a></li> <li class="page_item page-item-1098"><a href="http://office.wordpress.dev/appsworld/parent-page/child-page-05/">Child Page 05</a></li> </ul> </li> <li class="page_item page-item-2"><a href="http://office.wordpress.dev/appsworld/sample-page/">Sample Page</a></li> </ul> </aside> <aside id="monster-widget-placeholder-7" class="widget widget_meta"> <h1 class="widget-title">Meta</h1> <ul> <li><a href="http://office.wordpress.dev/appsworld/wp-admin/">Site Admin</a></li> <li><a href="http://office.wordpress.dev/appsworld/wp-login.php?action=logout&amp;_wpnonce=cffdbe35ea">Log out</a></li> <li><a href="http://office.wordpress.dev/appsworld/feed/">Entries <abbr title="Really Simple Syndication">RSS</abbr></a></li> <li><a href="http://office.wordpress.dev/appsworld/comments/feed/">Comments <abbr title="Really Simple Syndication">RSS</abbr></a></li> <li><a href="https://wordpress.org/" title="Powered by WordPress, state-of-the-art semantic personal publishing platform.">WordPress.org</a></li> </ul> </aside> <aside id="monster-widget-placeholder-8" class="widget widget_recent_comments"> <h1 class="widget-title">Recent Comments</h1> <ul id="recentcomments"> <li class="recentcomments"><span class="comment-author-link"><a href="https://wordpress.org/" rel="external nofollow" class="url">Mr WordPress</a></span> on <a href="http://office.wordpress.dev/appsworld/2015/06/06/hello-world/#comment-1">Hello world!</a></li> <li class="recentcomments"><span class="comment-author-link"><a href="http://chrisam.es/" rel="external nofollow" class="url">Chris Ames</a></span> on <a href="http://office.wordpress.dev/appsworld/page-comments/#comment-2">Page Comments</a></li> <li class="recentcomments"><span class="comment-author-link"><a href="http://jarederickson.com/" rel="external nofollow" class="url">Jared Erickson</a></span> on <a href="http://office.wordpress.dev/appsworld/2013/01/05/non-breaking-text/#comment-31">Super/Duper/Long/NonBreaking/Path/Name/To/A/File/That/Is/Way/Deep/Down/In/Some/Mysterious/Remote/Desolate/Part/Of/The/Operating/System/To/A/File/That/Just/So/Happens/To/Be/Strangely/Named/Supercalifragilisticexpialidocious.txt</a></li> <li class="recentcomments"><span class="comment-author-link"><a href="http://chrisam.es" rel="external nofollow" class="url">Chris Ames</a></span> on <a href="http://office.wordpress.dev/appsworld/2013/01/06/no-content/#comment-30">No Content</a></li> <li class="recentcomments"><span class="comment-author-link"><a href="http://tommcfarlin.com/" rel="external nofollow" class="url">Tom McFarlin</a></span> on <a href="http://office.wordpress.dev/appsworld/2013/01/04/password-protected/#comment-29">Protected: Password Protected (the password is “enter”)</a></li> <li class="recentcomments"><span class="comment-author-link"><a href="http://manovotny.com/" rel="external nofollow" class="url">Michael Novotny</a></span> on <a href="http://office.wordpress.dev/appsworld/2013/01/03/comments/#comment-23">Comments</a></li> <li class="recentcomments"><span class="comment-author-link"><a href="http://8bit.io/" rel="external nofollow" class="url">8BIT</a></span> on <a href="http://office.wordpress.dev/appsworld/2013/01/03/comments/#comment-22">Comments</a></li> </ul> </aside> <aside id="monster-widget-placeholder-9" class="widget widget_recent_entries"> <h1 class="widget-title">Recent Posts</h1> <ul> <li><a href="http://office.wordpress.dev/appsworld/2015/06/06/hello-world/">Hello world!</a></li> </ul> </aside> <aside id="monster-widget-placeholder-10" class="widget widget_rss"> <h1 class="widget-title"><a class="rsswidget" href="http://themeshaper.com/feed"> <img style="border:0" width="14" height="14" src="http://office.wordpress.dev/appsworld/wp-includes/images/rss.png" alt="RSS"></a> <a class="rsswidget" href="http://themeshaper.com/">RSS</a> </h1> <ul> <li> <a class="rsswidget" href="http://themeshaper.com/2015/06/01/cyanotype-satellite/">Cyanotype and Satellite Available on WordPress.org</a> <span class="rss-date">June 1, 2015</span> <div class="rssSummary"> Cyanotype and Satellite, two fresh new themes geared to personal bloggers, are now available for download at WordPress.org. Designed by … Continue reading → </div> <cite>Kathryn P.</cite> </li> <li> <a class="rsswidget" href="http://themeshaper.com/2015/05/07/theming-with-the-rest-api-meet-picard/">Theming with the REST API – Meet Picard</a> <span class="rss-date">May 7, 2015</span> <div class="rssSummary"> If there’s one thing that has been making waves in the WordPress ecosystem this year, it is the new REST … Continue reading → </div> <cite>Jack Lenox</cite> </li> <li> <a class="rsswidget" href="http://themeshaper.com/2015/04/28/scrawl/">Take Scrawl For a Spin</a> <span class="rss-date">April 28, 2015</span> <div class="rssSummary"> Scrawl, a new monochromatic theme designed by Automattic’s Caroline Moore, is available at&nbsp;WordPress.org for self-hosted sites. Featured images get bold … Continue reading → </div> <cite>Kathryn P.</cite> </li> <li> <a class="rsswidget" href="http://themeshaper.com/2015/03/31/hew/">Introducing Hew</a> <span class="rss-date">March 31, 2015</span> <div class="rssSummary"> Hew, a new theme crafted by Automattic’s Ola Laczek, is now available for self-hosted WordPress users. “Ryu was my initial … Continue reading → </div> <cite>Kathryn P.</cite> </li> <li> <a class="rsswidget" href="http://themeshaper.com/2015/03/20/sobe/">South Beach Inspires Sobe Theme</a> <span class="rss-date">March 20, 2015</span> <div class="rssSummary"> Sobe, a new personal-blogging theme created by Caroline Moore, is now available in the WordPress.org theme directory. “Sobe was inspired … Continue reading → </div> <cite>Kathryn P.</cite> </li> <li> <a class="rsswidget" href="http://themeshaper.com/2015/03/12/keyboard-accessibility/">Building a Strong Foundation with Keyboard Accessibility</a> <span class="rss-date">March 12, 2015</span> <div class="rssSummary"> When you build a house, you start with the foundation. It becomes the base upon which you form everything else … Continue reading → </div> <cite>David A. Kennedy</cite> </li> <li> <a class="rsswidget" href="http://themeshaper.com/2015/03/09/photobloggers-boardwalk-cubic/">Photobloggers Take Note: Boardwalk and Cubic are Here</a> <span class="rss-date">March 9, 2015</span> <div class="rssSummary"> Two fresh photoblogging themes crafted by Automattic’s Thomas Guillot are now available to download in the WordPress.org theme directory. Boardwalk … Continue reading → </div> <cite>Kathryn P.</cite> </li> <li> <a class="rsswidget" href="http://themeshaper.com/2015/02/27/theme-design-for-devs/">What Developers Need to Know About Theme Design</a> <span class="rss-date">February 27, 2015</span> <div class="rssSummary"> Making a theme is really exciting. It’s a great way to practice your coding skills. It could be a good … Continue reading → </div> <cite>Mel Choyce</cite> </li> <li> <a class="rsswidget" href="http://themeshaper.com/2015/02/18/sela/">Sela Puts a Vibrant Spin on the Business Theme</a> <span class="rss-date">February 18, 2015</span> <div class="rssSummary"> Designed by Automattic’s Ola Laczek, Sela puts a vibrant spin on the business theme and is now available for download … Continue reading → </div> <cite>Kathryn P.</cite> </li> <li><a class="rsswidget" href="http://themeshaper.com/2015/01/29/up-your-theming-game-by-reviewing-themes/">Up Your Theming Game by Reviewing Themes</a> <span class="rss-date">January 29, 2015</span> <div class="rssSummary">You have strong theme sense, you’ve started working on or released a theme into the world, and you want to … Continue reading → </div> <cite>David A. Kennedy</cite> </li> </ul> </aside> <aside id="monster-widget-placeholder-11" class="widget widget_search"> <h1 class="widget-title">Search</h1> <form role="search" method="get" class="search-form" action="http://office.wordpress.dev/appsworld/"> <label> <span class="screen-reader-text">Search for:</span> <input type="search" class="search-field" placeholder="Search …" value="" name="s" title="Search for:"> </label> <input type="submit" class="search-submit" value="Search"> </form> </aside> <aside id="monster-widget-placeholder-12" class="widget widget_text"> <h1 class="widget-title">Text</h1> <div class="textwidget"> <p><strong>Large image: Hand Coded</strong><br> <img src="http://office.wordpress.dev/appsworld/wp-content/plugins/monster-widget/images/bikes.jpg" alt=""><br> <strong>Large image: linked in a caption</strong> </p> <div class="wp-caption alignnone"> <a href="#"><img src="http://office.wordpress.dev/appsworld/wp-content/plugins/monster-widget/images/bikes.jpg" class="size-large" height="720" width="960" alt=""></a> <p class="wp-caption-text">This image is 960 by 720 pixels. <img src="http://office.wordpress.dev/appsworld/wp-includes/images/smilies/simple-smile.png" alt=":)" class="wp-smiley" style="height: 1em; max-height: 1em;"></p> </div> <p><strong>Meat!</strong><br> Hamburger fatback andouille, ball tip bacon t-bone turkey tenderloin. Ball tip shank pig, t-bone turducken prosciutto ground round rump bacon pork chop short loin turkey. Pancetta ball tip salami, hamburger t-bone capicola turkey ham hock pork belly tri-tip. Biltong bresaola tail, shoulder sausage turkey cow pork chop fatback. Turkey pork pig bacon short loin meatloaf, chicken ham hock flank andouille tenderloin shank rump filet mignon. Shoulder frankfurter shankle pancetta. Jowl andouille short ribs swine venison, pork loin pork chop meatball jerky filet mignon shoulder tenderloin chicken pork.<br> <strong>Smile!</strong><br> <img class="emoji" draggable="false" alt="😉" src="http://s.w.org/images/core/emoji/72x72/1f609.png"> <img src="http://office.wordpress.dev/appsworld/wp-includes/images/smilies/simple-smile.png" alt=":)" class="wp-smiley" style="height: 1em; max-height: 1em;"> <img class="emoji" draggable="false" alt="😀" src="http://s.w.org/images/core/emoji/72x72/1f600.png"><br> <strong>Select Element with long value</strong> </p> <form method="get" action="/"> <select name="monster-widget-just-testing"><option value="0">First</option><option value="1">Second</option><option value="2">Third OMG! How can one option contain soooo many words? This really is a lot of words.</option></select><br> </form> </div> </aside> <aside id="monster-widget-placeholder-13" class="widget widget_tag_cloud"> <h1 class="widget-title">Tag Cloud</h1> <div class="tagcloud"> <a href="http://office.wordpress.dev/appsworld/tag/8bit/" class="tag-link-43" title="1 topic" style="font-size: 8pt;">8BIT</a> <a href="http://office.wordpress.dev/appsworld/tag/articles/" class="tag-link-44" title="1 topic" style="font-size: 8pt;">Articles</a> <a href="http://office.wordpress.dev/appsworld/tag/dowork/" class="tag-link-45" title="1 topic" style="font-size: 8pt;">dowork</a> <a href="http://office.wordpress.dev/appsworld/tag/fail/" class="tag-link-46" title="1 topic" style="font-size: 8pt;">Fail</a> <a href="http://office.wordpress.dev/appsworld/tag/ftw/" class="tag-link-47" title="1 topic" style="font-size: 8pt;">FTW</a> <a href="http://office.wordpress.dev/appsworld/tag/fun/" class="tag-link-48" title="1 topic" style="font-size: 8pt;">Fun</a> <a href="http://office.wordpress.dev/appsworld/tag/love/" class="tag-link-49" title="1 topic" style="font-size: 8pt;">Love</a> <a href="http://office.wordpress.dev/appsworld/tag/mothership/" class="tag-link-50" title="1 topic" style="font-size: 8pt;">Mothership</a> <a href="http://office.wordpress.dev/appsworld/tag/mustread/" class="tag-link-51" title="1 topic" style="font-size: 8pt;">Must Read</a> <a href="http://office.wordpress.dev/appsworld/tag/nailedit/" class="tag-link-52" title="1 topic" style="font-size: 8pt;">Nailed It</a> <a href="http://office.wordpress.dev/appsworld/tag/pictures/" class="tag-link-53" title="1 topic" style="font-size: 8pt;">Pictures</a> <a href="http://office.wordpress.dev/appsworld/tag/success/" class="tag-link-54" title="1 topic" style="font-size: 8pt;">Success</a> <a href="http://office.wordpress.dev/appsworld/tag/swagger/" class="tag-link-55" title="1 topic" style="font-size: 8pt;">Swagger</a> <a href="http://office.wordpress.dev/appsworld/tag/tags/" class="tag-link-56" title="1 topic" style="font-size: 8pt;">Tags</a> <a href="http://office.wordpress.dev/appsworld/tag/unseen/" class="tag-link-57" title="1 topic" style="font-size: 8pt;">Unseen</a> <a href="http://office.wordpress.dev/appsworld/tag/wordpress/" class="tag-link-58" title="1 topic" style="font-size: 8pt;">WordPress</a> </div> </aside> <aside id="monster-widget-placeholder-14" class="widget widget_nav_menu"> <h1 class="widget-title">Nav Menu</h1> <div class="menu-long-menu-container"> <ul id="menu-long-menu" class="menu"> <li id="menu-item-1072" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1072"><a href="http://wptest.io/demo/">Home</a></li> <li id="menu-item-1340" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1340"><a href="http://office.wordpress.dev/appsworld/about/">About</a></li> <li id="menu-item-1341" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1341"><a href="http://office.wordpress.dev/appsworld/amazon-store/">Amazon Store</a></li> <li id="menu-item-1342" class="menu-item menu-item-type-post_type menu-item-object-page current_page_parent menu-item-1342"><a href="http://office.wordpress.dev/appsworld/blog/">Blog</a></li> <li id="menu-item-1343" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1343"><a href="http://office.wordpress.dev/appsworld/home-2/">Home</a></li> <li id="menu-item-1344" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1344"><a href="http://office.wordpress.dev/appsworld/page-comments/">Page Comments</a></li> <li id="menu-item-1345" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1345"><a href="http://office.wordpress.dev/appsworld/page-comments-disabled/">Page Comments Disabled</a></li> <li id="menu-item-1346" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1346"><a href="http://office.wordpress.dev/appsworld/page-image-alignment/">Page Image Alignment</a></li> <li id="menu-item-1347" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1347"><a href="http://office.wordpress.dev/appsworld/page-markup-and-formatting/">Page Markup And Formatting</a></li> <li id="menu-item-1348" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1348"><a href="http://office.wordpress.dev/appsworld/parent-page/">Parent Page</a></li> <li id="menu-item-1349" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1349"><a href="http://office.wordpress.dev/appsworld/parent-page/child-page-01/">Child Page 01</a></li> <li id="menu-item-1350" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1350"><a href="http://office.wordpress.dev/appsworld/parent-page/child-page-02/">Child Page 02</a></li> <li id="menu-item-1351" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1351"><a href="http://office.wordpress.dev/appsworld/parent-page/child-page-03/">Child Page 03</a></li> <li id="menu-item-1352" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1352"><a href="http://office.wordpress.dev/appsworld/parent-page/child-page-03/grandchild-page/">Grandchild Page</a></li> <li id="menu-item-1353" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1353"><a href="http://office.wordpress.dev/appsworld/parent-page/child-page-04/">Child Page 04</a></li> <li id="menu-item-1354" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1354"><a href="http://office.wordpress.dev/appsworld/parent-page/child-page-05/">Child Page 05</a></li> <li id="menu-item-1262" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1262"><a href="http://office.wordpress.dev/appsworld/category/alignment/">Alignment</a></li> <li id="menu-item-1263" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1263"><a href="http://office.wordpress.dev/appsworld/category/post-format-aside/">Aside</a></li> <li id="menu-item-1264" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1264"><a href="http://office.wordpress.dev/appsworld/category/post-format-audio/">Audio</a></li> <li id="menu-item-1265" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1265"><a href="http://office.wordpress.dev/appsworld/category/captions/">Captions</a></li> <li id="menu-item-1266" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1266"><a href="http://office.wordpress.dev/appsworld/category/post-format-chat/">Chat</a></li> <li id="menu-item-1267" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1267"><a href="http://office.wordpress.dev/appsworld/category/codex/">Codex</a></li> <li id="menu-item-1268" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1268"><a href="http://office.wordpress.dev/appsworld/category/comments/">Comments</a></li> <li id="menu-item-1269" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1269"><a href="http://office.wordpress.dev/appsworld/category/content/">Content</a></li> <li id="menu-item-1270" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1270"><a href="http://office.wordpress.dev/appsworld/category/corner-case/">Corner Case</a></li> <li id="menu-item-1271" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1271"><a href="http://office.wordpress.dev/appsworld/category/embeds/">Embeds</a></li> <li id="menu-item-1272" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1272"><a href="http://office.wordpress.dev/appsworld/category/excerpt/">Excerpt</a></li> <li id="menu-item-1273" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1273"><a href="http://office.wordpress.dev/appsworld/category/featured-images/">Featured Images</a></li> <li id="menu-item-1274" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1274"><a href="http://office.wordpress.dev/appsworld/category/formatting/">Formatting</a></li> <li id="menu-item-1275" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1275"><a href="http://office.wordpress.dev/appsworld/category/post-format-gallery/">Gallery</a></li> <li id="menu-item-1276" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1276"><a href="http://office.wordpress.dev/appsworld/category/images/">Images</a></li> <li id="menu-item-1277" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1277"><a href="http://office.wordpress.dev/appsworld/category/jetpack/">Jetpack</a></li> <li id="menu-item-1278" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1278"><a href="http://office.wordpress.dev/appsworld/category/post-format-link/">Link</a></li> <li id="menu-item-1279" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1279"><a href="http://office.wordpress.dev/appsworld/category/lists/">Lists</a></li> <li id="menu-item-1280" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1280"><a href="http://office.wordpress.dev/appsworld/category/markup/">Markup</a></li> <li id="menu-item-1281" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1281"><a href="http://office.wordpress.dev/appsworld/category/more-tag/">More Tag</a></li> <li id="menu-item-1282" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1282"><a href="http://office.wordpress.dev/appsworld/category/parent-category/">Parent Category</a></li> <li id="menu-item-1283" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1283"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-01/">Child Category 01</a></li> <li id="menu-item-1284" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1284"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-02/">Child Category 02</a></li> <li id="menu-item-1285" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1285"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-03/">Child Category 03</a></li> <li id="menu-item-1286" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1286"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-03/grandchild-category/">Grandchild Category</a></li> <li id="menu-item-1287" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1287"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-04/">Child Category 04</a></li> <li id="menu-item-1288" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1288"><a href="http://office.wordpress.dev/appsworld/category/parent-category/child-category-05/">Child Category 05</a></li> <li id="menu-item-1289" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1289"><a href="http://office.wordpress.dev/appsworld/category/password/">Password</a></li> <li id="menu-item-1290" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1290"><a href="http://office.wordpress.dev/appsworld/category/pingbacks/">Pingbacks</a></li> <li id="menu-item-1291" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1291"><a href="http://office.wordpress.dev/appsworld/category/post-formats/">Post Formats</a></li> <li id="menu-item-1292" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1292"><a href="http://office.wordpress.dev/appsworld/category/post-format-quote/">Quote</a></li> <li id="menu-item-1293" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1293"><a href="http://office.wordpress.dev/appsworld/category/shortcodes/">Shortcodes</a></li> <li id="menu-item-1294" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1294"><a href="http://office.wordpress.dev/appsworld/category/standard/">Standard</a></li> <li id="menu-item-1295" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1295"><a href="http://office.wordpress.dev/appsworld/category/post-format-status/">Status</a></li> <li id="menu-item-1296" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1296"><a href="http://office.wordpress.dev/appsworld/category/titles/">Titles</a></li> <li id="menu-item-1297" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1297"><a href="http://office.wordpress.dev/appsworld/category/trackbacks/">Trackbacks</a></li> <li id="menu-item-1298" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1298"><a href="http://office.wordpress.dev/appsworld/category/twitter/">Twitter</a></li> <li id="menu-item-1299" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1299"><a href="http://office.wordpress.dev/appsworld/category/uncategorized/">Uncategorized</a></li> <li id="menu-item-1300" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1300"><a href="http://office.wordpress.dev/appsworld/category/unpublished/">Unpublished</a></li> <li id="menu-item-1301" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1301"><a href="http://office.wordpress.dev/appsworld/category/post-format-video/">Video</a></li> <li id="menu-item-1302" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1302"><a href="http://office.wordpress.dev/appsworld/category/videopress/">VideoPress</a></li> <li id="menu-item-1338" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1338"><a href="http://office.wordpress.dev/appsworld/category/sticky/">Sticky</a></li> </ul> </div> </aside> <aside id="meta-3" class="widget widget_meta"> <h1 class="widget-title">Meta</h1> <ul> <li><a href="http://office.wordpress.dev/appsworld/wp-admin/">Site Admin</a></li> <li><a href="http://office.wordpress.dev/appsworld/wp-login.php?action=logout&amp;_wpnonce=cffdbe35ea">Log out</a></li> <li><a href="http://office.wordpress.dev/appsworld/feed/">Entries <abbr title="Really Simple Syndication">RSS</abbr></a></li> <li><a href="http://office.wordpress.dev/appsworld/comments/feed/">Comments <abbr title="Really Simple Syndication">RSS</abbr></a></li> <li><a href="https://wordpress.org/" title="Powered by WordPress, state-of-the-art semantic personal publishing platform.">WordPress.org</a></li> </ul> </aside> </div> </div><!-- /.col-md-4 --> </div><!-- /.row --> </div><!-- /.container --> </div><!-- /#blog-container --> <!-- Footer ==============================--> <section id="footer" class="footer-section"> <div class="container"> <p class="copyright-info text-center">Copyright &copy; 2015 <a href="#">AppsWorld</a> All Rights Reserves.</p><!-- /.copyright-info --> </div><!-- /.container --> </section><!-- /#footer --> <!-- Project Scripts =====================================--> <script src="dependencies/jquery/dist/jquery.js"></script> <script src="dependencies/bootstrap/dist/js/bootstrap.js"></script> <script src="dependencies/swiper/dist/js/swiper.js"></script> <script src="dependencies/formstone/dist/js/core.js"></script> <script src="dependencies/formstone/dist/js/transition.js"></script> <script src="dependencies/formstone/dist/js/lightbox.js"></script> <script src="http://maps.google.com/maps/api/js?sensor=false&amp;language=en"></script> <script src="dependencies/gmap3/dist/gmap3.min.js"></script> <script src="dependencies/wow.js/dist/wow.js"></script> <script src="assets/javascripts/app.js"></script> <script> $('#google-maps').gmap3({ map:{ options:{ center: [23.739283, 90.389137], zoom: 15 } }, marker:{ latLng:[23.739283, 90.389137], options: { icon: new google.maps.MarkerImage( "assets/images/map-marker.png", new google.maps.Size(48, 60, "px", "px") ) } } }); // scrollReveal Init if (screen.width > 966) { $( document ).ready(function() { new WOW().init(); }); } </script> </body> </html>
Nousware/nous-ware.com
AppsWorld/Package-HTML/blog-single.html
HTML
apache-2.0
83,493
package com.gps.sweeprobot.http; /** * @Author : zhoukan * @CreateDate : 2017/7/21 0021 * @Descriptiong : 存放App的静态常量 */ public class Constant { /* 焦建 */ public static String JiaoJian = "ws://192.168.2.136"; /* 域名 */ public static String DOMAIN = "http://192.168.2.136:82"; /* 获取预览地图 */ public static final String GET_MAP = "/maps/map_test.jpg"; }
ZhouKanZ/SweepRobot
app/src/main/java/com/gps/sweeprobot/http/Constant.java
Java
apache-2.0
415
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using ServiceStack.Logging; using ServiceStack.Text; using ServiceStack.Web; namespace ServiceStack.Script { public interface IPageResult {} // Render a Template Page to the Response OutputStream public class PageResult : IPageResult, IStreamWriterAsync, IHasOptions, IDisposable { /// <summary> /// The Page to Render /// </summary> public SharpPage Page { get; } /// <summary> /// The Code Page to Render /// </summary> public SharpCodePage CodePage { get; } /// <summary> /// Use specified Layout /// </summary> public SharpPage LayoutPage { get; set; } /// <summary> /// Use Layout with specified name /// </summary> public string Layout { get; set; } /// <summary> /// Render without any Layout /// </summary> public bool NoLayout { get; set; } /// <summary> /// Extract Model Properties into Scope Args /// </summary> public object Model { get; set; } /// <summary> /// Add additional Args available to all pages /// </summary> public Dictionary<string, object> Args { get; set; } /// <summary> /// Add additional script methods available to all pages /// </summary> public List<ScriptMethods> ScriptMethods { get; set; } [Obsolete("Use ScriptMethods")] public List<ScriptMethods> TemplateFilters => ScriptMethods; /// <summary> /// Add additional script blocks available to all pages /// </summary> public List<ScriptBlock> ScriptBlocks { get; set; } [Obsolete("Use ScriptBlocks")] public List<ScriptBlock> TemplateBlocks => ScriptBlocks; /// <summary> /// Add additional partials available to all pages /// </summary> public Dictionary<string, SharpPage> Partials { get; set; } /// <summary> /// Return additional HTTP Headers in HTTP Requests /// </summary> public IDictionary<string, string> Options { get; set; } /// <summary> /// Specify the Content-Type of the Response /// </summary> public string ContentType { get => Options.TryGetValue(HttpHeaders.ContentType, out string contentType) ? contentType : null; set => Options[HttpHeaders.ContentType] = value; } /// <summary> /// Transform the Page output using a chain of stream transformers /// </summary> public List<Func<Stream, Task<Stream>>> PageTransformers { get; set; } /// <summary> /// Transform the entire output using a chain of stream transformers /// </summary> public List<Func<Stream, Task<Stream>>> OutputTransformers { get; set; } /// <summary> /// Available transformers that can transform context filter stream outputs /// </summary> public Dictionary<string, Func<Stream, Task<Stream>>> FilterTransformers { get; set; } /// <summary> /// Don't allow access to specified filters /// </summary> public HashSet<string> ExcludeFiltersNamed { get; } = new HashSet<string>(); /// <summary> /// The last error thrown by a filter /// </summary> public Exception LastFilterError { get; set; } /// <summary> /// The StackTrace where the Last Error Occured /// </summary> public string[] LastFilterStackTrace { get; set; } /// <summary> /// What argument errors should be binded to /// </summary> public string AssignExceptionsTo { get; set; } /// <summary> /// Whether to skip execution of all page filters and just write page string fragments /// </summary> public bool SkipFilterExecution { get; set; } /// <summary> /// Overrides Context to specify whether to Ignore or Continue executing filters on error /// </summary> public bool? SkipExecutingFiltersIfError { get; set; } /// <summary> /// Whether to always rethrow Exceptions /// </summary> public bool RethrowExceptions { get; set; } /// <summary> /// Immediately halt execution of the page /// </summary> public bool HaltExecution { get; set; } /// <summary> /// Whether to disable buffering output and render directly to OutputStream /// </summary> public bool DisableBuffering { get; set; } /// <summary> /// The Return value of the page (if any) /// </summary> public ReturnValue ReturnValue { get; set; } /// <summary> /// The Current StackDepth /// </summary> public int StackDepth { get; internal set; } /// <summary> /// Can be used to track number of Evaluations /// </summary> public long Evaluations { get; private set; } public void AssertNextEvaluation() { if (Evaluations++ >= Context.MaxEvaluations) throw new NotSupportedException($"Exceeded Max Evaluations of {Context.MaxEvaluations}. \nMaxEvaluations can be changed in `ScriptContext.MaxEvaluations`."); } public void ResetIterations() => Evaluations = 0; private readonly Stack<string> stackTrace = new Stack<string>(); private PageResult(PageFormat format) { Args = new Dictionary<string, object>(); ScriptMethods = new List<ScriptMethods>(); ScriptBlocks = new List<ScriptBlock>(); Partials = new Dictionary<string, SharpPage>(); PageTransformers = new List<Func<Stream, Task<Stream>>>(); OutputTransformers = new List<Func<Stream, Task<Stream>>>(); FilterTransformers = new Dictionary<string, Func<Stream, Task<Stream>>>(); Options = new Dictionary<string, string> { {HttpHeaders.ContentType, format?.ContentType}, }; } public PageResult(SharpPage page) : this(page?.Format) { Page = page ?? throw new ArgumentNullException(nameof(page)); } public PageResult(SharpCodePage page) : this(page?.Format) { CodePage = page ?? throw new ArgumentNullException(nameof(page)); var hasRequest = (CodePage as IRequiresRequest)?.Request; if (hasRequest != null) Args[ScriptConstants.Request] = hasRequest; } //entry point public async Task WriteToAsync(Stream responseStream, CancellationToken token = default) { if (OutputTransformers.Count == 0) { var bufferOutput = !DisableBuffering && !(responseStream is MemoryStream); if (bufferOutput) { using (var ms = MemoryStreamFactory.GetStream()) { await WriteToAsyncInternal(ms, token); ms.Position = 0; await ms.WriteToAsync(responseStream, token); } } else { await WriteToAsyncInternal(responseStream, token); } return; } //If PageResult has any OutputFilters Buffer and chain stream responses to each using (var ms = MemoryStreamFactory.GetStream()) { stackTrace.Push("OutputTransformer"); await WriteToAsyncInternal(ms, token); Stream stream = ms; foreach (var transformer in OutputTransformers) { stream.Position = 0; stream = await transformer(stream); } using (stream) { stream.Position = 0; await stream.WriteToAsync(responseStream, token); } stackTrace.Pop(); } } internal async Task WriteToAsyncInternal(Stream outputStream, CancellationToken token) { await Init(); if (!NoLayout) { if (LayoutPage != null) { await LayoutPage.Init(); if (CodePage != null) InitIfNewPage(CodePage); if (Page != null) await InitIfNewPage(Page); } else { if (Page != null) { await InitIfNewPage(Page); if (Page.LayoutPage != null) { LayoutPage = Page.LayoutPage; await LayoutPage.Init(); } } else if (CodePage != null) { InitIfNewPage(CodePage); if (CodePage.LayoutPage != null) { LayoutPage = CodePage.LayoutPage; await LayoutPage.Init(); } } } } else { if (Page != null) { await InitIfNewPage(Page); } else if (CodePage != null) { InitIfNewPage(CodePage); } } token.ThrowIfCancellationRequested(); var pageScope = CreatePageContext(null, outputStream); if (!NoLayout && LayoutPage != null) { // sync impl with WriteFragmentsAsync stackTrace.Push("Layout: " + LayoutPage.VirtualPath); foreach (var fragment in LayoutPage.PageFragments) { if (HaltExecution) break; await WritePageFragmentAsync(pageScope, fragment, token); } stackTrace.Pop(); } else { await WritePageAsync(Page, CodePage, pageScope, token); } } internal async Task WriteFragmentsAsync(ScriptScopeContext scope, IEnumerable<PageFragment> fragments, string callTrace, CancellationToken token) { stackTrace.Push(callTrace); foreach (var fragment in fragments) { if (HaltExecution) return; await WritePageFragmentAsync(scope, fragment, token); } stackTrace.Pop(); } public async Task WritePageFragmentAsync(ScriptScopeContext scope, PageFragment fragment, CancellationToken token) { foreach (var scriptLanguage in Context.ScriptLanguagesArray) { if (ShouldSkipFilterExecution(fragment)) return; if (await scriptLanguage.WritePageFragmentAsync(scope, fragment, token)) break; } } public Task WriteStatementsAsync(ScriptScopeContext scope, IEnumerable<JsStatement> blockStatements, string callTrace, CancellationToken token) { try { stackTrace.Push(callTrace); return WriteStatementsAsync(scope, blockStatements, token); } finally { stackTrace.Pop(); } } public async Task WriteStatementsAsync(ScriptScopeContext scope, IEnumerable<JsStatement> blockStatements, CancellationToken token) { foreach (var statement in blockStatements) { foreach (var scriptLanguage in Context.ScriptLanguagesArray) { if (HaltExecution || ShouldSkipFilterExecution(statement)) return; if (await scriptLanguage.WriteStatementAsync(scope, statement, token)) break; } } } public bool ShouldSkipFilterExecution(PageVariableFragment var) { return HaltExecution || SkipFilterExecution && (var.Binding != null ? !Context.OnlyEvaluateFiltersWhenSkippingPageFilterExecution.Contains(var.Binding) : var.InitialExpression?.Name == null || !Context.OnlyEvaluateFiltersWhenSkippingPageFilterExecution.Contains(var.InitialExpression.Name)); } public bool ShouldSkipFilterExecution(PageFragment fragment) => !(fragment is PageStringFragment) && (fragment is PageVariableFragment var ? ShouldSkipFilterExecution(var) : HaltExecution || SkipFilterExecution); public bool ShouldSkipFilterExecution(JsStatement statement) => HaltExecution || SkipFilterExecution; public ScriptContext Context => Page?.Context ?? CodePage.Context; public PageFormat Format => Page?.Format ?? CodePage.Format; public string VirtualPath => Page?.VirtualPath ?? CodePage.VirtualPath; private bool hasInit; public async Task<PageResult> Init() { if (hasInit) return this; if (!Context.HasInit) throw new NotSupportedException($"{Context.GetType().Name} has not been initialized. Call 'Init()' to initialize Script Context."); if (Model != null) { var explodeModel = Model.ToObjectDictionary(); foreach (var entry in explodeModel) { Args[entry.Key] = entry.Value ?? JsNull.Value; } } Args[ScriptConstants.Model] = Model ?? JsNull.Value; foreach (var scriptLanguage in Context.ScriptLanguages) { if (scriptLanguage is IConfigurePageResult configurePageResult) { configurePageResult.Configure(this); } } foreach (var filter in ScriptMethods) { Context.InitMethod(filter); } foreach (var block in ScriptBlocks) { Context.InitBlock(block); blocksMap[block.Name] = block; } if (Page != null) { await Page.Init(); InitPageArgs(Page.Args); } else { CodePage.Init(); InitPageArgs(CodePage.Args); } if (Layout != null && !NoLayout) { LayoutPage = Page != null ? Context.Pages.ResolveLayoutPage(Page, Layout) : Context.Pages.ResolveLayoutPage(CodePage, Layout); } hasInit = true; return this; } private void InitPageArgs(Dictionary<string, object> pageArgs) { if (pageArgs?.Count > 0) { NoLayout = (pageArgs.TryGetValue("ignore", out object ignore) && "template".Equals(ignore?.ToString())) || (pageArgs.TryGetValue("layout", out object layout) && "none".Equals(layout?.ToString())); } } private Task InitIfNewPage(SharpPage page) => page != Page ? (Task) page.Init() : TypeConstants.EmptyTask; private void InitIfNewPage(SharpCodePage page) { if (page != CodePage) page.Init(); } private void AssertInit() { if (!hasInit) throw new NotSupportedException("PageResult.Init() required for this operation."); } public Task WritePageAsync(SharpPage page, SharpCodePage codePage, ScriptScopeContext scope, CancellationToken token = default(CancellationToken)) { if (page != null) return WritePageAsync(page, scope, token); return WriteCodePageAsync(codePage, scope, token); } public async Task WritePageAsync(SharpPage page, ScriptScopeContext scope, CancellationToken token = default(CancellationToken)) { if (PageTransformers.Count == 0) { await WritePageAsyncInternal(page, scope, token); return; } //If PageResult has any PageFilters Buffer and chain stream responses to each using (var ms = MemoryStreamFactory.GetStream()) { stackTrace.Push("PageTransformer"); await WritePageAsyncInternal(page, new ScriptScopeContext(this, ms, scope.ScopedParams), token); Stream stream = ms; foreach (var transformer in PageTransformers) { stream.Position = 0; stream = await transformer(stream); } using (stream) { stream.Position = 0; await stream.WriteToAsync(scope.OutputStream, token); } stackTrace.Pop(); } } internal async Task WritePageAsyncInternal(SharpPage page, ScriptScopeContext scope, CancellationToken token = default(CancellationToken)) { await page.Init(); //reload modified changes if needed await WriteFragmentsAsync(scope, page.PageFragments, "Page: " + page.VirtualPath, token); } public async Task WriteCodePageAsync(SharpCodePage page, ScriptScopeContext scope, CancellationToken token = default(CancellationToken)) { if (PageTransformers.Count == 0) { await WriteCodePageAsyncInternal(page, scope, token); return; } //If PageResult has any PageFilters Buffer and chain stream responses to each using (var ms = MemoryStreamFactory.GetStream()) { await WriteCodePageAsyncInternal(page, new ScriptScopeContext(this, ms, scope.ScopedParams), token); Stream stream = ms; foreach (var transformer in PageTransformers) { stream.Position = 0; stream = await transformer(stream); } using (stream) { stream.Position = 0; await stream.WriteToAsync(scope.OutputStream, token); } } } internal Task WriteCodePageAsyncInternal(SharpCodePage page, ScriptScopeContext scope, CancellationToken token = default(CancellationToken)) { page.Scope = scope; if (!page.HasInit) page.Init(); return page.WriteAsync(scope); } private string toDebugString(object instance) { using (JsConfig.With(new Config { ExcludeTypeInfo = true, IncludeTypeInfo = false, })) { if (instance is Dictionary<string, object> d) return d.ToJsv(); if (instance is List<object> l) return l.ToJsv(); if (instance is string s) return '"' + s.Replace("\"", "\\\"") + '"'; return instance.ToJsv(); } } public async Task WriteVarAsync(ScriptScopeContext scope, PageVariableFragment var, CancellationToken token) { if (var.Binding != null) stackTrace.Push($"Expression (binding): " + var.Binding); else if (var.InitialExpression?.Name != null) stackTrace.Push("Expression (filter): " + var.InitialExpression.Name); else if (var.InitialValue != null) stackTrace.Push($"Expression ({var.InitialValue.GetType().Name}): " + toDebugString(var.InitialValue).SubstringWithEllipsis(0, 200)); else stackTrace.Push($"{var.Expression.GetType().Name}: " + var.Expression.ToRawString().SubstringWithEllipsis(0, 200)); var value = await EvaluateAsync(var, scope, token); if (value != IgnoreResult.Value) { if (value != null) { var bytes = Format.EncodeValue(value).ToUtf8Bytes(); await scope.OutputStream.WriteAsync(bytes, token); } else { if (Context.OnUnhandledExpression != null) { var bytes = Context.OnUnhandledExpression(var); if (bytes.Length > 0) await scope.OutputStream.WriteAsync(bytes, token); } } } stackTrace.Pop(); } private Func<Stream, Task<Stream>> GetFilterTransformer(string name) { return FilterTransformers.TryGetValue(name, out Func<Stream, Task<Stream>> fn) ? fn : Context.FilterTransformers.TryGetValue(name, out fn) ? fn : null; } private static Dictionary<string, object> GetPageParams(PageVariableFragment var) { Dictionary<string, object> scopedParams = null; if (var != null && var.FilterExpressions.Length > 0) { if (var.FilterExpressions[0].Arguments.Length > 0) { var token = var.FilterExpressions[0].Arguments[0]; scopedParams = token.Evaluate(JS.CreateScope()) as Dictionary<string, object>; } } return scopedParams; } private ScriptScopeContext CreatePageContext(PageVariableFragment var, Stream outputStream) => new ScriptScopeContext(this, outputStream, GetPageParams(var)); private async Task<object> EvaluateAsync(PageVariableFragment var, ScriptScopeContext scope, CancellationToken token=default(CancellationToken)) { scope.ScopedParams[nameof(PageVariableFragment)] = var; var value = var.Evaluate(scope); if (value == null) { var handlesUnknownValue = Context.OnUnhandledExpression == null && var.FilterExpressions.Length > 0; if (!handlesUnknownValue) { if (var.Expression is JsMemberExpression memberExpr) { //allow nested null bindings from an existing target to evaluate to an empty string var targetValue = memberExpr.Object.Evaluate(scope); if (targetValue != null) return string.Empty; } if (var.Binding == null) return null; var hasFilterAsBinding = GetFilterAsBinding(var.Binding, out ScriptMethods filter); if (hasFilterAsBinding != null) { value = InvokeFilter(hasFilterAsBinding, filter, new object[0], var.Binding); } else { var hasContextFilterAsBinding = GetContextFilterAsBinding(var.Binding, out filter); if (hasContextFilterAsBinding != null) { value = InvokeFilter(hasContextFilterAsBinding, filter, new object[] { scope }, var.Binding); } else { return null; } } } } if (value == JsNull.Value) value = null; value = EvaluateIfToken(value, scope); for (var i = 0; i < var.FilterExpressions.Length; i++) { if (HaltExecution || value == StopExecution.Value) break; var expr = var.FilterExpressions[i]; try { var filterName = expr.Name; var fnArgValues = JsCallExpression.EvaluateArgumentValues(scope, expr.Arguments); var fnArgsLength = fnArgValues.Count; var invoker = GetFilterInvoker(filterName, 1 + fnArgsLength, out ScriptMethods filter); var contextFilterInvoker = invoker == null ? GetContextFilterInvoker(filterName, 2 + fnArgsLength, out filter) : null; var contextBlockInvoker = invoker == null && contextFilterInvoker == null ? GetContextBlockInvoker(filterName, 2 + fnArgsLength, out filter) : null; var delegateInvoker = invoker == null && contextFilterInvoker == null && contextBlockInvoker == null ? GetValue(filterName, scope) as Delegate : null; if (invoker == null && contextFilterInvoker == null && contextBlockInvoker == null && delegateInvoker == null) { if (i == 0) return null; // ignore on server (i.e. assume it's on client) if first filter is missing var errorMsg = CreateMissingFilterErrorMessage(filterName); throw new NotSupportedException(errorMsg); } if (value is Task<object> valueObjectTask) value = await valueObjectTask; if (delegateInvoker != null) { value = JsCallExpression.InvokeDelegate(delegateInvoker, value, true, fnArgValues); } else if (invoker != null) { fnArgValues.Insert(0, value); var args = fnArgValues.ToArray(); value = InvokeFilter(invoker, filter, args, expr.Name); } else if (contextFilterInvoker != null) { fnArgValues.Insert(0, scope); fnArgValues.Insert(1, value); // filter target var args = fnArgValues.ToArray(); value = InvokeFilter(contextFilterInvoker, filter, args, expr.Name); } else { var hasFilterTransformers = var.FilterExpressions.Length + i > 1; var useScope = hasFilterTransformers ? scope.ScopeWithStream(MemoryStreamFactory.GetStream()) : scope; fnArgValues.Insert(0, useScope); fnArgValues.Insert(1, value); // filter target var args = fnArgValues.ToArray(); try { var taskResponse = (Task)contextBlockInvoker(filter, args); await taskResponse; if (hasFilterTransformers) { using (useScope.OutputStream) { var stream = useScope.OutputStream; //If Context Filter has any Filter Transformers Buffer and chain stream responses to each for (var exprIndex = i + 1; exprIndex < var.FilterExpressions.Length; exprIndex++) { stream.Position = 0; contextBlockInvoker = GetContextBlockInvoker(var.FilterExpressions[exprIndex].Name, 1 + var.FilterExpressions[exprIndex].Arguments.Length, out filter); if (contextBlockInvoker != null) { args[0] = useScope; for (var cmdIndex = 0; cmdIndex < var.FilterExpressions[exprIndex].Arguments.Length; cmdIndex++) { var arg = var.FilterExpressions[exprIndex].Arguments[cmdIndex]; var varValue = arg.Evaluate(scope); args[1 + cmdIndex] = varValue; } await (Task)contextBlockInvoker(filter, args); } else { var transformer = GetFilterTransformer(var.FilterExpressions[exprIndex].Name); if (transformer == null) throw new NotSupportedException($"Could not find FilterTransformer '{var.FilterExpressions[exprIndex].Name}' in page '{Page.VirtualPath}'"); stream = await transformer(stream); useScope = useScope.ScopeWithStream(stream); } } if (stream.CanRead) { stream.Position = 0; await stream.WriteToAsync(scope.OutputStream, token); } } } } catch (StopFilterExecutionException) { throw; } catch (Exception ex) { var rethrow = ScriptConfig.FatalExceptions.Contains(ex.GetType()); var exResult = Format.OnExpressionException(this, ex); if (exResult != null) await scope.OutputStream.WriteAsync(Format.EncodeValue(exResult).ToUtf8Bytes(), token); else if (rethrow) throw; throw new TargetInvocationException($"Failed to invoke filter '{expr.GetDisplayName()}': {ex.Message}", ex); } return IgnoreResult.Value; } if (value is Task<object> valueTask) value = await valueTask; } catch (StopFilterExecutionException ex) { LastFilterError = ex.InnerException; LastFilterStackTrace = stackTrace.ToArray(); if (RethrowExceptions) throw ex.InnerException; var skipExecutingFilters = SkipExecutingFiltersIfError.GetValueOrDefault(Context.SkipExecutingFiltersIfError); if (skipExecutingFilters) this.SkipFilterExecution = true; var rethrow = ScriptConfig.FatalExceptions.Contains(ex.InnerException.GetType()); if (!rethrow) { string errorBinding = null; if (ex.Options is Dictionary<string, object> filterParams) { if (filterParams.TryGetValue(ScriptConstants.AssignError, out object assignError)) { errorBinding = assignError as string; } else if (filterParams.TryGetValue(ScriptConstants.CatchError, out object catchError)) { errorBinding = catchError as string; SkipFilterExecution = false; LastFilterError = null; LastFilterStackTrace = null; } if (filterParams.TryGetValue(ScriptConstants.IfErrorReturn, out object ifErrorReturn)) { SkipFilterExecution = false; LastFilterError = null; LastFilterStackTrace = null; return ifErrorReturn; } } if (errorBinding == null) errorBinding = AssignExceptionsTo ?? Context.AssignExceptionsTo; if (!string.IsNullOrEmpty(errorBinding)) { scope.ScopedParams[errorBinding] = ex.InnerException; scope.ScopedParams[errorBinding + "StackTrace"] = stackTrace.Map(x => " at " + x).Join(Environment.NewLine); return string.Empty; } } if (SkipExecutingFiltersIfError.HasValue || Context.SkipExecutingFiltersIfError) return string.Empty; // rethrow exceptions which aren't handled var exResult = Format.OnExpressionException(this, ex); if (exResult != null) await scope.OutputStream.WriteAsync(Format.EncodeValue(exResult).ToUtf8Bytes(), token); else if (rethrow) throw ex.InnerException; var filterName = expr.GetDisplayName(); if (filterName.StartsWith("throw")) throw ex.InnerException; throw new TargetInvocationException($"Failed to invoke filter '{filterName}': {ex.InnerException.Message}", ex.InnerException); } } return UnwrapValue(value); } private static object UnwrapValue(object value) { if (value == null || value == JsNull.Value || value == StopExecution.Value) return string.Empty; // treat as empty value if evaluated to null return value; } internal string CreateMissingFilterErrorMessage(string filterName) { var registeredMethods = ScriptMethods.Union(Context.ScriptMethods).ToList(); var similarNonMatchingFilters = registeredMethods .SelectMany(x => x.QueryFilters(filterName)) .Where(x => !(Context.ExcludeFiltersNamed.Contains(x.Name) || ExcludeFiltersNamed.Contains(x.Name))) .ToList(); var sb = StringBuilderCache.Allocate() .AppendLine($"Filter in '{VirtualPath}' named '{filterName}' was not found."); if (similarNonMatchingFilters.Count > 0) { sb.Append("Check for correct usage in similar (but non-matching) filters:").AppendLine(); var normalFilters = similarNonMatchingFilters .OrderBy(x => x.GetParameters().Length + (x.ReturnType == typeof(Task) ? 10 : 1)) .ToArray(); foreach (var mi in normalFilters) { var argsTypesWithoutContext = mi.GetParameters() .Where(x => x.ParameterType != typeof(ScriptScopeContext)) .ToList(); sb.Append("{{ "); if (argsTypesWithoutContext.Count == 0) { sb.Append($"{mi.Name} => {mi.ReturnType.Name}"); } else { sb.Append($"{argsTypesWithoutContext[0].ParameterType.Name} | {mi.Name}("); var piCount = 0; foreach (var pi in argsTypesWithoutContext.Skip(1)) { if (piCount++ > 0) sb.Append(", "); sb.Append(pi.ParameterType.Name); } var returnType = mi.ReturnType == typeof(Task) ? "(Stream)" : mi.ReturnType.Name; sb.Append($") => {returnType}"); } sb.AppendLine(" }}"); } } else { var registeredFilterNames = registeredMethods.Map(x => $"'{x.GetType().Name}'").Join(", "); sb.Append($"No similar filters named '{filterName}' were found in registered filter(s): {registeredFilterNames}."); } return StringBuilderCache.ReturnAndFree(sb); } // Filters with no args can be used in-place of bindings private MethodInvoker GetFilterAsBinding(string name, out ScriptMethods filter) => GetFilterInvoker(name, 0, out filter); private MethodInvoker GetContextFilterAsBinding(string name, out ScriptMethods filter) => GetContextFilterInvoker(name, 1, out filter); internal object InvokeFilter(MethodInvoker invoker, ScriptMethods filter, object[] args, string binding) { if (invoker == null) throw new NotSupportedException(CreateMissingFilterErrorMessage(binding.LeftPart('('))); try { return invoker(filter, args); } catch (StopFilterExecutionException) { throw; } catch (Exception ex) { var exResult = Format.OnExpressionException(this, ex); if (exResult != null) return exResult; if (binding.StartsWith("throw")) throw; throw new TargetInvocationException($"Failed to invoke filter '{binding}': {ex.Message}", ex); } } public ReadOnlySpan<char> ParseJsExpression(ScriptScopeContext scope, ReadOnlySpan<char> literal, out JsToken token) { try { return literal.ParseJsExpression(out token); } catch (ArgumentException e) { if (scope.ScopedParams.TryGetValue(nameof(PageVariableFragment), out var oVar) && oVar is PageVariableFragment var && !var.OriginalText.IsNullOrEmpty()) { throw new Exception($"Invalid literal: {literal.ToString()} in '{var.OriginalText}'", e); } throw; } } private readonly Dictionary<string, ScriptBlock> blocksMap = new Dictionary<string, ScriptBlock>(); public ScriptBlock TryGetBlock(string name) => blocksMap.TryGetValue(name, out var block) ? block : Context.GetBlock(name); public ScriptBlock GetBlock(string name) { var block = TryGetBlock(name); if (block == null) throw new NotSupportedException($"Block in '{VirtualPath}' named '{name}' was not found."); return block; } public ScriptScopeContext CreateScope(Stream outputStream=null) => new ScriptScopeContext(this, outputStream ?? MemoryStreamFactory.GetStream(), null); internal MethodInvoker GetFilterInvoker(string name, int argsCount, out ScriptMethods filter) => GetInvoker(name, argsCount, InvokerType.Filter, out filter); internal MethodInvoker GetContextFilterInvoker(string name, int argsCount, out ScriptMethods filter) => GetInvoker(name, argsCount, InvokerType.ContextFilter, out filter); internal MethodInvoker GetContextBlockInvoker(string name, int argsCount, out ScriptMethods filter) => GetInvoker(name, argsCount, InvokerType.ContextBlock, out filter); private MethodInvoker GetInvoker(string name, int argsCount, InvokerType invokerType, out ScriptMethods filter) { if (!Context.ExcludeFiltersNamed.Contains(name) && !ExcludeFiltersNamed.Contains(name)) { foreach (var tplFilter in ScriptMethods) { var invoker = tplFilter?.GetInvoker(name, argsCount, invokerType); if (invoker != null) { filter = tplFilter; return invoker; } } foreach (var tplFilter in Context.ScriptMethods) { var invoker = tplFilter?.GetInvoker(name, argsCount, invokerType); if (invoker != null) { filter = tplFilter; return invoker; } } } filter = null; return null; } public object EvaluateIfToken(object value, ScriptScopeContext scope) { if (value is JsToken token) return token.Evaluate(scope); return value; } internal bool TryGetValue(string name, ScriptScopeContext scope, out object value) { if (name == null) throw new ArgumentNullException(nameof(name)); MethodInvoker invoker; var ret = true; value = scope.ScopedParams != null && scope.ScopedParams.TryGetValue(name, out object obj) ? obj : Args.TryGetValue(name, out obj) ? obj : Page != null && Page.Args.TryGetValue(name, out obj) ? obj : CodePage != null && CodePage.Args.TryGetValue(name, out obj) ? obj : LayoutPage != null && LayoutPage.Args.TryGetValue(name, out obj) ? obj : Context.Args.TryGetValue(name, out obj) ? obj : (invoker = GetFilterAsBinding(name, out ScriptMethods filter)) != null ? InvokeFilter(invoker, filter, new object[0], name) : (invoker = GetContextFilterAsBinding(name, out filter)) != null ? InvokeFilter(invoker, filter, new object[]{ scope }, name) : ((ret = false) ? (object)null : null); return ret; } internal object GetValue(string name, ScriptScopeContext scope) { TryGetValue(name, scope, out var value); return value; } public string ResultOutput => resultOutput; private string resultOutput; public string Result { get { try { if (resultOutput != null) return resultOutput; Init().Wait(); resultOutput = this.RenderToStringAsync().Result; return resultOutput; } catch (AggregateException e) { var ex = e.UnwrapIfSingleException(); throw ex; } } } public PageResult Execute() { var render = Result; return this; } public PageResult Clone(SharpPage page) { return new PageResult(page) { Args = Args, ScriptMethods = ScriptMethods, ScriptBlocks = ScriptBlocks, FilterTransformers = FilterTransformers, }; } public void Dispose() { CodePage?.Dispose(); } } public class BindingExpressionException : Exception { public string Expression { get; } public string Member { get; } public BindingExpressionException(string message, string member, string expression, Exception inner=null) : base(message, inner) { Expression = expression; Member = member; } } public class SyntaxErrorException : ArgumentException { public SyntaxErrorException() { } public SyntaxErrorException(string message) : base(message) { } public SyntaxErrorException(string message, Exception innerException) : base(message, innerException) { } } }
Pathfinder-Fr/YAFNET
yafsrc/ServiceStack/ServiceStack.Common/Script/PageResult.cs
C#
apache-2.0
46,003
<div class="container-fluid margin-top-15" ng-controller="MatchController"> <div class="col-md-2"> <button type="button" class="btn btn-primary pull-right margin-right-10" ng-click="createNewMatch();"> Create Match </button> </div> <div ng-show="clicked"> <p>{{left.firstname}} {{left.lastname}} and {{right.firstname}} {{right.lastname}} will now sing {{song.title}} by {{song.interpreter}}.</p> </div> <br /> <div class="col-md-12"> <div class="list-group-item" ng-repeat="pairing in history"> <div class="row"> <div class="col-md-10"> <h4 class="list-group-item-heading">{{pairing.left.firstname}} {{pairing.left.lastname}} and {{pairing.right.firstname}} {{pairing.right.lastname}}</h4> <p class="list-group-item-text"><i>{{pairing.songToSing.title}} by {{pairing.songToSing.interpreter}}</i></p> </div> </div> </div> </div> </div>
atomfrede/turbo-adventure
src/main/resources/ui/match/matchPage.html
HTML
apache-2.0
1,013
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta property="og:title" content="Pacote Cruzeiro Soberano | Um roteiro magnífico pela costa brasileira!"> <meta property="og:site_name" content="Jungle Turismo"> <meta property="og:description" content="Pacote Cruzeiro Soberano. Confira esta e muitas outras viagens no nosso site. Viaje bem, viaje com a Jungle Turismo!"> <meta property="og:author" content="Jungle Turismo"> <meta property="og:image" content="http://jungleturismo.com.br/img/cruzeiro/cruzeiro.jpeg"> <meta property="og:image:type" content="image/jpeg"> <meta property="og:image:width" content="1000"> <meta property="og:image:height" content="1000"> <title>Jungle Turismo</title> <link rel="shortcut icon" href="logo_fav.ico"/> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/agency.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'> <style type="text/css"> @font-face{ font-family: secret; src: url('fonts/Gravity-Light.otf'); } .tit{ text-transform: none; color: rgb(30, 60, 108); font-family: secret; font-size: 50px; } p{ font-size: 20px; } h3{ color: rgb(255, 192, 66); } #fb{ border: solid 5px rgb(59, 89, 152); background-color: rgb(59, 89, 152); color: white; text-transform: none; width: 125px; border-radius: 5px; } a:hover{ text-decoration: none; } #fb:hover{ background-color: white; color: rgb(59, 89, 152); } .img{ margin: 3px; } .contato{ font-family: secret; font-weight: bold; } </style> <script type="text/javascript"> var url_atual = window.location.href; var viagem = "Cruzeiro Soberano"; function mudar(){ document.getElementById("wpp").href = "whatsapp://send?text=Confira este pacote para "+viagem+": "+url_atual; } </script> </head> <body style="background-color: #f7f7f7;" id="page-top" class="index" onload="mudar()"> <!-- Navigation --> <nav style="background-color: rgb(30, 60, 108); position: fixed;" class="navbar navbar-default navbar-fixed-top"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand page-scroll" href="index.html">Jungle Turismo</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="hidden"> <a href="#page-top"></a> </li> <li> <a class="page-scroll" href="agencia.html">a agência</a> </li> <li> <a class="page-scroll" href="index.html">Próximas Viagens</a> </li> <li> <a class="page-scroll" href="index.html">Últimas Viagens</a> </li> <li> <a class="page-scroll" href=".footer">Contatos</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <div style="margin-top: 14%;" class="container"> <div class="row"> <div style="" class="col-xs-12 col-sm-12 col-md-5 col-lg-5"> <img width="100%" src="img/cruzeiro/cruzeiro.jpeg"> </div> <div style="padding-bottom:20px; background-color: white;" class="col-xs-12 col-sm-12 col-md-7 col-lg-7"> <h1 class="tit"><span id="viagem">Cruzeiro Soberano All Inclusive</span></h1> <hr> <h3>PERÍODO:</h3> <p>5 dias</p> <h3>PROGRAMAÇÃO:</h3> <p><b>SAÍDA:</b> 29/01/2019<br> </p> <p> <b>PACOTE INCLUI:</b><br> Roteiro: Santos, Rio de Janeiro,<br> Armação dos búzios, Navegação e Santos<br> Para mais informações leia a imagem em anexo ou entre em contato conosco </p> <hr> <h1 class="tit">Pagamento</h1> <hr> <h3>12x:</h3> <h2 style="color: rgb(30, 60, 108)">R$ 91,00</h2> <h6>Valor do pacote por pessoa em cabine quádrupla R$ 2.040,00.</h6> <h6>Formas de pagamento:<br>Cartão<br>Cheque</h6> <hr> <h1 class="tit">Contatos</h1> <hr> <div style="text-align: center; width: 100%;" class="container"> <img width="50px" src="img/em.png"> <p class="contato" style="clor: rgb(36, 104, 255)"> Email:<br> <span style="color: rgb(100, 100, 100);">[email protected]</span> </p> <img width="50px" src="img/wpp.png"> <p class="contato"> WhatsApp:<br> <span style="color: rgb(45, 147, 57)">(84) 99958-1548</span> </p> <p class="contato"> <img width="50px" src="img/telefone.png"><br> Telefones:<br> <span style="color: rgb(100, 100, 100);">(84) 3274-2924</span><br><br> </p> <h3 style="color: rgb(30, 60, 108)">Visite nossos perfis</h3> <a target="blank" href="http://facebook.com/jungleturismo"><img width="50px" src="img/fb.png" style="margin-bottom:10px;"></a><br> <a target="blank" href="https://www.instagram.com/jungleturismo.cm/"><img width="60px" src="img/insta.png"></a> </div> <hr> <div style="text-align: center; width: 100%;" class="container"> <h1 class="tit">Compartilhe esse pacote</h1> <div style="text-align: center; width: 50%;" class="container"> <div class="row"> <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4"> <a href="#"><img width="50px" src="img/impressora.png"></a> </div> <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4"> <a id="wpp" href=""><img width="50px" src="img/wpp2.png"></a> </div> <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4"> <div class="fb-share-button" data-href="http://jungleturismo.com.br/cruzeiro.html" data-layout="button_count" data-size="large" data-mobile-iframe="true"><a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fjungleturismo.com.br%2Fcruzeiro.html&amp;src=sdkpreparse"><img width="50px" src="img/fb2.png"></a></div> </div> </div> </div> </div> <div class="col-md-6"> </div> <div class="col-md-6"> </div> </div> </div> </div> </div> <hr> <footer class="footer"> <div class="container"> <div class="row"> <div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"> <img width="80%" src="img/abav.png"> </div> <div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"> <img width="70%" src="img/foco-op.png"> </div> <div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"> <img width="80%" src="img/embratur.png"> </div> <div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"> <img width="120%" src="img/ministerio.png"> </div> </div> <hr> <div class="row"> <div class="col-md-5"> <ul class="list-inline quicklinks"> <li>Jungle Turismo 2016 </li><br> <li>CNPJ 25.989.749/0001-34</li> </ul> </div> <div class="col-md-1"> <ul class="list-inline social-buttons"> <li><a target="blank" href="http://facebook.com/jungleturismo"><i class="fa fa-facebook"></i></a> </li> </ul> </div> <div class="col-md-6"> <ul class="list-inline quicklinks"> <li>[email protected] </li> <li>Fone: (84) 3274-2924/(84) 99958-1548 <img style="margin-top: -8px" width="8%" src="img/whatsapp-logo.png"></li> <li>Rua Manoel Francisco Sobral, 381 - Centro, Ceará-Mirim/RN</li> </ul> </div> </div> </div> </footer> <!-- Facebook --> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v2.7"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="js/classie.js"></script> <script src="js/cbpAnimatedHeader.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <!-- Contact Form JavaScript --> <script src="js/jqBootstrapValidation.js"></script> <script src="js/contact_me.js"></script> <!-- Custom Theme JavaScript --> <script src="js/agency.js"></script> </body> </html>
fariias/fariias.github.io
cruzeiro.html
HTML
apache-2.0
11,830
// Copyright © 2013-2018 Andy Goryachev <[email protected]> package goryachev.common.test; import goryachev.common.util.CJob; import goryachev.common.util.CKit; import goryachev.common.util.CList; import goryachev.common.util.CSorter; import goryachev.common.util.Log; import goryachev.common.util.log.ConsoleLogWriter; import goryachev.common.util.log.LogWriter; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Date; import java.util.List; import java.util.Vector; public class TestRunner { private final CList<Class> classes = new CList<>(); private int failed; protected final Vector<TestCase> cases = new Vector<>(); protected long started; protected long ended; public TestRunner() { } public static void run(List<Class> tests) { initLog(); TestRunner r = new TestRunner(); r.print("Testing started " + (new Date()) + ".\n"); for(Class c: tests) { r.add(c); } r.executeTests(); r.printResults(); System.out.flush(); System.err.flush(); CKit.sleep(10); // command returns the number of failed tests (or 0 if all passed) System.exit(-r.failed); } public static void initLog() { LogWriter wr = new ConsoleLogWriter("console"); wr.setAsync(false); // Log.addWriter(wr); Log.addErrorWriter(wr); } public void add(Class c) { checkConstructor(c); classes.add(c); } @SuppressWarnings("unchecked") protected void checkConstructor(Class c) { try { if(c.getConstructor() != null) { if(c.getConstructors().length == 1) { return; } } } catch(Exception e) { throw new TestException("Test class must define a single no-arg constructor: " + CKit.simpleName(c), e); } } protected void extract(Class c, CList<RunEntry> list, Class<? extends Annotation> type, boolean needsStatic) { for(Method m: c.getDeclaredMethods()) { int mods = m.getModifiers(); if(Modifier.isPublic(mods)) { Annotation a = m.getAnnotation(type); if(a != null) { if(Modifier.isStatic(mods) != needsStatic) { if(needsStatic) { throw new TestException("method " + CKit.simpleName(c) + "." + m.getName() + "() must be static"); } else { throw new TestException("method " + CKit.simpleName(c) + "." + m.getName() + "() must not be static"); } } list.add(new RunEntry(m, a)); } } } CSorter.sort(list); } protected void print(String s) { System.out.print(s); } protected void executeTests() { CList<CJob> jobs = new CList<>(); started = System.currentTimeMillis(); for(final Class c: classes) { CJob job = new CJob("test " + CKit.simpleName(c)) { protected void process() throws Exception { try { executeTestClass(this, c); } catch(Throwable e) { e.printStackTrace(); } } }; jobs.add(job); job.submit(); } CJob.waitForAll(jobs); ended = System.currentTimeMillis(); } protected void executeTestClass(CJob parent, final Class c) throws Exception { final CList<RunEntry> beforeAll = new CList<>(); final CList<RunEntry> before = new CList<>(); final CList<RunEntry> tests = new CList<>(); final CList<RunEntry> after = new CList<>(); final CList<RunEntry> afterAll = new CList<>(); extract(c, beforeAll, BeforeClass.class, true); extract(c, before, Before.class, false); extract(c, tests, Test.class, false); extract(c, after, After.class, false); extract(c, afterAll, AfterClass.class, true); if(tests.size() == 0) { System.out.println("No tests in " + CKit.simpleName(c)); return; } for(RunEntry m: beforeAll) { m.invoke(null); } CList<CJob> jobs = new CList<>(); // individual tests for(final RunEntry m: tests) { CJob job = new CJob(parent, "test " + CKit.simpleName(c) + "." + m) { protected void process() throws Exception { executeInstance(c, m, before, after); } }; jobs.add(job); job.submit(); } CJob.waitForAll(jobs); for(RunEntry m: afterAll) { m.invoke(null); } } protected void executeInstance(Class c, RunEntry testMethod, CList<RunEntry> before, CList<RunEntry> after) { String name = CKit.simpleName(c) + "." + testMethod; final TestCase tc = new TestCase(name); cases.add(tc); tc.started(); try { Object instance = c.newInstance(); tc.setTestInstance(instance); for(RunEntry m: before) { m.invoke(instance); } try { testMethod.invoke(instance); testMethod.checkNoException(); } catch(InvocationTargetException e) { Throwable err = e.getTargetException(); if(testMethod.isUnexpected(err)) { if(err instanceof Exception) { throw (Exception)err; } else { throw new Exception(err); } } } catch(Exception e) { throw e; } for(RunEntry m: after) { m.invoke(instance); } tc.stopped(); testSuccess(tc); } catch(Throwable e) { tc.stopped(); tc.setFailed(e); testFailed(tc); } } protected void testSuccess(TestCase tc) { print("."); } protected void testFailed(TestCase tc) { print("E"); } public void printResults() { int count = cases.size(); for(TestCase c: cases) { if(c.isFailed()) { failed++; } } print("\n\n"); String elapsed = CKit.formatTimePeriod(ended - started); if(failed == 0) { print("OK"); } else { print("FAILED " + failed); } print(" (" + count + " tests) " + elapsed + "\n"); if(failed > 0) { for(TestCase c: cases) { if(c.isFailed()) { print("\n"); print(c.getName() + "\n"); print(c.getText()); print("\n"); print(CKit.stackTrace(c.getFailure())); print("\n"); } } } } // public static class RunEntry implements Comparable<RunEntry> { private final Method method; private final Annotation annotation; public RunEntry(Method method, Annotation annotation) { this.method = method; this.annotation = annotation; } public String toString() { return getName(); } public String getName() { return method.getName(); } public boolean isUnexpected(Throwable e) { Class<? extends Throwable> expected = ((Test)annotation).expected(); if(expected == null) { return true; } return !expected.isAssignableFrom(e.getClass()); } public void checkNoException() throws Exception { Class<? extends Throwable> expected = ((Test)annotation).expected(); if(expected == Test.NoThrowable.class) { return; } else if(expected != null) { throw new Exception("This test case is expected to throw an " + CKit.simpleName(expected)); } } public void invoke(Object x) throws Exception { method.invoke(x); } public int compareTo(RunEntry x) { return getName().compareTo(x.getName()); } } }
andy-goryachev/FindFiles
src/goryachev/common/test/TestRunner.java
Java
apache-2.0
7,542
/* * Copyright (c) 2014-2015 University of Ulm * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package models.service; import models.Location; /** * Created by bwpc on 09.12.2014. */ public interface LocationRepository extends RemoteModelRepository<Location> { }
cha87de/colosseum
app/models/service/LocationRepository.java
Java
apache-2.0
894
package cn.wizzer.modules.back.cms.services; import cn.wizzer.common.base.Service; import cn.wizzer.modules.back.cms.models.Cms_article; import org.nutz.dao.Dao; import org.nutz.ioc.loader.annotation.IocBean; /** * Created by Wizzer on 2016/7/18. */ @IocBean(args = {"refer:dao"}) public class CmsArticleService extends Service<Cms_article> { public CmsArticleService(Dao dao) { super(dao); } }
Wizzercn/NutzWeShop
src/main/java/cn/wizzer/modules/back/cms/services/CmsArticleService.java
Java
apache-2.0
415
/* * Copyright (c) 2020 Evolveum * * 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.evolveum.midpoint.client.api; import com.evolveum.midpoint.client.api.verb.Post; import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; public interface TaskOperationService extends Post<ObjectReference<TaskType>> { }
Evolveum/midpoint-client-java
midpoint-client-api/src/main/java/com/evolveum/midpoint/client/api/TaskOperationService.java
Java
apache-2.0
843
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>myTitle</title> </head> <body> here we go </body> </html>
leafyfresh/pluralNode
pluralNode/slice.html
HTML
apache-2.0
172
# Copyright 2016 Google LLC # Modifications: Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest.mock as mock import pytest import requests import gsi.transport.request from tests.transport import compliance class TestRequestResponse(compliance.RequestResponseTests): def make_request(self): return gsi.transport.request.Request() def make_cached_request(self): return gsi.transport.request.CacheRequest() def test_timeout(self): http = mock.create_autospec(requests.Session, instance=True) request = gsi.transport.request.Request(http) request(url="http://example.com", method="GET", timeout=5) assert http.request.call_args[1]["timeout"] == 5
googleinterns/server-side-identity
tests/transport/test_requests.py
Python
apache-2.0
1,263
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class ExtinguisherController : MonoBehaviour { public ParticleSystem ps; private Vector2 position; private Vector3 scale; private GameObject setaInvisivel; Quaternion rotacao; public void Start() { setaInvisivel = GameObject.Find("Seta03"); setaInvisivel.SetActive(false); ps = GetComponent<ParticleSystem>(); scale = new Vector3(0.8F, 1.3F, 0.3F); } private void OnTriggerEnter2D(Collider2D collider) { GameObject.Find("Prateleira09").SetActive(false); GameObject.Find("Trampolim05").SetActive(false); GameObject.Find("PlataformaEscada").SetActive(false); GameObject.Find("Seta01").SetActive(false); GameObject.Find("Seta02").SetActive(false); setaInvisivel.SetActive(true); Destroy(GameObject.Find("Escada").GetComponent<Rigidbody2D>()); Destroy(GameObject.Find("Escada").GetComponent<Collider2D>()); gameObject.transform.SetParent(GameObject.Find("L_Hand").transform); rotacao = GameObject.Find("Player").transform.rotation; position = GameObject.Find("L_Hand").transform.position; gameObject.transform.SetPositionAndRotation(position, rotacao); transform.localScale = scale; collider.GetComponent<MovementScript>().hasObject = true; gameObject.GetComponent<Collider2D>().enabled = false; } void OnParticleTrigger() { List<ParticleSystem.Particle> enter = new List<ParticleSystem.Particle>(); int numEnter = ps.GetTriggerParticles(ParticleSystemTriggerEventType.Enter, enter); for (int i = 0; i < numEnter; i++) { ControllerMaquina controller = GameObject.Find("MaquinaSalgadinhos").GetComponent<ControllerMaquina>(); if (controller.vida < 100F) { controller.vida += 0.03F; controller.AumentarBarraVida(); } else break; } } }
David-Allan/DiplomaRunning
Assets/Scripts/ExtinguisherController.cs
C#
apache-2.0
2,075
var Hapi = require('hapi'); var mongoose = require('mongoose'); var config = require('./app.json'); var Fitbit = require('fitbit-node'); var Q = require('q'); var client = new Fitbit('', ''); var redirect_uri = "http://localhost:8080/fitbit_oauth_callback"; var scope = "activity profile"; mongoose.connect('mongodb://localhost/test'); var db = mongoose.connection; var userSchema = mongoose.Schema({ userid: String, accessToken: String, refreshToken: String }); var User = mongoose.model('User', userSchema); var server = new Hapi.Server(); server.connection({ port: 8080 }); server.route([ // Auth callback { method: 'GET', path: '/fitbit', handler: function(request, reply) { console.log("AT FITBIT NOW"); reply().redirect(client.getAuthorizeUrl(scope, redirect_uri)); } }, { method: 'GET', path: '/fitbit_oauth_callback', handler: function(request, reply) { client.getAccessToken(request.query.code, redirect_uri).then(function(result) { updateUser(result.user_id, result.access_token, result.refresh_token); reply().redirect("/api/v1/users/" + result.user_id); }) } }, { method: 'GET', config: { json: { space: 2 } }, path: '/api/v1/users', handler: function(request, reply) { var result = User.find(); result.exec(function(err, users) { userlist = []; users.forEach(function(userDoc) { user = userDoc.toObject(); user._links = [{ "rel": "self", "href": "http://localhost:8080/api/v1/users/" + user.userid, "method": "GET" }, { "rel": "self", "href": "http://localhost:8080/api/v1/users/" + user.userid, "method": "DELETE" }, { "rel": "progress", "href": "http://localhost:8080/api/v1/users/" + user.userid + "/progress", "method": "GET" }, { "rel": "activities", "href": "http://localhost:8080/api/v1/users/" + user.userid + "/activities", "method": "GET" }, { "rel": "activities", "href": "http://localhost:8080/api/v1/users/" + user.userid + "/activities", "method": "POST" } ]; userlist.push(user); }) reply(userlist); }); } }, { method: 'DELETE', path: '/api/v1/users/{fitbitid}', handler: function(request, reply) { Task.findOneAndRemove({ userid: request.params.fitbitid }, function(err, response) { reply().code(204); }); } }, { method: 'GET', path: '/api/v1/users/{fitbitid}', handler: function(request, reply) { var result = User.findOne({ "userid": request.params.fitbitid }); result.exec(function(err, user) { client.get("/profile.json", user.accessToken).then(function(results) { reply(results); }) }) } }, { method: 'GET', config: { json: { space: 2 } }, path: '/api/v1/users/{fitbitid}/activities/summary', handler: function(request, reply) { var result = User.findOne({ "userid": request.params.fitbitid }); result.exec(function(err, user) { if (!user) { reply().redirect("/fitbit") } var requestDate = getFitbitDate(request.query.date); var requestUrl = "/activities/date/" + requestDate + ".json"; client.get(requestUrl, user.accessToken).then(function(results) { reply(results); }) }) } }, { method: 'GET', config: { json: { space: 2 } }, path: '/api/v1/users/{fitbitid}/activities', handler: function(request, reply) { var result = User.findOne({ "userid": request.params.fitbitid }); result.exec(function(err, user) { if (!user) { reply().redirect("/fitbit") } var requestDate = getFitbitDate(request.query.date); var queryString = "?afterDate=" + requestDate + "&sort=asc&offset=0&limit=50"; var requestUrl = "/activities/list.json" + queryString; console.log(user); getFitbit(requestUrl, user).then(function(results) { reply(results); }) }) } }, { method: 'POST', path: '/api/v1/users/{fitbitid}/activities', handler: function(request, reply) { var result = User.findOne({ "userid": request.params.fitbitid }); result.exec(function(err, user) { var requestDate = getFitbitDate(request.query.date); var activity = { "activityName": "Cycling", // Activity name or ID required "manualCalories": 300, // Required with activityName "startTime": "09:00:00", "durationMillis": 1000 * 60 * 30, "date": requestDate }; var requestUrl = "/activities.json"; client.post(requestUrl, user.accessToken, activity).then(function(results) { reply(results); }) }) } }, { method: 'DELETE', path: '/api/v1/users/{fitbitid}/activities/{activityId}', handler: function(request, reply) { var result = User.findOne({ "userid": request.params.fitbitid }); result.exec(function(err, user) { var requestUrl = "/activities/" + request.params.activityId + ".json"; client.delete(requestUrl, user.accessToken).then(function(results, response) { console.log(response); reply().code(204); }) }) } }, { method: 'GET', path: '/', handler: function(request, reply) { reply('Hello world from hapi'); } } ]); function updateUser(userid, accessToken, refreshToken) { var deferred = Q.defer(); var newUserInfo = { 'userid': userid, 'accessToken': accessToken, 'refreshToken': refreshToken }; var newUser = new User(newUserInfo); User.update({ "userid": userid }, newUser, { upsert: true }, function(err) { deferred.resolve(newUserInfo); }); return deferred.promise; } function getFitbitDate(requestDate) { if (requestDate) { var returnDate = request.query.date; } else { var d = new Date(); var dateArray = [d.getFullYear(), d.getMonth() + 1, d.getDate()]; var returnDate = dateArray.join('-'); } return returnDate; } function getFitbit(requestUrl, user) { var deferred = Q.defer(); client.get(requestUrl, user.accessToken).then(function(results) { if (results[0]["errors"]) { deferred.reject(results[0]["errors"]); } else { deferred.resolve(results); } }).catch(function(error) { deferred.reject(error); }) return deferred.promise; } server.start(function(err) { console.log('Hapi is listening to http://localhost:8080'); });
synedra/hapi-api
Chapter4/04_04/Start/04_04.js
JavaScript
apache-2.0
8,403
/** * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * This file is part of the Smart Developer Hub Project: * http://www.smartdeveloperhub.org/ * * Center for Open Middleware * http://www.centeropenmiddleware.com/ * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Copyright (C) 2015-2016 Center for Open Middleware. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * 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. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Artifact : org.smartdeveloperhub.harvesters.scm:scm-harvester-frontend:0.3.0 * Bundle : scm-harvester.war * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# */ package org.smartdeveloperhub.harvesters.scm.frontend.core.util; import org.ldp4j.application.ext.ApplicationRuntimeException; import org.ldp4j.application.ext.UnknownResourceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class Serviceable { private final Logger logger; // NOSONAR public Serviceable() { this.logger=LoggerFactory.getLogger(getClass()); } protected final String trace(final String message, final Object... arguments) { final String result = String.format(message,arguments); this.logger.trace(result); return result; } protected final String debug(final String message, final Object... arguments) { final String result = String.format(message,arguments); this.logger.debug(result); return result; } protected final String info(final String message, final Object... arguments) { final String result = String.format(message,arguments); this.logger.info(result); return result; } protected final ApplicationRuntimeException unexpectedFailure(final Throwable failure, final String message, final Object... args) { final String result = String.format(message,args); this.logger.error(result.concat(". Full stacktrace follows"),failure); final String errorMessage=result; return new ApplicationRuntimeException(errorMessage,failure); } protected final ApplicationRuntimeException unexpectedFailure(final String message, final Object... args) { final String result = String.format(message,args); this.logger.error(result); return new ApplicationRuntimeException(result); } protected final UnknownResourceException unknownResource(final Object resourceId, final String resourceType) { final String errorMessage = String.format("Could not find %s resource for %s",resourceType,resourceId); this.logger.error(errorMessage); return new UnknownResourceException(errorMessage); } }
SmartDeveloperHub/sdh-scm-harvester
frontend/src/main/java/org/smartdeveloperhub/harvesters/scm/frontend/core/util/Serviceable.java
Java
apache-2.0
3,234
# AUTOGENERATED FILE FROM balenalib/artik10-fedora:33-run # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 RUN dnf install -y \ python3-pip \ python3-dbus \ && dnf clean all # install "virtualenv", since the vast majority of users of this image will want it RUN pip3 install -U --no-cache-dir --ignore-installed pip setuptools \ && pip3 install --no-cache-dir virtualenv RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/python-deprecation-warnin CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@python" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Fedora 33 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.7.12, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
resin-io-library/base-images
balena-base-images/python/artik10/fedora/33/3.7.12/run/Dockerfile
Dockerfile
apache-2.0
2,430
#ifndef _INT_LIST_H_ #define _INT_LIST_H_ class IntList { public: virtual String toString(); private: const int head; const IntList tail; IntList(const int head); IntList(const int X, const IntList Xs); const boolean isEmpty(const IntList Xs); const int head(const IntList Xs); const IntList empty = null; const IntList tail(const IntList Xs); const IntList cons(const int X, const IntList Xs); const IntList app(const int[] xs, const IntList Ys); const IntStack toInts(IntList Xs); const int len(const IntList Xs); }; #endif
CSCE-5430/iPrologInCPP
IntList.h
C
apache-2.0
601
--- image_path: /img/portfolio/1.jpg category: Web Development project_name: Maitre D link: http://maitre-dbc.herokuapp.com/ ---
thunderenlight/thunderenlight.github.io
_portfolio/maitred.md
Markdown
apache-2.0
128
<?php namespace Gos\Component\DoctrineHydrator\ListHydrator\Strategy; use Doctrine\ORM\Query\ResultSetMapping; use Doctrine\ORM\UnitOfWork; use Gos\Component\DoctrineHydrator\ListHydrator\AbstractListHydrator; /** * Class ListStrategy * @package Gos\Component\DoctrineHydrator\ListHydrator\Strategy */ class ListStrategy extends AbstractListStrategy { /** * Pool of available strategy */ const PREDICT_PK = 'predict_PK'; const COMPOSITE_PREDICT_PK = 'composite_predict_PK'; const OVERRIDE_PK = 'override_PK'; const OVERRIDE_DEEP_PK = 'override_deep_PK'; const COMPOSITE_PK = 'composite_PK'; protected $predicatedBuffer = null; protected $identifierBuffer = null; /** * @param $PK * @param array $hints */ public function find(&$PK, array &$hints, ResultSetMapping $rsm, UnitOfWork $uow) { if (isset($hints[AbstractListHydrator::HINT_LIST_FIELD])) { $PK = $hints[AbstractListHydrator::HINT_LIST_FIELD]; if (is_string($PK)) { $this->_solution = (strpos($PK, '.') === false) ? self::OVERRIDE_PK : self::OVERRIDE_DEEP_PK; return true; } if (is_array($PK)) { if (count($PK) == 1) { $hints[AbstractListHydrator::HINT_LIST_FIELD] = current($PK); return $this->find($PK, $hints, $rsm, $uow); } else { $this->_solution = self::COMPOSITE_PK; } return true; } } else { if (1 === count($this->getIdentifier($rsm, $uow))) { $this->_solution = self::PREDICT_PK; } else { $this->_solution = self::COMPOSITE_PREDICT_PK; } return true; } return false; } /** * @param ResultSetMapping $rsm * @param UnitOfWork $uow * * @return array|null|string */ protected function getIdentifier(ResultSetMapping $rsm, UnitOfWork $uow) { if (null === $this->identifierBuffer) { $this->identifierBuffer = $uow->getEntityPersister(current($rsm->getAliasMap()))->getClassMetadata()->getIdentifier(); } return $this->identifierBuffer; } /** * @param ResultSetMapping $rsm * @param UnitOfWork $uow * @param array $hints * * @return mixed|string * @throws \Exception */ protected function predictStrategy(ResultSetMapping $rsm, UnitOfWork $uow, array $hints) { if (null == $this->predicatedBuffer) { $identifier = $this->getIdentifier($rsm, $uow); //A PK can be composite if (1 === count($identifier)) { $PK = current(array_values($identifier)); } else { $PK = $identifier; } $this->predicatedBuffer = $PK; } return $this->predicatedBuffer; } /** * @param ResultSetMapping $rsm * @param UnitOfWork $uow * @param array $hints * @param $PK * * @return mixed|void * @throws \Exception */ public function work(ResultSetMapping $rsm, UnitOfWork $uow, array &$hints, &$PK) { if (null === $this->getSolution() && null === $this->find($PK, $hints, $rsm, $uow)) { throw new \Exception('Unable to find a strategy to process'); } //In the case of we does not define a PK, make a predicate based on scheme table. if (self::PREDICT_PK === $this->getSolution() xor self::COMPOSITE_PREDICT_PK === $this->getSolution()) { $PK = $this->predictStrategy($rsm, $uow, $hints); } if (null === static::$_fallback) { $this->predictStrategy($rsm, $uow, $hints); } //Sync hint for the parent hydrator $hints[AbstractListHydrator::HINT_LIST_FIELD] = $PK; } /** * @return bool */ public function isTraversableSolution() { $traversableSolution = [self::COMPOSITE_PREDICT_PK, self::COMPOSITE_PK]; return in_array($this->getSolution(), $traversableSolution); } public function isPredictableSolution() { $predictableSolution = [self::COMPOSITE_PREDICT_PK, self::PREDICT_PK]; return in_array($this->getSolution(), $predictableSolution); } }
GeniusesOfSymfony/DoctrineHydrator
ListHydrator/Strategy/ListStrategy.php
PHP
apache-2.0
4,453
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. using Burrows.Log4Net.Logging; namespace Burrows.Tests { using System; using System.Diagnostics; using System.IO; using Logging; using NUnit.Framework; using log4net; using log4net.Config; [SetUpFixture] public class ContextSetup { [SetUp] public void Before_any() { string path = AppDomain.CurrentDomain.BaseDirectory; string file = Path.Combine(path, "masstransit.tests.log4net.xml"); XmlConfigurator.Configure(new FileInfo(file)); Trace.WriteLine("Loading Log4net: " + file); Logger.UseLogger(new Log4NetLogger()); } [TearDown] public void After_all() { LogManager.Shutdown(); } } }
eswann/Burrows
src/Tests/Burrows.Tests/ContextSetup.cs
C#
apache-2.0
1,462
# Nectria obvoluta P. Karst. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Nectria obvoluta P. Karst. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Sordariomycetes/Hypocreales/Nectriaceae/Nectria/Nectria obvoluta/README.md
Markdown
apache-2.0
181
/* * Copyright (C) 2004, 2006, 2008 Apple Inc. All rights reserved. * Copyright (C) 2005-2007 Alexey Proskuryakov <[email protected]> * Copyright (C) 2007, 2008 Julien Chaffraix <[email protected]> * Copyright (C) 2008, 2011 Google Inc. All rights reserved. * Copyright (C) 2012 Intel Corporation * * 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 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "core/xml/XMLHttpRequest.h" #include "FetchInitiatorTypeNames.h" #include "bindings/v8/ExceptionState.h" #include "core/dom/ContextFeatures.h" #include "core/dom/DOMImplementation.h" #include "core/dom/Event.h" #include "core/dom/EventListener.h" #include "core/dom/EventNames.h" #include "core/dom/ExceptionCode.h" #include "core/editing/markup.h" #include "core/fileapi/Blob.h" #include "core/fileapi/File.h" #include "core/html/DOMFormData.h" #include "core/html/HTMLDocument.h" #include "core/inspector/InspectorInstrumentation.h" #include "core/loader/CrossOriginAccessControl.h" #include "core/loader/TextResourceDecoder.h" #include "core/loader/ThreadableLoader.h" #include "core/page/ContentSecurityPolicy.h" #include "core/page/Settings.h" #include "core/platform/HistogramSupport.h" #include "core/platform/SharedBuffer.h" #include "core/platform/network/BlobData.h" #include "core/platform/network/HTTPParsers.h" #include "core/platform/network/ParsedContentType.h" #include "core/platform/network/ResourceError.h" #include "core/platform/network/ResourceRequest.h" #include "core/xml/XMLHttpRequestProgressEvent.h" #include "core/xml/XMLHttpRequestUpload.h" #include "weborigin/SecurityOrigin.h" #include "wtf/ArrayBuffer.h" #include "wtf/ArrayBufferView.h" #include "wtf/RefCountedLeakCounter.h" #include "wtf/StdLibExtras.h" #include "wtf/UnusedParam.h" #include "wtf/text/CString.h" namespace WebCore { DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, xmlHttpRequestCounter, ("XMLHttpRequest")); // Histogram enum to see when we can deprecate xhr.send(ArrayBuffer). enum XMLHttpRequestSendArrayBufferOrView { XMLHttpRequestSendArrayBuffer, XMLHttpRequestSendArrayBufferView, XMLHttpRequestSendArrayBufferOrViewMax, }; struct XMLHttpRequestStaticData { WTF_MAKE_NONCOPYABLE(XMLHttpRequestStaticData); WTF_MAKE_FAST_ALLOCATED; public: XMLHttpRequestStaticData(); String m_proxyHeaderPrefix; String m_secHeaderPrefix; HashSet<String, CaseFoldingHash> m_forbiddenRequestHeaders; }; XMLHttpRequestStaticData::XMLHttpRequestStaticData() : m_proxyHeaderPrefix("proxy-") , m_secHeaderPrefix("sec-") { m_forbiddenRequestHeaders.add("accept-charset"); m_forbiddenRequestHeaders.add("accept-encoding"); m_forbiddenRequestHeaders.add("access-control-request-headers"); m_forbiddenRequestHeaders.add("access-control-request-method"); m_forbiddenRequestHeaders.add("connection"); m_forbiddenRequestHeaders.add("content-length"); m_forbiddenRequestHeaders.add("content-transfer-encoding"); m_forbiddenRequestHeaders.add("cookie"); m_forbiddenRequestHeaders.add("cookie2"); m_forbiddenRequestHeaders.add("date"); m_forbiddenRequestHeaders.add("expect"); m_forbiddenRequestHeaders.add("host"); m_forbiddenRequestHeaders.add("keep-alive"); m_forbiddenRequestHeaders.add("origin"); m_forbiddenRequestHeaders.add("referer"); m_forbiddenRequestHeaders.add("te"); m_forbiddenRequestHeaders.add("trailer"); m_forbiddenRequestHeaders.add("transfer-encoding"); m_forbiddenRequestHeaders.add("upgrade"); m_forbiddenRequestHeaders.add("user-agent"); m_forbiddenRequestHeaders.add("via"); } static bool isSetCookieHeader(const AtomicString& name) { return equalIgnoringCase(name, "set-cookie") || equalIgnoringCase(name, "set-cookie2"); } static void replaceCharsetInMediaType(String& mediaType, const String& charsetValue) { unsigned int pos = 0, len = 0; findCharsetInMediaType(mediaType, pos, len); if (!len) { // When no charset found, do nothing. return; } // Found at least one existing charset, replace all occurrences with new charset. while (len) { mediaType.replace(pos, len, charsetValue); unsigned int start = pos + charsetValue.length(); findCharsetInMediaType(mediaType, pos, len, start); } } static const XMLHttpRequestStaticData* staticData = 0; static const XMLHttpRequestStaticData* createXMLHttpRequestStaticData() { staticData = new XMLHttpRequestStaticData; return staticData; } static const XMLHttpRequestStaticData* initializeXMLHttpRequestStaticData() { // Uses dummy to avoid warnings about an unused variable. AtomicallyInitializedStatic(const XMLHttpRequestStaticData*, dummy = createXMLHttpRequestStaticData()); return dummy; } static void logConsoleError(ScriptExecutionContext* context, const String& message) { if (!context) return; // FIXME: It's not good to report the bad usage without indicating what source line it came from. // We should pass additional parameters so we can tell the console where the mistake occurred. context->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message); } PassRefPtr<XMLHttpRequest> XMLHttpRequest::create(ScriptExecutionContext* context, PassRefPtr<SecurityOrigin> securityOrigin) { RefPtr<XMLHttpRequest> xmlHttpRequest(adoptRef(new XMLHttpRequest(context, securityOrigin))); xmlHttpRequest->suspendIfNeeded(); return xmlHttpRequest.release(); } XMLHttpRequest::XMLHttpRequest(ScriptExecutionContext* context, PassRefPtr<SecurityOrigin> securityOrigin) : ActiveDOMObject(context) , m_async(true) , m_includeCredentials(false) , m_timeoutMilliseconds(0) , m_state(UNSENT) , m_createdDocument(false) , m_error(false) , m_uploadEventsAllowed(true) , m_uploadComplete(false) , m_sameOriginRequest(true) , m_allowCrossOriginRequests(false) , m_receivedLength(0) , m_lastSendLineNumber(0) , m_exceptionCode(0) , m_progressEventThrottle(this) , m_responseTypeCode(ResponseTypeDefault) , m_protectionTimer(this, &XMLHttpRequest::dropProtection) , m_securityOrigin(securityOrigin) { initializeXMLHttpRequestStaticData(); #ifndef NDEBUG xmlHttpRequestCounter.increment(); #endif ScriptWrappable::init(this); } XMLHttpRequest::~XMLHttpRequest() { #ifndef NDEBUG xmlHttpRequestCounter.decrement(); #endif } Document* XMLHttpRequest::document() const { ASSERT(scriptExecutionContext()->isDocument()); return toDocument(scriptExecutionContext()); } SecurityOrigin* XMLHttpRequest::securityOrigin() const { return m_securityOrigin ? m_securityOrigin.get() : scriptExecutionContext()->securityOrigin(); } XMLHttpRequest::State XMLHttpRequest::readyState() const { return m_state; } ScriptString XMLHttpRequest::responseText(ExceptionState& es) { if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != ResponseTypeText) { es.throwDOMException(InvalidStateError); return ScriptString(); } if (m_error || (m_state != LOADING && m_state != DONE)) return ScriptString(); return m_responseText; } Document* XMLHttpRequest::responseXML(ExceptionState& es) { if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != ResponseTypeDocument) { es.throwDOMException(InvalidStateError); return 0; } if (m_error || m_state != DONE) return 0; if (!m_createdDocument) { bool isHTML = equalIgnoringCase(responseMIMEType(), "text/html"); // The W3C spec requires the final MIME type to be some valid XML type, or text/html. // If it is text/html, then the responseType of "document" must have been supplied explicitly. if ((m_response.isHTTP() && !responseIsXML() && !isHTML) || (isHTML && m_responseTypeCode == ResponseTypeDefault) || scriptExecutionContext()->isWorkerGlobalScope()) { m_responseDocument = 0; } else { if (isHTML) m_responseDocument = HTMLDocument::create(DocumentInit(m_url)); else m_responseDocument = Document::create(DocumentInit(m_url)); // FIXME: Set Last-Modified. m_responseDocument->setContent(m_responseText.flattenToString()); m_responseDocument->setSecurityOrigin(securityOrigin()); m_responseDocument->setContextFeatures(document()->contextFeatures()); if (!m_responseDocument->wellFormed()) m_responseDocument = 0; } m_createdDocument = true; } return m_responseDocument.get(); } Blob* XMLHttpRequest::responseBlob(ExceptionState& es) { if (m_responseTypeCode != ResponseTypeBlob) { es.throwDOMException(InvalidStateError); return 0; } // We always return null before DONE. if (m_error || m_state != DONE) return 0; if (!m_responseBlob) { // FIXME: This causes two (or more) unnecessary copies of the data. // Chromium stores blob data in the browser process, so we're pulling the data // from the network only to copy it into the renderer to copy it back to the browser. // Ideally we'd get the blob/file-handle from the ResourceResponse directly // instead of copying the bytes. Embedders who store blob data in the // same process as WebCore would at least to teach BlobData to take // a SharedBuffer, even if they don't get the Blob from the network layer directly. OwnPtr<BlobData> blobData = BlobData::create(); // If we errored out or got no data, we still return a blob, just an empty one. size_t size = 0; if (m_binaryResponseBuilder) { RefPtr<RawData> rawData = RawData::create(); size = m_binaryResponseBuilder->size(); rawData->mutableData()->append(m_binaryResponseBuilder->data(), size); blobData->appendData(rawData, 0, BlobDataItem::toEndOfFile); blobData->setContentType(responseMIMEType()); // responseMIMEType defaults to text/xml which may be incorrect. m_binaryResponseBuilder.clear(); } m_responseBlob = Blob::create(blobData.release(), size); } return m_responseBlob.get(); } ArrayBuffer* XMLHttpRequest::responseArrayBuffer(ExceptionState& es) { if (m_responseTypeCode != ResponseTypeArrayBuffer) { es.throwDOMException(InvalidStateError); return 0; } if (m_error || m_state != DONE) return 0; if (!m_responseArrayBuffer.get() && m_binaryResponseBuilder.get() && m_binaryResponseBuilder->size() > 0) { m_responseArrayBuffer = m_binaryResponseBuilder->getAsArrayBuffer(); m_binaryResponseBuilder.clear(); } return m_responseArrayBuffer.get(); } void XMLHttpRequest::setTimeout(unsigned long timeout, ExceptionState& es) { // FIXME: Need to trigger or update the timeout Timer here, if needed. http://webkit.org/b/98156 // XHR2 spec, 4.7.3. "This implies that the timeout attribute can be set while fetching is in progress. If that occurs it will still be measured relative to the start of fetching." if (scriptExecutionContext()->isDocument() && !m_async) { logConsoleError(scriptExecutionContext(), "XMLHttpRequest.timeout cannot be set for synchronous HTTP(S) requests made from the window context."); es.throwDOMException(InvalidAccessError); return; } m_timeoutMilliseconds = timeout; } void XMLHttpRequest::setResponseType(const String& responseType, ExceptionState& es) { if (m_state >= LOADING) { es.throwDOMException(InvalidStateError); return; } // Newer functionality is not available to synchronous requests in window contexts, as a spec-mandated // attempt to discourage synchronous XHR use. responseType is one such piece of functionality. // We'll only disable this functionality for HTTP(S) requests since sync requests for local protocols // such as file: and data: still make sense to allow. if (!m_async && scriptExecutionContext()->isDocument() && m_url.protocolIsInHTTPFamily()) { logConsoleError(scriptExecutionContext(), "XMLHttpRequest.responseType cannot be changed for synchronous HTTP(S) requests made from the window context."); es.throwDOMException(InvalidAccessError); return; } if (responseType == "") m_responseTypeCode = ResponseTypeDefault; else if (responseType == "text") m_responseTypeCode = ResponseTypeText; else if (responseType == "document") m_responseTypeCode = ResponseTypeDocument; else if (responseType == "blob") m_responseTypeCode = ResponseTypeBlob; else if (responseType == "arraybuffer") m_responseTypeCode = ResponseTypeArrayBuffer; else ASSERT_NOT_REACHED(); } String XMLHttpRequest::responseType() { switch (m_responseTypeCode) { case ResponseTypeDefault: return ""; case ResponseTypeText: return "text"; case ResponseTypeDocument: return "document"; case ResponseTypeBlob: return "blob"; case ResponseTypeArrayBuffer: return "arraybuffer"; } return ""; } XMLHttpRequestUpload* XMLHttpRequest::upload() { if (!m_upload) m_upload = XMLHttpRequestUpload::create(this); return m_upload.get(); } void XMLHttpRequest::changeState(State newState) { if (m_state != newState) { m_state = newState; callReadyStateChangeListener(); } } void XMLHttpRequest::callReadyStateChangeListener() { if (!scriptExecutionContext()) return; InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchXHRReadyStateChangeEvent(scriptExecutionContext(), this); if (m_async || (m_state <= OPENED || m_state == DONE)) m_progressEventThrottle.dispatchReadyStateChangeEvent(XMLHttpRequestProgressEvent::create(eventNames().readystatechangeEvent), m_state == DONE ? FlushProgressEvent : DoNotFlushProgressEvent); InspectorInstrumentation::didDispatchXHRReadyStateChangeEvent(cookie); if (m_state == DONE && !m_error) { InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchXHRLoadEvent(scriptExecutionContext(), this); m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadEvent)); InspectorInstrumentation::didDispatchXHRLoadEvent(cookie); m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadendEvent)); } } void XMLHttpRequest::setWithCredentials(bool value, ExceptionState& es) { if (m_state > OPENED || m_loader) { es.throwDOMException(InvalidStateError); return; } m_includeCredentials = value; } bool XMLHttpRequest::isAllowedHTTPMethod(const String& method) { return !equalIgnoringCase(method, "TRACE") && !equalIgnoringCase(method, "TRACK") && !equalIgnoringCase(method, "CONNECT"); } String XMLHttpRequest::uppercaseKnownHTTPMethod(const String& method) { if (equalIgnoringCase(method, "COPY") || equalIgnoringCase(method, "DELETE") || equalIgnoringCase(method, "GET") || equalIgnoringCase(method, "HEAD") || equalIgnoringCase(method, "INDEX") || equalIgnoringCase(method, "LOCK") || equalIgnoringCase(method, "M-POST") || equalIgnoringCase(method, "MKCOL") || equalIgnoringCase(method, "MOVE") || equalIgnoringCase(method, "OPTIONS") || equalIgnoringCase(method, "POST") || equalIgnoringCase(method, "PROPFIND") || equalIgnoringCase(method, "PROPPATCH") || equalIgnoringCase(method, "PUT") || equalIgnoringCase(method, "UNLOCK")) { return method.upper(); } return method; } bool XMLHttpRequest::isAllowedHTTPHeader(const String& name) { initializeXMLHttpRequestStaticData(); return !staticData->m_forbiddenRequestHeaders.contains(name) && !name.startsWith(staticData->m_proxyHeaderPrefix, false) && !name.startsWith(staticData->m_secHeaderPrefix, false); } void XMLHttpRequest::open(const String& method, const KURL& url, ExceptionState& es) { open(method, url, true, es); } void XMLHttpRequest::open(const String& method, const KURL& url, bool async, ExceptionState& es) { if (!internalAbort()) return; State previousState = m_state; m_state = UNSENT; m_error = false; m_uploadComplete = false; // clear stuff from possible previous load clearResponse(); clearRequest(); ASSERT(m_state == UNSENT); if (!isValidHTTPToken(method)) { es.throwDOMException(SyntaxError); return; } if (!isAllowedHTTPMethod(method)) { es.throwDOMException(SecurityError, "'XMLHttpRequest.open' does not support the '" + method + "' method."); return; } if (!ContentSecurityPolicy::shouldBypassMainWorld(scriptExecutionContext()) && !scriptExecutionContext()->contentSecurityPolicy()->allowConnectToSource(url)) { es.throwDOMException(SecurityError, "Refused to connect to '" + url.elidedString() + "' because it violates the document's Content Security Policy."); return; } if (!async && scriptExecutionContext()->isDocument()) { if (document()->settings() && !document()->settings()->syncXHRInDocumentsEnabled()) { logConsoleError(scriptExecutionContext(), "Synchronous XMLHttpRequests are disabled for this page."); es.throwDOMException(InvalidAccessError); return; } // Newer functionality is not available to synchronous requests in window contexts, as a spec-mandated // attempt to discourage synchronous XHR use. responseType is one such piece of functionality. // We'll only disable this functionality for HTTP(S) requests since sync requests for local protocols // such as file: and data: still make sense to allow. if (url.protocolIsInHTTPFamily() && m_responseTypeCode != ResponseTypeDefault) { logConsoleError(scriptExecutionContext(), "Synchronous HTTP(S) requests made from the window context cannot have XMLHttpRequest.responseType set."); es.throwDOMException(InvalidAccessError); return; } // Similarly, timeouts are disabled for synchronous requests as well. if (m_timeoutMilliseconds > 0) { logConsoleError(scriptExecutionContext(), "Synchronous XMLHttpRequests must not have a timeout value set."); es.throwDOMException(InvalidAccessError); return; } } m_method = uppercaseKnownHTTPMethod(method); m_url = url; m_async = async; ASSERT(!m_loader); // Check previous state to avoid dispatching readyState event // when calling open several times in a row. if (previousState != OPENED) changeState(OPENED); else m_state = OPENED; } void XMLHttpRequest::open(const String& method, const KURL& url, bool async, const String& user, ExceptionState& es) { KURL urlWithCredentials(url); urlWithCredentials.setUser(user); open(method, urlWithCredentials, async, es); } void XMLHttpRequest::open(const String& method, const KURL& url, bool async, const String& user, const String& password, ExceptionState& es) { KURL urlWithCredentials(url); urlWithCredentials.setUser(user); urlWithCredentials.setPass(password); open(method, urlWithCredentials, async, es); } bool XMLHttpRequest::initSend(ExceptionState& es) { if (!scriptExecutionContext()) return false; if (m_state != OPENED || m_loader) { es.throwDOMException(InvalidStateError); return false; } m_error = false; return true; } void XMLHttpRequest::send(ExceptionState& es) { send(String(), es); } bool XMLHttpRequest::areMethodAndURLValidForSend() { return m_method != "GET" && m_method != "HEAD" && m_url.protocolIsInHTTPFamily(); } void XMLHttpRequest::send(Document* document, ExceptionState& es) { ASSERT(document); if (!initSend(es)) return; if (areMethodAndURLValidForSend()) { String contentType = getRequestHeader("Content-Type"); if (contentType.isEmpty()) { // FIXME: this should include the charset used for encoding. setRequestHeaderInternal("Content-Type", "application/xml"); } // FIXME: According to XMLHttpRequest Level 2, this should use the Document.innerHTML algorithm // from the HTML5 specification to serialize the document. String body = createMarkup(document); // FIXME: This should use value of document.inputEncoding to determine the encoding to use. m_requestEntityBody = FormData::create(UTF8Encoding().normalizeAndEncode(body, WTF::EntitiesForUnencodables)); if (m_upload) m_requestEntityBody->setAlwaysStream(true); } createRequest(es); } void XMLHttpRequest::send(const String& body, ExceptionState& es) { if (!initSend(es)) return; if (!body.isNull() && areMethodAndURLValidForSend()) { String contentType = getRequestHeader("Content-Type"); if (contentType.isEmpty()) { setRequestHeaderInternal("Content-Type", "text/plain;charset=UTF-8"); } else { replaceCharsetInMediaType(contentType, "UTF-8"); m_requestHeaders.set("Content-Type", contentType); } m_requestEntityBody = FormData::create(UTF8Encoding().normalizeAndEncode(body, WTF::EntitiesForUnencodables)); if (m_upload) m_requestEntityBody->setAlwaysStream(true); } createRequest(es); } void XMLHttpRequest::send(Blob* body, ExceptionState& es) { if (!initSend(es)) return; if (areMethodAndURLValidForSend()) { const String& contentType = getRequestHeader("Content-Type"); if (contentType.isEmpty()) { const String& blobType = body->type(); if (!blobType.isEmpty() && isValidContentType(blobType)) setRequestHeaderInternal("Content-Type", blobType); else { // From FileAPI spec, whenever media type cannot be determined, empty string must be returned. setRequestHeaderInternal("Content-Type", ""); } } // FIXME: add support for uploading bundles. m_requestEntityBody = FormData::create(); if (body->isFile()) m_requestEntityBody->appendFile(toFile(body)->path()); else m_requestEntityBody->appendBlob(body->url()); } createRequest(es); } void XMLHttpRequest::send(DOMFormData* body, ExceptionState& es) { if (!initSend(es)) return; if (areMethodAndURLValidForSend()) { m_requestEntityBody = FormData::createMultiPart(*(static_cast<FormDataList*>(body)), body->encoding(), document()); String contentType = getRequestHeader("Content-Type"); if (contentType.isEmpty()) { contentType = String("multipart/form-data; boundary=") + m_requestEntityBody->boundary().data(); setRequestHeaderInternal("Content-Type", contentType); } } createRequest(es); } void XMLHttpRequest::send(ArrayBuffer* body, ExceptionState& es) { String consoleMessage("ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead."); scriptExecutionContext()->addConsoleMessage(JSMessageSource, WarningMessageLevel, consoleMessage); HistogramSupport::histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBuffer, XMLHttpRequestSendArrayBufferOrViewMax); sendBytesData(body->data(), body->byteLength(), es); } void XMLHttpRequest::send(ArrayBufferView* body, ExceptionState& es) { HistogramSupport::histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBufferView, XMLHttpRequestSendArrayBufferOrViewMax); sendBytesData(body->baseAddress(), body->byteLength(), es); } void XMLHttpRequest::sendBytesData(const void* data, size_t length, ExceptionState& es) { if (!initSend(es)) return; if (areMethodAndURLValidForSend()) { m_requestEntityBody = FormData::create(data, length); if (m_upload) m_requestEntityBody->setAlwaysStream(true); } createRequest(es); } void XMLHttpRequest::sendForInspectorXHRReplay(PassRefPtr<FormData> formData, ExceptionState& es) { m_requestEntityBody = formData ? formData->deepCopy() : 0; createRequest(es); m_exceptionCode = es.code(); } void XMLHttpRequest::createRequest(ExceptionState& es) { // Only GET request is supported for blob URL. if (m_url.protocolIs("blob") && m_method != "GET") { es.throwDOMException(NetworkError); return; } // The presence of upload event listeners forces us to use preflighting because POSTing to an URL that does not // permit cross origin requests should look exactly like POSTing to an URL that does not respond at all. // Also, only async requests support upload progress events. bool uploadEvents = false; if (m_async) { m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadstartEvent)); if (m_requestEntityBody && m_upload) { uploadEvents = m_upload->hasEventListeners(); m_upload->dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadstartEvent)); } } m_sameOriginRequest = securityOrigin()->canRequest(m_url); // We also remember whether upload events should be allowed for this request in case the upload listeners are // added after the request is started. m_uploadEventsAllowed = m_sameOriginRequest || uploadEvents || !isSimpleCrossOriginAccessRequest(m_method, m_requestHeaders); ResourceRequest request(m_url); request.setHTTPMethod(m_method); request.setTargetType(ResourceRequest::TargetIsXHR); InspectorInstrumentation::willLoadXHR(scriptExecutionContext(), this, m_method, m_url, m_async, m_requestEntityBody ? m_requestEntityBody->deepCopy() : 0, m_requestHeaders, m_includeCredentials); if (m_requestEntityBody) { ASSERT(m_method != "GET"); ASSERT(m_method != "HEAD"); request.setHTTPBody(m_requestEntityBody.release()); } if (m_requestHeaders.size() > 0) request.addHTTPHeaderFields(m_requestHeaders); ThreadableLoaderOptions options; options.sendLoadCallbacks = SendCallbacks; options.sniffContent = DoNotSniffContent; options.preflightPolicy = uploadEvents ? ForcePreflight : ConsiderPreflight; options.allowCredentials = (m_sameOriginRequest || m_includeCredentials) ? AllowStoredCredentials : DoNotAllowStoredCredentials; options.credentialsRequested = m_includeCredentials ? ClientRequestedCredentials : ClientDidNotRequestCredentials; options.crossOriginRequestPolicy = m_allowCrossOriginRequests ? AllowCrossOriginRequests : UseAccessControl; options.securityOrigin = securityOrigin(); options.initiator = FetchInitiatorTypeNames::xmlhttprequest; options.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(scriptExecutionContext()) ? DoNotEnforceContentSecurityPolicy : EnforceConnectSrcDirective; options.timeoutMilliseconds = m_timeoutMilliseconds; m_exceptionCode = 0; m_error = false; if (m_async) { if (m_upload) request.setReportUploadProgress(true); // ThreadableLoader::create can return null here, for example if we're no longer attached to a page. // This is true while running onunload handlers. // FIXME: Maybe we need to be able to send XMLHttpRequests from onunload, <http://bugs.webkit.org/show_bug.cgi?id=10904>. // FIXME: Maybe create() can return null for other reasons too? m_loader = ThreadableLoader::create(scriptExecutionContext(), this, request, options); if (m_loader) { // Neither this object nor the JavaScript wrapper should be deleted while // a request is in progress because we need to keep the listeners alive, // and they are referenced by the JavaScript wrapper. setPendingActivity(this); } } else { request.setPriority(ResourceLoadPriorityVeryHigh); InspectorInstrumentation::willLoadXHRSynchronously(scriptExecutionContext()); ThreadableLoader::loadResourceSynchronously(scriptExecutionContext(), request, *this, options); InspectorInstrumentation::didLoadXHRSynchronously(scriptExecutionContext()); } if (!m_exceptionCode && m_error) m_exceptionCode = NetworkError; if (m_exceptionCode) es.throwDOMException(m_exceptionCode); } void XMLHttpRequest::abort() { // internalAbort() calls dropProtection(), which may release the last reference. RefPtr<XMLHttpRequest> protect(this); bool sendFlag = m_loader; if (!internalAbort()) return; clearResponseBuffers(); // Clear headers as required by the spec m_requestHeaders.clear(); if ((m_state <= OPENED && !sendFlag) || m_state == DONE) m_state = UNSENT; else { ASSERT(!m_loader); changeState(DONE); m_state = UNSENT; } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().abortEvent)); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().abortEvent)); } } bool XMLHttpRequest::internalAbort() { bool hadLoader = m_loader; m_error = true; // FIXME: when we add the support for multi-part XHR, we will have to think be careful with this initialization. m_receivedLength = 0; if (hadLoader) { // Cancelling the ThreadableLoader m_loader may result in calling // window.onload synchronously. If such an onload handler contains // open() call on the same XMLHttpRequest object, reentry happens. If // m_loader is left to be non 0, internalAbort() call for the inner // open() makes an extra dropProtection() call (when we're back to the // outer open(), we'll call dropProtection()). To avoid that, clears // m_loader before calling cancel. // // If, window.onload contains open() and send(), m_loader will be set to // non 0 value. So, we cannot continue the outer open(). In such case, // just abort the outer open() by returning false. RefPtr<ThreadableLoader> loader = m_loader.release(); loader->cancel(); } m_decoder = 0; InspectorInstrumentation::didFailXHRLoading(scriptExecutionContext(), this); if (hadLoader) dropProtectionSoon(); return !m_loader; } void XMLHttpRequest::clearResponse() { m_response = ResourceResponse(); clearResponseBuffers(); } void XMLHttpRequest::clearResponseBuffers() { m_responseText.clear(); m_responseEncoding = String(); m_createdDocument = false; m_responseDocument = 0; m_responseBlob = 0; m_binaryResponseBuilder.clear(); m_responseArrayBuffer.clear(); } void XMLHttpRequest::clearRequest() { m_requestHeaders.clear(); m_requestEntityBody = 0; } void XMLHttpRequest::genericError() { clearResponse(); clearRequest(); m_error = true; changeState(DONE); } void XMLHttpRequest::networkError() { genericError(); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().errorEvent)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().errorEvent)); internalAbort(); } void XMLHttpRequest::abortError() { genericError(); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().abortEvent)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().abortEvent)); } void XMLHttpRequest::dropProtectionSoon() { if (m_protectionTimer.isActive()) return; m_protectionTimer.startOneShot(0); } void XMLHttpRequest::dropProtection(Timer<XMLHttpRequest>*) { unsetPendingActivity(this); } void XMLHttpRequest::overrideMimeType(const String& override) { m_mimeTypeOverride = override; } void XMLHttpRequest::setRequestHeader(const AtomicString& name, const String& value, ExceptionState& es) { if (m_state != OPENED || m_loader) { es.throwDOMException(InvalidStateError); return; } if (!isValidHTTPToken(name) || !isValidHTTPHeaderValue(value)) { es.throwDOMException(SyntaxError); return; } // No script (privileged or not) can set unsafe headers. if (!isAllowedHTTPHeader(name)) { logConsoleError(scriptExecutionContext(), "Refused to set unsafe header \"" + name + "\""); return; } setRequestHeaderInternal(name, value); } void XMLHttpRequest::setRequestHeaderInternal(const AtomicString& name, const String& value) { HTTPHeaderMap::AddResult result = m_requestHeaders.add(name, value); if (!result.isNewEntry) result.iterator->value = result.iterator->value + ", " + value; } String XMLHttpRequest::getRequestHeader(const AtomicString& name) const { return m_requestHeaders.get(name); } String XMLHttpRequest::getAllResponseHeaders(ExceptionState& es) const { if (m_state < HEADERS_RECEIVED) { es.throwDOMException(InvalidStateError); return ""; } StringBuilder stringBuilder; HTTPHeaderSet accessControlExposeHeaderSet; parseAccessControlExposeHeadersAllowList(m_response.httpHeaderField("Access-Control-Expose-Headers"), accessControlExposeHeaderSet); HTTPHeaderMap::const_iterator end = m_response.httpHeaderFields().end(); for (HTTPHeaderMap::const_iterator it = m_response.httpHeaderFields().begin(); it!= end; ++it) { // Hide Set-Cookie header fields from the XMLHttpRequest client for these reasons: // 1) If the client did have access to the fields, then it could read HTTP-only // cookies; those cookies are supposed to be hidden from scripts. // 2) There's no known harm in hiding Set-Cookie header fields entirely; we don't // know any widely used technique that requires access to them. // 3) Firefox has implemented this policy. if (isSetCookieHeader(it->key) && !securityOrigin()->canLoadLocalResources()) continue; if (!m_sameOriginRequest && !isOnAccessControlResponseHeaderWhitelist(it->key) && !accessControlExposeHeaderSet.contains(it->key)) continue; stringBuilder.append(it->key); stringBuilder.append(':'); stringBuilder.append(' '); stringBuilder.append(it->value); stringBuilder.append('\r'); stringBuilder.append('\n'); } return stringBuilder.toString(); } String XMLHttpRequest::getResponseHeader(const AtomicString& name, ExceptionState& es) const { if (m_state < HEADERS_RECEIVED) { es.throwDOMException(InvalidStateError); return String(); } // See comment in getAllResponseHeaders above. if (isSetCookieHeader(name) && !securityOrigin()->canLoadLocalResources()) { logConsoleError(scriptExecutionContext(), "Refused to get unsafe header \"" + name + "\""); return String(); } HTTPHeaderSet accessControlExposeHeaderSet; parseAccessControlExposeHeadersAllowList(m_response.httpHeaderField("Access-Control-Expose-Headers"), accessControlExposeHeaderSet); if (!m_sameOriginRequest && !isOnAccessControlResponseHeaderWhitelist(name) && !accessControlExposeHeaderSet.contains(name)) { logConsoleError(scriptExecutionContext(), "Refused to get unsafe header \"" + name + "\""); return String(); } return m_response.httpHeaderField(name); } String XMLHttpRequest::responseMIMEType() const { String mimeType = extractMIMETypeFromMediaType(m_mimeTypeOverride); if (mimeType.isEmpty()) { if (m_response.isHTTP()) mimeType = extractMIMETypeFromMediaType(m_response.httpHeaderField("Content-Type")); else mimeType = m_response.mimeType(); } if (mimeType.isEmpty()) mimeType = "text/xml"; return mimeType; } bool XMLHttpRequest::responseIsXML() const { // FIXME: Remove the lower() call when DOMImplementation.isXMLMIMEType() is modified // to do case insensitive MIME type matching. return DOMImplementation::isXMLMIMEType(responseMIMEType().lower()); } int XMLHttpRequest::status(ExceptionState& es) const { if (m_response.httpStatusCode()) return m_response.httpStatusCode(); if (m_state == OPENED) { // Firefox only raises an exception in this state; we match it. // Note the case of local file requests, where we have no HTTP response code! Firefox never raises an exception for those, but we match HTTP case for consistency. es.throwDOMException(InvalidStateError); } return 0; } String XMLHttpRequest::statusText(ExceptionState& es) const { if (!m_response.httpStatusText().isNull()) return m_response.httpStatusText(); if (m_state == OPENED) { // See comments in status() above. es.throwDOMException(InvalidStateError); } return String(); } void XMLHttpRequest::didFail(const ResourceError& error) { // If we are already in an error state, for instance we called abort(), bail out early. if (m_error) return; if (error.isCancellation()) { m_exceptionCode = AbortError; abortError(); return; } if (error.isTimeout()) { didTimeout(); return; } // Network failures are already reported to Web Inspector by ResourceLoader. if (error.domain() == errorDomainWebKitInternal) logConsoleError(scriptExecutionContext(), "XMLHttpRequest cannot load " + error.failingURL() + ". " + error.localizedDescription()); m_exceptionCode = NetworkError; networkError(); } void XMLHttpRequest::didFailRedirectCheck() { networkError(); } void XMLHttpRequest::didFinishLoading(unsigned long identifier, double) { if (m_error) return; if (m_state < HEADERS_RECEIVED) changeState(HEADERS_RECEIVED); if (m_decoder) m_responseText = m_responseText.concatenateWith(m_decoder->flush()); InspectorInstrumentation::didFinishXHRLoading(scriptExecutionContext(), this, identifier, m_responseText, m_url, m_lastSendURL, m_lastSendLineNumber); bool hadLoader = m_loader; m_loader = 0; changeState(DONE); m_responseEncoding = String(); m_decoder = 0; if (hadLoader) dropProtection(); } void XMLHttpRequest::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) { if (!m_upload) return; if (m_uploadEventsAllowed) m_upload->dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().progressEvent, true, bytesSent, totalBytesToBeSent)); if (bytesSent == totalBytesToBeSent && !m_uploadComplete) { m_uploadComplete = true; if (m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().loadEvent)); } } void XMLHttpRequest::didReceiveResponse(unsigned long identifier, const ResourceResponse& response) { InspectorInstrumentation::didReceiveXHRResponse(scriptExecutionContext(), identifier); m_response = response; if (!m_mimeTypeOverride.isEmpty()) { m_response.setHTTPHeaderField("Content-Type", m_mimeTypeOverride); m_responseEncoding = extractCharsetFromMediaType(m_mimeTypeOverride); } if (m_responseEncoding.isEmpty()) m_responseEncoding = response.textEncodingName(); } void XMLHttpRequest::didReceiveData(const char* data, int len) { if (m_error) return; if (m_state < HEADERS_RECEIVED) changeState(HEADERS_RECEIVED); bool useDecoder = m_responseTypeCode == ResponseTypeDefault || m_responseTypeCode == ResponseTypeText || m_responseTypeCode == ResponseTypeDocument; if (useDecoder && !m_decoder) { if (!m_responseEncoding.isEmpty()) m_decoder = TextResourceDecoder::create("text/plain", m_responseEncoding); // allow TextResourceDecoder to look inside the m_response if it's XML or HTML else if (responseIsXML()) { m_decoder = TextResourceDecoder::create("application/xml"); // Don't stop on encoding errors, unlike it is done for other kinds of XML resources. This matches the behavior of previous WebKit versions, Firefox and Opera. m_decoder->useLenientXMLDecoding(); } else if (equalIgnoringCase(responseMIMEType(), "text/html")) m_decoder = TextResourceDecoder::create("text/html", "UTF-8"); else m_decoder = TextResourceDecoder::create("text/plain", "UTF-8"); } if (!len) return; if (len == -1) len = strlen(data); if (useDecoder) m_responseText = m_responseText.concatenateWith(m_decoder->decode(data, len)); else if (m_responseTypeCode == ResponseTypeArrayBuffer || m_responseTypeCode == ResponseTypeBlob) { // Buffer binary data. if (!m_binaryResponseBuilder) m_binaryResponseBuilder = SharedBuffer::create(); m_binaryResponseBuilder->append(data, len); } if (!m_error) { long long expectedLength = m_response.expectedContentLength(); m_receivedLength += len; if (m_async) { bool lengthComputable = expectedLength > 0 && m_receivedLength <= expectedLength; unsigned long long total = lengthComputable ? expectedLength : 0; m_progressEventThrottle.dispatchProgressEvent(lengthComputable, m_receivedLength, total); } if (m_state != LOADING) changeState(LOADING); else // Firefox calls readyStateChanged every time it receives data, 4449442 callReadyStateChangeListener(); } } void XMLHttpRequest::didTimeout() { // internalAbort() calls dropProtection(), which may release the last reference. RefPtr<XMLHttpRequest> protect(this); if (!internalAbort()) return; clearResponse(); clearRequest(); m_error = true; m_exceptionCode = TimeoutError; if (!m_async) { m_state = DONE; m_exceptionCode = TimeoutError; return; } changeState(DONE); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } bool XMLHttpRequest::canSuspend() const { return !m_loader; } void XMLHttpRequest::suspend(ReasonForSuspension) { m_progressEventThrottle.suspend(); } void XMLHttpRequest::resume() { m_progressEventThrottle.resume(); } void XMLHttpRequest::stop() { internalAbort(); } void XMLHttpRequest::contextDestroyed() { ASSERT(!m_loader); ActiveDOMObject::contextDestroyed(); } const AtomicString& XMLHttpRequest::interfaceName() const { return eventNames().interfaceForXMLHttpRequest; } ScriptExecutionContext* XMLHttpRequest::scriptExecutionContext() const { return ActiveDOMObject::scriptExecutionContext(); } EventTargetData* XMLHttpRequest::eventTargetData() { return &m_eventTargetData; } EventTargetData* XMLHttpRequest::ensureEventTargetData() { return &m_eventTargetData; } } // namespace WebCore
indashnet/InDashNet.Open.UN2000
android/external/chromium_org/third_party/WebKit/Source/core/xml/XMLHttpRequest.cpp
C++
apache-2.0
44,885
""" Contains POST and GET web operations for OpenData Python Package. """ #from __future__ import absolute_import from __future__ import print_function from __future__ import absolute_import import io import os import re import sys import json import uuid import zlib import shutil import tempfile import mimetypes import email.generator from io import BytesIO try: from cStringIO import StringIO except: from io import StringIO from ..packages.six.moves.urllib import request from ..packages.six.moves import http_cookiejar as cookiejar from ..packages.six.moves.urllib_parse import urlencode ######################################################################## __version__ = "3.5.6" ######################################################################## class RedirectHandler(request.HTTPRedirectHandler): def http_error_301(self, req, fp, code, msg, headers): result = request.HTTPRedirectHandler.http_error_301( self, req, fp, code, msg, headers) result.status = code return result #---------------------------------------------------------------------- def http_error_302(self, req, fp, code, msg, headers): result = request.HTTPRedirectHandler.http_error_302( self, req, fp, code, msg, headers) result.status = code return result ######################################################################## class MultiPartForm(object): """Accumulate the data to be used when posting a form.""" PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 files = [] form_fields = [] boundary = None form_data = "" #---------------------------------------------------------------------- def __init__(self, param_dict={}, files={}): if len(param_dict) == 0: self.form_fields = [] else: for k,v in param_dict.items(): self.form_fields.append((k,v)) del k,v if len(files) == 0: self.files = [] else: for key,v in files.items(): self.add_file(fieldname=key, filename=os.path.basename(v), filePath=v, mimetype=None) self.boundary = email.generator._make_boundary() #---------------------------------------------------------------------- def get_content_type(self): return 'multipart/form-data; boundary=%s' % self.boundary #---------------------------------------------------------------------- def add_field(self, name, value): """Add a simple field to the form data.""" self.form_fields.append((name, value)) #---------------------------------------------------------------------- def add_file(self, fieldname, filename, filePath, mimetype=None): """Add a file to be uploaded. Inputs: fieldname - name of the POST value fieldname - name of the file to pass to the server filePath - path to the local file on disk mimetype - MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format. Default is None. """ body = filePath if mimetype is None: mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' self.files.append((fieldname, filename, mimetype, body)) #---------------------------------------------------------------------- @property def make_result(self): if self.PY2: self._2() elif self.PY3: self._3() return self.form_data #---------------------------------------------------------------------- def _2(self): """python 2.x version of formatting body data""" boundary = self.boundary buf = StringIO() for (key, value) in self.form_fields: buf.write('--%s\r\n' % boundary) buf.write('Content-Disposition: form-data; name="%s"' % key) buf.write('\r\n\r\n%s\r\n' % value) for (key, filename, mimetype, filepath) in self.files: if os.path.isfile(filepath): buf.write('--{boundary}\r\n' 'Content-Disposition: form-data; name="{key}"; ' 'filename="{filename}"\r\n' 'Content-Type: {content_type}\r\n\r\n'.format( boundary=boundary, key=key, filename=filename, content_type=mimetype)) with open(filepath, "rb") as f: shutil.copyfileobj(f, buf) buf.write('\r\n') buf.write('--' + boundary + '--\r\n\r\n') buf = buf.getvalue() self.form_data = buf #---------------------------------------------------------------------- def _3(self): """ python 3 method""" boundary = self.boundary buf = BytesIO() textwriter = io.TextIOWrapper( buf, 'utf8', newline='', write_through=True) for (key, value) in self.form_fields: textwriter.write( '--{boundary}\r\n' 'Content-Disposition: form-data; name="{key}"\r\n\r\n' '{value}\r\n'.format( boundary=boundary, key=key, value=value)) for(key, filename, mimetype, filepath) in self.files: if os.path.isfile(filepath): textwriter.write( '--{boundary}\r\n' 'Content-Disposition: form-data; name="{key}"; ' 'filename="{filename}"\r\n' 'Content-Type: {content_type}\r\n\r\n'.format( boundary=boundary, key=key, filename=filename, content_type=mimetype)) with open(filepath, "rb") as f: shutil.copyfileobj(f, buf) textwriter.write('\r\n') textwriter.write('--{}--\r\n\r\n'.format(boundary)) self.form_data = buf.getvalue() ######################################################################## class WebOperations(object): """performs the get/post operations""" PY3 = sys.version_info[0] == 3 PY2 = sys.version_info[0] == 2 _referer_url = None _last_url = None _last_code = None _last_method = None _useragent = "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0" #---------------------------------------------------------------------- @property def last_method(self): """gets the last method used (either POST or GET)""" return self._last_method #---------------------------------------------------------------------- @property def last_code(self): """gets the last code from the last web operation""" return self._last_code #---------------------------------------------------------------------- @property def last_url(self): """gets the last web url called""" return self._last_url #---------------------------------------------------------------------- @property def referer_url(self): """gets/sets the referer url value""" return self._referer_url #---------------------------------------------------------------------- @referer_url.setter def referer_url(self, value): """gets/sets the referer url value""" if self._referer_url != value: self._referer_url = value #---------------------------------------------------------------------- @property def useragent(self): """gets/sets the user agent value""" return self._useragent #---------------------------------------------------------------------- @useragent.setter def useragent(self, value): """gets/sets the user agent value""" if value is None: self._useragent = "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0" elif self._useragent != value: self._useragent = value #---------------------------------------------------------------------- def _get_file_name(self, contentDisposition, url, ext=".unknown"): """ gets the file name from the header or url if possible """ if self.PY2: if contentDisposition is not None: return re.findall(r'filename[^;=\n]*=(([\'"]).*?\2|[^;\n]*)', contentDisposition.strip().replace('"', ''))[0][0] elif os.path.basename(url).find('.') > -1: return os.path.basename(url) elif self.PY3: if contentDisposition is not None: p = re.compile(r'filename[^;=\n]*=(([\'"]).*?\2|[^;\n]*)') return p.findall(contentDisposition.strip().replace('"', ''))[0][0] elif os.path.basename(url).find('.') > -1: return os.path.basename(url) return "%s.%s" % (uuid.uuid4().get_hex(), ext) #---------------------------------------------------------------------- def _processHandler(self, securityHandler, param_dict): """proceses the handler and returns the cookiejar""" cj = None handler = None if securityHandler is None: cj = cookiejar.CookieJar() elif securityHandler.method.lower() == "token": param_dict['token'] = securityHandler.token if hasattr(securityHandler, 'cookiejar'): cj = securityHandler.cookiejar if hasattr(securityHandler, 'handler'): handler = securityHandler.handler elif securityHandler.method.lower() == "handler": handler = securityHandler.handler cj = securityHandler.cookiejar return param_dict, handler, cj #---------------------------------------------------------------------- def _process_response(self, resp, out_folder=None): """ processes the response object""" CHUNK = 4056 maintype = self._mainType(resp) contentDisposition = resp.headers.get('content-disposition') contentEncoding = resp.headers.get('content-encoding') contentType = resp.headers.get('content-type') contentLength = resp.headers.get('content-length') if maintype.lower() in ('image', 'application/x-zip-compressed') or \ contentType == 'application/x-zip-compressed' or \ (contentDisposition is not None and \ contentDisposition.lower().find('attachment;') > -1): fname = self._get_file_name( contentDisposition=contentDisposition, url=resp.geturl()) if out_folder is None: out_folder = tempfile.gettempdir() if contentLength is not None: max_length = int(contentLength) if max_length < CHUNK: CHUNK = max_length file_name = os.path.join(out_folder, fname) with open(file_name, 'wb') as writer: for data in self._chunk(response=resp): writer.write(data) del data del writer return file_name else: read = "" for data in self._chunk(response=resp, size=4096): if self.PY3 == True: read += data.decode('utf-8') else: read += data del data try: return json.loads(read.strip()) except: return read return None #---------------------------------------------------------------------- def _make_boundary(self): """ creates a boundary for multipart post (form post)""" if self.PY2: return '===============%s==' % uuid.uuid4().get_hex() elif self.PY3: return '===============%s==' % uuid.uuid4().hex else: from random import choice digits = "0123456789" letters = "abcdefghijklmnopqrstuvwxyz" return '===============%s==' % ''.join(choice(letters + digits) \ for i in range(15)) #---------------------------------------------------------------------- def _get_content_type(self, filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream' #---------------------------------------------------------------------- def _mainType(self, resp): """ gets the main type from the response object""" if self.PY2: return resp.headers.maintype elif self.PY3: return resp.headers.get_content_maintype() else: return None #---------------------------------------------------------------------- def _chunk(self, response, size=4096): """ downloads a web response in pieces """ method = response.headers.get("content-encoding") if method == "gzip": d = zlib.decompressobj(16+zlib.MAX_WBITS) b = response.read(size) while b: data = d.decompress(b) yield data b = response.read(size) del data else: while True: chunk = response.read(size) if not chunk: break yield chunk #---------------------------------------------------------------------- def _post(self, url, param_dict={}, files={}, securityHandler=None, additional_headers={}, custom_handlers=[], proxy_url=None, proxy_port=80, compress=True, out_folder=None, file_name=None): """ Performs a POST operation on a URL. Inputs: param_dict - key/value pair of values ex: {"foo": "bar"} files - key/value pair of file objects where the key is the input name and the value is the file path ex: {"file": r"c:\temp\myfile.zip"} securityHandler - object that handles the token or other site security. It must inherit from the base security class. ex: arcrest.AGOLSecurityHandler("SomeUsername", "SOMEPASSWORD") additional_headers - are additional key/value headers that a user wants to pass during the operation. ex: {"accept-encoding": "gzip"} custom_handlers - this is additional web operation handlers as a list of objects. Ex: [CustomAuthHandler] proxy_url - url of the proxy proxy_port - default 80, port number of the proxy compress - default true, determines if gzip should be used of not for the web operation. out_folder - if the URL requested returns a file, this will be the disk save location file_name - if the operation returns a file and the file name is not given in the header or a user wishes to override the return saved file name, provide value here. Output: returns dictionary or string depending on web operation. """ self._last_method = "POST" headers = {} opener = None return_value = None handlers = [RedirectHandler()] param_dict, handler, cj = self._processHandler(securityHandler, param_dict) if handler is not None: handlers.append(handler) if cj is not None: handlers.append(request.HTTPCookieProcessor(cj)) if isinstance(custom_handlers, list) and \ len(custom_handlers) > 0: for h in custom_handlers: handlers.append(h) if compress: headers['Accept-Encoding'] = 'gzip' else: headers['Accept-Encoding'] = '' for k,v in additional_headers.items(): headers[k] = v del k,v opener = request.build_opener(*handlers) request.install_opener(opener) opener.addheaders = [(k,v) for k,v in headers.items()] if len(files) == 0: data = urlencode(param_dict) if self.PY3: data = data.encode('ascii') opener.data = data resp = opener.open(url, data=data) else: mpf = MultiPartForm(param_dict=param_dict, files=files) req = request.Request(url) body = mpf.make_result req.add_header('User-agent', self.useragent) req.add_header('Content-type', mpf.get_content_type()) req.add_header('Content-length', len(body)) req.data = body resp = request.urlopen(req) self._last_code = resp.getcode() self._last_url = resp.geturl() return_value = self._process_response(resp=resp, out_folder=out_folder) if isinstance(return_value, dict): if "error" in return_value and \ 'message' in return_value['error']: if return_value['error']['message'].lower() == 'request not made over ssl': if url.startswith('http://'): url = url.replace('http://', 'https://') return self._post(url, param_dict, files, securityHandler, additional_headers, custom_handlers, proxy_url, proxy_port, compress, out_folder, file_name) return return_value else: return return_value return return_value #---------------------------------------------------------------------- def _get(self, url, param_dict={}, securityHandler=None, additional_headers=[], handlers=[], proxy_url=None, proxy_port=None, compress=True, custom_handlers=[], out_folder=None, file_name=None): """ Performs a GET operation Inputs: Output: returns dictionary, string or None """ self._last_method = "GET" CHUNK = 4056 param_dict, handler, cj = self._processHandler(securityHandler, param_dict) headers = [] + additional_headers if compress: headers.append(('Accept-encoding', 'gzip')) else: headers.append(('Accept-encoding', '')) headers.append(('User-Agent', self.useragent)) if len(param_dict.keys()) == 0: param_dict = None if handlers is None: handlers = [] if handler is not None: handlers.append(handler) handlers.append(RedirectHandler()) if cj is not None: handlers.append(request.HTTPCookieProcessor(cj)) if proxy_url is not None: if proxy_port is None: proxy_port = 80 proxies = {"http":"http://%s:%s" % (proxy_url, proxy_port), "https":"https://%s:%s" % (proxy_url, proxy_port)} proxy_support = request.ProxyHandler(proxies) handlers.append(proxy_support) opener = request.build_opener(*handlers) opener.addheaders = headers if param_dict is None: resp = opener.open(url, data=param_dict) elif len(str(urlencode(param_dict))) + len(url) >= 1999: resp = opener.open(url, data=urlencode(param_dict)) else: format_url = url + "?%s" % urlencode(param_dict) resp = opener.open(fullurl=format_url) self._last_code = resp.getcode() self._last_url = resp.geturl() # Get some headers from the response maintype = self._mainType(resp) contentDisposition = resp.headers.get('content-disposition') contentEncoding = resp.headers.get('content-encoding') contentType = resp.headers.get('content-Type').split(';')[0].lower() contentLength = resp.headers.get('content-length') if maintype.lower() in ('image', 'application/x-zip-compressed') or \ contentType == 'application/x-zip-compressed' or \ (contentDisposition is not None and \ contentDisposition.lower().find('attachment;') > -1): fname = self._get_file_name( contentDisposition=contentDisposition, url=url) if out_folder is None: out_folder = tempfile.gettempdir() if contentLength is not None: max_length = int(contentLength) if max_length < CHUNK: CHUNK = max_length file_name = os.path.join(out_folder, fname) with open(file_name, 'wb') as writer: for data in self._chunk(response=resp, size=CHUNK): writer.write(data) writer.flush() writer.flush() del writer return file_name else: read = "" for data in self._chunk(response=resp, size=CHUNK): if self.PY3 == True: read += data.decode('utf-8') else: read += data del data try: results = json.loads(read) if 'error' in results: if 'message' in results['error']: if results['error']['message'] == 'Request not made over ssl': if url.startswith('http://'): url = url.replace('http://', 'https://') return self._get(url, param_dict, securityHandler, additional_headers, handlers, proxy_url, proxy_port, compress, custom_handlers, out_folder, file_name) return results except: return read
pLeBlanc93/ArcREST
src/arcrest/opendata/_web.py
Python
apache-2.0
23,187
namespace NetSpec.TestProject.LineSpecTest { using Core; using Core.Ex; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class LineSpecUnitTest { #region " Métodos " [TestMethod] [ExpectedException(typeof(NullSpecificationLineException))] public void LineSpecConstructor_ComArgumentoNulo_Test() { // Arrange string anSpecificationLine = null; // Act var target = new LineSpec(anSpecificationLine); } [TestMethod] public void LineSpecConstructor_ComArgumentoVálido_Test() { // Arrange const string anSpecificationLine = "uma linha"; // Act var target = new LineSpec(anSpecificationLine); // Assert Assert.AreEqual(target.Text, "uma linha"); } #endregion } }
Diullei/NetSpec
src/NetSpec/NetSpec.TestProject/LineSpecTest/LineSpecUnitTest.cs
C#
apache-2.0
927
'use strict'; angular.module('jhipstersampleApp') .controller('SettingController', function ($scope, $state, Setting) { $scope.settings = []; $scope.loadAll = function() { Setting.query(function(result) { $scope.settings = result; }); }; $scope.loadAll(); $scope.refresh = function () { $scope.loadAll(); $scope.clear(); }; $scope.clear = function () { $scope.setting = { weeklyGoal: null, weightUnit: null, id: null }; }; });
marhan/jhipstersample
src/main/webapp/scripts/app/entities/setting/setting.controller.js
JavaScript
apache-2.0
639
# Franklandia fucifolia R.Br. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Proteales/Proteaceae/Franklandia/Franklandia fucifolia/README.md
Markdown
apache-2.0
177
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_02) on Tue Oct 20 05:53:12 CEST 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>CopyProcessingSpec (Gradle API 2.8)</title> <meta name="date" content="2015-10-20"> <link rel="stylesheet" type="text/css" href="../../../../javadoc.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="CopyProcessingSpec (Gradle API 2.8)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/gradle/api/file/ContentFilterable.html" title="interface in org.gradle.api.file"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/gradle/api/file/CopySourceSpec.html" title="interface in org.gradle.api.file"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/gradle/api/file/CopyProcessingSpec.html" target="_top">Frames</a></li> <li><a href="CopyProcessingSpec.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.gradle.api.file</div> <h2 title="Interface CopyProcessingSpec" class="title">Interface CopyProcessingSpec</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Superinterfaces:</dt> <dd><a href="../../../../org/gradle/api/file/ContentFilterable.html" title="interface in org.gradle.api.file">ContentFilterable</a></dd> </dl> <dl> <dt>All Known Subinterfaces:</dt> <dd><a href="../../../../org/gradle/api/file/CopySpec.html" title="interface in org.gradle.api.file">CopySpec</a></dd> </dl> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../org/gradle/api/tasks/bundling/AbstractArchiveTask.html" title="class in org.gradle.api.tasks.bundling">AbstractArchiveTask</a>, <a href="../../../../org/gradle/api/tasks/AbstractCopyTask.html" title="class in org.gradle.api.tasks">AbstractCopyTask</a>, <a href="../../../../org/gradle/api/tasks/Copy.html" title="class in org.gradle.api.tasks">Copy</a>, <a href="../../../../org/gradle/jvm/tasks/Jar.html" title="class in org.gradle.jvm.tasks">Jar</a>, <a href="../../../../org/gradle/language/jvm/tasks/ProcessResources.html" title="class in org.gradle.language.jvm.tasks">ProcessResources</a>, <a href="../../../../org/gradle/api/tasks/Sync.html" title="class in org.gradle.api.tasks">Sync</a>, <a href="../../../../org/gradle/api/tasks/bundling/Tar.html" title="class in org.gradle.api.tasks.bundling">Tar</a>, <a href="../../../../org/gradle/api/tasks/bundling/Zip.html" title="class in org.gradle.api.tasks.bundling">Zip</a></dd> </dl> <hr> <br> <pre>public interface <span class="strong">CopyProcessingSpec</span> extends <a href="../../../../org/gradle/api/file/ContentFilterable.html" title="interface in org.gradle.api.file">ContentFilterable</a></pre> <div class="block">Specifies the destination of a copy.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html#eachFile(org.gradle.api.Action)">eachFile</a></strong>(<a href="../../../../org/gradle/api/Action.html" title="interface in org.gradle.api">Action</a>&lt;? super <a href="../../../../org/gradle/api/file/FileCopyDetails.html" title="interface in org.gradle.api.file">FileCopyDetails</a>&gt;&nbsp;action)</code> <div class="block">Adds an action to be applied to each file as it is about to be copied into its destination.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html#eachFile(groovy.lang.Closure)">eachFile</a></strong>(<a href="http://docs.groovy-lang.org/docs/groovy-2.4.4/html/gapi/groovy/lang/Closure.html?is-external=true" title="class or interface in groovy.lang">Closure</a>&nbsp;closure)</code> <div class="block">Adds an action to be applied to each file as it about to be copied into its destination.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html?is-external=true" title="class or interface in java.lang">Integer</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html#getDirMode()">getDirMode</a></strong>()</code> <div class="block">Returns the Unix permissions to use for the target directories.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html?is-external=true" title="class or interface in java.lang">Integer</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html#getFileMode()">getFileMode</a></strong>()</code> <div class="block">Returns the Unix permissions to use for the target files.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html#into(java.lang.Object)">into</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;destPath)</code> <div class="block">Specifies the destination directory for a copy.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html#rename(groovy.lang.Closure)">rename</a></strong>(<a href="http://docs.groovy-lang.org/docs/groovy-2.4.4/html/gapi/groovy/lang/Closure.html?is-external=true" title="class or interface in groovy.lang">Closure</a>&nbsp;closure)</code> <div class="block">Renames a source file to a different relative location under the target directory.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html#rename(java.util.regex.Pattern, java.lang.String)">rename</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html?is-external=true" title="class or interface in java.util.regex">Pattern</a>&nbsp;sourceRegEx, <a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;replaceWith)</code> <div class="block">Renames files based on a regular expression.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html#rename(java.lang.String, java.lang.String)">rename</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;sourceRegEx, <a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;replaceWith)</code> <div class="block">Renames files based on a regular expression.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html#setDirMode(java.lang.Integer)">setDirMode</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html?is-external=true" title="class or interface in java.lang">Integer</a>&nbsp;mode)</code> <div class="block">Sets the Unix permissions to use for the target directories.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a></code></td> <td class="colLast"><code><strong><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html#setFileMode(java.lang.Integer)">setFileMode</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html?is-external=true" title="class or interface in java.lang">Integer</a>&nbsp;mode)</code> <div class="block">Sets the Unix permissions to use for the target files.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.gradle.api.file.ContentFilterable"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;org.gradle.api.file.<a href="../../../../org/gradle/api/file/ContentFilterable.html" title="interface in org.gradle.api.file">ContentFilterable</a></h3> <code><a href="../../../../org/gradle/api/file/ContentFilterable.html#expand(java.util.Map)">expand</a>, <a href="../../../../org/gradle/api/file/ContentFilterable.html#filter(java.lang.Class)">filter</a>, <a href="../../../../org/gradle/api/file/ContentFilterable.html#filter(groovy.lang.Closure)">filter</a>, <a href="../../../../org/gradle/api/file/ContentFilterable.html#filter(java.util.Map, java.lang.Class)">filter</a></code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="into(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>into</h4> <pre><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a>&nbsp;into(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;destPath)</pre> <div class="block">Specifies the destination directory for a copy. The destination is evaluated as per <a href="../../../../org/gradle/api/Project.html#file(java.lang.Object)"><code>Project.file(Object)</code></a>.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>destPath</code> - Path to the destination directory for a Copy</dd> <dt><span class="strong">Returns:</span></dt><dd>this</dd></dl> </li> </ul> <a name="rename(groovy.lang.Closure)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>rename</h4> <pre><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a>&nbsp;rename(<a href="http://docs.groovy-lang.org/docs/groovy-2.4.4/html/gapi/groovy/lang/Closure.html?is-external=true" title="class or interface in groovy.lang">Closure</a>&nbsp;closure)</pre> <div class="block">Renames a source file to a different relative location under the target directory. The closure will be called with a single parameter, the name of the file. The closure should return a String object with a new target name. The closure may return null, in which case the original name will be used.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>closure</code> - rename closure</dd> <dt><span class="strong">Returns:</span></dt><dd>this</dd></dl> </li> </ul> <a name="rename(java.lang.String, java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>rename</h4> <pre><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a>&nbsp;rename(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;sourceRegEx, <a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;replaceWith)</pre> <div class="block">Renames files based on a regular expression. Uses java.util.regex type of regular expressions. Note that the replace string should use the '$1' syntax to refer to capture groups in the source regular expression. Files that do not match the source regular expression will be copied with the original name. <p> Example: <pre> rename '(.*)_OEM_BLUE_(.*)', '$1$2' </pre> would map the file 'style_OEM_BLUE_.css' to 'style.css'</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>sourceRegEx</code> - Source regular expression</dd><dd><code>replaceWith</code> - Replacement string (use $ syntax for capture groups)</dd> <dt><span class="strong">Returns:</span></dt><dd>this</dd></dl> </li> </ul> <a name="rename(java.util.regex.Pattern, java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>rename</h4> <pre><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a>&nbsp;rename(<a href="https://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html?is-external=true" title="class or interface in java.util.regex">Pattern</a>&nbsp;sourceRegEx, <a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;replaceWith)</pre> <div class="block">Renames files based on a regular expression. See <a href="../../../../org/gradle/api/file/CopyProcessingSpec.html#rename(java.lang.String, java.lang.String)"><code>rename(String, String)</code></a>.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>sourceRegEx</code> - Source regular expression</dd><dd><code>replaceWith</code> - Replacement string (use $ syntax for capture groups)</dd> <dt><span class="strong">Returns:</span></dt><dd>this</dd></dl> </li> </ul> <a name="getFileMode()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getFileMode</h4> <pre><a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html?is-external=true" title="class or interface in java.lang">Integer</a>&nbsp;getFileMode()</pre> <div class="block">Returns the Unix permissions to use for the target files. <code>null</code> means that existing permissions are preserved. It is dependent on the copy action implementation whether these permissions will actually be applied.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>The file permissions, or <code>null</code> if existing permissions should be preserved.</dd></dl> </li> </ul> <a name="setFileMode(java.lang.Integer)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setFileMode</h4> <pre><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a>&nbsp;setFileMode(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html?is-external=true" title="class or interface in java.lang">Integer</a>&nbsp;mode)</pre> <div class="block">Sets the Unix permissions to use for the target files. <code>null</code> means that existing permissions are preserved. It is dependent on the copy action implementation whether these permissions will actually be applied.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>mode</code> - The file permissions.</dd> <dt><span class="strong">Returns:</span></dt><dd>this</dd></dl> </li> </ul> <a name="getDirMode()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getDirMode</h4> <pre><a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html?is-external=true" title="class or interface in java.lang">Integer</a>&nbsp;getDirMode()</pre> <div class="block">Returns the Unix permissions to use for the target directories. <code>null</code> means that existing permissions are preserved. It is dependent on the copy action implementation whether these permissions will actually be applied.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>The directory permissions, or <code>null</code> if existing permissions should be preserved.</dd></dl> </li> </ul> <a name="setDirMode(java.lang.Integer)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setDirMode</h4> <pre><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a>&nbsp;setDirMode(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html?is-external=true" title="class or interface in java.lang">Integer</a>&nbsp;mode)</pre> <div class="block">Sets the Unix permissions to use for the target directories. <code>null</code> means that existing permissions are preserved. It is dependent on the copy action implementation whether these permissions will actually be applied.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>mode</code> - The directory permissions.</dd> <dt><span class="strong">Returns:</span></dt><dd>this</dd></dl> </li> </ul> <a name="eachFile(org.gradle.api.Action)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>eachFile</h4> <pre><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a>&nbsp;eachFile(<a href="../../../../org/gradle/api/Action.html" title="interface in org.gradle.api">Action</a>&lt;? super <a href="../../../../org/gradle/api/file/FileCopyDetails.html" title="interface in org.gradle.api.file">FileCopyDetails</a>&gt;&nbsp;action)</pre> <div class="block">Adds an action to be applied to each file as it is about to be copied into its destination. The action can change the destination path of the file, filter the contents of the file, or exclude the file from the result entirely. Actions are executed in the order added, and are inherited from the parent spec.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>action</code> - The action to execute.</dd> <dt><span class="strong">Returns:</span></dt><dd>this</dd></dl> </li> </ul> <a name="eachFile(groovy.lang.Closure)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>eachFile</h4> <pre><a href="../../../../org/gradle/api/file/CopyProcessingSpec.html" title="interface in org.gradle.api.file">CopyProcessingSpec</a>&nbsp;eachFile(<a href="http://docs.groovy-lang.org/docs/groovy-2.4.4/html/gapi/groovy/lang/Closure.html?is-external=true" title="class or interface in groovy.lang">Closure</a>&nbsp;closure)</pre> <div class="block">Adds an action to be applied to each file as it about to be copied into its destination. The given closure is called with a <a href="../../../../org/gradle/api/file/FileCopyDetails.html" title="interface in org.gradle.api.file"><code>FileCopyDetails</code></a> as its parameter. Actions are executed in the order added, and are inherited from the parent spec.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>closure</code> - The action to execute.</dd> <dt><span class="strong">Returns:</span></dt><dd>this</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/gradle/api/file/ContentFilterable.html" title="interface in org.gradle.api.file"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/gradle/api/file/CopySourceSpec.html" title="interface in org.gradle.api.file"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/gradle/api/file/CopyProcessingSpec.html" target="_top">Frames</a></li> <li><a href="CopyProcessingSpec.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
FinishX/coolweather
gradle/gradle-2.8/docs/javadoc/org/gradle/api/file/CopyProcessingSpec.html
HTML
apache-2.0
24,339
# Lophiotricha viburni Richon SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Bull. Soc. bot. Fr. 32: XI (1885) #### Original name Lophiotricha viburni Richon ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Lophiostomataceae/Lophiotricha/Lophiotricha viburni/README.md
Markdown
apache-2.0
212
/* Copyright 2015 Cyril Delmas 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.cdelmas.spike.dropwizard.car; import io.dropwizard.auth.Auth; import io.github.cdelmas.spike.common.auth.User; import io.github.cdelmas.spike.common.domain.Car; import io.github.cdelmas.spike.common.domain.CarRepository; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import java.util.List; import static java.util.stream.Collectors.toList; @Path("/cars") public class CarsResource { @Context UriInfo uriInfo; @Inject private CarRepository carRepository; @GET @Produces(MediaType.APPLICATION_JSON) public Response all(@Auth User user) { List<Car> cars = carRepository.all(); List<CarRepresentation> representations = cars.stream() .map(c -> { CarRepresentation representation = new CarRepresentation(c); representation.addLink(io.github.cdelmas.spike.common.hateoas.Link.self(uriInfo.getAbsolutePathBuilder().build(c.getId()).toString())); return representation; }).collect(toList()); return Response.ok(representations) .header("total-count", String.valueOf(cars.size())) .build(); } @POST @Consumes(MediaType.APPLICATION_JSON) public Response createCar(@Auth User user, Car car) { carRepository.save(car); return Response.created(UriBuilder.fromResource(CarsResource.class).path("/{id}").build(String.valueOf(car.getId()))) .build(); } }
cdelmas/microservices-comparison
dropwizard/src/main/java/io/github/cdelmas/spike/dropwizard/car/CarsResource.java
Java
apache-2.0
2,368
/* Copyright 2019 The Tekton 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 dockercreds import ( "encoding/base64" "encoding/json" "flag" "fmt" "io/ioutil" "os" "path/filepath" "strings" corev1 "k8s.io/api/core/v1" "github.com/tektoncd/pipeline/pkg/credentials" ) const annotationPrefix = "tekton.dev/docker-" var config basicDocker var dockerConfig arrayArg var dockerCfg arrayArg // AddFlags adds CLI flags that dockercreds supports to a given flag.FlagSet. func AddFlags(flagSet *flag.FlagSet) { flags(flagSet) } func flags(fs *flag.FlagSet) { config = basicDocker{make(map[string]entry)} dockerConfig = arrayArg{[]string{}} dockerCfg = arrayArg{[]string{}} fs.Var(&config, "basic-docker", "List of secret=url pairs.") fs.Var(&dockerConfig, "docker-config", "Docker config.json secret file.") fs.Var(&dockerCfg, "docker-cfg", "Docker .dockercfg secret file.") } // As the flag is read, this status is populated. // basicDocker implements flag.Value type basicDocker struct { Entries map[string]entry `json:"auths"` } func (dc *basicDocker) String() string { if dc == nil { // According to flag.Value this can happen. return "" } var urls []string for k, v := range dc.Entries { urls = append(urls, fmt.Sprintf("%s=%s", v.Secret, k)) } return strings.Join(urls, ",") } // Set sets a secret for a URL from a value in the format of "secret=url" func (dc *basicDocker) Set(value string) error { parts := strings.Split(value, "=") if len(parts) != 2 { return fmt.Errorf("expect entries of the form secret=url, got: %v", value) } secret := parts[0] url := parts[1] if _, ok := dc.Entries[url]; ok { return fmt.Errorf("multiple entries for url: %v", url) } e, err := newEntry(secret) if err != nil { return err } dc.Entries[url] = *e return nil } type arrayArg struct { Values []string } // Set adds a value to the arrayArg's value slice func (aa *arrayArg) Set(value string) error { aa.Values = append(aa.Values, value) return nil } func (aa *arrayArg) String() string { return strings.Join(aa.Values, ",") } type configFile struct { Auth map[string]entry `json:"auths"` } type entry struct { Secret string `json:"-"` Username string `json:"username,omitempty"` Password string `json:"password,omitempty"` Auth string `json:"auth"` Email string `json:"email,omitempty"` } func newEntry(secret string) (*entry, error) { secretPath := credentials.VolumeName(secret) ub, err := ioutil.ReadFile(filepath.Join(secretPath, corev1.BasicAuthUsernameKey)) if err != nil { return nil, err } username := string(ub) pb, err := ioutil.ReadFile(filepath.Join(secretPath, corev1.BasicAuthPasswordKey)) if err != nil { return nil, err } password := string(pb) return &entry{ Secret: secret, Username: username, Password: password, Auth: base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))), Email: "[email protected]", }, nil } type basicDockerBuilder struct{} // NewBuilder returns a new builder for Docker credentials. func NewBuilder() credentials.Builder { return &basicDockerBuilder{} } // MatchingAnnotations extracts flags for the credential helper // from the supplied secret and returns a slice (of length 0 or // greater) of applicable domains. func (*basicDockerBuilder) MatchingAnnotations(secret *corev1.Secret) []string { var flags []string switch secret.Type { case corev1.SecretTypeBasicAuth: for _, v := range credentials.SortAnnotations(secret.Annotations, annotationPrefix) { flags = append(flags, fmt.Sprintf("-basic-docker=%s=%s", secret.Name, v)) } case corev1.SecretTypeDockerConfigJson: flags = append(flags, fmt.Sprintf("-docker-config=%s", secret.Name)) case corev1.SecretTypeDockercfg: flags = append(flags, fmt.Sprintf("-docker-cfg=%s", secret.Name)) default: return flags } return flags } // Write builds a .docker/config.json file from a combination // of kubernetes docker registry secrets and tekton docker // secret entries and writes it to the given directory. If // no entries exist then nothing will be written to disk. func (*basicDockerBuilder) Write(directory string) error { dockerDir := filepath.Join(directory, ".docker") basicDocker := filepath.Join(dockerDir, "config.json") cf := configFile{Auth: config.Entries} auth := map[string]entry{} for _, secretName := range dockerCfg.Values { dockerConfigAuthMap, err := authsFromDockerCfg(secretName) if err != nil { return err } for k, v := range dockerConfigAuthMap { auth[k] = v } } for _, secretName := range dockerConfig.Values { dockerConfigAuthMap, err := authsFromDockerConfig(secretName) if err != nil { return err } for k, v := range dockerConfigAuthMap { auth[k] = v } } for k, v := range config.Entries { auth[k] = v } if len(auth) == 0 { return nil } if err := os.MkdirAll(dockerDir, os.ModePerm); err != nil { return err } cf.Auth = auth content, err := json.Marshal(cf) if err != nil { return err } return ioutil.WriteFile(basicDocker, content, 0600) } func authsFromDockerCfg(secret string) (map[string]entry, error) { secretPath := credentials.VolumeName(secret) m := make(map[string]entry) data, err := ioutil.ReadFile(filepath.Join(secretPath, corev1.DockerConfigKey)) if err != nil { return m, err } err = json.Unmarshal(data, &m) return m, err } func authsFromDockerConfig(secret string) (map[string]entry, error) { secretPath := credentials.VolumeName(secret) m := make(map[string]entry) c := configFile{} data, err := ioutil.ReadFile(filepath.Join(secretPath, corev1.DockerConfigJsonKey)) if err != nil { return m, err } if err := json.Unmarshal(data, &c); err != nil { return m, err } for k, v := range c.Auth { m[k] = v } return m, nil }
tektoncd/pipeline
pkg/credentials/dockercreds/creds.go
GO
apache-2.0
6,293
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the files COPYING and Copyright.html. COPYING can be found at the root * * of the source code distribution tree; Copyright.html can be found at the * * root level of an installed copy of the electronic HDF5 document set and * * is linked from the top-level documents page. It can also be found at * * http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * * access to either file, you may request a copy from [email protected]. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <stdio.h> #include <stdlib.h> #include "H5private.h" #include "h5tools.h" #include "h5tools_dump.h" #include "h5tools_utils.h" #include "h5tools_ref.h" #include "h5trav.h" #include "h5dump_extern.h" #include "h5dump_ddl.h" typedef struct { hid_t fid; /* File ID being traversed */ char *op_name; /* Object name wanted */ } trav_handle_udata_t; typedef struct { char *path; /* Path of object being searched */ char *op_name; /* Object name wanted */ } trav_attr_udata_t; /* callback function used by H5Literate() */ static herr_t dump_all_cb(hid_t group, const char *name, const H5L_info_t *linfo, void *op_data); static int dump_extlink(hid_t group, const char *linkname, const char *objname); /*------------------------------------------------------------------------- * Function: dump_datatype * * Purpose: Dump the datatype. Datatype can be HDF5 predefined * atomic datatype or committed/transient datatype. * * Return: void * * Programmer: Ruey-Hsia Li * * Modifications: * *------------------------------------------------------------------------- */ void dump_datatype(hid_t type) { h5tools_context_t ctx; /* print context */ h5tool_format_t *outputformat = &h5tools_dataformat; HDmemset(&ctx, 0, sizeof(ctx)); ctx.indent_level = dump_indent/COL; ctx.cur_column = dump_indent; h5dump_type_table = type_table; h5tools_dump_datatype(rawoutstream, outputformat, &ctx, type); h5dump_type_table = NULL; } /*------------------------------------------------------------------------- * Function: dump_dataspace * * Purpose: Dump the dataspace. Dataspace can be named dataspace, * array, or others. * * Return: void * * Programmer: Ruey-Hsia Li * * Modifications: * *------------------------------------------------------------------------- */ void dump_dataspace(hid_t space) { h5tools_context_t ctx; /* print context */ h5tool_format_t *outputformat = &h5tools_dataformat; HDmemset(&ctx, 0, sizeof(ctx)); ctx.indent_level = dump_indent/COL; ctx.cur_column = dump_indent; h5tools_dump_dataspace(rawoutstream, outputformat, &ctx, space); } /*------------------------------------------------------------------------- * Function: dump_attr_cb * * Purpose: attribute function callback called by H5Aiterate2, displays the attribute * * Return: Success: SUCCEED * * Failure: FAIL * * Programmer: Ruey-Hsia Li * * Modifications: Pedro Vicente, October 4, 2007 * Added H5A_info_t parameter to conform with H5Aiterate2 * *------------------------------------------------------------------------- */ herr_t dump_attr_cb(hid_t oid, const char *attr_name, const H5A_info_t UNUSED *info, void UNUSED *_op_data) { h5tools_context_t ctx; /* print context */ h5tool_format_t *outputformat = &h5tools_dataformat; h5tool_format_t string_dataformat; hid_t attr_id; herr_t ret = SUCCEED; HDmemset(&ctx, 0, sizeof(ctx)); ctx.indent_level = dump_indent/COL; ctx.cur_column = dump_indent; attr_id = H5Aopen(oid, attr_name, H5P_DEFAULT); oid_output = display_oid; data_output = display_data; attr_data_output = display_attr_data; string_dataformat = *outputformat; if (fp_format) { string_dataformat.fmt_double = fp_format; string_dataformat.fmt_float = fp_format; } if (h5tools_nCols==0) { string_dataformat.line_ncols = 65535; string_dataformat.line_per_line = 1; } else string_dataformat.line_ncols = h5tools_nCols; string_dataformat.do_escape = display_escape; outputformat = &string_dataformat; h5dump_type_table = type_table; h5tools_dump_attribute(rawoutstream, outputformat, &ctx, attr_name, attr_id, display_ai, display_char); h5dump_type_table = NULL; if(attr_id < 0) { h5tools_setstatus(EXIT_FAILURE); ret = FAIL; } return ret; } /*------------------------------------------------------------------------- * Function: dump_all_cb * * Purpose: function callback called by H5Literate, * displays everything in the specified object * * Return: Success: SUCCEED * * Failure: FAIL * * Programmer: Ruey-Hsia Li * * Modifications: * RMcG, November 2000 * Added XML support. Also, optionally checks the op_data argument * * PVN, May 2008 * Dump external links * *------------------------------------------------------------------------- */ static herr_t dump_all_cb(hid_t group, const char *name, const H5L_info_t *linfo, void UNUSED *op_data) { hid_t obj; herr_t ret = SUCCEED; char *obj_path = NULL; /* Full path of object */ h5tools_str_t buffer; /* string into which to render */ h5tools_context_t ctx; /* print context */ h5tool_format_t *outputformat = &h5tools_dataformat; h5tool_format_t string_dataformat; hsize_t curr_pos = 0; /* total data element position */ /* setup */ HDmemset(&buffer, 0, sizeof(h5tools_str_t)); HDmemset(&ctx, 0, sizeof(ctx)); ctx.indent_level = dump_indent/COL; ctx.cur_column = dump_indent; string_dataformat = *outputformat; if (fp_format) { string_dataformat.fmt_double = fp_format; string_dataformat.fmt_float = fp_format; } if (h5tools_nCols==0) { string_dataformat.line_ncols = 65535; string_dataformat.line_per_line = 1; } else string_dataformat.line_ncols = h5tools_nCols; string_dataformat.do_escape = display_escape; outputformat = &string_dataformat; /* Build the object's path name */ obj_path = (char *)HDmalloc(HDstrlen(prefix) + HDstrlen(name) + 2); if(!obj_path) { ret = FAIL; goto done; } HDstrcpy(obj_path, prefix); HDstrcat(obj_path, "/"); HDstrcat(obj_path, name); if(linfo->type == H5L_TYPE_HARD) { H5O_info_t oinfo; /* Stat the object */ if(H5Oget_info_by_name(group, name, &oinfo, H5P_DEFAULT) < 0) { error_msg("unable to get object information for \"%s\"\n", name); h5tools_setstatus(EXIT_FAILURE); ret = FAIL; goto done; } /* end if */ switch(oinfo.type) { case H5O_TYPE_GROUP: if((obj = H5Gopen2(group, name, H5P_DEFAULT)) < 0) { error_msg("unable to dump group \"%s\"\n", name); h5tools_setstatus(EXIT_FAILURE); ret = FAIL; } else { char *old_prefix; /* Pointer to previous prefix */ /* Keep copy of prefix before iterating into group */ old_prefix = HDstrdup(prefix); HDassert(old_prefix); /* Append group name to prefix */ add_prefix(&prefix, &prefix_len, name); /* Iterate into group */ dump_function_table->dump_group_function(obj, name); /* Restore old prefix name */ HDstrcpy(prefix, old_prefix); HDfree(old_prefix); /* Close group */ H5Gclose(obj); } break; case H5O_TYPE_DATASET: if((obj = H5Dopen2(group, name, H5P_DEFAULT)) >= 0) { if(oinfo.rc > 1 || hit_elink) { obj_t *found_obj; /* Found object */ found_obj = search_obj(dset_table, oinfo.addr); if(found_obj == NULL) { ctx.indent_level++; ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "%s \"%s\" %s", h5tools_dump_header_format->datasetbegin, name, h5tools_dump_header_format->datasetblockbegin); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); error_msg("internal error (file %s:line %d)\n", __FILE__, __LINE__); ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); if(HDstrlen(h5tools_dump_header_format->datasetblockend)) { h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->datasetblockend); if(HDstrlen(h5tools_dump_header_format->datasetend)) h5tools_str_append(&buffer, " "); } if(HDstrlen(h5tools_dump_header_format->datasetend)) h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->datasetend); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); ctx.indent_level--; h5tools_setstatus(EXIT_FAILURE); ret = FAIL; H5Dclose(obj); goto done; } else if(found_obj->displayed) { ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "%s \"%s\" %s", h5tools_dump_header_format->datasetbegin, name, h5tools_dump_header_format->datasetblockbegin); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); ctx.indent_level++; ctx.need_prefix = TRUE; /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "%s \"%s\"", HARDLINK, found_obj->objname); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); ctx.indent_level--; ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); if(HDstrlen(h5tools_dump_header_format->datasetblockend)) { h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->datasetblockend); if(HDstrlen(h5tools_dump_header_format->datasetend)) h5tools_str_append(&buffer, " "); } if(HDstrlen(h5tools_dump_header_format->datasetend)) h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->datasetend); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); H5Dclose(obj); goto done; } else { found_obj->displayed = TRUE; } } /* end if */ dump_function_table->dump_dataset_function(obj, name, NULL); H5Dclose(obj); } else { error_msg("unable to dump dataset \"%s\"\n", name); h5tools_setstatus(EXIT_FAILURE); ret = FAIL; } break; case H5O_TYPE_NAMED_DATATYPE: if((obj = H5Topen2(group, name, H5P_DEFAULT)) < 0) { error_msg("unable to dump datatype \"%s\"\n", name); h5tools_setstatus(EXIT_FAILURE); ret = FAIL; } else { dump_function_table->dump_named_datatype_function(obj, name); H5Tclose(obj); } break; default: error_msg("unknown object \"%s\"\n", name); h5tools_setstatus(EXIT_FAILURE); ret = FAIL; } } /* end if */ else { char *targbuf; switch(linfo->type) { case H5L_TYPE_SOFT: targbuf = (char *)HDmalloc(linfo->u.val_size); HDassert(targbuf); ctx.need_prefix = TRUE; /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "%s \"%s\" %s", h5tools_dump_header_format->softlinkbegin, name, h5tools_dump_header_format->softlinkblockbegin); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); ctx.indent_level++; if(H5Lget_val(group, name, targbuf, linfo->u.val_size, H5P_DEFAULT) < 0) { error_msg("unable to get link value\n"); h5tools_setstatus(EXIT_FAILURE); ret = FAIL; } else { /* print the value of a soft link */ /* Standard DDL: no modification */ ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "LINKTARGET \"%s\"", targbuf); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); } ctx.indent_level--; ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); if(HDstrlen(h5tools_dump_header_format->softlinkblockend)) { h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->softlinkblockend); if(HDstrlen(h5tools_dump_header_format->softlinkend)) h5tools_str_append(&buffer, " "); } if(HDstrlen(h5tools_dump_header_format->softlinkend)) h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->softlinkend); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); HDfree(targbuf); break; case H5L_TYPE_EXTERNAL: targbuf = (char *)HDmalloc(linfo->u.val_size); HDassert(targbuf); ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "%s \"%s\" %s", h5tools_dump_header_format->extlinkbegin, name, h5tools_dump_header_format->extlinkblockbegin); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); if(H5Lget_val(group, name, targbuf, linfo->u.val_size, H5P_DEFAULT) < 0) { indentation(dump_indent); error_msg("unable to get external link value\n"); h5tools_setstatus(EXIT_FAILURE); ret = FAIL; } /* end if */ else { const char *filename; const char *targname; if(H5Lunpack_elink_val(targbuf, linfo->u.val_size, NULL, &filename, &targname) < 0) { indentation(dump_indent); error_msg("unable to unpack external link value\n"); h5tools_setstatus(EXIT_FAILURE); ret = FAIL; } /* end if */ else { ctx.indent_level++; ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "TARGETFILE \"%s\"", filename); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "TARGETPATH \"%s\"", targname); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); /* dump the external link */ dump_extlink(group, name, targname); ctx.indent_level--; } /* end else */ } /* end else */ ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); if(HDstrlen(h5tools_dump_header_format->extlinkblockend)) { h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->extlinkblockend); if(HDstrlen(h5tools_dump_header_format->extlinkend)) h5tools_str_append(&buffer, " "); } if(HDstrlen(h5tools_dump_header_format->extlinkend)) h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->extlinkend); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); HDfree(targbuf); break; default: ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "%s \"%s\" %s", h5tools_dump_header_format->udlinkbegin, name, h5tools_dump_header_format->udlinkblockbegin); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); ctx.indent_level++; ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "LINKCLASS %d", linfo->type); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); ctx.indent_level--; ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); if(HDstrlen(h5tools_dump_header_format->udlinkblockend)) { h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->udlinkblockend); if(HDstrlen(h5tools_dump_header_format->udlinkend)) h5tools_str_append(&buffer, " "); } if(HDstrlen(h5tools_dump_header_format->udlinkend)) h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->udlinkend); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); break; } /* end switch */ } /* end else */ done: h5tools_str_close(&buffer); if(obj_path) HDfree(obj_path); return ret; } /*------------------------------------------------------------------------- * Function: attr_iteration * * Purpose: Iterate and display attributes within the specified group * * Return: void * *------------------------------------------------------------------------- */ void attr_iteration(hid_t gid, unsigned attr_crt_order_flags) { /* attribute iteration: if there is a request to do H5_INDEX_CRT_ORDER and tracking order is set in the group for attributes, then, sort by creation order, otherwise by name */ if(include_attrs) { if((sort_by == H5_INDEX_CRT_ORDER) && (attr_crt_order_flags & H5P_CRT_ORDER_TRACKED)) { if(H5Aiterate2(gid, sort_by, sort_order, NULL, dump_attr_cb, NULL) < 0) { error_msg("error getting attribute information\n"); h5tools_setstatus(EXIT_FAILURE); } /* end if */ } /* end if */ else { if(H5Aiterate2(gid, H5_INDEX_NAME, sort_order, NULL, dump_attr_cb, NULL) < 0) { error_msg("error getting attribute information\n"); h5tools_setstatus(EXIT_FAILURE); } /* end if */ } /* end else */ } } /*------------------------------------------------------------------------- * Function: link_iteration * * Purpose: Iterate and display links within the specified group * * Return: void * *------------------------------------------------------------------------- */ void link_iteration(hid_t gid, unsigned crt_order_flags) { /* if there is a request to do H5_INDEX_CRT_ORDER and tracking order is set in the group, then, sort by creation order, otherwise by name */ if((sort_by == H5_INDEX_CRT_ORDER) && (crt_order_flags & H5P_CRT_ORDER_TRACKED)) H5Literate(gid, sort_by, sort_order, NULL, dump_all_cb, NULL); else H5Literate(gid, H5_INDEX_NAME, sort_order, NULL, dump_all_cb, NULL); } /*------------------------------------------------------------------------- * Function: dump_named_datatype * * Purpose: Dump named datatype * * Return: void * * Programmer: Ruey-Hsia Li * * Modifications: * Pedro Vicente, March 27, 2006 * added display of attributes * Pedro Vicente, October 4, 2007, added parameters to H5Aiterate2() to allow for * other iteration orders * *------------------------------------------------------------------------- */ void dump_named_datatype(hid_t tid, const char *name) { H5O_info_t oinfo; unsigned attr_crt_order_flags; hid_t tcpl_id = -1; /* datatype creation property list ID */ hsize_t curr_pos = 0; /* total data element position */ h5tools_str_t buffer; /* string into which to render */ h5tools_context_t ctx; /* print context */ h5tool_format_t *outputformat = &h5tools_dataformat; h5tool_format_t string_dataformat; /* setup */ HDmemset(&buffer, 0, sizeof(h5tools_str_t)); HDmemset(&ctx, 0, sizeof(ctx)); ctx.indent_level = dump_indent/COL; ctx.cur_column = dump_indent; string_dataformat = *outputformat; if (fp_format) { string_dataformat.fmt_double = fp_format; string_dataformat.fmt_float = fp_format; } if (h5tools_nCols==0) { string_dataformat.line_ncols = 65535; string_dataformat.line_per_line = 1; } else string_dataformat.line_ncols = h5tools_nCols; string_dataformat.do_escape = display_escape; outputformat = &string_dataformat; if ((tcpl_id = H5Tget_create_plist(tid)) < 0) { error_msg("error in getting creation property list ID\n"); h5tools_setstatus(EXIT_FAILURE); } /* query the creation properties for attributes */ if (H5Pget_attr_creation_order(tcpl_id, &attr_crt_order_flags) < 0) { error_msg("error in getting creation properties\n"); h5tools_setstatus(EXIT_FAILURE); } if(H5Pclose(tcpl_id) < 0) { error_msg("error in closing creation property list ID\n"); h5tools_setstatus(EXIT_FAILURE); } ctx.need_prefix = TRUE; /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "%s \"%s\" %s", h5tools_dump_header_format->datatypebegin, name, h5tools_dump_header_format->datatypeblockbegin); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); H5Oget_info(tid, &oinfo); /* Must check for uniqueness of all objects if we've traversed an elink, * otherwise only check if the reference count > 1. */ if(oinfo.rc > 1 || hit_elink) { obj_t *found_obj; /* Found object */ found_obj = search_obj(type_table, oinfo.addr); if (found_obj == NULL) { error_msg("internal error (file %s:line %d)\n", __FILE__, __LINE__); h5tools_setstatus(EXIT_FAILURE); goto done; } else if (found_obj->displayed) { /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "%s \"%s\"", HARDLINK, found_obj->objname); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); goto done; } else found_obj->displayed = TRUE; } /* end if */ /* Render the element */ h5tools_str_reset(&buffer); h5tools_print_datatype(rawoutstream, &buffer, outputformat, &ctx, tid, FALSE); if(H5Tget_class(tid) != H5T_COMPOUND) { h5tools_str_append(&buffer, ";"); } h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); /* print attributes */ dump_indent += COL; attr_iteration(tid, attr_crt_order_flags); dump_indent -= COL; done: /* Render the element */ h5tools_str_reset(&buffer); if(HDstrlen(h5tools_dump_header_format->datatypeblockend)) { h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->datatypeblockend); if(HDstrlen(h5tools_dump_header_format->datatypeend)) h5tools_str_append(&buffer, " "); } if(HDstrlen(h5tools_dump_header_format->datatypeend)) h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->datatypeend); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); h5tools_str_close(&buffer); } /*------------------------------------------------------------------------- * Function: dump_group * * Purpose: Dump everything within the specified group * * Return: void * * Programmer: Ruey-Hsia Li * * Modifications: * * Call to dump_all_cb -- add parameter to select everything. * * Pedro Vicente, October 1, 2007 * handle several iteration orders for attributes and groups * *------------------------------------------------------------------------- */ void dump_group(hid_t gid, const char *name) { H5O_info_t oinfo; hid_t dset; hid_t type; hid_t gcpl_id; unsigned crt_order_flags; unsigned attr_crt_order_flags; char type_name[1024]; h5tools_str_t buffer; /* string into which to render */ h5tools_context_t ctx; /* print context */ h5tool_format_t *outputformat = &h5tools_dataformat; h5tool_format_t string_dataformat; hsize_t curr_pos = 0; /* total data element position */ if ((gcpl_id = H5Gget_create_plist(gid)) < 0) { error_msg("error in getting group creation property list ID\n"); h5tools_setstatus(EXIT_FAILURE); } /* query the group creation properties for attributes */ if (H5Pget_attr_creation_order(gcpl_id, &attr_crt_order_flags) < 0) { error_msg("error in getting group creation properties\n"); h5tools_setstatus(EXIT_FAILURE); } /* query the group creation properties */ if(H5Pget_link_creation_order(gcpl_id, &crt_order_flags) < 0) { error_msg("error in getting group creation properties\n"); h5tools_setstatus(EXIT_FAILURE); } if(H5Pclose(gcpl_id) < 0) { error_msg("error in closing group creation property list ID\n"); h5tools_setstatus(EXIT_FAILURE); } /* setup */ HDmemset(&buffer, 0, sizeof(h5tools_str_t)); HDmemset(&ctx, 0, sizeof(ctx)); ctx.indent_level = dump_indent/COL; ctx.cur_column = dump_indent; string_dataformat = *outputformat; if (fp_format) { string_dataformat.fmt_double = fp_format; string_dataformat.fmt_float = fp_format; } if (h5tools_nCols==0) { string_dataformat.line_ncols = 65535; string_dataformat.line_per_line = 1; } else string_dataformat.line_ncols = h5tools_nCols; string_dataformat.do_escape = display_escape; outputformat = &string_dataformat; ctx.need_prefix = TRUE; /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "%s \"%s\" %s", h5tools_dump_header_format->groupbegin, name, h5tools_dump_header_format->groupblockbegin); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); ctx.indent_level++; dump_indent += COL; if(!HDstrcmp(name, "/") && unamedtype) { unsigned u; /* Local index variable */ /* dump unamed type in root group */ for(u = 0; u < type_table->nobjs; u++) if(!type_table->objs[u].recorded) { dset = H5Dopen2(gid, type_table->objs[u].objname, H5P_DEFAULT); type = H5Dget_type(dset); sprintf(type_name, "#"H5_PRINTF_HADDR_FMT, type_table->objs[u].objno); dump_function_table->dump_named_datatype_function(type, type_name); H5Tclose(type); H5Dclose(dset); } } /* end if */ if(display_oid) { h5tools_dump_oid(rawoutstream, outputformat, &ctx, gid); } h5tools_dump_comment(rawoutstream, outputformat, &ctx, gid); H5Oget_info(gid, &oinfo); /* Must check for uniqueness of all objects if we've traversed an elink, * otherwise only check if the reference count > 1. */ if(oinfo.rc > 1 || hit_elink) { obj_t *found_obj; /* Found object */ found_obj = search_obj(group_table, oinfo.addr); if (found_obj == NULL) { error_msg("internal error (file %s:line %d)\n", __FILE__, __LINE__); h5tools_setstatus(EXIT_FAILURE); } else if (found_obj->displayed) { ctx.need_prefix = TRUE; /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "%s \"%s\"", HARDLINK, found_obj->objname); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); } else { found_obj->displayed = TRUE; attr_iteration(gid, attr_crt_order_flags); link_iteration(gid, crt_order_flags); } } else { attr_iteration(gid, attr_crt_order_flags); link_iteration(gid, crt_order_flags); } dump_indent -= COL; ctx.indent_level--; ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); if(HDstrlen(h5tools_dump_header_format->groupblockend)) { h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->groupblockend); if(HDstrlen(h5tools_dump_header_format->groupend)) h5tools_str_append(&buffer, " "); } if(HDstrlen(h5tools_dump_header_format->groupend)) h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->groupend); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); h5tools_str_close(&buffer); } /*------------------------------------------------------------------------- * Function: dump_dataset * * Purpose: Dump the specified data set * * Return: void * * Programmer: Ruey-Hsia Li * * Modifications: * Pedro Vicente, 2004, added dataset creation property list display * Pedro Vicente, October 4, 2007, added parameters to H5Aiterate2() to allow for * other iteration orders * *------------------------------------------------------------------------- */ void dump_dataset(hid_t did, const char *name, struct subset_t *sset) { h5tools_context_t ctx; /* print context */ h5tool_format_t *outputformat = &h5tools_dataformat; h5tool_format_t string_dataformat; hid_t type, space; unsigned attr_crt_order_flags; hid_t dcpl_id; /* dataset creation property list ID */ h5tools_str_t buffer; /* string into which to render */ hsize_t curr_pos = 0; /* total data element position */ HDmemset(&ctx, 0, sizeof(ctx)); ctx.indent_level = dump_indent/COL; ctx.cur_column = dump_indent; string_dataformat = *outputformat; if (fp_format) { string_dataformat.fmt_double = fp_format; string_dataformat.fmt_float = fp_format; } if (h5tools_nCols==0) { string_dataformat.line_ncols = 65535; string_dataformat.line_per_line = 1; } else string_dataformat.line_ncols = h5tools_nCols; string_dataformat.do_escape = display_escape; outputformat = &string_dataformat; if ((dcpl_id = H5Dget_create_plist(did)) < 0) { error_msg("error in getting creation property list ID\n"); h5tools_setstatus(EXIT_FAILURE); } /* query the creation properties for attributes */ if (H5Pget_attr_creation_order(dcpl_id, &attr_crt_order_flags) < 0) { error_msg("error in getting creation properties\n"); h5tools_setstatus(EXIT_FAILURE); } /* setup */ HDmemset(&buffer, 0, sizeof(h5tools_str_t)); ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "%s \"%s\" %s", h5tools_dump_header_format->datasetbegin, name, h5tools_dump_header_format->datasetblockbegin); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); h5tools_dump_comment(rawoutstream, outputformat, &ctx, did); dump_indent += COL; ctx.indent_level++; type = H5Dget_type(did); h5dump_type_table = type_table; h5tools_dump_datatype(rawoutstream, outputformat, &ctx, type); h5dump_type_table = NULL; space = H5Dget_space(did); h5tools_dump_dataspace(rawoutstream, outputformat, &ctx, space); H5Sclose(space); if(display_oid) { h5tools_dump_oid(rawoutstream, outputformat, &ctx, did); } if(display_dcpl) { h5dump_type_table = type_table; h5tools_dump_dcpl(rawoutstream, outputformat, &ctx, dcpl_id, type, did); h5dump_type_table = NULL; } H5Pclose(dcpl_id); if(display_data) { int data_loop = 1; int i; if(display_packed_bits) data_loop = packed_bits_num; for(i=0; i<data_loop; i++) { if(display_packed_bits) { ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); packed_data_mask = packed_mask[i]; packed_data_offset = packed_offset[i]; packed_data_length = packed_length[i]; h5tools_print_packed_bits(&buffer, type); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); } switch(H5Tget_class(type)) { case H5T_TIME: ctx.indent_level++; ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "DATA{ not yet implemented.}"); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); ctx.indent_level--; break; case H5T_INTEGER: case H5T_FLOAT: case H5T_STRING: case H5T_BITFIELD: case H5T_OPAQUE: case H5T_COMPOUND: case H5T_REFERENCE: case H5T_ENUM: case H5T_VLEN: case H5T_ARRAY: { printf("\nbefore h5tools_dump_data\n"); h5tools_dump_data(rawoutstream, outputformat, &ctx, did, TRUE, sset, display_ai, display_char); } break; default: break; } /* end switch */ } /* for(i=0;i<data_loop;i++) */ } H5Tclose(type); if (!bin_output) { attr_iteration(did, attr_crt_order_flags); } ctx.indent_level--; dump_indent -= COL; ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); if(HDstrlen(h5tools_dump_header_format->datasetblockend)) { h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->datasetblockend); if(HDstrlen(h5tools_dump_header_format->datasetend)) h5tools_str_append(&buffer, " "); } if(HDstrlen(h5tools_dump_header_format->datasetend)) h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->datasetend); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); h5tools_str_close(&buffer); } /*------------------------------------------------------------------------- * Function: dump_data * * Purpose: Dump attribute or dataset data * * Return: void * * Programmer: Ruey-Hsia Li * * Modifications: pvn, print the matrix indices * Albert Cheng, 2004/11/18 * Add --string printing for attributes too. * *------------------------------------------------------------------------- */ void dump_data(hid_t obj_id, int obj_data, struct subset_t *sset, int display_index) { h5tools_context_t ctx; /* print context */ h5tool_format_t *outputformat = &h5tools_dataformat; h5tool_format_t string_dataformat; int print_dataset = FALSE; string_dataformat = *outputformat; if (fp_format) { string_dataformat.fmt_double = fp_format; string_dataformat.fmt_float = fp_format; } if (h5tools_nCols==0) { string_dataformat.line_ncols = 65535; string_dataformat.line_per_line = 1; } else string_dataformat.line_ncols = h5tools_nCols; string_dataformat.do_escape = display_escape; outputformat = &string_dataformat; HDmemset(&ctx, 0, sizeof(ctx)); ctx.indent_level = dump_indent/COL; ctx.cur_column = dump_indent; if(obj_data == DATASET_DATA) print_dataset = TRUE; h5tools_dump_data(rawoutstream, outputformat, &ctx, obj_id, print_dataset, sset, display_index, display_char); } /*------------------------------------------------------------------------- * Function: dump_fcpl * * Purpose: prints file creation property list information * * Return: void * * Programmer: pvn * * Modifications: * *------------------------------------------------------------------------- */ void dump_fcpl(hid_t fid) { hid_t fcpl; /* file creation property list ID */ hsize_t userblock; /* userblock size retrieved from FCPL */ size_t off_size; /* size of offsets in the file */ size_t len_size; /* size of lengths in the file */ unsigned super; /* superblock version # */ unsigned freelist; /* free list version # */ unsigned stab; /* symbol table entry version # */ unsigned shhdr; /* shared object header version # */ #ifdef SHOW_FILE_DRIVER hid_t fapl; /* file access property list ID */ hid_t fdriver; /* file driver */ char dname[32]; /* buffer to store driver name */ #endif unsigned sym_lk; /* symbol table B-tree leaf 'K' value */ unsigned sym_ik; /* symbol table B-tree internal 'K' value */ unsigned istore_ik; /* indexed storage B-tree internal 'K' value */ fcpl=H5Fget_create_plist(fid); H5Pget_version(fcpl, &super, &freelist, &stab, &shhdr); H5Pget_userblock(fcpl,&userblock); H5Pget_sizes(fcpl,&off_size,&len_size); H5Pget_sym_k(fcpl,&sym_ik,&sym_lk); H5Pget_istore_k(fcpl,&istore_ik); H5Pclose(fcpl); #ifdef SHOW_FILE_DRIVER fapl=h5_fileaccess(); fdriver=H5Pget_driver(fapl); H5Pclose(fapl); #endif /*------------------------------------------------------------------------- * SUPER_BLOCK *------------------------------------------------------------------------- */ PRINTSTREAM(rawoutstream, "\n%s %s\n",SUPER_BLOCK, BEGIN); indentation(dump_indent + COL); PRINTSTREAM(rawoutstream, "%s %u\n","SUPERBLOCK_VERSION", super); indentation(dump_indent + COL); PRINTSTREAM(rawoutstream, "%s %u\n","FREELIST_VERSION", freelist); indentation(dump_indent + COL); PRINTSTREAM(rawoutstream, "%s %u\n","SYMBOLTABLE_VERSION", stab); indentation(dump_indent + COL); PRINTSTREAM(rawoutstream, "%s %u\n","OBJECTHEADER_VERSION", shhdr); indentation(dump_indent + COL); PRINTSTREAM(rawoutstream,"%s %zu\n","OFFSET_SIZE", off_size); indentation(dump_indent + COL); PRINTSTREAM(rawoutstream,"%s %zu\n","LENGTH_SIZE", len_size); indentation(dump_indent + COL); PRINTSTREAM(rawoutstream, "%s %u\n","BTREE_RANK", sym_ik); indentation(dump_indent + COL); PRINTSTREAM(rawoutstream, "%s %d\n","BTREE_LEAF", sym_lk); #ifdef SHOW_FILE_DRIVER if(H5FD_CORE==fdriver) HDstrcpy(dname,"H5FD_CORE"); #ifdef H5_HAVE_DIRECT else if(H5FD_DIRECT==fdriver) HDstrcpy(dname,"H5FD_DIRECT"); #endif else if(H5FD_FAMILY==fdriver) HDstrcpy(dname,"H5FD_FAMILY"); else if(H5FD_LOG==fdriver) HDstrcpy(dname,"H5FD_LOG"); else if(H5FD_MPIO==fdriver) HDstrcpy(dname,"H5FD_MPIO"); else if(H5FD_MULTI==fdriver) HDstrcpy(dname,"H5FD_MULTI"); else if(H5FD_SEC2==fdriver) HDstrcpy(dname,"H5FD_SEC2"); else if(H5FD_STDIO==fdriver) HDstrcpy(dname,"H5FD_STDIO"); else HDstrcpy(dname,"Unknown driver"); /* Take out this because the driver used can be different from the * standard output. */ /*indentation(dump_indent + COL); PRINTSTREAM(rawoutstream, "%s %s\n","FILE_DRIVER", dname);*/ #endif indentation(dump_indent + COL); PRINTSTREAM(rawoutstream, "%s %u\n","ISTORE_K", istore_ik); /*------------------------------------------------------------------------- * USER_BLOCK *------------------------------------------------------------------------- */ indentation(dump_indent + COL); PRINTSTREAM(rawoutstream, "USER_BLOCK %s\n",BEGIN); indentation(dump_indent + COL + COL); PRINTSTREAM(rawoutstream,"%s %Hu\n","USERBLOCK_SIZE", userblock); indentation(dump_indent + COL); PRINTSTREAM(rawoutstream, "%s\n",END); PRINTSTREAM(rawoutstream, "%s",END); } /*------------------------------------------------------------------------- * Function: dump_fcontents * * Purpose: prints all objects * * Return: void * * Programmer: pvn * * Modifications: * *------------------------------------------------------------------------- */ void dump_fcontents(hid_t fid) { PRINTSTREAM(rawoutstream, "%s %s\n",FILE_CONTENTS, BEGIN); /* special case of unamed types in root group */ if (unamedtype) { unsigned u; for (u = 0; u < type_table->nobjs; u++) { if (!type_table->objs[u].recorded) PRINTSTREAM(rawoutstream, " %-10s /#"H5_PRINTF_HADDR_FMT"\n", "datatype", type_table->objs[u].objno); } } /* print objects in the files */ h5trav_print(fid); PRINTSTREAM(rawoutstream, " %s\n",END); } static herr_t attr_search(hid_t oid, const char *attr_name, const H5A_info_t UNUSED *ainfo, void *_op_data) { herr_t ret = SUCCEED; int i; int j; int k; char *obj_op_name; char *obj_name; trav_attr_udata_t *attr_data = (trav_attr_udata_t*)_op_data; char *buf = attr_data->path; char *op_name = attr_data->op_name; j = (int)HDstrlen(op_name) - 1; /* find the last / */ while(j >= 0) { if (op_name[j] == '/' && (j==0 || (j>0 && op_name[j-1]!='\\'))) break; j--; } obj_op_name = h5tools_str_replace(op_name + j + 1, "\\/", "/"); if(obj_op_name == NULL) { h5tools_setstatus(EXIT_FAILURE); ret = FAIL; } else { if(HDstrcmp(attr_name, obj_op_name)==0) { /* object name */ i = (int)HDstrlen(buf); j = (int)HDstrlen(op_name); k = (size_t)i + 1 + (size_t)j + 1 + 2; obj_name = (char *)HDmalloc((size_t)k); if(obj_name == NULL) { h5tools_setstatus(EXIT_FAILURE); ret = FAIL; } else { HDmemset(obj_name, '\0', (size_t)k); if(op_name[0] != '/') { HDstrncat(obj_name, buf, (size_t)i + 1); if(buf[i-1] != '/') HDstrncat(obj_name, "/", (size_t)2); } HDstrncat(obj_name, op_name, (size_t)j + 1); handle_attributes(oid, obj_name, NULL, 0, NULL); HDfree(obj_name); } } HDfree(obj_op_name); } return ret; } /* end attr_search() */ static herr_t obj_search(const char *path, const H5O_info_t *oi, const char UNUSED *already_visited, void *_op_data) { trav_handle_udata_t *handle_data = (trav_handle_udata_t*)_op_data; char *op_name = (char*)handle_data->op_name; trav_attr_udata_t attr_data; attr_data.path = (char*)path; attr_data.op_name = op_name; H5Aiterate_by_name(handle_data->fid, path, H5_INDEX_NAME, H5_ITER_INC, NULL, attr_search, (void*)&attr_data, H5P_DEFAULT); if(HDstrcmp(path, op_name)==0) { switch(oi->type) { case H5O_TYPE_GROUP: handle_groups(handle_data->fid, path, NULL, 0, NULL); break; case H5O_TYPE_DATASET: handle_datasets(handle_data->fid, path, NULL, 0, NULL); break; case H5O_TYPE_NAMED_DATATYPE: handle_datatypes(handle_data->fid, path, NULL, 0, NULL); break; case H5O_TYPE_UNKNOWN: case H5O_TYPE_NTYPES: default: error_msg("unknown object type value\n"); h5tools_setstatus(EXIT_FAILURE); } /* end switch */ } return 0; } /* end obj_search() */ static herr_t lnk_search(const char *path, const H5L_info_t *li, void *_op_data) { int search_len; int k; char *search_name; trav_handle_udata_t *handle_data = (trav_handle_udata_t*)_op_data; char *op_name = (char*)handle_data->op_name; search_len = HDstrlen(op_name); if(search_len > 0 && op_name[0] != '/') { k = 2; } else k = 1; search_name = (char *)HDmalloc((size_t)(search_len + k)); if(search_name == NULL) { error_msg("creating temporary link\n"); h5tools_setstatus(EXIT_FAILURE); } else { if (k == 2) { HDstrcpy(search_name, "/"); HDstrncat(search_name, op_name, (size_t)search_len + 1); } else HDstrncpy(search_name, op_name, (size_t)search_len + 1); search_name[search_len + k - 1] = '\0'; if(HDstrcmp(path, search_name) == 0) { switch(li->type) { case H5L_TYPE_SOFT: case H5L_TYPE_EXTERNAL: handle_links(handle_data->fid, op_name, NULL, 0, NULL); break; case H5L_TYPE_HARD: case H5L_TYPE_MAX: case H5L_TYPE_ERROR: default: error_msg("unknown link type value\n"); h5tools_setstatus(EXIT_FAILURE); break; } /* end switch() */ } HDfree(search_name); } return 0; } /* end lnk_search() */ /*------------------------------------------------------------------------- * Function: handle_paths * * Purpose: Handle objects from the command. * * Return: void * *------------------------------------------------------------------------- */ void handle_paths(hid_t fid, const char *path_name, void UNUSED * data, int UNUSED pe, const char UNUSED *display_name) { hid_t gid = -1; if((gid = H5Gopen2(fid, "/", H5P_DEFAULT)) < 0) { error_msg("unable to open root group\n"); h5tools_setstatus(EXIT_FAILURE); } else { hid_t gcpl_id; unsigned crt_order_flags; unsigned attr_crt_order_flags; trav_handle_udata_t handle_udata; /* User data for traversal */ if ((gcpl_id = H5Gget_create_plist(gid)) < 0) { error_msg("error in getting group creation property list ID\n"); h5tools_setstatus(EXIT_FAILURE); } /* query the group creation properties for attributes */ if (H5Pget_attr_creation_order(gcpl_id, &attr_crt_order_flags) < 0) { error_msg("error in getting group creation properties\n"); h5tools_setstatus(EXIT_FAILURE); } /* query the group creation properties */ if(H5Pget_link_creation_order(gcpl_id, &crt_order_flags) < 0) { error_msg("error in getting group creation properties\n"); h5tools_setstatus(EXIT_FAILURE); } if(H5Pclose(gcpl_id) < 0) { error_msg("error in closing group creation property list ID\n"); h5tools_setstatus(EXIT_FAILURE); } handle_udata.fid = fid; handle_udata.op_name = (char*)path_name; if(h5trav_visit(fid, "/", TRUE, TRUE, obj_search, lnk_search, &handle_udata) < 0) { error_msg("error traversing information\n"); h5tools_setstatus(EXIT_FAILURE); } } } /*------------------------------------------------------------------------- * Function: handle_attributes * * Purpose: Handle the attributes from the command. * * Return: void * * Programmer: Bill Wendling * Tuesday, 9. January 2001 * * Modifications: * * PVN, May 2008 * add an extra parameter PE, to allow printing/not printing of error messages * *------------------------------------------------------------------------- */ void handle_attributes(hid_t fid, const char *attr, void UNUSED * data, int UNUSED pe, const char UNUSED *display_name) { hid_t oid = -1; hid_t attr_id = -1; char *obj_name; char *attr_name; int j; h5tools_str_t buffer; /* string into which to render */ h5tools_context_t ctx; /* print context */ h5tool_format_t *outputformat = &h5tools_dataformat; h5tool_format_t string_dataformat; hsize_t curr_pos = 0; /* total data element position */ j = (int)HDstrlen(attr) - 1; obj_name = (char *)HDmalloc((size_t)j + 2); if(obj_name == NULL) goto error; /* find the last / */ while(j >= 0) { if (attr[j] == '/' && (j==0 || (j>0 && attr[j-1]!='\\'))) break; j--; } /* object name */ if(j == -1) HDstrcpy(obj_name, "/"); else { HDstrncpy(obj_name, attr, (size_t)j + 1); obj_name[j + 1] = '\0'; } /* end else */ dump_indent += COL; HDmemset(&ctx, 0, sizeof(ctx)); ctx.indent_level = dump_indent/COL; ctx.cur_column = dump_indent; string_dataformat = *outputformat; if (fp_format) { string_dataformat.fmt_double = fp_format; string_dataformat.fmt_float = fp_format; } if (h5tools_nCols==0) { string_dataformat.line_ncols = 65535; string_dataformat.line_per_line = 1; } else string_dataformat.line_ncols = h5tools_nCols; string_dataformat.do_escape = display_escape; outputformat = &string_dataformat; attr_name = h5tools_str_replace(attr + j + 1, "\\/", "/"); /* handle error case: cannot open the object with the attribute */ if((oid = H5Oopen(fid, obj_name, H5P_DEFAULT)) < 0) { /* setup */ HDmemset(&buffer, 0, sizeof(h5tools_str_t)); ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); h5tools_str_append(&buffer, "%s \"%s\" %s", h5tools_dump_header_format->attributebegin, attr, h5tools_dump_header_format->attributeblockbegin); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); error_msg("unable to open object \"%s\"\n", obj_name); ctx.need_prefix = TRUE; h5tools_simple_prefix(rawoutstream, outputformat, &ctx, (hsize_t)0, 0); /* Render the element */ h5tools_str_reset(&buffer); if(HDstrlen(h5tools_dump_header_format->attributeblockend)) { h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->attributeblockend); if(HDstrlen(h5tools_dump_header_format->attributeend)) h5tools_str_append(&buffer, " "); } if(HDstrlen(h5tools_dump_header_format->attributeend)) h5tools_str_append(&buffer, "%s", h5tools_dump_header_format->attributeend); h5tools_render_element(rawoutstream, outputformat, &ctx, &buffer, &curr_pos, (size_t)outputformat->line_ncols, (hsize_t)0, (hsize_t)0); h5tools_str_close(&buffer); goto error; } /* end if */ attr_id = H5Aopen(oid, attr_name, H5P_DEFAULT); oid_output = display_oid; data_output = display_data; attr_data_output = display_attr_data; h5dump_type_table = type_table; h5tools_dump_attribute(rawoutstream, outputformat, &ctx, attr_name, attr_id, display_ai, display_char); h5dump_type_table = NULL; if(attr_id < 0) { goto error; } /* Close object */ if(H5Oclose(oid) < 0) { goto error; } /* end if */ HDfree(obj_name); HDfree(attr_name); dump_indent -= COL; return; error: h5tools_setstatus(EXIT_FAILURE); if(obj_name) HDfree(obj_name); if (attr_name) HDfree(attr_name); H5E_BEGIN_TRY { H5Oclose(oid); H5Aclose(attr_id); } H5E_END_TRY; dump_indent -= COL; } /*------------------------------------------------------------------------- * Function: handle_datasets * * Purpose: Handle the datasets from the command. * * Return: void * * Programmer: Bill Wendling * Tuesday, 9. January 2001 * * Modifications: * Pedro Vicente, Tuesday, January 15, 2008 * check for block overlap\ * * Pedro Vicente, May 8, 2008 * added a flag PE that prints/not prints error messages * added for cases of external links not found, to avoid printing of * objects not found, since external links are dumped on a trial error basis * *------------------------------------------------------------------------- */ void handle_datasets(hid_t fid, const char *dset, void *data, int pe, const char *display_name) { H5O_info_t oinfo; hid_t dsetid; struct subset_t *sset = (struct subset_t *)data; const char *real_name = display_name ? display_name : dset; if((dsetid = H5Dopen2(fid, dset, H5P_DEFAULT)) < 0) { if (pe) { handle_links(fid, dset, data, pe, display_name); } return; } /* end if */ if(sset) { unsigned int i; unsigned int ndims; hid_t sid = H5Dget_space(dsetid); int ndims_res = H5Sget_simple_extent_ndims(sid); H5Sclose(sid); if(ndims_res < 0) { error_msg("H5Sget_simple_extent_ndims failed\n"); h5tools_setstatus(EXIT_FAILURE); return; } else ndims = ndims_res; if(!sset->start.data || !sset->stride.data || !sset->count.data || !sset->block.data) { /* they didn't specify a ``stride'' or ``block''. default to 1 in all * dimensions */ if(!sset->start.data) { /* default to (0, 0, ...) for the start coord */ sset->start.data = (hsize_t *)HDcalloc((size_t)ndims, sizeof(hsize_t)); sset->start.len = ndims; } if(!sset->stride.data) { sset->stride.data = (hsize_t *)HDcalloc((size_t)ndims, sizeof(hsize_t)); sset->stride.len = ndims; for (i = 0; i < ndims; i++) sset->stride.data[i] = 1; } if(!sset->count.data) { sset->count.data = (hsize_t *)HDcalloc((size_t)ndims, sizeof(hsize_t)); sset->count.len = ndims; for (i = 0; i < ndims; i++) sset->count.data[i] = 1; } if(!sset->block.data) { sset->block.data = (hsize_t *)HDcalloc((size_t)ndims, sizeof(hsize_t)); sset->block.len = ndims; for (i = 0; i < ndims; i++) sset->block.data[i] = 1; } } /*------------------------------------------------------------------------- * check for dimension overflow *------------------------------------------------------------------------- */ if(sset->start.len > ndims) { error_msg("number of start dims (%u) exceed dataset dims (%u)\n", sset->start.len, ndims); h5tools_setstatus(EXIT_FAILURE); return; } if(sset->stride.len > ndims) { error_msg("number of stride dims (%u) exceed dataset dims (%u)\n", sset->stride.len, ndims); h5tools_setstatus(EXIT_FAILURE); return; } if(sset->count.len > ndims) { error_msg("number of count dims (%u) exceed dataset dims (%u)\n", sset->count.len, ndims); h5tools_setstatus(EXIT_FAILURE); return; } if(sset->block.len > ndims) { error_msg("number of block dims (%u) exceed dataset dims (%u)\n", sset->block.len, ndims); h5tools_setstatus(EXIT_FAILURE); return; } /*------------------------------------------------------------------------- * check for block overlap *------------------------------------------------------------------------- */ for(i = 0; i < ndims; i++) { if(sset->count.data[i] > 1) { if(sset->stride.data[i] < sset->block.data[i]) { error_msg("wrong subset selection; blocks overlap\n"); h5tools_setstatus(EXIT_FAILURE); return; } /* end if */ } /* end if */ } /* end for */ } /* end if */ H5Oget_info(dsetid, &oinfo); if(oinfo.rc > 1 || hit_elink) { obj_t *found_obj; /* Found object */ found_obj = search_obj(dset_table, oinfo.addr); if(found_obj) { if (found_obj->displayed) { PRINTVALSTREAM(rawoutstream, "\n"); indentation(dump_indent); begin_obj(h5tools_dump_header_format->datasetbegin, real_name, h5tools_dump_header_format->datasetblockbegin); PRINTVALSTREAM(rawoutstream, "\n"); indentation(dump_indent + COL); PRINTSTREAM(rawoutstream, "%s \"%s\"\n", HARDLINK, found_obj->objname); indentation(dump_indent); end_obj(h5tools_dump_header_format->datasetend, h5tools_dump_header_format->datasetblockend); } else { found_obj->displayed = TRUE; dump_indent += COL; dump_dataset(dsetid, real_name, sset); dump_indent -= COL; } } else h5tools_setstatus(EXIT_FAILURE); } else { dump_indent += COL; printf("\n--------------------->>>> (real_name, sset) = (%s, %x)\n", real_name, sset); dump_dataset(dsetid, real_name, sset); dump_indent -= COL; } if(H5Dclose(dsetid) < 0) h5tools_setstatus(EXIT_FAILURE); } /*------------------------------------------------------------------------- * Function: handle_groups * * Purpose: Handle the groups from the command. * * Return: void * * Programmer: Bill Wendling * Tuesday, 9. January 2001 * * Modifications: Pedro Vicente, September 26, 2007 * handle creation order * * Pedro Vicente, May 8, 2008 * added a flag PE that prints/not prints error messages * added for cases of external links not found, to avoid printing of * objects not found, since external links are dumped on a trial error basis * *------------------------------------------------------------------------- */ void handle_groups(hid_t fid, const char *group, void UNUSED *data, int pe, const char *display_name) { hid_t gid; const char *real_name = display_name ? display_name : group; if((gid = H5Gopen2(fid, group, H5P_DEFAULT)) < 0) { if (pe) { PRINTVALSTREAM(rawoutstream, "\n"); begin_obj(h5tools_dump_header_format->groupbegin, real_name, h5tools_dump_header_format->groupblockbegin); PRINTVALSTREAM(rawoutstream, "\n"); indentation(COL); error_msg("unable to open group \"%s\"\n", real_name); end_obj(h5tools_dump_header_format->groupend, h5tools_dump_header_format->groupblockend); h5tools_setstatus(EXIT_FAILURE); } } else { size_t new_len = HDstrlen(group) + 1; if(prefix_len <= new_len) { prefix_len = new_len; prefix = (char *)HDrealloc(prefix, prefix_len); } /* end if */ HDstrcpy(prefix, group); dump_indent += COL; dump_group(gid, real_name); dump_indent -= COL; if(H5Gclose(gid) < 0) h5tools_setstatus(EXIT_FAILURE); } /* end else */ } /* end handle_groups() */ /*------------------------------------------------------------------------- * Function: handle_links * * Purpose: Handle soft or UD links from the command. * * Return: void * * Programmer: Bill Wendling * Tuesday, 9. January 2001 * * Modifications: * *------------------------------------------------------------------------- */ void handle_links(hid_t fid, const char *links, void UNUSED * data, int UNUSED pe, const char UNUSED *display_name) { H5L_info_t linfo; if(H5Lget_info(fid, links, &linfo, H5P_DEFAULT) < 0) { error_msg("unable to get link info from \"%s\"\n", links); h5tools_setstatus(EXIT_FAILURE); } else if(linfo.type == H5L_TYPE_HARD) { error_msg("\"%s\" is a hard link\n", links); h5tools_setstatus(EXIT_FAILURE); } else { char *buf = (char *)HDmalloc(linfo.u.val_size); PRINTVALSTREAM(rawoutstream, "\n"); switch(linfo.type) { case H5L_TYPE_SOFT: /* Soft link */ begin_obj(h5tools_dump_header_format->softlinkbegin, links, h5tools_dump_header_format->softlinkblockbegin); PRINTVALSTREAM(rawoutstream, "\n"); indentation(COL); if(H5Lget_val(fid, links, buf, linfo.u.val_size, H5P_DEFAULT) >= 0) PRINTSTREAM(rawoutstream, "LINKTARGET \"%s\"\n", buf); else { error_msg("h5dump error: unable to get link value for \"%s\"\n", links); h5tools_setstatus(EXIT_FAILURE); } end_obj(h5tools_dump_header_format->softlinkend, h5tools_dump_header_format->softlinkblockend); break; case H5L_TYPE_EXTERNAL: begin_obj(h5tools_dump_header_format->udlinkbegin, links, h5tools_dump_header_format->udlinkblockbegin); PRINTVALSTREAM(rawoutstream, "\n"); indentation(COL); begin_obj(h5tools_dump_header_format->extlinkbegin, links, h5tools_dump_header_format->extlinkblockbegin); PRINTVALSTREAM(rawoutstream, "\n"); if(H5Lget_val(fid, links, buf, linfo.u.val_size, H5P_DEFAULT) >= 0) { const char *elink_file; const char *elink_path; if(H5Lunpack_elink_val(buf, linfo.u.val_size, NULL, &elink_file, &elink_path)>=0) { indentation(COL); PRINTSTREAM(rawoutstream, "LINKCLASS %d\n", linfo.type); indentation(COL); PRINTSTREAM(rawoutstream, "TARGETFILE \"%s\"\n", elink_file); indentation(COL); PRINTSTREAM(rawoutstream, "TARGETPATH \"%s\"\n", elink_path); } else { error_msg("h5dump error: unable to unpack external link value for \"%s\"\n", links); h5tools_setstatus(EXIT_FAILURE); } } else { error_msg("h5dump error: unable to get external link value for \"%s\"\n", links); h5tools_setstatus(EXIT_FAILURE); } end_obj(h5tools_dump_header_format->extlinkend, h5tools_dump_header_format->extlinkblockend); break; default: begin_obj(h5tools_dump_header_format->udlinkbegin, links, h5tools_dump_header_format->udlinkblockbegin); PRINTVALSTREAM(rawoutstream, "\n"); indentation(COL); begin_obj(h5tools_dump_header_format->udlinkbegin, links, h5tools_dump_header_format->udlinkblockbegin); PRINTVALSTREAM(rawoutstream, "\n"); indentation(COL); PRINTSTREAM(rawoutstream, "LINKCLASS %d\n", linfo.type); end_obj(h5tools_dump_header_format->udlinkend, h5tools_dump_header_format->udlinkblockend); break; } /* end switch */ HDfree(buf); } /* end else */ } /*------------------------------------------------------------------------- * Function: handle_datatypes * * Purpose: Handle the datatypes from the command. * * Return: void * * Programmer: Bill Wendling * Tuesday, 9. January 2001 * * Modifications: * * Pedro Vicente, May 8, 2008 * added a flag PE that prints/not prints error messages * added for cases of external links not found, to avoid printing of * objects not found, since external links are dumped on a trial error basis * *------------------------------------------------------------------------- */ void handle_datatypes(hid_t fid, const char *type, void UNUSED * data, int pe, const char *display_name) { hid_t type_id; const char *real_name = display_name ? display_name : type; if((type_id = H5Topen2(fid, type, H5P_DEFAULT)) < 0) { /* check if type is unamed datatype */ unsigned idx = 0; while(idx < type_table->nobjs ) { char name[128]; if(!type_table->objs[idx].recorded) { /* unamed datatype */ sprintf(name, "/#"H5_PRINTF_HADDR_FMT, type_table->objs[idx].objno); if(!HDstrcmp(name, real_name)) break; } /* end if */ idx++; } /* end while */ if(idx == type_table->nobjs) { if (pe) { /* unknown type */ PRINTVALSTREAM(rawoutstream, "\n"); begin_obj(h5tools_dump_header_format->datatypebegin, real_name, h5tools_dump_header_format->datatypeblockbegin); PRINTVALSTREAM(rawoutstream, "\n"); indentation(COL); error_msg("unable to open datatype \"%s\"\n", real_name); end_obj(h5tools_dump_header_format->datatypeend, h5tools_dump_header_format->datatypeblockend); h5tools_setstatus(EXIT_FAILURE); } } else { hid_t dsetid = H5Dopen2(fid, type_table->objs[idx].objname, H5P_DEFAULT); type_id = H5Dget_type(dsetid); dump_indent += COL; dump_named_datatype(type_id, real_name); dump_indent -= COL; H5Tclose(type_id); H5Dclose(dsetid); } } else { dump_indent += COL; dump_named_datatype(type_id, real_name); dump_indent -= COL; if(H5Tclose(type_id) < 0) h5tools_setstatus(EXIT_FAILURE); } } /*------------------------------------------------------------------------- * Function: dump_extlink * * made by: PVN * * Purpose: Dump an external link * Since external links are soft links, they are dumped on a trial error * basis, attempting to dump as a dataset, as a group and as a named datatype * Error messages are supressed * * Modifications: * Neil Fortner * 13 October 2008 * Function basically rewritten. No longer directly opens the target file, * now initializes a new set of tables for the external file. No longer * dumps on a trial and error basis, but errors are still suppressed. * *------------------------------------------------------------------------- */ static int dump_extlink(hid_t group, const char *linkname, const char *objname) { hid_t oid; H5O_info_t oi; table_t *old_group_table = group_table; table_t *old_dset_table = dset_table; table_t *old_type_table = type_table; hbool_t old_hit_elink; ssize_t idx; /* Open target object */ if ((oid = H5Oopen(group, linkname, H5P_DEFAULT)) < 0) goto fail; /* Get object info */ if (H5Oget_info(oid, &oi) < 0) { H5Oclose(oid); goto fail; } /* Check if we have visited this file already */ if ((idx = table_list_visited(oi.fileno)) < 0) { /* We have not visited this file, build object tables */ if ((idx = table_list_add(oid, oi.fileno)) < 0) { H5Oclose(oid); goto fail; } } /* Do not recurse through an external link into the original file (idx=0) */ if (idx) { /* Update table pointers */ group_table = table_list.tables[idx].group_table; dset_table = table_list.tables[idx].dset_table; type_table = table_list.tables[idx].type_table; /* We will now traverse the external link, set this global to indicate this */ old_hit_elink = hit_elink; hit_elink = TRUE; /* add some indentation to distinguish that these objects are external */ dump_indent += COL; /* Recurse into the external file */ switch (oi.type) { case H5O_TYPE_GROUP: handle_groups(group, linkname, NULL, 0, objname); break; case H5O_TYPE_DATASET: handle_datasets(group, linkname, NULL, 0, objname); break; case H5O_TYPE_NAMED_DATATYPE: handle_datatypes(group, linkname, NULL, 0, objname); break; default: h5tools_setstatus(EXIT_FAILURE); } dump_indent -= COL; /* Reset table pointers */ group_table = old_group_table; dset_table = old_dset_table; type_table = old_type_table; /* Reset hit_elink */ hit_elink = old_hit_elink; } /* end if */ if (H5Idec_ref(oid) < 0) h5tools_setstatus(EXIT_FAILURE); return SUCCEED; fail: return FAIL; }
opencb/hpg-pore
src/main/third-party/hdf5-1.8.14/tools/h5dump/h5dump_ddl.c
C
apache-2.0
74,600